From 8db84c54f11edd36b378a672776da2f742010634 Mon Sep 17 00:00:00 2001 From: prekabreki Date: Tue, 13 Oct 2026 21:17:34 +0200 Subject: [PATCH 01/94] craft-ui: a tab dragged out of the window floats where it left On X11 (including XWayland) and Windows, the pointer leaving the window reaches egui as PointerGone, and egui-winit then drops the button release because it has no pointer position. finish_drag never saw the drag end: the panel stayed in its dock with the drop outline following the pointer until the next click inside the window. Leaving the window now ends the drag as a drop. interact_pos still holds the last position on that frame, and the panel floats there (clamped to the window) instead of docking into whatever target sits at the edge. Test: tab_dragged_out_of_the_window_floats_where_it_left. It fails without the fix (no action at all). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit aecdf819ba753df0092eef73633706d3f6ce1f24) --- crates/ui/src/docking/surface.rs | 12 ++++++++---- crates/ui/src/docking/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index b0e5badd22..764cfc76db 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -829,8 +829,12 @@ impl Renderer<'_, P> { fn finish_drag(&mut self, ctx: &Context) { let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("drag"))) else { return }; - let (pointer, down, released, focused) = - ctx.input(|i| (i.pointer.interact_pos(), i.pointer.primary_down(), i.pointer.primary_released(), i.focused)); + let (pointer, down, released, focused, gone) = + ctx.input(|i| (i.pointer.interact_pos(), i.pointer.primary_down(), i.pointer.primary_released(), i.focused, !i.pointer.has_pointer())); + // Leaving the window is the drop: on X11 and Windows the release outside never reaches + // egui, so the drag would otherwise stay on the pointer. `interact_pos` still holds the + // last position this frame, and the panel floats there rather than docking at the edge. + let released = released || gone; let escape = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)); if escape || !focused || !self.layout.contains(&drag.panel) || (!down && !released) { cancel_drag::

(ctx, self.id); @@ -854,10 +858,10 @@ impl Renderer<'_, P> { if pointer.distance(drag.origin) < 2.0 { return; } - let action = if let Some(proposal) = proposal { + let action = if let Some(proposal) = proposal.filter(|_| !gone) { Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) } else if (self.permissions)(&drag.panel).floatable - && (!drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.panels.contains(&drag.panel))) + && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.panels.contains(&drag.panel))) { let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }) diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 54d37df6cb..11936502aa 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -395,6 +395,30 @@ fn actual_pointer_drag_docks_a_floating_panel_into_the_main_tab_strip() { assert_eq!(panels.get(*active), Some(&5)); } +/// On X11 and Windows a release outside the window never reaches egui (egui-winit drops a +/// button event once the pointer has left), so a tab dragged out of the window used to stay on +/// the pointer for good. Leaving the window detaches the panel where it left, even over a dock +/// target, and ends the drag. +#[test] +fn tab_dragged_out_of_the_window_floats_where_it_left() { + let ctx = Context::default(); + let mut layout = sample(); + for _ in 0..3 { + step(&ctx, &mut layout, Vec::new()); + } + let tab = ctx.read_response(Id::new("test-area").with(("tab", &3u32))).unwrap().rect.center(); + let exit = pos2(4.0, 300.0); + step(&ctx, &mut layout, vec![Event::PointerMoved(tab), pointer_button(tab, true)]); + step(&ctx, &mut layout, vec![Event::PointerMoved(tab + vec2(-8.0, 0.0))]); + step(&ctx, &mut layout, vec![Event::PointerMoved(exit)]); + let actions = step(&ctx, &mut layout, vec![Event::PointerGone]); + assert!(actions.iter().any(|a| matches!(a, Action::Float { panel: 3, .. })), "{actions:?}"); + assert!(layout.floating.iter().any(|g| g.panels == [3]), "{layout:?}"); + let back = pos2(400.0, 300.0); + assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(back)]).is_empty()); + assert!(step(&ctx, &mut layout, vec![pointer_button(back, false)]).is_empty(), "the drag ended when the pointer left"); +} + #[test] fn panel_size_limits_clamp_geometry_without_overwriting_preferred_widths() { let layout = Layout { From 9cbc0888ce3f7c7e41598bb21eff96f6627b91d9 Mon Sep 17 00:00:00 2001 From: euisuh <55032583+euisuh@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:22:24 +0900 Subject: [PATCH 02/94] fix(ui): end floating group drags on pointer exit Discard a renderer-owned group gesture when its pointer disappears so a missing outside release cannot resume dragging, while retaining touch drops. Closes #95 Co-Authored-By: OpenAI Codex (cherry picked from commit 9a6f159fc5c2fca4773109ca124705cf289c07fc) --- crates/ui/src/docking/surface.rs | 9 ++- crates/ui/src/docking/tests.rs | 102 +++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 2 deletions(-) diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 764cfc76db..c5715e93cd 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -812,11 +812,16 @@ impl Renderer<'_, P> { } let (escape, focused, down, released, pointer) = ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); - if escape || !focused || !down { - ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); + // A button release outside the window may never reach egui. + let has_pointer = ctx.input(|i| i.pointer.has_pointer()); + // Touch-up also removes the pointer, but still completes a drop. + let touch_ended = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::End, .. }))); + if escape || !focused || !down || !has_pointer { + cancel_drag::

(ctx, self.id); if escape || !focused { self.output.actions.push(Action::MoveFloating { panel: drag.panel, rect: drag.original }); } else if released + && (has_pointer || touch_ended) && let Some(pointer) = pointer.filter(|p| p.is_finite()) && !self.blockers.iter().any(|r| r.contains(pointer)) { diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 11936502aa..474a01a081 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -667,6 +667,108 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() { assert_eq!(layout.floating[0].panels, vec![6]); } +#[test] +fn floating_group_drag_ends_on_release_or_pointer_exit() { + for (released, leaves) in [(false, true), (true, true), (true, false)] { + let ctx = Context::default(); + let mut layout = sample(); + for _ in 0..2 { + step(&ctx, &mut layout, vec![]); + } + let start = pos2(86.0, 82.0); + step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); + let moved = start + vec2(50.0, 40.0); + let actions = step(&ctx, &mut layout, vec![Event::PointerMoved(moved)]); + assert!(actions.iter().any(|action| matches!(action, Action::MoveFloating { .. }))); + let last = layout.clone(); + let mut events = vec![]; + if released { + events.push(pointer_button(moved, false)); + } + if leaves { + events.push(Event::PointerGone); + } + let (out, _) = frame(&ctx, &layout, events, true); + assert_eq!(out.group_drop, if leaves { None } else { Some((5, moved)) }); + for action in out.actions { + layout.apply(action).unwrap(); + } + assert_eq!(layout, last); + for pointer in [moved + vec2(20.0, 20.0), moved + vec2(30.0, 30.0)] { + let (out, _) = frame(&ctx, &layout, vec![Event::PointerMoved(pointer)], true); + assert!(out.actions.is_empty(), "{out:?}"); + assert!(out.group_drag.is_none() && out.group_drop.is_none()); + } + assert!(out.group_drag.is_none()); + assert_eq!(ctx.dragged_id(), None); + } +} + +#[test] +fn floating_group_touch_release_reports_drop_after_pointer_gone() { + for web_order in [false, true] { + let ctx = Context::default(); + let mut layout = sample(); + for _ in 0..2 { + step(&ctx, &mut layout, vec![]); + } + let touch = |phase, pos| Event::Touch { device_id: egui::TouchDeviceId(0), id: egui::TouchId(1), phase, pos, force: None }; + let start = pos2(86.0, 82.0); + let press = pointer_button(start, true); + let events = if web_order { + vec![press, touch(egui::TouchPhase::Start, start)] + } else { + vec![touch(egui::TouchPhase::Start, start), Event::PointerMoved(start), press] + }; + step(&ctx, &mut layout, events); + let moved = start + vec2(50.0, 40.0); + let events = if web_order { + vec![Event::PointerMoved(moved), touch(egui::TouchPhase::Move, moved)] + } else { + vec![touch(egui::TouchPhase::Move, moved), Event::PointerMoved(moved)] + }; + assert!(step(&ctx, &mut layout, events).iter().any(|action| matches!(action, Action::MoveFloating { .. }))); + // egui-winit emits Touch before release/gone; eframe web emits it afterwards. + let events = if web_order { + vec![pointer_button(moved, false), Event::PointerGone, touch(egui::TouchPhase::End, moved)] + } else { + vec![touch(egui::TouchPhase::End, moved), pointer_button(moved, false), Event::PointerGone] + }; + let (out, _) = frame(&ctx, &layout, events, true); + assert!(!ctx.input(|i| i.pointer.has_pointer())); + assert_eq!(out.group_drop, Some((5, moved))); + assert!(out.group_drag.is_none()); + assert_eq!(ctx.dragged_id(), None); + assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(moved + vec2(30.0, 30.0))]).is_empty()); + } +} + +#[test] +fn floating_group_exit_with_escape_or_focus_loss_restores_original_geometry() { + for escape in [false, true] { + let ctx = Context::default(); + let mut layout = sample(); + let original = layout.clone(); + for _ in 0..2 { + step(&ctx, &mut layout, vec![]); + } + let start = pos2(86.0, 82.0); + step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); + step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(50.0, 40.0))]); + assert_ne!(layout.floating[0].rect, original.floating[0].rect); + let mut events = vec![Event::PointerGone]; + if escape { + events.push(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + } + let (out, _) = frame(&ctx, &layout, events, escape); + assert!(out.group_drag.is_none() && out.group_drop.is_none()); + for action in out.actions { + layout.apply(action).unwrap(); + } + assert_eq!(layout.floating[0].rect, original.floating[0].rect); + } +} + struct CustomContent { labels: Vec, headers: usize, From 5ac5d26be183a10a201db3a1c324b7426c4ba4f3 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Tue, 13 Oct 2026 00:48:41 +0200 Subject: [PATCH 03/94] Truncate dock tab labels that do not fit their tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tab squeezed below its natural width painted its whole label centred and only clipped it, so long names ran over the tab's edges and under its neighbours. The label is now cut with '…' inside the same padding the natural width is measured with, and a cut tab names its panel in full on hover. (cherry picked from commit 5c28add6cfc2d381959773a31e2fc501024f1744) --- crates/ui/src/docking/surface.rs | 13 +++++++-- crates/ui/src/docking/tests.rs | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index c5715e93cd..0cf548916f 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -9,6 +9,9 @@ use crate::{ use super::{Action, DockError, DropTarget, Layout, Node, Permissions, Placement, resolve_drop}; +/// Horizontal room around a tab's label, both when measuring its natural width and when cutting it. +const TAB_PADDING: f32 = 24.0; + /// Application-supplied chrome. Body renderers retain their own UI style and contents. #[derive(Clone, Debug)] pub struct DockStyle { @@ -609,7 +612,7 @@ impl Renderer<'_, P> { .into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, self.style.font.clone()) .size() .x - + 24.0 + + TAB_PADDING }) .collect(); let fit = tabs::fit(&widths, active, (strip.width() - header_width).max(0.0), 40.0, 22.0); @@ -671,12 +674,15 @@ impl Renderer<'_, P> { let policy = (self.permissions)(panel); let label = (self.label)(panel); let color = if active { self.style.text } else { self.style.inactive_text }; + // A tab squeezed below its natural width cuts its label with '…' inside the padding its + // natural width was measured with, instead of letting it run under its neighbours. let galley = self.content.label(ui, panel, &label, &self.style.font, color).into_galley( ui, - Some(egui::TextWrapMode::Extend), - f32::INFINITY, + Some(egui::TextWrapMode::Truncate), + (rect.width() - TAB_PADDING).max(0.0), self.style.font.clone(), ); + let elided = galley.elided; let response = tabs::Tab::new(self.id.with(("tab", panel)), &label, active) .sense(if policy.movable { Sense::click_and_drag() } else { Sense::click() }) .focus_stroke(Stroke::new(1.0, self.style.accent)) @@ -685,6 +691,7 @@ impl Renderer<'_, P> { painter.rect_filled(rect, 0.0, if active || response.hovered() { self.style.active_background } else { self.style.tab_background }); painter.galley(rect.center() - galley.size() * 0.5, galley.clone(), color); }); + let response = if elided { response.on_hover_text(&label) } else { response }; self.register_interaction(ui.ctx(), response.id); if response.clicked() { self.output.actions.push(Action::Activate { panel: panel.clone() }); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 474a01a081..38c9f9fc8d 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1216,3 +1216,52 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() { ); } } + +#[test] +fn tab_labels_that_do_not_fit_are_truncated_inside_their_tab_and_named_in_a_tooltip() { + let ctx = Context::default(); + ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + let layout = Layout { root: Some(tabs(&[1, 2, 3], 0)), floating: vec![] }; + let label = |p: &u32| format!("Eigenschaften und Anpassungen {p}"); + let run = |events: Vec| { + let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 200.0))), events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + DockArea::new(Id::new("truncate")).show( + ui, + &layout, + &DockStyle::from_ui(ui), + label, + |_| Permissions::default(), + |ui, _| { + ui.label("Body"); + }, + ); + }); + output.textures_delta.clear(); + output.shapes + }; + run(vec![]); + let shapes = run(vec![]); + let tab = |p: u32| ctx.read_response(Id::new("truncate").with(("tab", &p))).unwrap().rect; + for p in 1..=3 { + let tab = tab(p); + // The clip rect would hide an overflowing label; what is laid out must itself fit. + let painted: Vec = shapes + .iter() + .filter(|shape| matches!(&shape.shape, egui::Shape::Text(_))) + .map(|shape| shape.shape.visual_bounding_rect()) + .filter(|r| tab.contains(r.center())) + .collect(); + assert_eq!(painted.len(), 1, "tab {p}: {painted:?}"); + assert!(tab.contains_rect(painted[0]), "tab {p}: label {:?} overflows {tab:?}", painted[0]); + } + let at = tab(2).center(); + run(vec![Event::PointerMoved(at)]); + let shapes = run(vec![]); + let full = label(&2); + // An elided galley still reports its whole text, so the cut tab label alone would match. + assert!( + shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == full && !text.galley.elided)), + "a truncated tab names its panel in full on hover" + ); +} From c4b007706d3adb1b23ff5192eea0bad2a293428e Mon Sep 17 00:00:00 2001 From: NibrasAz7 Date: Wed, 14 Oct 2026 23:31:53 +0200 Subject: [PATCH 04/94] Docking: hide 'Move to group' when no panel accepts the move (lightcraft#1768) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A movable panel's context menu always offered 'Move to group', even when the layout held no other panel that accepts tabs — one open panel showed an empty submenu. Layout gains move_targets() (the same filter the menu applies: every other panel that accepts_tabs), the menu renders only when it is non-empty, and a test pins the lone-panel and protected-anchor cases. (cherry picked from commit 671463c1af06015c0c7020450777343c39065be1) --- crates/ui/src/docking/model.rs | 6 ++++++ crates/ui/src/docking/surface.rs | 6 +++--- crates/ui/src/docking/tests.rs | 16 ++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index babb3e2fd8..a7056677f2 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -287,6 +287,12 @@ impl Layout

{ self.panels().contains(&panel) } + /// The panels `panel` can join as a tab: every other panel whose permissions accept tabs. + /// A "Move to group" menu with an empty answer has nothing to offer and stays hidden. + pub fn move_targets(&self, panel: &P, permissions: impl Fn(&P) -> Permissions) -> Vec<&P> { + self.panels().into_iter().filter(|target| *target != panel && permissions(target).accepts_tabs).collect() + } + /// Capture a panel's nearest surviving group/split neighbor before hiding it. pub fn location(&self, panel: &P) -> Result, DockError> { self.validate()?; diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 0cf548916f..53b8137285 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -712,12 +712,12 @@ impl Renderer<'_, P> { ui.close(); } } - if policy.movable { + if policy.movable && !self.layout.move_targets(panel, self.permissions).is_empty() { let text = self.content.action_label(ui, &self.style.move_label, &self.style.font, self.style.text); let response = ui.menu_button(text, |ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { - for target in self.layout.panels() { - if target != panel && (self.permissions)(target).accepts_tabs && self.menu_label(ui, target).clicked() { + for target in self.layout.move_targets(panel, self.permissions) { + if self.menu_label(ui, target).clicked() { self.output.actions.push(Action::Move { panel: panel.clone(), anchor: target.clone(), diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 38c9f9fc8d..941220dbdb 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -51,6 +51,22 @@ fn detach_redock_merge_and_collapse_empty_source_containers() { assert_eq!(layout.panels().len(), 6); } +#[test] +fn move_targets_skip_the_panel_itself_and_protected_anchors() { + let layout = sample(); + let all = |_: &u32| Permissions::default(); + let targets = layout.move_targets(&1, all); + assert_eq!(targets.len(), 5); + assert!(!targets.contains(&&1)); + let guarded = |p: &u32| if *p == 3 { Permissions::PROTECTED } else { Permissions::default() }; + assert!(!layout.move_targets(&1, guarded).contains(&&3)); + + // A lone panel has nowhere to go — its "Move to group" menu hides + // (storytold/lightcraft#1768). + let single = Layout { root: Some(tabs(&[1], 0)), floating: Vec::new() }; + assert!(single.move_targets(&1, all).is_empty()); +} + #[test] fn invalid_moves_are_atomic_including_after_a_source_would_have_been_removed() { let layout = sample(); From 0ae7cddbb5fbf97aba98961873a96facb9a296cb Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:35:13 +0000 Subject: [PATCH 05/94] docking: docks, columns, groups and floating stacks in the layout model Node::Dock holds columns of groups on a logical window edge (Side::Start or Side::End). Floating windows hold a stack of groups and an optional native rect; the v1 {panels, active, rect} shape still parses, and a window with one plain group writes it. Placement gains Group and Column, Target names where a group, column or window goes, and the new actions move, close, minimize, collapse and resize groups, columns and windows atomically. Location records group and column state so a panel closed from a dock or floating stack restores to the same group, seam, column or dock. Layout gains apply_all, closed_by and panel_state; Permissions gains locked. Node, Action, Placement and DockError are non_exhaustive. The renderer draws each floating window's groups stacked and a dock's columns side by side until the dock and floating-stack profiles land. --- crates/ui/src/docking/dock_model.rs | 573 +++++++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 2 + crates/ui/src/docking/model.rs | 572 +++++++++++++++++++++++--- crates/ui/src/docking/surface.rs | 41 +- crates/ui/src/docking/tests.rs | 32 +- crates/ui/tests/docking_workflows.rs | 4 +- 6 files changed, 1140 insertions(+), 84 deletions(-) create mode 100644 crates/ui/src/docking/dock_model.rs diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs new file mode 100644 index 0000000000..d4200fe3b3 --- /dev/null +++ b/crates/ui/src/docking/dock_model.rs @@ -0,0 +1,573 @@ +//! Docks, columns, groups and floating stacks: their types and the structural edits behind +//! group, column and window moves. +//! +//! A group, column or floating window is named by a panel it contains. Edits run on a proposed +//! copy of the layout, so a helper that fails part-way leaves nothing behind. + +use std::hash::Hash; + +use super::model::{DockError, Floating, Layout, MAX_NODES, Node, Placement, Zone, valid_rect, valid_width}; +use crate::layout::{SplitAxis, SplitSize}; + +/// Width of a new column when nothing better is known. +pub(super) const DEFAULT_COLUMN_WIDTH: f32 = 240.0; +/// Rect of a new floating window when the caller gives none and the source has no size. +const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0]; + +/// The window edge a [`Node::Dock`] sits on, in reading order so right-to-left interfaces +/// mirror. `Start` is the edge of a horizontal split's first child (left in a left-to-right +/// layout); the renderer maps it to a physical edge from the layout direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Side { + Start, + End, +} + +/// Tabs that move, minimize and size together, in a dock column or a floating stack. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(bound(deserialize = "P: serde::Deserialize<'de>")))] +pub struct Group

{ + pub panels: Vec

, + pub active: usize, + /// Only the tab strip shows. `height` is kept for when the group expands again. + #[cfg_attr(feature = "serde", serde(default))] + pub minimized: bool, + /// Preferred height in points; `None` shares the free height of the column or stack. + #[cfg_attr(feature = "serde", serde(default))] + pub height: Option, +} + +impl

Group

{ + pub fn new(panels: Vec

, active: usize) -> Self { + Self { panels, active, minimized: false, height: None } + } + + pub fn active_panel(&self) -> Option<&P> { + self.panels.get(self.active) + } +} + +/// One column of a dock: groups from top to bottom. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(bound(deserialize = "P: serde::Deserialize<'de>")))] +pub struct Column

{ + pub groups: Vec>, + /// Expanded width in points. + pub width: f32, + /// Collapsed to one icon per panel. + #[cfg_attr(feature = "serde", serde(default))] + pub iconic: bool, + /// Width while iconic; labels show beside the icons when it is wide enough. + #[cfg_attr(feature = "serde", serde(default))] + pub iconic_width: Option, +} + +impl

Column

{ + pub fn new(groups: Vec>, width: f32) -> Self { + Self { groups, width, iconic: false, iconic_width: None } + } +} + +/// Where a group, column or floating window goes. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Target

{ + /// Relative to the panel `anchor`, which must not be part of what moves. + At { anchor: P, placement: Placement

}, + /// A new dock on an edge that has none (or an empty one). The root becomes the other side + /// of a horizontal split. + NewDock { side: Side }, + /// A new floating window. `None` keeps the source's size at a default position. + Float { rect: Option<[f32; 4]> }, +} + +/// What the Window menu shows for a panel. The model does not track the z-order of floating +/// windows, so `Front` means "showing": the active tab of an expanded group in an expanded column. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PanelState { + Hidden, + Open, + Front, +} + +/// The group a closed panel was in, when that group was in a dock or a floating stack. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct GroupLocation { + pub minimized: bool, + pub height: Option, + /// The column, when the group was docked. + pub column: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct ColumnLocation { + pub side: Side, + pub width: f32, + pub iconic: bool, + pub iconic_width: Option, +} + +/// Where a panel is. Paths lead from the root: false is a split's first child, true its second. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Place { + /// A `Tabs` or `Stack` node. + Node(Vec), + Dock { + path: Vec, + column: usize, + group: usize, + }, + Floating { + window: usize, + group: usize, + }, +} + +/// Which container a whole-container action names. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Unit { + Group, + Column, + Window, +} + +/// Groups in transit, with the size and state of the container they came from. +pub(super) struct Moving

{ + pub groups: Vec>, + pub width: Option, + pub iconic: bool, + pub iconic_width: Option, + pub rect: Option<[f32; 4]>, + pub native: Option<[f32; 4]>, +} + +impl

Moving

{ + pub fn group(group: Group

) -> Self { + Self { groups: vec![group], width: None, iconic: false, iconic_width: None, rect: None, native: None } + } + + fn into_column(self, width: f32) -> Column

{ + Column { groups: self.groups, width: self.width.unwrap_or(width), iconic: self.iconic, iconic_width: self.iconic_width } + } +} + +pub(super) fn node_at<'a, P>(mut node: &'a Node

, path: &[bool]) -> Option<&'a Node

> { + for second_child in path { + let Node::Split { first, second, .. } = node else { return None }; + node = if *second_child { second } else { first }; + } + Some(node) +} + +pub(super) fn node_at_mut<'a, P>(mut node: &'a mut Node

, path: &[bool]) -> Option<&'a mut Node

> { + for second_child in path { + let Node::Split { first, second, .. } = node else { return None }; + node = if *second_child { second } else { first }; + } + Some(node) +} + +/// Insert `new` at `index` and select the member at `index + selected`. +fn splice

(panels: &mut Vec

, active: &mut usize, index: usize, new: Vec

, selected: usize) { + let index = index.min(panels.len()); + let count = new.len(); + panels.splice(index..index, new); + *active = index + selected.min(count.saturating_sub(1)); +} + +impl Layout

{ + pub(super) fn place(&self, panel: &P) -> Option { + for (w, window) in self.floating.iter().enumerate() { + if let Some(g) = window.groups.iter().position(|group| group.panels.contains(panel)) { + return Some(Place::Floating { window: w, group: g }); + } + } + let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); + let mut visited = 0usize; + while let Some((node, path)) = visit.pop() { + visited = visited.saturating_add(1); + if visited > MAX_NODES { + return None; + } + match node { + Node::Split { first, second, .. } => { + let mut second_path = path.clone(); + second_path.push(true); + let mut first_path = path; + first_path.push(false); + visit.push((second, second_path)); + visit.push((first, first_path)); + } + Node::Tabs { panels, .. } if panels.contains(panel) => return Some(Place::Node(path)), + Node::Stack { entries } if entries.iter().any(|e| &e.panel == panel) => return Some(Place::Node(path)), + Node::Dock { columns, .. } => { + for (c, column) in columns.iter().enumerate() { + if let Some(g) = column.groups.iter().position(|group| group.panels.contains(panel)) { + return Some(Place::Dock { path, column: c, group: g }); + } + } + } + Node::Tabs { .. } | Node::Stack { .. } => {} + } + } + None + } + + pub(super) fn dock_path(&self, side: Side) -> Option> { + let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); + let mut visited = 0usize; + while let Some((node, path)) = visit.pop() { + visited = visited.saturating_add(1); + if visited > MAX_NODES { + return None; + } + match node { + Node::Split { first, second, .. } => { + let mut second_path = path.clone(); + second_path.push(true); + let mut first_path = path; + first_path.push(false); + visit.push((second, second_path)); + visit.push((first, first_path)); + } + Node::Dock { side: s, .. } if *s == side => return Some(path), + _ => {} + } + } + None + } + + pub(super) fn columns_mut(&mut self, path: &[bool]) -> Option<&mut Vec>> { + match self.root.as_mut().and_then(|root| node_at_mut(root, path)) { + Some(Node::Dock { columns, .. }) => Some(columns), + _ => None, + } + } + + pub(super) fn column(&self, place: &Place) -> Option<&Column

> { + let Place::Dock { path, column, .. } = place else { return None }; + match self.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Dock { columns, .. }) => columns.get(*column), + _ => None, + } + } + + pub(super) fn column_mut(&mut self, place: &Place) -> Option<&mut Column

> { + let Place::Dock { path, column, .. } = place else { return None }; + self.columns_mut(path)?.get_mut(*column) + } + + /// The dock or floating group at `place`; `None` for a `Tabs` or `Stack` node. + pub(super) fn group(&self, place: &Place) -> Option<&Group

> { + match place { + Place::Node(_) => None, + Place::Dock { group, .. } => self.column(place)?.groups.get(*group), + Place::Floating { window, group } => self.floating.get(*window)?.groups.get(*group), + } + } + + pub(super) fn group_mut(&mut self, place: &Place) -> Option<&mut Group

> { + match place { + Place::Node(_) => None, + Place::Dock { group, .. } => self.column_mut(place)?.groups.get_mut(*group), + Place::Floating { window, group } => self.floating.get_mut(*window)?.groups.get_mut(*group), + } + } + + /// Remove the node at `path`; its parent split collapses into the sibling. + pub(super) fn take_node(&mut self, path: &[bool]) -> Option> { + let Some((second_child, parent_path)) = path.split_last() else { return self.root.take() }; + let parent = self.root.as_mut().and_then(|root| node_at_mut(root, parent_path))?; + if !matches!(parent, Node::Split { .. }) { + return None; + } + match std::mem::replace(parent, Node::Tabs { panels: Vec::new(), active: 0 }) { + Node::Split { first, second, .. } => { + let (taken, kept) = if *second_child { (second, first) } else { (first, second) }; + *parent = *kept; + Some(*taken) + } + other => { + *parent = other; + None + } + } + } + + /// The members of the group, column or floating window containing `panel`, in order. + /// An accordion entry is a group of one. + pub(super) fn members(&self, panel: &P, unit: Unit) -> Result, DockError> { + let place = self.place(panel).ok_or(DockError::MissingPanel)?; + match (unit, &place) { + (Unit::Group, Place::Node(path)) => match self.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Tabs { panels, .. }) => Ok(panels.clone()), + Some(Node::Stack { .. }) => Ok(vec![panel.clone()]), + _ => Err(DockError::MissingPanel), + }, + (Unit::Group, _) => self.group(&place).map(|g| g.panels.clone()).ok_or(DockError::MissingPanel), + (Unit::Column, Place::Dock { .. }) => { + let column = self.column(&place).ok_or(DockError::MissingPanel)?; + Ok(column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect()) + } + (Unit::Window, Place::Floating { window, .. }) => { + let window = self.floating.get(*window).ok_or(DockError::MissingPanel)?; + Ok(window.panels().cloned().collect()) + } + (Unit::Column | Unit::Window, _) => Err(DockError::InvalidPlacement), + } + } + + pub(super) fn take_unit(&mut self, panel: &P, unit: Unit) -> Result, DockError> { + match unit { + Unit::Group => self.take_group(panel), + Unit::Column => self.take_column(panel), + Unit::Window => self.take_window(panel), + } + } + + fn take_group(&mut self, panel: &P) -> Result, DockError> { + let place = self.place(panel).ok_or(DockError::MissingPanel)?; + match place { + Place::Node(path) => { + if let Some(Node::Stack { entries }) = self.root.as_mut().and_then(|root| node_at_mut(root, &path)) + && entries.len() > 1 + && let Some(index) = entries.iter().position(|e| &e.panel == panel) + { + let entry = entries.remove(index); + let group = Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height }; + return Ok(Moving::group(group)); + } + match self.take_node(&path) { + Some(Node::Tabs { panels, active }) => Ok(Moving::group(Group::new(panels, active))), + Some(Node::Stack { mut entries }) if entries.len() == 1 => { + let entry = entries.remove(0); + Ok(Moving::group(Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height })) + } + _ => Err(DockError::MissingPanel), + } + } + Place::Dock { path, column, group } => { + let columns = self.columns_mut(&path).ok_or(DockError::MissingPanel)?; + let source = columns.get_mut(column).ok_or(DockError::MissingPanel)?; + if group >= source.groups.len() { + return Err(DockError::MissingPanel); + } + let taken = source.groups.remove(group); + let width = source.width; + if source.groups.is_empty() { + columns.remove(column); + } + if columns.is_empty() { + self.take_node(&path); + } + Ok(Moving { width: Some(width), ..Moving::group(taken) }) + } + Place::Floating { window, group } => { + let source = self.floating.get_mut(window).ok_or(DockError::MissingPanel)?; + if group >= source.groups.len() { + return Err(DockError::MissingPanel); + } + let taken = source.groups.remove(group); + let rect = source.rect; + let native = source.native; + let whole = source.groups.is_empty(); + if whole { + self.floating.remove(window); + } + let width = rect.get(2).copied(); + Ok(Moving { width, rect: whole.then_some(rect), native: native.filter(|_| whole), ..Moving::group(taken) }) + } + } + } + + fn take_column(&mut self, panel: &P) -> Result, DockError> { + let Some(Place::Dock { path, column, .. }) = self.place(panel) else { return Err(DockError::InvalidPlacement) }; + let columns = self.columns_mut(&path).ok_or(DockError::MissingPanel)?; + if column >= columns.len() { + return Err(DockError::MissingPanel); + } + let taken = columns.remove(column); + if columns.is_empty() { + self.take_node(&path); + } + Ok(Moving { + groups: taken.groups, + width: Some(taken.width), + iconic: taken.iconic, + iconic_width: taken.iconic_width, + rect: None, + native: None, + }) + } + + fn take_window(&mut self, panel: &P) -> Result, DockError> { + let Some(Place::Floating { window, .. }) = self.place(panel) else { return Err(DockError::InvalidPlacement) }; + if window >= self.floating.len() { + return Err(DockError::MissingPanel); + } + let taken = self.floating.remove(window); + Ok(Moving { + groups: taken.groups, + width: taken.rect.get(2).copied(), + iconic: false, + iconic_width: None, + rect: Some(taken.rect), + native: taken.native, + }) + } + + /// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). + pub(super) fn insert_moving(&mut self, moving: Moving

, to: Target

) -> Result<(), DockError> { + if moving.groups.is_empty() || moving.groups.iter().any(|g| g.panels.is_empty()) { + return Err(DockError::MissingPanel); + } + match to { + Target::Float { rect } => { + let native = if rect.is_none() { moving.native } else { None }; + let rect = rect.or(moving.rect).unwrap_or_else(|| { + let [x, y, width, height] = DEFAULT_FLOAT; + [x, y, moving.width.unwrap_or(width), height] + }); + if !valid_rect(rect) { + return Err(DockError::InvalidGeometry); + } + self.floating.push(Floating { groups: moving.groups, rect, native }); + Ok(()) + } + Target::NewDock { side } => { + if let Some(path) = self.dock_path(side) { + let columns = self.columns_mut(&path).ok_or(DockError::MissingTarget)?; + if !columns.is_empty() { + return Err(DockError::InvalidPlacement); + } + columns.push(moving.into_column(DEFAULT_COLUMN_WIDTH)); + return Ok(()); + } + let column = moving.into_column(DEFAULT_COLUMN_WIDTH); + self.add_dock(side, column); + Ok(()) + } + Target::At { anchor, placement } => { + let place = self.place(&anchor).ok_or(DockError::MissingTarget)?; + match placement { + Placement::Tab { before } => { + let index = match &before { + Some(before) => { + if self.place(before).as_ref() != Some(&place) { + return Err(DockError::MissingTarget); + } + self.index_in(&place, before) + } + None => None, + }; + self.merge(&place, index, moving) + } + Placement::Split(Zone::Center) => { + let index = self.index_in(&place, &anchor).map(|i| i + 1); + self.merge(&place, index, moving) + } + Placement::Split(zone) => { + let Place::Node(path) = place else { return Err(DockError::InvalidPlacement) }; + let node = self.root.as_mut().and_then(|root| node_at_mut(root, &path)).ok_or(DockError::MissingTarget)?; + let (panels, active) = flatten(moving.groups); + let new = Node::Tabs { panels, active }; + let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); + let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; + let (first, second) = if matches!(zone, Zone::Top | Zone::Left) { (new, old) } else { (old, new) }; + *node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) }; + Ok(()) + } + Placement::Group { below } => { + let (groups, index) = match &place { + Place::Dock { group, .. } => (&mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups, *group), + Place::Floating { window, group } => { + (&mut self.floating.get_mut(*window).ok_or(DockError::MissingTarget)?.groups, *group) + } + Place::Node(_) => return Err(DockError::InvalidPlacement), + }; + let index = (index + usize::from(below)).min(groups.len()); + groups.splice(index..index, moving.groups); + Ok(()) + } + Placement::Column { after } => { + let Place::Dock { path, column, .. } = &place else { return Err(DockError::InvalidPlacement) }; + let columns = self.columns_mut(path).ok_or(DockError::MissingTarget)?; + let width = columns.get(*column).map_or(DEFAULT_COLUMN_WIDTH, |c| c.width); + let index = (column + usize::from(after)).min(columns.len()); + columns.insert(index, moving.into_column(width)); + Ok(()) + } + } + } + } + } + + /// Wrap the root in a horizontal split with a new dock on `side`. The split's fixed size is + /// the column width. + pub(super) fn add_dock(&mut self, side: Side, column: Column

) { + let width = column.width; + let dock = Node::Dock { side, columns: vec![column] }; + self.root = Some(match self.root.take() { + None => dock, + Some(root) => { + let (first, second, size) = match side { + Side::Start => (dock, root, SplitSize::FixedFirst(width)), + Side::End => (root, dock, SplitSize::FixedSecond(width)), + }; + Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(first), second: Box::new(second) } + } + }); + } + + fn index_in(&self, place: &Place, panel: &P) -> Option { + match place { + Place::Node(path) => match self.root.as_ref().and_then(|root| node_at(root, path))? { + Node::Tabs { panels, .. } => panels.iter().position(|p| p == panel), + Node::Stack { entries } => entries.iter().position(|e| &e.panel == panel), + _ => None, + }, + _ => self.group(place)?.panels.iter().position(|p| p == panel), + } + } + + /// Join every moving panel to the group at `place`, before `index` or at the end. The first + /// moving group's active panel becomes active. + fn merge(&mut self, place: &Place, index: Option, moving: Moving

) -> Result<(), DockError> { + let (panels, selected) = flatten(moving.groups); + match place { + Place::Node(path) => match self.root.as_mut().and_then(|root| node_at_mut(root, path)) { + Some(Node::Tabs { panels: target, active }) => { + splice(target, active, index.unwrap_or(target.len()), panels, selected); + Ok(()) + } + Some(Node::Stack { entries }) => { + let index = index.unwrap_or(entries.len()).min(entries.len()); + entries.splice(index..index, panels.into_iter().map(|panel| super::StackEntry { panel, open: true, height: None })); + Ok(()) + } + _ => Err(DockError::MissingTarget), + }, + _ => { + let group = self.group_mut(place).ok_or(DockError::MissingTarget)?; + let end = group.panels.len(); + splice(&mut group.panels, &mut group.active, index.unwrap_or(end), panels, selected); + Ok(()) + } + } + } +} + +/// All panels in order, and the index of the first group's active panel among them. +fn flatten

(groups: Vec>) -> (Vec

, usize) { + let selected = groups.first().map_or(0, |g| g.active.min(g.panels.len().saturating_sub(1))); + (groups.into_iter().flat_map(|g| g.panels).collect(), selected) +} + +pub(super) fn valid_column

(column: &Column

) -> bool { + valid_width(column.width) && column.iconic_width.is_none_or(valid_width) +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index a7bf3f98b8..d29be7a4bd 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -5,10 +5,12 @@ //! Validate deserialized layouts before rendering them. Every transaction checks its complete //! input and commits only a valid result; a rejected move cannot lose the source panel. +mod dock_model; mod model; mod surface; mod targets; +pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; pub use surface::{DockArea, DockContent, DockOutput, DockStyle, PanelLimits, begin_drag, cancel_drag}; pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect}; diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index a7056677f2..92eeedbb78 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -1,11 +1,12 @@ use std::{collections::HashSet, fmt, hash::Hash}; +use super::dock_model::{Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, valid_column}; use crate::layout::{SplitAxis, SplitSize}; /// Limits are checked before cloning or recursively modifying an application layout. pub const MAX_DEPTH: usize = 64; pub const MAX_PANELS: usize = 4096; -const MAX_NODES: usize = MAX_PANELS * 2; +pub(super) const MAX_NODES: usize = MAX_PANELS * 2; const MAX_EXTENT: f32 = 1_000_000.0; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -20,6 +21,7 @@ pub enum Zone { #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] pub enum Node

{ Split { axis: SplitAxis, @@ -35,6 +37,13 @@ pub enum Node

{ Stack { entries: Vec>, }, + /// One window edge's dock, columns from the window edge inwards. A dock is the root or, + /// following only same-side children of horizontal splits, at its window edge. At most one + /// per side. An empty dock (no columns) is valid and accepts [`Target::NewDock`]. + Dock { + side: Side, + columns: Vec>, + }, } #[derive(Clone, Debug, PartialEq)] @@ -45,13 +54,93 @@ pub struct StackEntry

{ pub height: Option, } +/// A floating window: a stack of groups, top to bottom. +/// +/// Serde reads the v1 shape `{panels, active, rect}` as one group. A window with one plain group +/// (not minimized, no height, no native rect) writes that shape, so older builds can read files +/// that use no newer feature. #[derive(Clone, Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Floating

{ - pub panels: Vec

, - pub active: usize, + pub groups: Vec>, /// `[x, y, width, height]` in logical points, in the application's egui viewport. pub rect: [f32; 4], + /// Desktop rect while the window is in its own OS window. + pub native: Option<[f32; 4]>, +} + +impl

Floating

{ + pub fn single(panels: Vec

, active: usize, rect: [f32; 4]) -> Self { + Self { groups: vec![Group::new(panels, active)], rect, native: None } + } + + pub fn panels(&self) -> impl Iterator { + self.groups.iter().flat_map(|group| group.panels.iter()) + } + + pub fn contains(&self, panel: &P) -> bool + where + P: PartialEq, + { + self.groups.iter().any(|group| group.panels.contains(panel)) + } +} + +#[cfg(feature = "serde")] +mod floating_serde { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use super::{Floating, Group}; + + #[derive(Serialize)] + struct V1<'a, P> { + panels: &'a [P], + active: usize, + rect: [f32; 4], + } + + #[derive(Serialize)] + struct V2<'a, P> { + groups: &'a [Group

], + rect: [f32; 4], + #[serde(skip_serializing_if = "Option::is_none")] + native: Option<[f32; 4]>, + } + + impl Serialize for Floating

{ + fn serialize(&self, serializer: S) -> Result { + match self.groups.as_slice() { + [only] if !only.minimized && only.height.is_none() && self.native.is_none() => { + V1 { panels: &only.panels, active: only.active, rect: self.rect }.serialize(serializer) + } + groups => V2 { groups, rect: self.rect, native: self.native }.serialize(serializer), + } + } + } + + #[derive(Deserialize)] + #[serde(bound(deserialize = "P: Deserialize<'de>"))] + struct Repr

{ + groups: Option>>, + panels: Option>, + #[serde(default)] + active: usize, + rect: [f32; 4], + #[serde(default)] + native: Option<[f32; 4]>, + } + + impl<'de, P: Deserialize<'de>> Deserialize<'de> for Floating

{ + fn deserialize>(deserializer: D) -> Result { + let repr = Repr::

::deserialize(deserializer)?; + let groups = match (repr.groups, repr.panels) { + (Some(groups), None) => groups, + (None, Some(panels)) => vec![Group::new(panels, repr.active)], + (None, None) => return Err(serde::de::Error::missing_field("groups")), + (Some(_), Some(_)) => return Err(serde::de::Error::duplicate_field("panels")), + }; + Ok(Floating { groups, rect: repr.rect, native: repr.native }) + } + } } #[derive(Clone, Debug, PartialEq)] @@ -69,11 +158,17 @@ impl

Default for Layout

{ #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] pub enum Placement

{ /// Insert before this existing destination member, or append. Also reorders a group. Tab { before: Option

}, - /// Center inserts after the anchor; sides create a new half-size split. + /// Center inserts after the anchor; sides create a new half-size split. Sides apply to + /// `Tabs` and `Stack` nodes only. Split(Zone), + /// A new group above or below the anchor's group, in a dock column or a floating stack. + Group { below: bool }, + /// A new column before (towards the window edge) or after the anchor's column. + Column { after: bool }, } /// A closed panel's former placement. Applications may retain this beside visibility flags. @@ -92,10 +187,16 @@ pub struct Location

{ /// rather than accidentally inserting beside only its first leaf when restoring. #[cfg_attr(feature = "serde", serde(default))] pub sibling: Vec

, + /// Group and column state when the panel was in a dock or a floating stack. Applies when + /// restoring creates a new group, column or dock for the panel. + #[cfg_attr(feature = "serde", serde(default))] + pub group: Option, } +/// Groups, columns and floating windows are named by a panel they contain. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] pub enum Action

{ Move { panel: P, @@ -141,6 +242,62 @@ pub enum Action

{ panel: P, height: Option, }, + /// Move the group containing `panel` with its order, active tab and minimized state. + /// `Target::At` with `Tab` or `Split(Center)` merges every member. An accordion entry is a + /// group of one. A target inside the group is a no-op. + MoveGroup { + panel: P, + to: Target

, + }, + /// Move the dock column containing `panel`. `Float` makes a window of its groups. + MoveColumn { + panel: P, + to: Target

, + }, + /// Dock or merge the floating window containing `panel`, every group included. + MoveWindow { + panel: P, + to: Target

, + }, + /// Close Tab Group. + CloseGroup { + panel: P, + }, + /// × on a floating window: closes all its panels. + CloseWindow { + panel: P, + }, + /// Close Other Panels in Group. + CloseOthers { + panel: P, + }, + /// Minimize a dock or floating group to its tab strip. On an accordion entry, closes it. + SetMinimized { + panel: P, + minimized: bool, + }, + SetIconic { + panel: P, + iconic: bool, + }, + ResizeColumn { + panel: P, + width: f32, + }, + /// Preferred height of a dock or floating group, or of an accordion entry. + ResizeGroup { + panel: P, + height: Option, + }, + ResizeIconic { + panel: P, + width: Option, + }, + /// Put the floating window in its own OS window at `rect`, or back in the app window. + SetNative { + panel: P, + rect: Option<[f32; 4]>, + }, } /// Rendering and command adapters can protect a document canvas while leaving panels movable. @@ -160,9 +317,17 @@ impl Default for Permissions { impl Permissions { pub const PROTECTED: Self = Self { movable: false, floatable: false, closable: false, accepts_tabs: false }; + + /// Lock Workspace: nothing moves, floats or closes; tab drops keep their policy. + /// [`super::Workspace::apply`] applies this when the workspace is locked; an application + /// with a global lock preference applies it in its own permissions callback. + pub fn locked(self) -> Self { + Self { movable: false, floatable: false, closable: false, accepts_tabs: self.accepts_tabs } + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum DockError { LimitExceeded, DuplicatePanel, @@ -172,6 +337,8 @@ pub enum DockError { InvalidGeometry, InvalidPlacement, NotAllowed, + /// Saved by a newer version of the docking format. + UnsupportedVersion, } impl fmt::Display for DockError { @@ -185,6 +352,7 @@ impl fmt::Display for DockError { Self::InvalidGeometry => "docking geometry is not finite and bounded", Self::InvalidPlacement => "docking destination does not support this placement", Self::NotAllowed => "this panel does not allow the requested docking operation", + Self::UnsupportedVersion => "docking data was saved by a newer version", }) } } @@ -195,6 +363,10 @@ pub(super) fn valid_rect(rect: [f32; 4]) -> bool { rect.iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT) && rect.get(2).is_some_and(|v| *v > 0.0) && rect.get(3).is_some_and(|v| *v > 0.0) } +pub(super) fn valid_width(width: f32) -> bool { + width.is_finite() && width > 0.0 && width <= MAX_EXTENT +} + fn valid_size(size: SplitSize) -> bool { match size { SplitSize::Ratio(r) => r.is_finite() && (0.0..=1.0).contains(&r), @@ -219,19 +391,47 @@ impl Layout

{ } let mut seen = HashSet::new(); let mut count = 0usize; - let mut visit = self.root.as_ref().map(|n| vec![(n, 1usize)]).unwrap_or_default(); - while let Some((node, depth)) = visit.pop() { + let mut docks = (false, false); + // Each node carries whether it touches the window's start and end edges. + let mut visit = self.root.as_ref().map(|n| vec![(n, 1usize, true, true)]).unwrap_or_default(); + while let Some((node, depth, start, end)) = visit.pop() { count = count.saturating_add(1); if depth > MAX_DEPTH || count > MAX_NODES { return Err(DockError::LimitExceeded); } match node { - Node::Split { size, first, second, .. } => { + Node::Split { axis, size, first, second } => { if !valid_size(*size) { return Err(DockError::InvalidGeometry); } - visit.push((second, depth + 1)); - visit.push((first, depth + 1)); + let horizontal = *axis == SplitAxis::Horizontal; + visit.push((second, depth + 1, false, end && horizontal)); + visit.push((first, depth + 1, start && horizontal, false)); + } + Node::Dock { side, columns } => { + let (at_edge, taken) = match side { + Side::Start => (start, &mut docks.0), + Side::End => (end, &mut docks.1), + }; + if !at_edge || *taken { + return Err(DockError::InvalidPlacement); + } + *taken = true; + if columns.len() > MAX_PANELS { + return Err(DockError::LimitExceeded); + } + for column in columns { + if !valid_column(column) || column.groups.is_empty() { + return Err(DockError::InvalidGeometry); + } + count = count.saturating_add(column.groups.len().saturating_add(1)); + if count > MAX_NODES { + return Err(DockError::LimitExceeded); + } + for group in &column.groups { + check_group(group, &mut seen)?; + } + } } Node::Tabs { panels, active } => { check_tabs(panels, *active, &mut seen)?; @@ -250,10 +450,16 @@ impl Layout

{ } } for floating in &self.floating { - if !valid_rect(floating.rect) || floating.panels.is_empty() { + if !valid_rect(floating.rect) || floating.groups.is_empty() || floating.native.is_some_and(|r| !valid_rect(r)) { return Err(DockError::InvalidGeometry); } - check_tabs(&floating.panels, floating.active, &mut seen)?; + count = count.saturating_add(floating.groups.len()); + if count > MAX_NODES { + return Err(DockError::LimitExceeded); + } + for group in &floating.groups { + check_group(group, &mut seen)?; + } } Ok(()) } @@ -275,10 +481,14 @@ impl Layout

{ } Node::Tabs { panels: group, .. } => panels.extend(group.iter().take(MAX_PANELS - panels.len())), Node::Stack { entries } => panels.extend(entries.iter().map(|e| &e.panel).take(MAX_PANELS - panels.len())), + Node::Dock { columns, .. } => { + let members = columns.iter().flat_map(|c| c.groups.iter()).flat_map(|g| g.panels.iter()); + panels.extend(members.take(MAX_PANELS - panels.len())); + } } } - for group in self.floating.iter().take(MAX_PANELS) { - panels.extend(group.panels.iter().take(MAX_PANELS - panels.len())); + for window in self.floating.iter().take(MAX_PANELS) { + panels.extend(window.panels().take(MAX_PANELS - panels.len())); } panels } @@ -296,12 +506,69 @@ impl Layout

{ /// Capture a panel's nearest surviving group/split neighbor before hiding it. pub fn location(&self, panel: &P) -> Result, DockError> { self.validate()?; - if let Some(group) = self.floating.iter().find(|g| g.panels.contains(panel)) { - let mut location = group_location(&group.panels, panel).ok_or(DockError::MissingPanel)?; - location.floating = Some(group.rect); + let place = self.place(panel).ok_or(DockError::MissingPanel)?; + let (groups, group, floating, column) = match &place { + Place::Node(_) => return self.root.as_ref().and_then(|node| node_location(node, panel)).ok_or(DockError::MissingPanel), + Place::Floating { window, group } => { + let window = self.floating.get(*window).ok_or(DockError::MissingPanel)?; + (&window.groups, *group, Some(window.rect), None) + } + Place::Dock { path, group, .. } => { + let side = match self.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Dock { side, .. }) => *side, + _ => return Err(DockError::MissingPanel), + }; + let column = self.column(&place).ok_or(DockError::MissingPanel)?; + let state = ColumnLocation { side, width: column.width, iconic: column.iconic, iconic_width: column.iconic_width }; + (&column.groups, *group, None, Some(state)) + } + }; + let own = groups.get(group).ok_or(DockError::MissingPanel)?; + let mut location = group_location(&own.panels, panel).ok_or(DockError::MissingPanel)?; + location.floating = floating; + location.group = Some(GroupLocation { minimized: own.minimized, height: own.height, column }); + if location.anchor.is_some() { return Ok(location); } - self.root.as_ref().and_then(|node| node_location(node, panel)).ok_or(DockError::MissingPanel) + // Alone in its group: anchor to the neighbouring group, then the neighbouring column. + let first = |g: Option<&Group

>| g.and_then(|g| g.panels.first()).cloned(); + if let Some(anchor) = first(groups.get(group + 1)) { + location.anchor = Some(anchor); + location.placement = Placement::Group { below: false }; + } else if let Some(anchor) = first(group.checked_sub(1).and_then(|i| groups.get(i))) { + location.anchor = Some(anchor); + location.placement = Placement::Group { below: true }; + } else if groups.len() == 1 + && let Place::Dock { path, column, .. } = &place + && let Some(Node::Dock { columns, .. }) = self.root.as_ref().and_then(|root| node_at(root, path)) + { + let first_of = |c: Option<&Column

>| first(c.and_then(|c| c.groups.first())); + if let Some(anchor) = first_of(columns.get(column + 1)) { + location.anchor = Some(anchor); + location.placement = Placement::Column { after: false }; + } else if let Some(anchor) = first_of(column.checked_sub(1).and_then(|i| columns.get(i))) { + location.anchor = Some(anchor); + location.placement = Placement::Column { after: true }; + } + } + Ok(location) + } + + /// Hidden, open behind another tab or in a collapsed container, or showing. + pub fn panel_state(&self, panel: &P) -> PanelState { + let showing = match self.place(panel) { + None => return PanelState::Hidden, + Some(Place::Node(path)) => match self.root.as_ref().and_then(|root| node_at(root, &path)) { + Some(Node::Tabs { panels, active }) => panels.get(*active) == Some(panel), + Some(Node::Stack { entries }) => entries.iter().any(|e| &e.panel == panel && e.open), + _ => false, + }, + Some(place) => { + let iconic = self.column(&place).is_some_and(|c| c.iconic); + self.group(&place).is_some_and(|g| !g.minimized && g.active_panel() == Some(panel)) && !iconic + } + }; + if showing { PanelState::Front } else { PanelState::Open } } /// Restore an absent panel at a captured location. Missing anchors are reported without @@ -314,18 +581,57 @@ impl Layout

{ if location.size.is_some_and(|s| !valid_size(s)) || location.stack.is_some_and(|(_, h)| !valid_height(h)) { return Err(DockError::InvalidGeometry); } + let state = location.group.as_ref(); + if state.is_some_and(|s| { + !valid_height(s.height) || s.column.is_some_and(|c| !valid_width(c.width) || c.iconic_width.is_some_and(|w| !valid_width(w))) + }) { + return Err(DockError::InvalidGeometry); + } + // A restore that creates a group, column or dock gives it the saved state. + let moving = || { + let group = + Group { panels: vec![panel.clone()], active: 0, minimized: state.is_some_and(|s| s.minimized), height: state.and_then(|s| s.height) }; + let column = state.and_then(|s| s.column); + Moving { + width: column.map(|c| c.width), + iconic: column.is_some_and(|c| c.iconic), + iconic_width: column.and_then(|c| c.iconic_width), + ..Moving::group(group) + } + }; let mut proposed = self.clone(); if let Some(rect) = location.floating { if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } if let Some(anchor) = &location.anchor { - if !proposed.floating.iter().any(|g| g.panels.contains(anchor)) { + if !proposed.floating.iter().any(|g| g.contains(anchor)) { return Err(DockError::MissingTarget); } - proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor: anchor.clone(), placement: location.placement.clone() })?; + if let Placement::Group { .. } = location.placement { + proposed.insert_moving(moving(), Target::At { anchor: anchor.clone(), placement: location.placement.clone() })?; + } else { + proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor: anchor.clone(), placement: location.placement.clone() })?; + } } else { - proposed.floating.push(Floating { panels: vec![panel.clone()], active: 0, rect }); + proposed.insert_moving(moving(), Target::Float { rect: Some(rect) })?; + } + } else if let Some(anchor) = &location.anchor + && matches!(location.placement, Placement::Group { .. } | Placement::Column { .. }) + { + if !proposed.contains(anchor) { + return Err(DockError::MissingTarget); + } + proposed.insert_moving(moving(), Target::At { anchor: anchor.clone(), placement: location.placement.clone() })?; + } else if let Some(column) = state.and_then(|s| s.column).filter(|_| location.anchor.is_none()) { + // Alone in its dock: back at that edge, as the outermost column if a dock exists. + match proposed.dock_path(column.side) { + Some(path) => { + let columns = proposed.columns_mut(&path).ok_or(DockError::MissingTarget)?; + let Moving { groups, .. } = moving(); + columns.insert(0, Column { groups, width: column.width, iconic: column.iconic, iconic_width: column.iconic_width }); + } + None => proposed.insert_moving(moving(), Target::NewDock { side: column.side })?, } } else if let Some(anchor) = &location.anchor { if !proposed.contains(anchor) { @@ -397,6 +703,31 @@ impl Layout

{ Action::Close { panel } if !permissions(panel).closable => return Err(DockError::NotAllowed), Action::MoveFloating { panel, .. } if !permissions(panel).movable => return Err(DockError::NotAllowed), Action::Open { anchor: Some(anchor), .. } if !permissions(anchor).accepts_tabs => return Err(DockError::NotAllowed), + Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } | Action::MoveWindow { panel, to } => { + let members = self.members(panel, unit_of(&action))?; + if members.iter().any(|p| !permissions(p).movable) { + return Err(DockError::NotAllowed); + } + match to { + Target::Float { .. } if members.iter().any(|p| !permissions(p).floatable) => return Err(DockError::NotAllowed), + Target::At { anchor, placement: Placement::Tab { .. } | Placement::Split(Zone::Center) } + if !members.contains(anchor) && !permissions(anchor).accepts_tabs => + { + return Err(DockError::NotAllowed); + } + _ => {} + } + } + Action::CloseGroup { panel } | Action::CloseWindow { panel } | Action::CloseOthers { panel } => { + let others = matches!(action, Action::CloseOthers { .. }); + let members = self.members(panel, unit_of(&action))?; + if members.iter().filter(|p| !others || *p != panel).any(|p| !permissions(p).closable) { + return Err(DockError::NotAllowed); + } + } + Action::SetNative { panel, rect: Some(_) } if self.members(panel, Unit::Window)?.iter().any(|p| !permissions(p).floatable) => { + return Err(DockError::NotAllowed); + } _ => {} } let mut proposed = self.clone(); @@ -406,6 +737,28 @@ impl Layout

{ Ok(()) } + /// Apply every action in order, or none: the first rejection leaves the layout unchanged. + pub fn apply_all(&mut self, actions: impl IntoIterator>, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + let mut proposed = self.clone(); + for action in actions { + proposed.apply_with_permissions(action, &permissions)?; + } + *self = proposed; + Ok(()) + } + + /// The panels a close action (`Close`, `CloseGroup`, `CloseWindow`, `CloseOthers`) would + /// remove, in group order, so the application can release their state once the action is + /// applied. Empty for other actions. + pub fn closed_by(&self, action: &Action

) -> Result, DockError> { + Ok(match action { + Action::Close { panel } => vec![panel.clone()], + Action::CloseGroup { panel } | Action::CloseWindow { panel } => self.members(panel, unit_of(action))?, + Action::CloseOthers { panel } => self.members(panel, Unit::Group)?.into_iter().filter(|p| p != panel).collect(), + _ => Vec::new(), + }) + } + fn apply_inner(&mut self, action: Action

) -> Result<(), DockError> { match action { Action::Move { panel, anchor, placement } => { @@ -432,19 +785,20 @@ impl Layout

{ return Err(DockError::InvalidGeometry); } let entry = self.take(&panel).ok_or(DockError::MissingPanel)?; - self.floating.push(Floating { panels: vec![entry.panel], active: 0, rect }); + self.floating.push(Floating::single(vec![entry.panel], 0, rect)); Ok(()) } Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel), Action::Activate { panel } => { - if self.root.as_mut().is_some_and(|node| activate(node, &panel)) { + let place = self.place(&panel).ok_or(DockError::MissingPanel)?; + if let Some(group) = self.group_mut(&place) { + // Selecting a panel shows it: a minimized group expands. + group.active = group.panels.iter().position(|p| p == &panel).ok_or(DockError::MissingPanel)?; + group.minimized = false; return Ok(()); } - for group in &mut self.floating { - if let Some(i) = group.panels.iter().position(|p| p == &panel) { - group.active = i; - return Ok(()); - } + if self.root.as_mut().is_some_and(|node| activate(node, &panel)) { + return Ok(()); } Err(DockError::MissingPanel) } @@ -477,8 +831,8 @@ impl Layout

{ if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } - let group = self.floating.iter_mut().find(|g| g.panels.contains(&panel)).ok_or(DockError::MissingPanel)?; - group.rect = rect; + let window = self.floating.iter_mut().find(|g| g.contains(&panel)).ok_or(DockError::MissingPanel)?; + window.rect = rect; Ok(()) } Action::ResizeSplit { path, size } => { @@ -510,47 +864,115 @@ impl Layout

{ entry.height = height; Ok(()) } + Action::MoveGroup { ref panel, ref to } | Action::MoveColumn { ref panel, ref to } | Action::MoveWindow { ref panel, ref to } => { + let unit = unit_of(&action); + if let Target::At { anchor, .. } = to + && self.members(panel, unit)?.contains(anchor) + { + // Dropped on itself. + return Ok(()); + } + let moving = self.take_unit(panel, unit)?; + self.insert_moving(moving, to.clone()) + } + Action::CloseGroup { ref panel } | Action::CloseWindow { ref panel } => self.take_unit(panel, unit_of(&action)).map(|_| ()), + Action::CloseOthers { panel } => { + for other in self.members(&panel, Unit::Group)? { + if other != panel { + self.take(&other).ok_or(DockError::MissingPanel)?; + } + } + Ok(()) + } + Action::SetMinimized { panel, minimized } => { + let place = self.place(&panel).ok_or(DockError::MissingPanel)?; + if let Some(group) = self.group_mut(&place) { + group.minimized = minimized; + return Ok(()); + } + let entry = self.root.as_mut().and_then(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; + entry.open = !minimized; + Ok(()) + } + Action::ResizeGroup { panel, height } => { + if !valid_height(height) { + return Err(DockError::InvalidGeometry); + } + let place = self.place(&panel).ok_or(DockError::MissingPanel)?; + if let Some(group) = self.group_mut(&place) { + group.height = height; + return Ok(()); + } + let entry = self.root.as_mut().and_then(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; + entry.height = height; + Ok(()) + } + Action::SetIconic { panel, iconic } => { + self.column_of(&panel)?.iconic = iconic; + Ok(()) + } + Action::ResizeColumn { panel, width } => { + if !valid_width(width) { + return Err(DockError::InvalidGeometry); + } + self.column_of(&panel)?.width = width; + Ok(()) + } + Action::ResizeIconic { panel, width } => { + if width.is_some_and(|w| !valid_width(w)) { + return Err(DockError::InvalidGeometry); + } + self.column_of(&panel)?.iconic_width = width; + Ok(()) + } + Action::SetNative { panel, rect } => { + if rect.is_some_and(|r| !valid_rect(r)) { + return Err(DockError::InvalidGeometry); + } + let window = self.floating.iter_mut().find(|g| g.contains(&panel)).ok_or(DockError::InvalidPlacement)?; + window.native = rect; + Ok(()) + } } } + fn column_of(&mut self, panel: &P) -> Result<&mut Column

, DockError> { + let place = self.place(panel).ok_or(DockError::MissingPanel)?; + self.column_mut(&place).ok_or(DockError::InvalidPlacement) + } + fn same_group(&self, panel: &P, anchor: &P) -> bool { - fn in_node(node: &Node

, panel: &P, anchor: &P) -> bool { - match node { - Node::Tabs { panels, .. } => panels.contains(panel) && panels.contains(anchor), - Node::Stack { entries } => entries.iter().any(|e| &e.panel == panel) && entries.iter().any(|e| &e.panel == anchor), - Node::Split { first, second, .. } => in_node(first, panel, anchor) || in_node(second, panel, anchor), - } - } - self.root.as_ref().is_some_and(|n| in_node(n, panel, anchor)) - || self.floating.iter().any(|g| g.panels.contains(panel) && g.panels.contains(anchor)) + let place = self.place(panel); + place.is_some() && place == self.place(anchor) } - fn take(&mut self, panel: &P) -> Option> { + pub(super) fn take(&mut self, panel: &P) -> Option> { let mut removed = None; self.root = self.root.take().and_then(|n| remove_node(n, panel, &mut removed)); if removed.is_some() { return removed; } - for group in &mut self.floating { - if let Some(p) = remove_tab(&mut group.panels, &mut group.active, panel) { - removed = Some(StackEntry { panel: p, open: true, height: None }); + for window in &mut self.floating { + for group in &mut window.groups { + if let Some(p) = remove_tab(&mut group.panels, &mut group.active, panel) { + removed = Some(StackEntry { panel: p, open: true, height: None }); + break; + } + } + if removed.is_some() { + window.groups.retain(|g| !g.panels.is_empty()); break; } } - self.floating.retain(|g| !g.panels.is_empty()); + self.floating.retain(|g| !g.groups.is_empty()); removed } fn insert(&mut self, entry: StackEntry

, anchor: &P, placement: Placement

) -> Result<(), DockError> { - if let Some(group) = self.floating.iter_mut().find(|g| g.panels.contains(anchor)) { - let index = match placement { - Placement::Tab { before } => before.as_ref().and_then(|p| group.panels.iter().position(|q| q == p)).unwrap_or(group.panels.len()), - Placement::Split(Zone::Center) => group.panels.iter().position(|p| p == anchor).map_or(group.panels.len(), |i| i + 1), - Placement::Split(_) => return Err(DockError::InvalidPlacement), - }; - group.panels.insert(index, entry.panel); - group.active = index; - return Ok(()); + let place = self.place(anchor).ok_or(DockError::MissingTarget)?; + if matches!(place, Place::Dock { .. } | Place::Floating { .. }) || matches!(placement, Placement::Group { .. } | Placement::Column { .. }) { + let group = Group::new(vec![entry.panel], 0); + return self.insert_moving(Moving::group(group), Target::At { anchor: anchor.clone(), placement }); } if let Some(root) = self.root.as_mut() && insert_node(root, &entry, anchor, &placement) @@ -561,6 +983,14 @@ impl Layout

{ } } +fn unit_of

(action: &Action

) -> Unit { + match action { + Action::MoveColumn { .. } => Unit::Column, + Action::MoveWindow { .. } | Action::CloseWindow { .. } => Unit::Window, + _ => Unit::Group, + } +} + fn check_panel<'a, P: Eq + Hash>(panel: &'a P, seen: &mut HashSet<&'a P>) -> Result<(), DockError> { if seen.len() >= MAX_PANELS { return Err(DockError::LimitExceeded); @@ -571,6 +1001,13 @@ fn check_panel<'a, P: Eq + Hash>(panel: &'a P, seen: &mut HashSet<&'a P>) -> Res Ok(()) } +fn check_group<'a, P: Eq + Hash>(group: &'a Group

, seen: &mut HashSet<&'a P>) -> Result<(), DockError> { + if group.panels.is_empty() || !valid_height(group.height) { + return Err(DockError::InvalidGeometry); + } + check_tabs(&group.panels, group.active, seen) +} + fn check_tabs<'a, P: Eq + Hash>(panels: &'a [P], active: usize, seen: &mut HashSet<&'a P>) -> Result<(), DockError> { if panels.len() > MAX_PANELS { return Err(DockError::LimitExceeded); @@ -614,6 +1051,20 @@ fn remove_node(node: Node

, panel: &P, removed: &mut Option node, } } + Node::Dock { side, mut columns } => { + // A dock that was already empty stays; one emptied by this removal collapses. + let had_columns = !columns.is_empty(); + for column in &mut columns { + for group in &mut column.groups { + if let Some(panel) = remove_tab(&mut group.panels, &mut group.active, panel) { + *removed = Some(StackEntry { panel, open: true, height: None }); + } + } + column.groups.retain(|g| !g.panels.is_empty()); + } + columns.retain(|c| !c.groups.is_empty()); + (!had_columns || !columns.is_empty()).then_some(Node::Dock { side, columns }) + } } } @@ -636,6 +1087,7 @@ fn activate(node: &mut Node

, panel: &P) -> bool { } } Node::Split { first, second, .. } => activate(first, panel) || activate(second, panel), + Node::Dock { .. } => false, } } @@ -643,7 +1095,7 @@ fn stack_entry_mut<'a, P: Eq>(node: &'a mut Node

, panel: &P) -> Option<&'a mu match node { Node::Stack { entries } => entries.iter_mut().find(|e| &e.panel == panel), Node::Split { first, second, .. } => stack_entry_mut(first, panel).or_else(|| stack_entry_mut(second, panel)), - Node::Tabs { .. } => None, + Node::Tabs { .. } | Node::Dock { .. } => None, } } @@ -652,6 +1104,7 @@ fn insert_node(node: &mut Node

, entry: &StackEntry

, anchor: Node::Split { first, second, .. } => return insert_node(first, entry, anchor, placement) || insert_node(second, entry, anchor, placement), Node::Tabs { panels, .. } => panels.contains(anchor), Node::Stack { entries } => entries.iter().any(|e| &e.panel == anchor), + Node::Dock { .. } => false, }; if !here { return false; @@ -668,7 +1121,7 @@ fn insert_node(node: &mut Node

, entry: &StackEntry

, anchor: Node::Tabs { panels, active } => { let index = match placement { Placement::Tab { before } => before.as_ref().and_then(|p| panels.iter().position(|q| q == p)).unwrap_or(panels.len()), - Placement::Split(_) => panels.iter().position(|p| p == anchor).map_or(panels.len(), |i| i + 1), + _ => panels.iter().position(|p| p == anchor).map_or(panels.len(), |i| i + 1), }; panels.insert(index, entry.panel.clone()); *active = index; @@ -676,11 +1129,11 @@ fn insert_node(node: &mut Node

, entry: &StackEntry

, anchor: Node::Stack { entries } => { let index = match placement { Placement::Tab { before } => before.as_ref().and_then(|p| entries.iter().position(|e| &e.panel == p)).unwrap_or(entries.len()), - Placement::Split(_) => entries.iter().position(|e| &e.panel == anchor).map_or(entries.len(), |i| i + 1), + _ => entries.iter().position(|e| &e.panel == anchor).map_or(entries.len(), |i| i + 1), }; entries.insert(index, entry.clone()); } - Node::Split { .. } => return false, + Node::Split { .. } | Node::Dock { .. } => return false, } true } @@ -689,7 +1142,7 @@ fn group_location(panels: &[P], panel: &P) -> Option> let index = panels.iter().position(|p| p == panel)?; let anchor = panels.iter().find(|p| *p != panel).cloned(); let before = panels.get(index + 1).cloned(); - Some(Location { floating: None, anchor, placement: Placement::Tab { before }, size: None, stack: None, sibling: Vec::new() }) + Some(Location { floating: None, anchor, placement: Placement::Tab { before }, size: None, stack: None, sibling: Vec::new(), group: None }) } fn first_panel

(node: &Node

) -> Option<&P> { @@ -697,6 +1150,7 @@ fn first_panel

(node: &Node

) -> Option<&P> { Node::Tabs { panels, .. } => panels.first(), Node::Stack { entries } => entries.first().map(|e| &e.panel), Node::Split { first, second, .. } => first_panel(first).or_else(|| first_panel(second)), + Node::Dock { columns, .. } => columns.iter().flat_map(|c| c.groups.iter()).find_map(|g| g.panels.first()), } } @@ -733,6 +1187,7 @@ fn node_location(node: &Node

, panel: &P) -> Option } Some(location) } + Node::Dock { .. } => None, } } @@ -773,6 +1228,7 @@ fn node_members<'a, P>(node: &'a Node

, members: &mut Vec<&'a P>) { node_members(first, members); node_members(second, members); } + Node::Dock { columns, .. } => members.extend(columns.iter().flat_map(|c| c.groups.iter()).flat_map(|g| g.panels.iter())), } } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 53b8137285..545bc43285 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -208,7 +208,9 @@ impl DockArea

{ || matches(self.id.with(("move-group", panels.first()))) }; for floating in &layout.floating { - if group(&floating.panels) || floating.panels.first().is_some_and(|first| matches(self.id.with(("floating", first)).with("resize"))) { + if floating.groups.iter().any(|g| group(&g.panels)) + || floating.panels().next().is_some_and(|first| matches(self.id.with(("floating", first)).with("resize"))) + { return true; } } @@ -216,6 +218,7 @@ impl DockArea

{ while let Some((node, path)) = nodes.pop() { match node { Node::Tabs { panels, .. } if group(panels) => return true, + Node::Dock { columns, .. } if columns.iter().flat_map(|c| c.groups.iter()).any(|g| group(&g.panels)) => return true, Node::Stack { entries } => { if entries.iter().any(|entry| { matches(self.id.with(("tab", &entry.panel))) @@ -401,6 +404,17 @@ impl Renderer<'_, P> { } } Node::Tabs { panels, active } => self.group(ui, panels, *active, rect, false), + Node::Dock { columns, .. } => { + // Interim rendering: columns side by side, groups stacked evenly. + let total: f32 = columns.iter().map(|c| c.width).sum(); + let mut left = rect.left(); + for column in columns { + let width = if total > 0.0 { rect.width() * column.width / total } else { 0.0 }; + let column_rect = Rect::from_min_max(pos2(left, rect.top()), pos2(left + width, rect.bottom())); + left += width; + self.stacked_groups(ui, &column.groups, column_rect, false); + } + } Node::Stack { entries } => { let total_header = (entries.len() as f32 * self.style.tab_height).min(rect.height()); let remaining = (rect.height() - total_header).max(0.0); @@ -487,8 +501,19 @@ impl Renderer<'_, P> { } } + /// Groups stacked top to bottom in equal shares of `rect`. + fn stacked_groups(&mut self, ui: &mut Ui, groups: &[super::Group

], rect: Rect, floating: bool) { + let share = rect.height() / groups.len().max(1) as f32; + for (index, group) in groups.iter().enumerate() { + let top = rect.top() + share * index as f32; + let group_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + share)); + self.group(ui, &group.panels, group.active, group_rect, floating); + } + } + fn node_limits(&self, node: &Node

) -> PanelLimits { match node { + Node::Dock { .. } => PanelLimits { min: Vec2::splat(self.style.min_pane), ..PanelLimits::default() }, Node::Tabs { panels, .. } => { let mut limits = PanelLimits::default(); for panel in panels { @@ -750,17 +775,17 @@ impl Renderer<'_, P> { let layers = ctx.memory(|memory| memory.layer_ids().collect::>()); let mut groups: Vec<_> = self.layout.floating.iter().collect(); groups.sort_by_key(|group| { - let id = group.panels.first().map(|panel| self.id.with(("floating", panel))); + let id = group.panels().next().map(|panel| self.id.with(("floating", panel))); layers.iter().position(|layer| Some(layer.id) == id).unwrap_or(usize::MAX) }); for group in groups { - let Some(first) = group.panels.first() else { continue }; + let Some(first) = group.panels().next() else { continue }; let [x, y, width, height] = group.rect; - let limits = self.node_limits(&Node::Tabs { panels: group.panels.clone(), active: group.active }); + let limits = self.node_limits(&Node::Tabs { panels: group.panels().cloned().collect(), active: 0 }); let size = vec2(width, height).max(limits.min).min(limits.max); let rect = clamp_float(Rect::from_min_size(pos2(x, y), size), screen); let id = self.id.with(("floating", first)); - if self.activation.as_ref().is_some_and(|panel| group.panels.contains(panel)) { + if self.activation.as_ref().is_some_and(|panel| group.contains(panel)) { ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); self.output.focused = self.activation.clone(); @@ -769,7 +794,7 @@ impl Renderer<'_, P> { ui.set_min_size(rect.size()); let rect = Rect::from_min_size(ui.min_rect().min, rect.size()); ui.allocate_rect(rect, Sense::hover()); - self.group(ui, &group.panels, group.active, rect, true); + self.stacked_groups(ui, &group.groups, rect, true); let corner = Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max); let response = ui.interact(corner, id.with("resize"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeNwSe); self.register_interaction(ui.ctx(), response.id); @@ -813,7 +838,7 @@ impl Renderer<'_, P> { fn finish_group_drag(&mut self, ctx: &Context) { let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("group-drag"))) else { return }; - if !self.layout.floating.iter().any(|g| g.panels.contains(&drag.panel) && g.panels.iter().all(|p| (self.permissions)(p).movable)) { + if !self.layout.floating.iter().any(|g| g.contains(&drag.panel) && g.panels().all(|p| (self.permissions)(p).movable)) { ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); return; } @@ -873,7 +898,7 @@ impl Renderer<'_, P> { let action = if let Some(proposal) = proposal.filter(|_| !gone) { Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) } else if (self.permissions)(&drag.panel).floatable - && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.panels.contains(&drag.panel))) + && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))) { let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }) diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 941220dbdb..6840132465 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -14,7 +14,7 @@ fn sample() -> Layout { first: Box::new(tabs(&[1], 0)), second: Box::new(tabs(&[2, 3, 4], 1)), }), - floating: vec![Floating { panels: vec![5, 6], active: 1, rect: [80.0, 70.0, 300.0, 220.0] }], + floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])], } } @@ -29,8 +29,8 @@ fn floating_brush_panel_joins_main_tabs_without_losing_other_panels() { let Node::Split { size, second, .. } = layout.root.as_ref().unwrap() else { panic!() }; assert_eq!(*size, SplitSize::FixedSecond(240.0)); assert_eq!(**second, tabs(&[2, 3, 5, 4], 2)); - assert_eq!(layout.floating[0].panels, vec![6]); - assert_eq!(layout.floating[0].active, 0); + assert_eq!(layout.floating[0].groups[0].panels, vec![6]); + assert_eq!(layout.floating[0].groups[0].active, 0); layout.validate().unwrap(); assert_eq!(layout.panels().len(), 6); } @@ -43,8 +43,8 @@ fn detach_redock_merge_and_collapse_empty_source_containers() { layout.apply(move_to(1, 2, Zone::Left)).unwrap(); assert_eq!(layout.floating.len(), 1); layout.apply(move_to(5, 6, Zone::Center)).unwrap(); - assert_eq!(layout.floating[0].panels, vec![6, 5]); - assert_eq!(layout.floating[0].active, 1); + assert_eq!(layout.floating[0].groups[0].panels, vec![6, 5]); + assert_eq!(layout.floating[0].groups[0].active, 1); layout.apply(move_to(6, 3, Zone::Center)).unwrap(); layout.apply(move_to(5, 3, Zone::Center)).unwrap(); assert!(layout.floating.is_empty()); @@ -154,7 +154,7 @@ fn close_and_restore_preserve_fixed_side_and_floating_geometry() { first: Box::new(tabs(&[1], 0)), second: Box::new(tabs(&[2], 0)), }), - floating: vec![Floating { panels: vec![3], active: 0, rect: [41.0, 52.0, 233.0, 244.0] }], + floating: vec![Floating::single(vec![3], 0, [41.0, 52.0, 233.0, 244.0])], }; let saved = layout.clone(); let first = layout.location(&1).unwrap(); @@ -197,12 +197,12 @@ fn closing_and_reopening_an_entire_accordion_restores_its_kind_and_heights() { #[test] fn invalid_saved_layouts_reject_duplicates_selection_depth_and_nonfinite_geometry() { let mut duplicate = sample(); - duplicate.floating[0].panels.push(1); + duplicate.floating[0].groups[0].panels.push(1); assert_eq!(duplicate.validate(), Err(DockError::DuplicatePanel)); let mut invalid = sample(); - invalid.floating[0].active = usize::MAX; + invalid.floating[0].groups[0].active = usize::MAX; assert_eq!(invalid.validate(), Err(DockError::InvalidSelection)); - invalid.floating[0].active = 0; + invalid.floating[0].groups[0].active = 0; invalid.floating[0].rect[3] = f32::INFINITY; assert_eq!(invalid.validate(), Err(DockError::InvalidGeometry)); let mut deep = tabs(&[0], 0); @@ -404,7 +404,7 @@ fn actual_pointer_drag_docks_a_floating_panel_into_the_main_tab_strip() { step(&ctx, &mut layout, vec![Event::PointerMoved(target)]); let actions = step(&ctx, &mut layout, vec![pointer_button(target, false)]); assert!(actions.iter().any(|a| matches!(a, Action::Move { panel: 5, .. })), "{actions:?}"); - assert!(!layout.floating.iter().any(|g| g.panels.contains(&5))); + assert!(!layout.floating.iter().any(|g| g.contains(&5))); assert_eq!(layout.panels().len(), 6); let Node::Split { second, .. } = layout.root.as_ref().unwrap() else { panic!() }; let Node::Tabs { panels, active } = second.as_ref() else { panic!() }; @@ -429,7 +429,7 @@ fn tab_dragged_out_of_the_window_floats_where_it_left() { step(&ctx, &mut layout, vec![Event::PointerMoved(exit)]); let actions = step(&ctx, &mut layout, vec![Event::PointerGone]); assert!(actions.iter().any(|a| matches!(a, Action::Float { panel: 3, .. })), "{actions:?}"); - assert!(layout.floating.iter().any(|g| g.panels == [3]), "{layout:?}"); + assert!(layout.floating.iter().any(|g| g.panels().eq([3].iter())), "{layout:?}"); let back = pos2(400.0, 300.0); assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(back)]).is_empty()); assert!(step(&ctx, &mut layout, vec![pointer_button(back, false)]).is_empty(), "the drag ended when the pointer left"); @@ -634,7 +634,7 @@ fn restoring_a_panel_beside_a_nested_subtree_preserves_the_complete_workspace() #[test] fn floating_only_surface_does_not_allocate_the_callers_document_region() { let ctx = Context::default(); - let layout = Layout { root: None, floating: vec![Floating { panels: vec![1u32], active: 0, rect: [30.0, 40.0, 200.0, 200.0] }] }; + let layout = Layout { root: None, floating: vec![Floating::single(vec![1u32], 0, [30.0, 40.0, 200.0, 200.0])] }; ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, |ui| { let before = ui.available_rect_before_wrap(); let out = DockArea::new(Id::new("float-only")).show( @@ -666,8 +666,8 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() { step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); let actions = step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(50.0, 40.0))]); assert!(actions.iter().any(|a| matches!(a, Action::MoveFloating { .. }))); - assert_eq!(layout.floating[0].panels, original.panels); - assert_eq!(layout.floating[0].active, original.active); + assert_eq!(layout.floating[0].groups[0].panels, original.groups[0].panels); + assert_eq!(layout.floating[0].groups[0].active, original.groups[0].active); assert_ne!(layout.floating[0].rect, original.rect); step(&ctx, &mut layout, vec![pointer_button(start + vec2(50.0, 40.0), false)]); for _ in 0..2 { @@ -680,7 +680,7 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() { let detached = step(&ctx, &mut layout, vec![pointer_button(tab + vec2(100.0, 100.0), false)]); assert!(detached.iter().any(|a| matches!(a, Action::Float { panel: 5, .. }))); assert_eq!(layout.floating.len(), 2); - assert_eq!(layout.floating[0].panels, vec![6]); + assert_eq!(layout.floating[0].groups[0].panels, vec![6]); } #[test] @@ -1026,7 +1026,7 @@ fn chrome_focus_classifies_rendered_tab_but_excludes_body_text_field_and_invalid assert!(!DockArea::new(Id::new("focus-area")).chrome_has_focus(&ctx, &layout)); paint(tab); let mut invalid = layout.clone(); - invalid.floating.push(Floating { panels: vec![3], active: 0, rect: [10.0, 10.0, 100.0, 100.0] }); + invalid.floating.push(Floating::single(vec![3], 0, [10.0, 10.0, 100.0, 100.0])); assert!(!DockArea::new(Id::new("focus-area")).chrome_has_focus(&ctx, &invalid)); assert!(!DockArea::::new(Id::new("focus-area")).chrome_has_focus(&ctx, &Layout::default())); ctx.memory_mut(|memory| memory.request_focus(Id::new("unrendered"))); diff --git a/crates/ui/tests/docking_workflows.rs b/crates/ui/tests/docking_workflows.rs index 996c29e2ff..29a6c9d910 100644 --- a/crates/ui/tests/docking_workflows.rs +++ b/crates/ui/tests/docking_workflows.rs @@ -55,7 +55,7 @@ impl Harness { first: Box::new(Node::Tabs { panels: vec![CANVAS], active: 0 }), second: Box::new(Node::Tabs { panels: vec![LAYERS, PROPERTIES], active: 0 }), }), - floating: vec![Floating { panels: vec![BRUSHES], active: 0, rect: [38.0, 76.0, 210.0, 250.0] }], + floating: vec![Floating::single(vec![BRUSHES], 0, [38.0, 76.0, 210.0, 250.0])], }; let mut harness = Self { ctx, @@ -235,7 +235,7 @@ fn floating_brushes_merge_detach_and_redock_through_real_pointer_input() { assert_eq!(h.body_ids[&BRUSHES], brush_id); h.capture(&directory, "02-merged-main-tabs"); h.drag(h.tab(BRUSHES).center(), pos2((width - 240.0) * 0.5, 270.0)); - assert!(h.layout.floating.iter().any(|g| g.panels.contains(&BRUSHES)), "{name}: {:?}", h.applied); + assert!(h.layout.floating.iter().any(|g| g.contains(&BRUSHES)), "{name}: {:?}", h.applied); h.capture(&directory, "03-detached-again"); h.drag(h.tab(BRUSHES).center(), h.tab(LAYERS).left_center() + vec2(4.0, 0.0)); assert!(h.layout.floating.is_empty(), "{name}"); From 0ea5f8200ca1bf8a1327e129debf9f73c3436f52 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:35:13 +0000 Subject: [PATCH 06/94] docking: Workspace with hidden locations, lock, reconcile and reset Workspace

keeps the current layout, where hidden panels go back, the user's saved arrangement and Lock Workspace. It reads the {layout, hidden} files lightcraft, pdfcraft, cadcraft and soundcraft write today. Close actions record a location per closed panel; set_visible follows hidden anchors when a panel's own anchor is hidden too. reconcile moves panels the app does not register now to hidden and places missing registered panels at their default place; reset returns to the saved or default arrangement. --- crates/ui/src/docking/mod.rs | 2 + crates/ui/src/docking/workspace.rs | 243 +++++++++++++++++++++++++++++ 2 files changed, 245 insertions(+) create mode 100644 crates/ui/src/docking/workspace.rs diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index d29be7a4bd..841e2f31bf 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -9,11 +9,13 @@ mod dock_model; mod model; mod surface; mod targets; +mod workspace; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; pub use surface::{DockArea, DockContent, DockOutput, DockStyle, PanelLimits, begin_drag, cancel_drag}; pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect}; +pub use workspace::Workspace; #[cfg(test)] mod tests; diff --git a/crates/ui/src/docking/workspace.rs b/crates/ui/src/docking/workspace.rs new file mode 100644 index 0000000000..90fe8d6e05 --- /dev/null +++ b/crates/ui/src/docking/workspace.rs @@ -0,0 +1,243 @@ +//! A saved arrangement: the current layout, where hidden panels go back, the user's saved +//! arrangement for Reset, and Lock Workspace. +//! +//! Storage, file names and size caps stay with the application. A file that does not parse or +//! validate, or comes from a newer version, should be kept on disk and not overwritten. + +use std::{collections::HashSet, hash::Hash}; + +use super::model::{Action, DockError, Layout, Location, MAX_PANELS, Permissions}; + +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(default, bound(deserialize = "P: serde::Deserialize<'de>")))] +pub struct Workspace

{ + /// Format version; files without one are v1 (`{layout, hidden}`). Always written as + /// [`Workspace::VERSION`]. + #[cfg_attr(feature = "serde", serde(default = "first_version", serialize_with = "write_version"))] + pub version: u32, + /// The current arrangement, changes included. + pub layout: Layout

, + /// Closed panels, and panels the application does not register now, with where each one + /// goes back. + pub hidden: Vec<(P, Location

)>, + /// A user workspace's saved arrangement; Reset returns to it. Built-in workspaces use the + /// application's default instead. + pub saved: Option>, + /// Lock Workspace, saved with this workspace: [`Self::apply`] uses + /// [`Permissions::locked`], so moving, floating and closing are rejected while activating, + /// opening, minimizing and resizing still work. An application with a global lock + /// preference instead passes locked permissions itself. + pub locked: bool, +} + +#[cfg(feature = "serde")] +fn first_version() -> u32 { + 1 +} + +#[cfg(feature = "serde")] +fn write_version(_: &u32, serializer: S) -> Result { + serializer.serialize_u32(Workspace::<()>::VERSION) +} + +impl

Default for Workspace

{ + fn default() -> Self { + Self::new(Layout::default()) + } +} + +impl

Workspace

{ + pub const VERSION: u32 = 2; + + pub fn new(layout: Layout

) -> Self { + Self { version: Self::VERSION, layout, hidden: Vec::new(), saved: None, locked: false } + } +} + +impl Workspace

{ + /// Check the version, both layouts and that every hidden panel is hidden once and absent + /// from the current layout. + pub fn validate(&self) -> Result<(), DockError> { + if self.version > Self::VERSION { + return Err(DockError::UnsupportedVersion); + } + self.layout.validate()?; + if let Some(saved) = &self.saved { + saved.validate()?; + } + if self.hidden.len() > MAX_PANELS { + return Err(DockError::LimitExceeded); + } + let visible: HashSet<&P> = self.layout.panels().into_iter().collect(); + let mut seen = HashSet::new(); + for (panel, _) in &self.hidden { + if visible.contains(panel) || !seen.insert(panel) { + return Err(DockError::DuplicatePanel); + } + } + Ok(()) + } + + /// Apply one action. Closed panels record where they go back, so each one can be reopened + /// with [`Self::set_visible`]. Honours [`Self::locked`]. [`Layout::closed_by`], called + /// before applying, names the panels a close action removes. + pub fn apply(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + self.apply_all([action], permissions) + } + + /// Apply every action in order, or none. + pub fn apply_all(&mut self, actions: impl IntoIterator>, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + self.validate()?; + let locked = self.locked; + let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) }; + let mut proposed = self.clone(); + for action in actions { + let closed = proposed.layout.closed_by(&action)?; + let locations = close_locations(&proposed.layout, &closed); + proposed.layout.apply_with_permissions(action, policy)?; + for (panel, location) in locations { + proposed.hidden.retain(|(p, _)| p != &panel); + proposed.hidden.push((panel, location)); + } + } + let visible: HashSet

= proposed.layout.panels().into_iter().cloned().collect(); + proposed.hidden.retain(|(p, _)| !visible.contains(p)); + proposed.validate()?; + *self = proposed; + Ok(()) + } + + /// Show or hide one panel. Showing restores its recorded location, following the chain of + /// hidden anchors when its own anchor is hidden too; otherwise it opens beside `fallback`. + /// A shown panel becomes the active tab of its group. + pub fn set_visible(&mut self, panel: P, visible: bool, fallback: Option

) -> Result<(), DockError> { + self.validate()?; + if !visible { + if !self.layout.contains(&panel) { + return Ok(()); + } + return self.apply(Action::Close { panel }, |_| Permissions::default()); + } + if self.layout.contains(&panel) { + return self.apply(Action::Activate { panel }, |_| Permissions::default()); + } + let mut layout = self.layout.clone(); + if self.restore_into(&mut layout, &panel).is_err() { + layout = self.layout.clone(); + layout.apply(Action::Open { panel: panel.clone(), anchor: fallback })?; + } + layout.apply(Action::Activate { panel: panel.clone() })?; + self.layout = layout; + self.hidden.retain(|(p, _)| p != &panel); + Ok(()) + } + + fn restore_into(&self, layout: &mut Layout

, panel: &P) -> Result<(), DockError> { + let find = |p: &P| self.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location); + let mut location = find(panel).ok_or(DockError::MissingTarget)?; + for _ in 0..=self.hidden.len() { + match layout.restore(panel.clone(), location) { + Err(DockError::MissingTarget) => { + let next = location.anchor.as_ref().filter(|anchor| *anchor != panel).and_then(find); + location = next.ok_or(DockError::MissingTarget)?; + } + result => return result, + } + } + Err(DockError::MissingTarget) + } + + /// Fit a loaded workspace to the panels the application registers now. An invalid + /// workspace is replaced by `default`. Panels not registered now (plug-ins, on-demand or + /// numbered panels) move to `hidden` with their location, so they come back once registered; + /// the saved arrangement drops them. Registered panels in `default` that are neither shown + /// nor hidden go to their default place, or to `hidden` when that place cannot be rebuilt. + /// `hidden` keeps at most [`MAX_PANELS`] entries, dropping the oldest unregistered ones first. + pub fn reconcile(&mut self, registered: impl Fn(&P) -> bool, default: &Workspace

) { + if self.validate().is_err() { + *self = Workspace { locked: self.locked, ..default.clone() }; + } + let unknown: Vec

= self.layout.panels().into_iter().filter(|p| !registered(p)).cloned().collect(); + let locations = close_locations(&self.layout, &unknown); + for panel in &unknown { + self.layout.take(panel); + } + self.hidden.extend(locations); + if let Some(saved) = self.saved.as_mut() { + let unknown: Vec

= saved.panels().into_iter().filter(|p| !registered(p)).cloned().collect(); + for panel in unknown { + saved.take(&panel); + } + if saved.validate().is_err() { + self.saved = None; + } + } + let known: HashSet

= self.layout.panels().into_iter().chain(self.hidden.iter().map(|(p, _)| p)).cloned().collect(); + let mut missing: Vec<(P, Location

)> = Vec::new(); + for panel in default.layout.panels() { + if registered(panel) + && !known.contains(panel) + && let Ok(location) = default.layout.location(panel) + { + missing.push((panel.clone(), location)); + } + } + // Anchors may themselves be missing: place what fits, then retry the rest. + while !missing.is_empty() { + let before = missing.len(); + missing.retain(|(panel, location)| self.layout.restore(panel.clone(), location).is_err()); + if missing.len() == before { + break; + } + } + self.hidden.extend(missing); + for (panel, location) in &default.hidden { + if registered(panel) && !known.contains(panel) && !self.layout.contains(panel) && !self.hidden.iter().any(|(p, _)| p == panel) { + self.hidden.push((panel.clone(), location.clone())); + } + } + let mut excess = self.hidden.len().saturating_sub(MAX_PANELS); + self.hidden.retain(|(p, _)| { + let drop = excess > 0 && !registered(p); + excess -= usize::from(drop); + !drop + }); + self.hidden.truncate(MAX_PANELS); + } + + /// Reset: return to the saved arrangement, or `default` when there is none. Panels the + /// reset layout does not show stay hidden with their last location. + pub fn reset(&mut self, default: &Layout

) { + let layout = self.saved.clone().unwrap_or_else(|| default.clone()); + let shown: HashSet

= layout.panels().into_iter().cloned().collect(); + for panel in self.layout.panels() { + if !shown.contains(panel) + && !self.hidden.iter().any(|(p, _)| p == panel) + && let Ok(location) = self.layout.location(panel) + { + self.hidden.push((panel.clone(), location)); + } + } + self.hidden.retain(|(p, _)| !shown.contains(p)); + self.layout = layout; + } +} + +/// Where each of `closed` goes back, captured as if they closed last to first. Reopening them +/// first to last rebuilds the group: the first restores the group itself, the rest join it. +fn close_locations(layout: &Layout

, closed: &[P]) -> Vec<(P, Location

)> { + if let [panel] = closed { + return layout.location(panel).map(|location| vec![(panel.clone(), location)]).unwrap_or_default(); + } + let mut scratch = layout.clone(); + let mut locations = Vec::new(); + for panel in closed.iter().rev() { + if let Ok(location) = scratch.location(panel) { + locations.push((panel.clone(), location)); + } + scratch.take(panel); + } + locations.reverse(); + locations +} From 69a1adf699238f36379bc35d24809907c0183d22 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:35:13 +0000 Subject: [PATCH 07/94] docking: model, workspace and v1 fixture tests Group, column and window moves, close and restore round trips, dock validation, Lock Workspace, reconcile and reset, the random action sequence over dock layouts, and one v1 fixture per app shape that must parse and write back unchanged. --- crates/ui/src/docking/mod.rs | 2 + crates/ui/src/docking/model_tests.rs | 472 +++++++++++++++++++ crates/ui/src/docking/tests.rs | 79 ++-- crates/ui/tests/fixtures/v1/cadcraft.json | 91 ++++ crates/ui/tests/fixtures/v1/designcraft.json | 123 +++++ crates/ui/tests/fixtures/v1/lightcraft.json | 67 +++ crates/ui/tests/fixtures/v1/pdfcraft.json | 51 ++ crates/ui/tests/fixtures/v1/photocraft.json | 151 ++++++ crates/ui/tests/fixtures/v1/soundcraft.json | 180 +++++++ crates/ui/tests/fixtures/v1/vectorcraft.json | 91 ++++ 10 files changed, 1279 insertions(+), 28 deletions(-) create mode 100644 crates/ui/src/docking/model_tests.rs create mode 100644 crates/ui/tests/fixtures/v1/cadcraft.json create mode 100644 crates/ui/tests/fixtures/v1/designcraft.json create mode 100644 crates/ui/tests/fixtures/v1/lightcraft.json create mode 100644 crates/ui/tests/fixtures/v1/pdfcraft.json create mode 100644 crates/ui/tests/fixtures/v1/photocraft.json create mode 100644 crates/ui/tests/fixtures/v1/soundcraft.json create mode 100644 crates/ui/tests/fixtures/v1/vectorcraft.json diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 841e2f31bf..304e46d2f5 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -17,5 +17,7 @@ pub use surface::{DockArea, DockContent, DockOutput, DockStyle, PanelLimits, beg pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect}; pub use workspace::Workspace; +#[cfg(test)] +mod model_tests; #[cfg(test)] mod tests; diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs new file mode 100644 index 0000000000..bbd9ae0570 --- /dev/null +++ b/crates/ui/src/docking/model_tests.rs @@ -0,0 +1,472 @@ +use super::dock_model::{Place, node_at}; +use super::*; +use crate::layout::{SplitAxis, SplitSize}; + +pub(super) fn g(panels: &[u32], active: usize) -> Group { + Group::new(panels.to_vec(), active) +} + +fn tabs(panels: &[u32], active: usize) -> Node { + Node::Tabs { panels: panels.to_vec(), active } +} + +fn hsplit(size: SplitSize, first: Node, second: Node) -> Node { + Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(first), second: Box::new(second) } +} + +/// Canvas 1 above frame tabs [11, 12]; an end dock with column A ([2, 3], [4]) and column B +/// ([5]); a floating window with groups [6, 7] and [8]. +pub(super) fn docked() -> Layout { + let middle = + Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(0.7), first: Box::new(tabs(&[1], 0)), second: Box::new(tabs(&[11, 12], 1)) }; + let dock = + Node::Dock { side: Side::End, columns: vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)], 180.0), Column::new(vec![g(&[5], 0)], 120.0)] }; + Layout { + root: Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), + floating: vec![Floating { groups: vec![g(&[6, 7], 1), g(&[8], 0)], rect: [100.0, 100.0, 300.0, 400.0], native: None }], + } +} + +pub(super) const ALL: [u32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12]; + +fn sorted(layout: &Layout) -> Vec { + let mut panels: Vec = layout.panels().into_iter().copied().collect(); + panels.sort_unstable(); + panels +} + +/// Members, active panel and minimized state of the group holding `panel`. +fn group_state(layout: &Layout, panel: u32) -> (Vec, u32, bool) { + match layout.place(&panel).unwrap() { + Place::Node(path) => match node_at(layout.root.as_ref().unwrap(), &path).unwrap() { + Node::Tabs { panels, active } => (panels.clone(), panels[*active], false), + other => panic!("{other:?}"), + }, + place => { + let group = layout.group(&place).unwrap(); + (group.panels.clone(), group.panels[group.active], group.minimized) + } + } +} + +fn dock(layout: &Layout, side: Side) -> &Vec> { + let path = layout.dock_path(side).unwrap(); + let Some(Node::Dock { columns, .. }) = node_at(layout.root.as_ref().unwrap(), &path) else { panic!() }; + columns +} + +fn panels_of(groups: &[Group]) -> Vec> { + groups.iter().map(|g| g.panels.clone()).collect() +} + +#[test] +fn group_moves_keep_order_active_tab_and_minimized_state() { + let targets = [ + Target::At { anchor: 5, placement: Placement::Group { below: true } }, + Target::At { anchor: 5, placement: Placement::Column { after: true } }, + Target::At { anchor: 8, placement: Placement::Group { below: false } }, + Target::NewDock { side: Side::Start }, + Target::Float { rect: Some([20.0, 20.0, 200.0, 300.0]) }, + Target::Float { rect: None }, + ]; + // A frame Tabs node, a column group and a floating group. + for source in [11, 2, 6] { + for to in &targets { + let mut layout = docked(); + if source != 11 { + layout.apply(Action::SetMinimized { panel: source, minimized: true }).unwrap(); + } + let before = group_state(&layout, source); + layout.apply(Action::MoveGroup { panel: source, to: to.clone() }).unwrap_or_else(|e| panic!("{source} {to:?}: {e}")); + assert_eq!(group_state(&layout, source), before, "{source} {to:?}"); + assert_eq!(sorted(&layout), ALL); + } + } + // Into a frame split the group becomes a Tabs node with the same order and selection. + let mut layout = docked(); + layout.apply(Action::MoveGroup { panel: 6, to: Target::At { anchor: 1, placement: Placement::Split(Zone::Left) } }).unwrap(); + assert_eq!(group_state(&layout, 6), (vec![6, 7], 7, false)); + assert_eq!(layout.floating[0].groups.len(), 1); +} + +#[test] +fn group_merge_into_tabs_inserts_every_member_before_the_anchor_tab() { + let mut layout = docked(); + layout.apply(Action::MoveGroup { panel: 6, to: Target::At { anchor: 2, placement: Placement::Tab { before: Some(3) } } }).unwrap(); + assert_eq!(group_state(&layout, 2), (vec![2, 6, 7, 3], 7, false)); + assert_eq!(panels_of(&layout.floating[0].groups), [vec![8]]); + + let mut layout = docked(); + layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 11, placement: Placement::Tab { before: Some(12) } } }).unwrap(); + assert_eq!(group_state(&layout, 11), (vec![11, 2, 3, 12], 3, false)); + assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![4]]); + + // A target inside the moving group is a no-op; a protected anchor refuses tabs. + let before = docked(); + let mut layout = before.clone(); + layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 3, placement: Placement::Tab { before: None } } }).unwrap(); + assert_eq!(layout, before); + let protect = |p: &u32| if *p == 1 { Permissions::PROTECTED } else { Permissions::default() }; + let to = Target::At { anchor: 1, placement: Placement::Tab { before: None } }; + assert_eq!(layout.apply_with_permissions(Action::MoveGroup { panel: 2, to }, protect), Err(DockError::NotAllowed)); + assert_eq!(layout, before); +} + +#[test] +fn column_moves_and_floats_keep_every_group() { + let mut layout = docked(); + layout.apply(Action::SetIconic { panel: 4, iconic: true }).unwrap(); + layout.apply(Action::MoveColumn { panel: 2, to: Target::NewDock { side: Side::Start } }).unwrap(); + let Some(Node::Split { size, first, .. }) = &layout.root else { panic!() }; + assert_eq!(*size, SplitSize::FixedFirst(180.0)); + assert!(matches!(**first, Node::Dock { side: Side::Start, .. })); + let start = dock(&layout, Side::Start); + assert_eq!(start.len(), 1); + assert_eq!(panels_of(&start[0].groups), [vec![2, 3], vec![4]]); + assert_eq!((start[0].width, start[0].iconic, start[0].groups[0].active), (180.0, true, 1)); + assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![5]]); + + // The last column leaves the end dock, which collapses. + layout.apply(Action::MoveColumn { panel: 5, to: Target::At { anchor: 2, placement: Placement::Column { after: false } } }).unwrap(); + assert!(layout.dock_path(Side::End).is_none()); + let start = dock(&layout, Side::Start); + assert_eq!(start.iter().map(|c| c.width).collect::>(), [120.0, 180.0]); + + layout.apply(Action::MoveColumn { panel: 3, to: Target::Float { rect: None } }).unwrap(); + let window = layout.floating.last().unwrap(); + assert_eq!(panels_of(&window.groups), [vec![2, 3], vec![4]]); + assert_eq!(window.rect[2], 180.0); + assert_eq!(sorted(&layout), ALL); + assert_eq!(layout.apply(Action::MoveColumn { panel: 11, to: Target::Float { rect: None } }), Err(DockError::InvalidPlacement)); +} + +#[test] +fn window_docks_as_stacked_groups_or_merges_as_tabs() { + let mut layout = docked(); + layout.apply(Action::MoveWindow { panel: 8, to: Target::At { anchor: 4, placement: Placement::Group { below: true } } }).unwrap(); + assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![2, 3], vec![4], vec![6, 7], vec![8]]); + assert!(layout.floating.is_empty()); + + let mut layout = docked(); + layout.apply(Action::MoveWindow { panel: 8, to: Target::At { anchor: 11, placement: Placement::Tab { before: None } } }).unwrap(); + assert_eq!(group_state(&layout, 11), (vec![11, 12, 6, 7, 8], 7, false)); + + let mut layout = docked(); + layout.apply(Action::MoveWindow { panel: 6, to: Target::NewDock { side: Side::Start } }).unwrap(); + let start = dock(&layout, Side::Start); + assert_eq!((panels_of(&start[0].groups), start[0].width), (vec![vec![6, 7], vec![8]], 300.0)); + + let before = docked(); + let mut layout = before.clone(); + layout.apply(Action::MoveWindow { panel: 7, to: Target::At { anchor: 8, placement: Placement::Tab { before: None } } }).unwrap(); + assert_eq!(layout, before); + assert_eq!(layout.apply(Action::MoveWindow { panel: 2, to: Target::Float { rect: None } }), Err(DockError::InvalidPlacement)); +} + +#[test] +fn close_group_and_close_window_record_a_restorable_location_per_member() { + let mut workspace = Workspace::new(docked()); + let allow = |_: &u32| Permissions::default(); + workspace.apply(Action::CloseGroup { panel: 3 }, allow).unwrap(); + assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [2, 3]); + assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![4]]); + workspace.set_visible(2, true, None).unwrap(); + workspace.set_visible(3, true, None).unwrap(); + assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![2, 3], vec![4]]); + + assert_eq!(workspace.layout.closed_by(&Action::CloseWindow { panel: 7 }).unwrap(), [6, 7, 8]); + workspace.apply(Action::CloseWindow { panel: 7 }, allow).unwrap(); + assert!(workspace.layout.floating.is_empty()); + assert_eq!(workspace.hidden.len(), 3); + for panel in [6, 7, 8] { + workspace.set_visible(panel, true, None).unwrap(); + } + assert_eq!(workspace.layout.floating.len(), 1); + assert_eq!(panels_of(&workspace.layout.floating[0].groups), [vec![6, 7], vec![8]]); + assert_eq!(workspace.layout.floating[0].rect, [100.0, 100.0, 300.0, 400.0]); + + workspace.apply(Action::CloseOthers { panel: 12 }, allow).unwrap(); + assert_eq!(group_state(&workspace.layout, 12).0, [12]); + workspace.set_visible(11, true, None).unwrap(); + assert_eq!(group_state(&workspace.layout, 12).0, [11, 12]); + assert!(workspace.hidden.is_empty()); + assert_eq!(sorted(&workspace.layout), ALL); + + // A member that may not close keeps the whole group open. + let keep = |p: &u32| if *p == 4 { Permissions { closable: false, ..Permissions::default() } } else { Permissions::default() }; + let before = workspace.clone(); + assert_eq!(workspace.apply(Action::CloseGroup { panel: 4 }, keep), Err(DockError::NotAllowed)); + assert_eq!(workspace, before); +} + +#[test] +fn restore_into_a_column_group_seam_and_new_column_round_trips() { + let column_a = Column::new(vec![g(&[2, 3], 1), Group { minimized: true, height: Some(150.0), ..g(&[4], 0) }, g(&[9], 0)], 180.0); + let column_b = Column { iconic: true, iconic_width: Some(48.0), ..Column::new(vec![g(&[5], 0)], 120.0) }; + let end = Node::Dock { side: Side::End, columns: vec![column_a, column_b] }; + let start = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![g(&[10], 0)], 200.0)] }; + let original = Layout { + root: Some(hsplit(SplitSize::FixedFirst(200.0), start, hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end))), + floating: vec![Floating { + groups: vec![g(&[6], 0), Group { height: Some(90.0), ..g(&[7], 0) }], + rect: [10.0, 10.0, 200.0, 300.0], + native: None, + }], + }; + original.validate().unwrap(); + // 4: the seam between [2, 3] and [9]; 9: below [4]; 5: a new column after A; 10: alone in + // its dock; 3: a tab; 7: below a floating group. + for panel in [4, 9, 5, 10, 3, 7] { + let mut layout = original.clone(); + let location = layout.location(&panel).unwrap(); + #[cfg(feature = "serde")] + let location: Location = serde_json::from_str(&serde_json::to_string(&location).unwrap()).unwrap(); + layout.apply(Action::Close { panel }).unwrap(); + layout.restore(panel, &location).unwrap_or_else(|e| panic!("{panel}: {e} {location:?}")); + assert_eq!(layout, original, "{panel}: {location:?}"); + } +} + +#[test] +fn dock_validation_rejects_two_docks_per_side_nested_docks_empty_columns_and_bad_widths() { + docked().validate().unwrap(); + let empty_dock = |side| Node::Dock { side, columns: Vec::new() }; + Layout { root: Some(hsplit(SplitSize::FixedFirst(10.0), empty_dock(Side::Start), tabs(&[1], 0))), floating: Vec::new() }.validate().unwrap(); + + let two = hsplit(SplitSize::Ratio(0.5), empty_dock(Side::Start), empty_dock(Side::Start)); + let nested = Node::Split { + axis: SplitAxis::Vertical, + size: SplitSize::Ratio(0.5), + first: Box::new(empty_dock(Side::Start)), + second: Box::new(tabs(&[1], 0)), + }; + let wrong_side = hsplit(SplitSize::Ratio(0.5), empty_dock(Side::End), tabs(&[1], 0)); + for root in [two, nested, wrong_side] { + assert_eq!(Layout { root: Some(root), floating: Vec::new() }.validate(), Err(DockError::InvalidPlacement)); + } + + let with_column = |column: Column| Layout { root: Some(Node::Dock { side: Side::End, columns: vec![column] }), floating: Vec::new() }; + let bad = [ + Column::new(Vec::new(), 100.0), + Column::new(vec![g(&[], 0)], 100.0), + Column::new(vec![g(&[2], 1)], 100.0), + Column::new(vec![Group { height: Some(f32::NAN), ..g(&[2], 0) }], 100.0), + Column::new(vec![g(&[2], 0)], 0.0), + Column::new(vec![g(&[2], 0)], -5.0), + Column::new(vec![g(&[2], 0)], f32::INFINITY), + Column::new(vec![g(&[2], 0)], 2.0e6), + Column { iconic_width: Some(f32::NAN), ..Column::new(vec![g(&[2], 0)], 100.0) }, + ]; + for column in bad { + assert!(with_column(column.clone()).validate().is_err(), "{column:?}"); + } + + let mut duplicate = docked(); + duplicate.floating[0].groups[1].panels.push(2); + assert_eq!(duplicate.validate(), Err(DockError::DuplicatePanel)); + let mut empty_window = docked(); + empty_window.floating[0].groups.clear(); + assert_eq!(empty_window.validate(), Err(DockError::InvalidGeometry)); + let mut native = docked(); + native.floating[0].native = Some([0.0, 0.0, -1.0, 10.0]); + assert_eq!(native.validate(), Err(DockError::InvalidGeometry)); + let mut layout = docked(); + assert_eq!(layout.apply(Action::ResizeColumn { panel: 2, width: f32::NAN }), Err(DockError::InvalidGeometry)); + assert_eq!(layout.apply(Action::ResizeColumn { panel: 11, width: 50.0 }), Err(DockError::InvalidPlacement)); + assert_eq!(layout, docked()); +} + +#[test] +fn locked_workspace_rejects_structure_but_allows_activate_open_minimize_and_resize() { + let mut workspace = Workspace::new(docked()); + let allow = |_: &u32| Permissions::default(); + workspace.apply(Action::Close { panel: 12 }, allow).unwrap(); + workspace.locked = true; + let before = workspace.clone(); + let refused = [ + Action::Move { panel: 2, anchor: 5, placement: Placement::Tab { before: None } }, + Action::MoveGroup { panel: 2, to: Target::Float { rect: None } }, + Action::MoveColumn { panel: 5, to: Target::NewDock { side: Side::Start } }, + Action::MoveWindow { panel: 6, to: Target::At { anchor: 4, placement: Placement::Group { below: true } } }, + Action::Float { panel: 4, rect: [0.0, 0.0, 100.0, 100.0] }, + Action::MoveFloating { panel: 6, rect: [0.0, 0.0, 100.0, 100.0] }, + Action::Close { panel: 4 }, + Action::CloseGroup { panel: 4 }, + Action::CloseWindow { panel: 6 }, + Action::SetNative { panel: 6, rect: Some([0.0, 0.0, 100.0, 100.0]) }, + ]; + for action in refused { + assert_eq!(workspace.apply(action.clone(), allow), Err(DockError::NotAllowed), "{action:?}"); + assert_eq!(workspace, before); + } + assert_eq!(workspace.set_visible(4, false, None), Err(DockError::NotAllowed)); + let allowed = [ + Action::Activate { panel: 2 }, + Action::Open { panel: 12, anchor: Some(11) }, + Action::SetMinimized { panel: 4, minimized: true }, + Action::SetIconic { panel: 5, iconic: true }, + Action::ResizeColumn { panel: 5, width: 160.0 }, + Action::ResizeGroup { panel: 4, height: Some(120.0) }, + Action::ResizeIconic { panel: 5, width: Some(60.0) }, + Action::ResizeSplit { path: Vec::new(), size: SplitSize::FixedSecond(320.0) }, + ]; + workspace.apply_all(allowed, allow).unwrap(); + assert!(workspace.hidden.is_empty()); + assert_eq!(workspace.layout.panel_state(&12), PanelState::Front); + assert_eq!(workspace.layout.panel_state(&4), PanelState::Open); + assert_eq!(workspace.layout.panel_state(&5), PanelState::Open); + assert_eq!(workspace.layout.panel_state(&2), PanelState::Front); + assert_eq!(workspace.layout.panel_state(&3), PanelState::Open); +} + +#[test] +fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() { + let default = Workspace::new(docked()); + let mut workspace = default.clone(); + workspace.layout.apply(Action::Close { panel: 5 }).unwrap(); + workspace.layout.apply(Action::Close { panel: 12 }).unwrap(); + workspace.layout.apply(Action::OpenAt { panel: 99, anchor: 2, placement: Placement::Tab { before: None } }).unwrap(); + let stray = workspace.layout.location(&99).unwrap(); + workspace.hidden.push((98, stray)); + let registered = |p: &u32| *p < 90; + workspace.reconcile(registered, &default); + workspace.validate().unwrap(); + // Unregistered panels wait in `hidden` and come back once registered. + assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [98, 99]); + assert_eq!(sorted(&workspace.layout), ALL); + workspace.set_visible(99, true, None).unwrap(); + assert_eq!(group_state(&workspace.layout, 2).0, [2, 3, 99]); + assert_eq!(dock(&workspace.layout, Side::End).len(), 2); + assert_eq!(group_state(&workspace.layout, 11).0, [11, 12]); + + let mut broken = default.clone(); + broken.layout.floating[0].rect[2] = -1.0; + broken.reconcile(registered, &default); + assert_eq!(broken.layout, default.layout); +} + +#[test] +fn reset_returns_to_saved_or_default() { + let default = docked(); + let mut workspace = Workspace::new(default.clone()); + workspace.apply(Action::MoveGroup { panel: 6, to: Target::NewDock { side: Side::Start } }, |_| Permissions::default()).unwrap(); + workspace.reset(&default); + assert_eq!(workspace.layout, default); + + let mut saved = default.clone(); + saved.apply(Action::Close { panel: 8 }).unwrap(); + saved.apply(Action::MoveGroup { panel: 11, to: Target::Float { rect: None } }).unwrap(); + workspace.saved = Some(saved.clone()); + workspace.reset(&default); + assert_eq!(workspace.layout, saved); + assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [8]); + workspace.validate().unwrap(); +} + +#[cfg(feature = "serde")] +mod serde_tests { + use super::*; + use serde_json::{Value, json}; + + #[test] + fn single_plain_floating_window_writes_the_v1_shape() { + let rect = [1.0, 2.0, 300.0, 200.0]; + let plain = Floating::single(vec![4u32, 5], 1, rect); + assert_eq!(serde_json::to_value(&plain).unwrap(), json!({"panels": [4, 5], "active": 1, "rect": rect})); + let minimized = Floating { groups: vec![Group { minimized: true, ..g(&[4], 0) }], rect, native: None }; + let stacked = Floating { groups: vec![g(&[4], 0), g(&[5], 0)], rect, native: None }; + let native = Floating { native: Some(rect), ..Floating::single(vec![4u32], 0, rect) }; + for window in [minimized, stacked, native] { + let value = serde_json::to_value(&window).unwrap(); + assert!(value.get("groups").is_some() && value.get("panels").is_none(), "{value}"); + assert_eq!(serde_json::from_value::>(value).unwrap(), window); + } + assert!(serde_json::from_value::>(json!({"rect": rect})).is_err()); + } + + #[test] + fn v2_round_trips() { + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::CloseGroup { panel: 4 }, |_| Permissions::default()).unwrap(); + workspace.apply(Action::SetNative { panel: 8, rect: Some([5.0, 5.0, 400.0, 300.0]) }, |_| Permissions::default()).unwrap(); + workspace.saved = Some(docked()); + workspace.locked = true; + let text = serde_json::to_string(&workspace).unwrap(); + let parsed: Workspace = serde_json::from_str(&text).unwrap(); + assert_eq!(parsed, workspace); + assert_eq!(serde_json::from_str::(&text).unwrap()["version"], json!(2)); + + let mut old = parsed.clone(); + old.version = 1; + let mut value = serde_json::to_value(&old).unwrap(); + value.as_object_mut().unwrap().remove("version"); + assert_eq!(serde_json::from_value::>(value).unwrap().version, 1); + old.version = 3; + assert_eq!(old.validate(), Err(DockError::UnsupportedVersion)); + } + + #[derive(Clone, Copy, Debug)] + enum Kind { + Layout, + Workspace, + Hidden, + } + + /// App, file contents, and the JSON pointers to its docking values. + type Fixture = (&'static str, &'static str, &'static [(&'static str, Kind)]); + + #[test] + fn v1_layout_json_parses_unchanged() { + use Kind::*; + let fixtures: [Fixture; 7] = [ + ( + "designcraft", + include_str!("../../tests/fixtures/v1/designcraft.json"), + &[ + ("/docking", Layout), + ("/dockingHidden", Hidden), + ("/customWorkspaces/0/docking", Layout), + ("/customWorkspaces/0/dockingHidden", Hidden), + ], + ), + ("vectorcraft", include_str!("../../tests/fixtures/v1/vectorcraft.json"), &[("/docking", Layout), ("/docking_hidden", Hidden)]), + ("lightcraft", include_str!("../../tests/fixtures/v1/lightcraft.json"), &[("/docking", Workspace)]), + ("pdfcraft", include_str!("../../tests/fixtures/v1/pdfcraft.json"), &[("/docking", Workspace)]), + ("cadcraft", include_str!("../../tests/fixtures/v1/cadcraft.json"), &[("/workspace/docking", Workspace)]), + ("soundcraft", include_str!("../../tests/fixtures/v1/soundcraft.json"), &[("/docking", Workspace), ("/mix_docking", Workspace)]), + ( + "photocraft", + include_str!("../../tests/fixtures/v1/photocraft.json"), + &[("/docking", Layout), ("/docking_hidden", Hidden), ("/panel_layout/docking", Layout), ("/panel_layout/dockingHidden", Hidden)], + ), + ]; + for (app, text, fields) in fixtures { + let file: Value = serde_json::from_str(text).unwrap(); + for (pointer, kind) in fields { + let value = file.pointer(pointer).unwrap_or_else(|| panic!("{app}{pointer}")).clone(); + let layout_value = match kind { + Layout => value.clone(), + Workspace => value["layout"].clone(), + Hidden => { + let hidden: std::collections::BTreeMap> = serde_json::from_value(value).unwrap(); + assert!(!hidden.is_empty(), "{app}{pointer}"); + continue; + } + }; + if let Workspace = kind { + let workspace: super::Workspace = serde_json::from_value(value).unwrap_or_else(|e| panic!("{app}{pointer}: {e}")); + workspace.validate().unwrap_or_else(|e| panic!("{app}{pointer}: {e}")); + assert_eq!(workspace.version, 1); + for (panel, location) in &workspace.hidden { + let mut layout = workspace.layout.clone(); + layout.restore(panel.clone(), location).unwrap_or_else(|e| panic!("{app}{pointer} {panel}: {e}")); + } + } + let layout: super::Layout = serde_json::from_value(layout_value.clone()).unwrap_or_else(|e| panic!("{app}{pointer}: {e}")); + layout.validate().unwrap_or_else(|e| panic!("{app}{pointer}: {e}")); + // Nothing new is in use, so the layout writes back exactly as read. + assert_eq!(serde_json::to_value(&layout).unwrap(), layout_value, "{app}{pointer}"); + } + } + } +} diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 6840132465..5180b76deb 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -253,35 +253,58 @@ fn pointer_targets_distinguish_reorder_center_split_and_occlusion() { #[test] fn long_action_sequence_never_loses_or_duplicates_a_panel() { - let mut layout = sample(); - let mut seed = 72u64; - for step in 0..800 { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); - let panel = (seed % 6 + 1) as u32; - let anchor = ((seed >> 16) % 6 + 1) as u32; - let action = if step % 7 == 0 { - Action::Float { panel, rect: [10.0, 20.0, 200.0, 220.0] } - } else { - move_to( - panel, - anchor, - match seed % 5 { - 0 => Zone::Left, - 1 => Zone::Right, - 2 => Zone::Top, - 3 => Zone::Bottom, - _ => Zone::Center, - }, - ) - }; - let before = layout.clone(); - if layout.apply(action).is_err() { - assert_eq!(layout, before); + for (start, ids) in [(sample(), vec![1, 2, 3, 4, 5, 6]), (super::model_tests::docked(), super::model_tests::ALL.to_vec())] { + let mut workspace = Workspace::new(start); + let mut seed = 72u64; + for step in 0..800 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let pick = |bits: u64| ids[(bits % ids.len() as u64) as usize]; + let (panel, anchor) = (pick(seed >> 8), pick(seed >> 24)); + let placement = match (seed >> 40) % 7 { + 0 => Placement::Split(Zone::Left), + 1 => Placement::Split(Zone::Right), + 2 => Placement::Split(Zone::Top), + 3 => Placement::Split(Zone::Bottom), + 4 => Placement::Split(Zone::Center), + 5 => Placement::Group { below: seed & 1 == 0 }, + _ => Placement::Column { after: seed & 2 == 0 }, + }; + let to = match (seed >> 32) % 4 { + 0 => Target::Float { rect: None }, + 1 => Target::NewDock { side: if seed & 4 == 0 { Side::Start } else { Side::End } }, + _ => Target::At { anchor, placement: placement.clone() }, + }; + let action = match step % 13 { + 0 => Action::Float { panel, rect: [10.0, 20.0, 200.0, 220.0] }, + 1 => Action::MoveGroup { panel, to }, + 2 => Action::MoveColumn { panel, to }, + 3 => Action::MoveWindow { panel, to }, + 4 => Action::CloseGroup { panel }, + 5 => Action::CloseWindow { panel }, + 6 => Action::CloseOthers { panel }, + 7 => Action::Close { panel }, + 8 => Action::SetMinimized { panel, minimized: seed & 8 == 0 }, + 9 => Action::SetIconic { panel, iconic: seed & 16 == 0 }, + _ => Action::Move { panel, anchor, placement }, + }; + let before = workspace.clone(); + if workspace.apply(action, |_| Permissions::default()).is_err() { + assert_eq!(workspace, before); + } + if step % 3 == 0 + && let Some((hidden, _)) = workspace.hidden.first().cloned() + { + let fallback = workspace.layout.panels().first().map(|p| **p); + let before = workspace.clone(); + if workspace.set_visible(hidden, true, fallback).is_err() { + assert_eq!(workspace, before); + } + } + workspace.validate().unwrap(); + let mut panels: Vec = workspace.layout.panels().into_iter().copied().chain(workspace.hidden.iter().map(|(p, _)| *p)).collect(); + panels.sort_unstable(); + assert_eq!(panels, ids, "step {step}"); } - layout.validate().unwrap(); - let mut panels: Vec = layout.panels().into_iter().copied().collect(); - panels.sort_unstable(); - assert_eq!(panels, vec![1, 2, 3, 4, 5, 6]); } } diff --git a/crates/ui/tests/fixtures/v1/cadcraft.json b/crates/ui/tests/fixtures/v1/cadcraft.json new file mode 100644 index 0000000000..996bb02e0a --- /dev/null +++ b/crates/ui/tests/fixtures/v1/cadcraft.json @@ -0,0 +1,91 @@ +{ + "version": 1, + "workspace": { + "docking": { + "layout": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedFirst": 220.0 + }, + "first": { + "Tabs": { + "panels": [ + "toolSets" + ], + "active": 0 + } + }, + "second": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedSecond": 300.0 + }, + "first": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + }, + "second": { + "Stack": { + "entries": [ + { + "panel": "layers", + "open": true, + "height": 280.0 + }, + { + "panel": "properties", + "open": false, + "height": null + } + ] + } + } + } + } + } + }, + "floating": [ + { + "panels": [ + "quickCalc" + ], + "active": 0, + "rect": [ + 320.0, + 200.0, + 240.0, + 300.0 + ] + } + ] + }, + "hidden": [ + [ + "externalReferences", + { + "floating": null, + "anchor": "layers", + "placement": { + "Tab": { + "before": "properties" + } + }, + "size": null, + "stack": [ + true, + null + ], + "sibling": [] + } + ] + ] + } + } +} diff --git a/crates/ui/tests/fixtures/v1/designcraft.json b/crates/ui/tests/fixtures/v1/designcraft.json new file mode 100644 index 0000000000..ea99c2c182 --- /dev/null +++ b/crates/ui/tests/fixtures/v1/designcraft.json @@ -0,0 +1,123 @@ +{ + "uiScale": 1.0, + "theme": "dark", + "docking": { + "root": { + "Tabs": { + "panels": [ + "properties", + "pages", + "layers", + "stroke" + ], + "active": 2 + } + }, + "floating": [ + { + "panels": [ + "swatches", + "color" + ], + "active": 1, + "rect": [ + 640.0, + 120.0, + 280.0, + 360.0 + ] + } + ] + }, + "dockingHidden": { + "gradient": { + "floating": [ + 640.0, + 120.0, + 280.0, + 360.0 + ], + "anchor": "swatches", + "placement": { + "Tab": { + "before": null + } + }, + "size": null, + "stack": null, + "sibling": [] + }, + "effects": { + "floating": null, + "anchor": "layers", + "placement": { + "Tab": { + "before": "stroke" + } + }, + "size": null, + "stack": null, + "sibling": [] + } + }, + "customWorkspaces": [ + { + "name": "Print", + "docking": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedFirst": 268.0 + }, + "first": { + "Tabs": { + "panels": [ + "layers" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "properties", + "pages" + ], + "active": 0 + } + } + } + }, + "floating": [ + { + "panels": [ + "swatches" + ], + "active": 0, + "rect": [ + 120.0, + 160.0, + 280.0, + 360.0 + ] + } + ] + }, + "dockingHidden": { + "stroke": { + "floating": null, + "anchor": "layers", + "placement": { + "Tab": { + "before": null + } + }, + "size": null, + "stack": null, + "sibling": [] + } + } + } + ] +} diff --git a/crates/ui/tests/fixtures/v1/lightcraft.json b/crates/ui/tests/fixtures/v1/lightcraft.json new file mode 100644 index 0000000000..5b558be6aa --- /dev/null +++ b/crates/ui/tests/fixtures/v1/lightcraft.json @@ -0,0 +1,67 @@ +{ + "uiScale": 1.0, + "docking": { + "layout": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedSecond": 270.0 + }, + "first": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedFirst": 268.0 + }, + "first": { + "Tabs": { + "panels": [ + "library" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + } + } + }, + "second": { + "Tabs": { + "panels": [ + "tools" + ], + "active": 0 + } + } + } + }, + "floating": [] + }, + "hidden": [ + [ + "presets", + { + "floating": null, + "anchor": "canvas", + "placement": { + "Split": "Right" + }, + "size": { + "FixedSecond": 300.0 + }, + "stack": null, + "sibling": [ + "canvas" + ] + } + ] + ] + } +} diff --git a/crates/ui/tests/fixtures/v1/pdfcraft.json b/crates/ui/tests/fixtures/v1/pdfcraft.json new file mode 100644 index 0000000000..2951f997df --- /dev/null +++ b/crates/ui/tests/fixtures/v1/pdfcraft.json @@ -0,0 +1,51 @@ +{ + "docking": { + "layout": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedFirst": 272.0 + }, + "first": { + "Tabs": { + "panels": [ + "tools" + ], + "active": 0 + } + }, + "second": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedSecond": 330.0 + }, + "first": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "inspector" + ], + "active": 0 + } + } + } + } + } + }, + "floating": [] + }, + "hidden": [] + }, + "docking_left_open": true, + "docking_right": null, + "recent": [] +} diff --git a/crates/ui/tests/fixtures/v1/photocraft.json b/crates/ui/tests/fixtures/v1/photocraft.json new file mode 100644 index 0000000000..34aed08be4 --- /dev/null +++ b/crates/ui/tests/fixtures/v1/photocraft.json @@ -0,0 +1,151 @@ +{ + "docking": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedSecond": 300.0 + }, + "first": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + }, + "second": { + "Split": { + "axis": "Vertical", + "size": { + "Ratio": 0.5 + }, + "first": { + "Tabs": { + "panels": [ + "layers", + "channels", + "paths" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "adjustments", + "history" + ], + "active": 1 + } + } + } + } + } + }, + "floating": [ + { + "panels": [ + "properties" + ], + "active": 0, + "rect": [ + 120.0, + 160.0, + 320.0, + 440.0 + ] + } + ] + }, + "docking_hidden": { + "navigator": { + "floating": null, + "anchor": "layers", + "placement": { + "Tab": { + "before": "channels" + } + }, + "size": null, + "stack": null, + "sibling": [] + } + }, + "panel_layout": { + "docking": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedSecond": 300.0 + }, + "first": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + }, + "second": { + "Split": { + "axis": "Vertical", + "size": { + "Ratio": 0.5 + }, + "first": { + "Tabs": { + "panels": [ + "layers", + "channels", + "paths" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "adjustments", + "history" + ], + "active": 1 + } + } + } + } + } + }, + "floating": [ + { + "panels": [ + "properties" + ], + "active": 0, + "rect": [ + 120.0, + 160.0, + 320.0, + 440.0 + ] + } + ] + }, + "dockingHidden": { + "navigator": { + "floating": null, + "anchor": "layers", + "placement": { + "Tab": { + "before": "channels" + } + }, + "size": null, + "stack": null, + "sibling": [] + } + }, + "dockingCollapsed": [] + } +} diff --git a/crates/ui/tests/fixtures/v1/soundcraft.json b/crates/ui/tests/fixtures/v1/soundcraft.json new file mode 100644 index 0000000000..51bd013d21 --- /dev/null +++ b/crates/ui/tests/fixtures/v1/soundcraft.json @@ -0,0 +1,180 @@ +{ + "docking": { + "layout": { + "root": { + "Split": { + "axis": "Vertical", + "size": { + "FixedSecond": 348.0 + }, + "first": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedFirst": 168.0 + }, + "first": { + "Tabs": { + "panels": [ + "tracks" + ], + "active": 0 + } + }, + "second": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedSecond": 230.0 + }, + "first": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "clips" + ], + "active": 0 + } + } + } + } + } + }, + "second": { + "Tabs": { + "panels": [ + "midi" + ], + "active": 0 + } + } + } + }, + "floating": [ + { + "panels": [ + "memory" + ], + "active": 0, + "rect": [ + 160.0, + 120.0, + 480.0, + 280.0 + ] + }, + { + "panels": [ + "history" + ], + "active": 0, + "rect": [ + 680.0, + 120.0, + 260.0, + 300.0 + ] + } + ] + }, + "hidden": [] + }, + "mix_docking": { + "layout": { + "root": { + "Split": { + "axis": "Horizontal", + "size": { + "FixedFirst": 168.0 + }, + "first": { + "Tabs": { + "panels": [ + "tracks" + ], + "active": 0 + } + }, + "second": { + "Tabs": { + "panels": [ + "canvas" + ], + "active": 0 + } + } + } + }, + "floating": [ + { + "panels": [ + "memory" + ], + "active": 0, + "rect": [ + 160.0, + 120.0, + 480.0, + 280.0 + ] + }, + { + "panels": [ + "history" + ], + "active": 0, + "rect": [ + 680.0, + 120.0, + 260.0, + 300.0 + ] + } + ] + }, + "hidden": [ + [ + "clips", + { + "floating": null, + "anchor": "canvas", + "placement": { + "Split": "Right" + }, + "size": { + "FixedSecond": 230.0 + }, + "stack": null, + "sibling": [ + "canvas" + ] + } + ], + [ + "midi", + { + "floating": null, + "anchor": "tracks", + "placement": { + "Split": "Bottom" + }, + "size": { + "FixedSecond": 348.0 + }, + "stack": null, + "sibling": [ + "tracks", + "canvas" + ] + } + ] + ] + } +} diff --git a/crates/ui/tests/fixtures/v1/vectorcraft.json b/crates/ui/tests/fixtures/v1/vectorcraft.json new file mode 100644 index 0000000000..d9c255420a --- /dev/null +++ b/crates/ui/tests/fixtures/v1/vectorcraft.json @@ -0,0 +1,91 @@ +{ + "dock_tab": "layers", + "docking": { + "root": { + "Split": { + "axis": "Vertical", + "size": { + "Ratio": 0.625 + }, + "first": { + "Tabs": { + "panels": [ + "properties", + "layers", + "libraries" + ], + "active": 1 + } + }, + "second": { + "Stack": { + "entries": [ + { + "panel": "color", + "open": true, + "height": 180.0 + }, + { + "panel": "swatches", + "open": false, + "height": null + }, + { + "panel": "stroke", + "open": true, + "height": null + } + ] + } + } + } + }, + "floating": [ + { + "panels": [ + "brushes", + "symbols" + ], + "active": 0, + "rect": [ + 200.0, + 140.0, + 300.0, + 400.0 + ] + }, + { + "panels": [ + "gradient" + ], + "active": 0, + "rect": [ + 540.0, + 180.0, + 260.0, + 320.0 + ] + } + ] + }, + "docking_hidden": { + "patternOptions": { + "floating": null, + "anchor": "color", + "placement": { + "Tab": { + "before": "swatches" + } + }, + "size": null, + "stack": [ + true, + 240.0 + ], + "sibling": [] + } + }, + "docking_icons": [ + "stroke" + ] +} From 87ddebd73ab8e214c4d2591f74ef256d17513fbc Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:41:18 +0000 Subject: [PATCH 08/94] docking: split the renderer into render modules DockArea, DockContent, DockStyle, DockOutput and the drag state stay in surface.rs. The Renderer moves to docking/render: the node tree, limits and helpers in mod.rs, groups and tabs in group.rs, floating windows in floating.rs, and drop resolution and previews in preview.rs. --- crates/ui/src/docking/mod.rs | 3 + crates/ui/src/docking/render/floating.rs | 77 +++ crates/ui/src/docking/render/group.rs | 214 ++++++++ crates/ui/src/docking/render/mod.rs | 260 +++++++++ crates/ui/src/docking/render/preview.rs | 106 ++++ crates/ui/src/docking/surface.rs | 652 +---------------------- 6 files changed, 673 insertions(+), 639 deletions(-) create mode 100644 crates/ui/src/docking/render/floating.rs create mode 100644 crates/ui/src/docking/render/group.rs create mode 100644 crates/ui/src/docking/render/mod.rs create mode 100644 crates/ui/src/docking/render/preview.rs diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 304e46d2f5..b47dd39d25 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -7,6 +7,7 @@ mod dock_model; mod model; +mod render; mod surface; mod targets; mod workspace; @@ -17,6 +18,8 @@ pub use surface::{DockArea, DockContent, DockOutput, DockStyle, PanelLimits, beg pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect}; pub use workspace::Workspace; +use surface::{Drag, GroupDrag}; + #[cfg(test)] mod model_tests; #[cfg(test)] diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs new file mode 100644 index 0000000000..64ca2da441 --- /dev/null +++ b/crates/ui/src/docking/render/floating.rs @@ -0,0 +1,77 @@ +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Key, Rect, Sense, Stroke, Vec2, pos2, vec2}; + +use super::{Renderer, clamp_float}; +use crate::docking::{Action, Node}; + +impl Renderer<'_, P> { + pub(in crate::docking) fn floating(&mut self, ctx: &Context) { + let screen = ctx.content_rect(); + if !crate::docking::targets::usable(screen) { + return; + } + let layers = ctx.memory(|memory| memory.layer_ids().collect::>()); + let mut groups: Vec<_> = self.layout.floating.iter().collect(); + groups.sort_by_key(|group| { + let id = group.panels().next().map(|panel| self.id.with(("floating", panel))); + layers.iter().position(|layer| Some(layer.id) == id).unwrap_or(usize::MAX) + }); + for group in groups { + let Some(first) = group.panels().next() else { continue }; + let [x, y, width, height] = group.rect; + let limits = self.node_limits(&Node::Tabs { panels: group.panels().cloned().collect(), active: 0 }); + let size = vec2(width, height).max(limits.min).min(limits.max); + let rect = clamp_float(Rect::from_min_size(pos2(x, y), size), screen); + let id = self.id.with(("floating", first)); + if self.activation.as_ref().is_some_and(|panel| group.contains(panel)) { + ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); + ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); + self.output.focused = self.activation.clone(); + } + egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).constrain_to(screen).show(ctx, |ui| { + ui.set_min_size(rect.size()); + let rect = Rect::from_min_size(ui.min_rect().min, rect.size()); + ui.allocate_rect(rect, Sense::hover()); + self.stacked_groups(ui, &group.groups, rect, true); + let corner = Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max); + let response = ui.interact(corner, id.with("resize"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeNwSe); + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.resize_window_label)); + if response.drag_started() { + response.request_focus(); + } + let mut delta = if response.dragged() { ui.input(|i| i.pointer.delta()) } else { Vec2::ZERO }; + if response.has_focus() { + ui.memory_mut(|memory| { + memory.set_focus_lock_filter( + response.id, + egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }, + ) + }); + ui.input_mut(|input| { + if input.consume_key(egui::Modifiers::NONE, Key::ArrowLeft) { + delta.x -= 8.0; + } + if input.consume_key(egui::Modifiers::NONE, Key::ArrowRight) { + delta.x += 8.0; + } + if input.consume_key(egui::Modifiers::NONE, Key::ArrowUp) { + delta.y -= 8.0; + } + if input.consume_key(egui::Modifiers::NONE, Key::ArrowDown) { + delta.y += 8.0; + } + }); + } + if response.enabled() && delta != Vec2::ZERO { + let size = (rect.size() + delta).max(limits.min.max(vec2(40.0, self.style.tab_height + 20.0))).min(limits.max).min(screen.size()); + self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [rect.left(), rect.top(), size.x, size.y] }); + } + if response.hovered() || response.dragged() || response.has_focus() { + ui.painter().line_segment([corner.left_bottom(), corner.right_top()], Stroke::new(2.0, self.style.accent)); + } + }); + } + } +} diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs new file mode 100644 index 0000000000..850a22aaa9 --- /dev/null +++ b/crates/ui/src/docking/render/group.rs @@ -0,0 +1,214 @@ +use std::{fmt::Debug, hash::Hash}; + +use egui::{Key, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; + +use super::{Renderer, clamp_float}; +use crate::docking::{Action, DropTarget, GroupDrag, Permissions, Placement, begin_drag, surface::TAB_PADDING}; +use crate::tabs; + +impl Renderer<'_, P> { + /// Groups stacked top to bottom in equal shares of `rect`. + pub(super) fn stacked_groups(&mut self, ui: &mut Ui, groups: &[crate::docking::Group

], rect: Rect, floating: bool) { + let share = rect.height() / groups.len().max(1) as f32; + for (index, group) in groups.iter().enumerate() { + let top = rect.top() + share * index as f32; + let group_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + share)); + self.group(ui, &group.panels, group.active, group_rect, floating); + } + } + + pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, rect: Rect, floating: bool) { + let Some(selected) = panels.get(active) else { return }; + let policy = (self.permissions)(selected); + let bare = panels.len() == 1 && policy == Permissions::PROTECTED; + if bare { + self.contents(ui, selected, rect); + self.targets.push(DropTarget { + anchor: selected.clone(), + rect, + tab_strip: None, + tabs: Vec::new(), + allow_splits: !floating, + accepts_tabs: false, + }); + return; + } + let mut strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom()))); + ui.painter().rect_filled(strip, 0.0, self.style.tab_background); + if floating { + let grip = Rect::from_min_max(strip.min, pos2((strip.left() + 12.0).min(strip.right()), strip.bottom())); + let response = ui.interact(grip, self.id.with(("move-group", panels.first())), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); + if panels.iter().all(|p| (self.permissions)(p).movable) + && response.drag_started() + && let Some(first) = panels.first() + { + ui.ctx().data_mut(|d| { + d.insert_temp( + self.id.with("group-drag"), + GroupDrag { panel: first.clone(), original: [rect.left(), rect.top(), rect.width(), rect.height()] }, + ) + }); + } + if panels.iter().all(|p| (self.permissions)(p).movable) + && response.dragged() + && ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))).is_some() + && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) + { + let moved = clamp_float(rect.translate(ui.input(|i| i.pointer.delta())), ui.ctx().content_rect()); + if let Some(first) = panels.first() { + self.output + .actions + .push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); + } + } + ui.painter().line_segment([grip.center() - vec2(0.0, 5.0), grip.center() + vec2(0.0, 5.0)], self.style.border); + strip.min.x = grip.right(); + } + let requested = self.content.group_header_width(panels, selected, floating); + let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 }; + if header_width > 0.0 { + let header = Rect::from_min_max(pos2(strip.right() - header_width, strip.top()), strip.max); + let mut child = ui.new_child(UiBuilder::new().id(self.id.with(("header", selected))).max_rect(header)); + child.set_clip_rect(header.intersect(ui.clip_rect())); + self.content.group_header(&mut child, panels, selected, floating); + } + let widths: Vec = panels + .iter() + .map(|p| { + self.content + .label(ui, p, &(self.label)(p), &self.style.font, self.style.text) + .into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, self.style.font.clone()) + .size() + .x + + TAB_PADDING + }) + .collect(); + let fit = tabs::fit(&widths, active, (strip.width() - header_width).max(0.0), 40.0, 22.0); + let mut x = strip.left(); + let mut targets = Vec::new(); + for (index, width) in &fit.shown { + let Some(panel) = panels.get(*index) else { continue }; + let tab = Rect::from_min_size(pos2(x, strip.top()), vec2(*width, strip.height())); + self.tab(ui, panel, tab, *index == active, rect); + targets.push((panel.clone(), tab)); + x += width; + } + if !fit.overflow.is_empty() && fit.overflow_width > 0.0 { + let overflow = Rect::from_min_size(pos2(x, strip.top()), vec2(fit.overflow_width, strip.height())); + let response = ui.interact(overflow, self.id.with(("overflow", selected)), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.panels_label)); + ui.painter().with_clip_rect(overflow).text(overflow.center(), egui::Align2::CENTER_CENTER, "…", self.style.font.clone(), self.style.text); + egui::Popup::menu(&response).show(|ui| { + egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { + for index in &fit.overflow { + if let Some(panel) = panels.get(*index) + && self.menu_label(ui, panel).clicked() + { + self.output.actions.push(Action::Activate { panel: panel.clone() }); + self.output.focused = Some(panel.clone()); + ui.close(); + } + } + }); + }); + } + // Include hidden tab identities for source-group detection without creating hit areas. + for panel in panels { + if !targets.iter().any(|(p, _)| p == panel) { + targets.push((panel.clone(), Rect::NOTHING)); + } + } + self.targets.push(DropTarget { + anchor: selected.clone(), + rect, + tab_strip: Some(strip), + tabs: targets, + allow_splits: !floating, + accepts_tabs: policy.accepts_tabs, + }); + self.contents(ui, selected, Rect::from_min_max(pos2(rect.left(), strip.bottom()), rect.max)); + ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); + } + + pub(super) fn menu_label(&mut self, ui: &mut Ui, panel: &P) -> egui::Response { + let logical = (self.label)(panel); + let text = self.content.label(ui, panel, &logical, &self.style.font, self.style.text); + let response = ui.button(text); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); + response + } + + pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect) { + let policy = (self.permissions)(panel); + let label = (self.label)(panel); + let color = if active { self.style.text } else { self.style.inactive_text }; + // A tab squeezed below its natural width cuts its label with '…' inside the padding its + // natural width was measured with, instead of letting it run under its neighbours. + let galley = self.content.label(ui, panel, &label, &self.style.font, color).into_galley( + ui, + Some(egui::TextWrapMode::Truncate), + (rect.width() - TAB_PADDING).max(0.0), + self.style.font.clone(), + ); + let elided = galley.elided; + let response = tabs::Tab::new(self.id.with(("tab", panel)), &label, active) + .sense(if policy.movable { Sense::click_and_drag() } else { Sense::click() }) + .focus_stroke(Stroke::new(1.0, self.style.accent)) + .show_at(ui, rect, |ui, response| { + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + painter.rect_filled(rect, 0.0, if active || response.hovered() { self.style.active_background } else { self.style.tab_background }); + painter.galley(rect.center() - galley.size() * 0.5, galley.clone(), color); + }); + let response = if elided { response.on_hover_text(&label) } else { response }; + self.register_interaction(ui.ctx(), response.id); + if response.clicked() { + self.output.actions.push(Action::Activate { panel: panel.clone() }); + self.output.focused = Some(panel.clone()); + } + if policy.movable && response.drag_started() { + begin_drag(ui.ctx(), self.id, panel.clone(), group); + } + response.context_menu(|ui| { + self.content.panel_menu(ui, panel); + if policy.movable && policy.floatable { + let text = self.content.action_label(ui, &self.style.float_label, &self.style.font, self.style.text); + let response = ui.button(text); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.float_label)); + if response.clicked() { + let rect = clamp_float(group.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); + self.output.actions.push(Action::Float { panel: panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }); + ui.close(); + } + } + if policy.movable && !self.layout.move_targets(panel, self.permissions).is_empty() { + let text = self.content.action_label(ui, &self.style.move_label, &self.style.font, self.style.text); + let response = ui.menu_button(text, |ui| { + egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { + for target in self.layout.move_targets(panel, self.permissions) { + if self.menu_label(ui, target).clicked() { + self.output.actions.push(Action::Move { + panel: panel.clone(), + anchor: target.clone(), + placement: Placement::Tab { before: None }, + }); + ui.close(); + } + } + }); + }); + response.response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); + } + if policy.closable { + let text = self.content.action_label(ui, &self.style.close_label, &self.style.font, self.style.text); + let response = ui.button(text); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.close_label)); + if response.clicked() { + self.output.actions.push(Action::Close { panel: panel.clone() }); + ui.close(); + } + } + }); + } +} diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs new file mode 100644 index 0000000000..c5a031f942 --- /dev/null +++ b/crates/ui/src/docking/render/mod.rs @@ -0,0 +1,260 @@ +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Id, Rect, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; + +use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split_rect}; + +use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions}; + +mod floating; +mod group; +mod preview; + +pub(super) struct Renderer<'a, P> { + pub(super) id: Id, + pub(super) style: &'a DockStyle, + pub(super) label: &'a dyn Fn(&P) -> String, + pub(super) permissions: &'a dyn Fn(&P) -> Permissions, + pub(super) limits: &'a dyn Fn(&P) -> PanelLimits, + pub(super) content: &'a mut dyn DockContent

, + pub(super) activation: Option

, + pub(super) blockers: Vec, + pub(super) layout: &'a Layout

, + pub(super) targets: Vec>, + pub(super) owned_interactions: Vec, + pub(super) output: DockOutput

, +} + +impl Renderer<'_, P> { + pub(super) fn register_interaction(&mut self, ctx: &Context, id: Id) { + // A validated tree has at most 2*MAX_PANELS nodes. Tabs, stack dividers, + // floating grips/corners and splits fit comfortably inside this fixed bound. + const CAP: usize = 8 * crate::docking::MAX_PANELS; + if self.owned_interactions.len() < CAP && !self.owned_interactions.contains(&id) { + self.owned_interactions.push(id); + } + // Retain prior-frame controls until return, and publish current controls before + // app callbacks. No Context lock spans a callback or a stop_dragging call. + ctx.data_mut(|d| { + let ids = d.get_temp_mut_or_default::>(self.id.with("owned-interactions")); + if ids.len() < CAP && !ids.contains(&id) { + ids.push(id); + } + }); + } + + pub(in crate::docking) fn node(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &mut Vec) { + if !crate::docking::targets::usable(rect) { + return; + } + match node { + Node::Split { axis, size, first, second } => { + let Some(wanted) = split_rect(rect, *axis, *size, self.style.gap, 0.0) else { return }; + let (lo, hi) = split_bounds(wanted.available(), *axis, self.node_limits(first), self.node_limits(second)); + let first_size = wanted.first_size().clamp(lo, hi); + let Some(split) = split_rect(rect, *axis, SplitSize::FixedFirst(first_size), self.style.gap, 0.0) else { return }; + path.push(false); + self.node(ui, first, split.first, path); + path.pop(); + path.push(true); + self.node(ui, second, split.second, path); + path.pop(); + // The divider's inner-edge hit margin must win over child scrollbars, just + // as accordion dividers win over the adjacent panel's content. + let response = ResizeHandle::new( + self.id.with(("split", &*path)), + *axis, + split.divider, + &self.style.resize_label, + ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, + ) + .value(split.first_size(), lo..=hi) + .show(ui); + self.register_interaction(ui.ctx(), response.response.id); + if response.delta != 0.0 + && let Some(size) = split.resized(*size, (split.first_size() + response.delta).clamp(lo, hi) - split.first_size(), 0.0) + { + self.output.actions.push(Action::ResizeSplit { path: path.clone(), size }); + } + } + Node::Tabs { panels, active } => self.group(ui, panels, *active, rect, false), + Node::Dock { columns, .. } => { + // Interim rendering: columns side by side, groups stacked evenly. + let total: f32 = columns.iter().map(|c| c.width).sum(); + let mut left = rect.left(); + for column in columns { + let width = if total > 0.0 { rect.width() * column.width / total } else { 0.0 }; + let column_rect = Rect::from_min_max(pos2(left, rect.top()), pos2(left + width, rect.bottom())); + left += width; + self.stacked_groups(ui, &column.groups, column_rect, false); + } + } + Node::Stack { entries } => { + let total_header = (entries.len() as f32 * self.style.tab_height).min(rect.height()); + let remaining = (rect.height() - total_header).max(0.0); + let total_wanted: f64 = entries.iter().filter(|e| e.open).map(|e| f64::from(e.height.unwrap_or(self.style.min_pane).max(1.0))).sum(); + let header = self.style.tab_height.min(rect.height() / entries.len().max(1) as f32); + let mut top = rect.top(); + let mut dividers = Vec::new(); + for (index, entry) in entries.iter().enumerate() { + let share = if entry.open && total_wanted > 0.0 { + (f64::from(remaining) * f64::from(entry.height.unwrap_or(self.style.min_pane).max(1.0)) / total_wanted) as f32 + } else { + 0.0 + }; + let panel_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), (top + header + share).min(rect.bottom()))); + let title_rect = Rect::from_min_max(panel_rect.min, pos2(panel_rect.right(), (top + header).min(panel_rect.bottom()))); + self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect); + let collapse = Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max); + let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click()); + response.widget_info(|| { + egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), entry.open, (self.label)(&entry.panel)) + }); + ui.painter().with_clip_rect(collapse).text( + collapse.center(), + egui::Align2::CENTER_CENTER, + if entry.open { "−" } else { "+" }, + self.style.font.clone(), + self.style.text, + ); + if response.clicked() { + self.output.actions.push(Action::SetStackOpen { panel: entry.panel.clone(), open: !entry.open }); + } + let body_rect = Rect::from_min_max(pos2(rect.left(), title_rect.bottom()), panel_rect.max); + if entry.open { + self.contents(ui, &entry.panel, body_rect); + } + self.targets.push(DropTarget { + anchor: entry.panel.clone(), + rect: panel_rect, + tab_strip: Some(title_rect), + tabs: vec![(entry.panel.clone(), title_rect)], + allow_splits: true, + accepts_tabs: (self.permissions)(&entry.panel).accepts_tabs, + }); + top = panel_rect.bottom(); + if entry.open && remaining > 0.0 { + dividers.push((index, Rect::from_min_max(pos2(rect.left(), top - 1.0), pos2(rect.right(), top + 1.0)).intersect(rect))); + } + } + // Register dividers after the headers so their narrow hit regions win at the + // shared boundary. Closed entries retain their saved sizes and are skipped. + for (index, divider) in dividers { + let Some(first) = entries.get(index) else { continue }; + let Some(second) = entries.iter().skip(index.saturating_add(1)).find(|entry| entry.open) else { continue }; + let a = f64::from(first.height.unwrap_or(self.style.min_pane).max(1.0)); + let b = f64::from(second.height.unwrap_or(self.style.min_pane).max(1.0)); + let scale = f64::from(remaining) / total_wanted; + let first_size = (a * scale) as f32; + let pair_size = ((a + b) * scale) as f32; + let body_limits = |panel: &P| { + let mut limits = (self.limits)(panel); + limits.min.y = limits.min.y.max(self.style.min_pane); + limits.max = limits.max.max(limits.min); + limits + }; + let (lo, hi) = split_bounds(pair_size, SplitAxis::Vertical, body_limits(&first.panel), body_limits(&second.panel)); + let response = ResizeHandle::new( + self.id.with(("stack-resize", &first.panel)), + SplitAxis::Vertical, + divider, + &self.style.resize_label, + ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, + ) + .value(first_size, lo..=hi) + .show(ui); + self.register_interaction(ui.ctx(), response.response.id); + if response.delta != 0.0 && scale > 0.0 { + let delta = f64::from((first_size + response.delta).clamp(lo, hi) - first_size) / scale; + let next_a = (a + delta).clamp((a + b - 1_000_000.0).max(1.0), (a + b - 1.0).min(1_000_000.0)); + self.output.actions.push(Action::ResizeStack { panel: first.panel.clone(), height: Some(next_a as f32) }); + self.output.actions.push(Action::ResizeStack { panel: second.panel.clone(), height: Some((a + b - next_a) as f32) }); + } + } + } + } + } + + pub(super) fn node_limits(&self, node: &Node

) -> PanelLimits { + match node { + Node::Dock { .. } => PanelLimits { min: Vec2::splat(self.style.min_pane), ..PanelLimits::default() }, + Node::Tabs { panels, .. } => { + let mut limits = PanelLimits::default(); + for panel in panels { + let policy = (self.limits)(panel); + limits.min = limits.min.max(policy.min).max(Vec2::splat(self.style.min_pane)); + limits.max = limits.max.min(policy.max); + } + limits.max = limits.max.max(limits.min); + if panels.len() != 1 || panels.first().is_some_and(|p| (self.permissions)(p) != Permissions::PROTECTED) { + limits.min.y = (limits.min.y + self.style.tab_height).min(1_000_000.0); + limits.max.y = (limits.max.y + self.style.tab_height).min(1_000_000.0); + } + limits + } + Node::Stack { entries } => { + let mut limits = PanelLimits::default(); + for entry in entries { + let policy = (self.limits)(&entry.panel); + limits.min.x = limits.min.x.max(policy.min.x).max(self.style.min_pane); + limits.min.y += if entry.open { policy.min.y.max(self.style.min_pane) } else { 0.0 } + self.style.tab_height; + limits.max.x = limits.max.x.min(policy.max.x); + } + limits.min = limits.min.min(Vec2::splat(1_000_000.0)); + limits.max = limits.max.max(limits.min); + limits + } + Node::Split { axis, first, second, .. } => { + let a = self.node_limits(first); + let b = self.node_limits(second); + let limits = match axis { + SplitAxis::Horizontal => PanelLimits { + min: vec2(a.min.x + b.min.x + self.style.gap, a.min.y.max(b.min.y)), + max: vec2(a.max.x + b.max.x + self.style.gap, a.max.y.min(b.max.y)), + }, + SplitAxis::Vertical => PanelLimits { + min: vec2(a.min.x.max(b.min.x), a.min.y + b.min.y + self.style.gap), + max: vec2(a.max.x.min(b.max.x), a.max.y + b.max.y + self.style.gap), + }, + }; + PanelLimits { min: limits.min.min(Vec2::splat(1_000_000.0)), max: limits.max.max(limits.min).min(Vec2::splat(1_000_000.0)) } + } + } + } + + pub(super) fn contents(&mut self, ui: &mut Ui, panel: &P, rect: Rect) { + if !crate::docking::targets::usable(rect) { + return; + } + ui.painter().rect_filled(rect, 0.0, self.style.background); + let mut child = + ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); + child.set_clip_rect(rect.intersect(ui.clip_rect())); + self.content.body(&mut child, panel); + if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.primary_pressed()) { + self.output.focused = Some(panel.clone()); + } + } +} + +pub(super) fn clamp_float(rect: Rect, screen: Rect) -> Rect { + if !crate::docking::targets::usable(screen) { + return rect; + } + let size = rect.size().max(vec2(1.0, 1.0)).min(screen.size()); + let min = rect.min.max(screen.min).min(screen.max - size); + Rect::from_min_size(min, size) +} + +pub(super) fn split_bounds(available: f32, axis: SplitAxis, first: PanelLimits, second: PanelLimits) -> (f32, f32) { + let (a_min, a_max, b_min, b_max) = match axis { + SplitAxis::Horizontal => (first.min.x, first.max.x, second.min.x, second.max.x), + SplitAxis::Vertical => (first.min.y, first.max.y, second.min.y, second.max.y), + }; + let scale = if a_min + b_min > available { available / (a_min + b_min).max(1.0) } else { 1.0 }; + let lo = (a_min * scale).min(available); + let hi = (available - b_min * scale).max(lo).min(available); + let constrained_lo = lo.max(available - b_max); + let constrained_hi = hi.min(a_max); + if constrained_lo <= constrained_hi { (constrained_lo, constrained_hi) } else { (lo, hi) } +} diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs new file mode 100644 index 0000000000..e4e427eda5 --- /dev/null +++ b/crates/ui/src/docking/render/preview.rs @@ -0,0 +1,106 @@ +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Key, Rect, Stroke, StrokeKind}; + +use super::{Renderer, clamp_float}; +use crate::docking::{Action, Drag, GroupDrag, cancel_drag, resolve_drop}; + +impl Renderer<'_, P> { + pub(in crate::docking) fn finish_group_drag(&mut self, ctx: &Context) { + let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("group-drag"))) else { return }; + if !self.layout.floating.iter().any(|g| g.contains(&drag.panel) && g.panels().all(|p| (self.permissions)(p).movable)) { + ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); + return; + } + let (escape, focused, down, released, pointer) = + ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); + // A button release outside the window may never reach egui. + let has_pointer = ctx.input(|i| i.pointer.has_pointer()); + // Touch-up also removes the pointer, but still completes a drop. + let touch_ended = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::End, .. }))); + if escape || !focused || !down || !has_pointer { + cancel_drag::

(ctx, self.id); + if escape || !focused { + self.output.actions.push(Action::MoveFloating { panel: drag.panel, rect: drag.original }); + } else if released + && (has_pointer || touch_ended) + && let Some(pointer) = pointer.filter(|p| p.is_finite()) + && !self.blockers.iter().any(|r| r.contains(pointer)) + { + self.output.group_drop = Some((drag.panel, pointer)); + } + } else if pointer.is_some_and(|p| !self.blockers.iter().any(|r| r.contains(p))) { + self.output.group_drag = Some(drag.panel); + } + } + + pub(in crate::docking) fn finish_drag(&mut self, ctx: &Context) { + let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("drag"))) else { return }; + let (pointer, down, released, focused, gone) = + ctx.input(|i| (i.pointer.interact_pos(), i.pointer.primary_down(), i.pointer.primary_released(), i.focused, !i.pointer.has_pointer())); + // Leaving the window is the drop: on X11 and Windows the release outside never reaches + // egui, so the drag would otherwise stay on the pointer. `interact_pos` still holds the + // last position this frame, and the panel floats there rather than docking at the edge. + let released = released || gone; + let escape = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)); + if escape || !focused || !self.layout.contains(&drag.panel) || (!down && !released) { + cancel_drag::

(ctx, self.id); + return; + } + let Some(pointer) = pointer.filter(|p| p.is_finite()) else { + if released { + cancel_drag::

(ctx, self.id); + } + return; + }; + if self.blockers.iter().any(|rect| rect.contains(pointer)) { + if released { + cancel_drag::

(ctx, self.id); + } + return; + } + let proposal = resolve_drop(&drag.panel, pointer, &self.targets); + if released { + cancel_drag::

(ctx, self.id); + if pointer.distance(drag.origin) < 2.0 { + return; + } + let action = if let Some(proposal) = proposal.filter(|_| !gone) { + Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) + } else if (self.permissions)(&drag.panel).floatable + && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))) + { + let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); + Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }) + } else { + None + }; + if let Some(action) = action { + // Validate the proposed gesture against the same complete snapshot. The app + // still applies it via its own command path after body rendering finishes. + let mut candidate = self.layout.clone(); + if candidate.apply_with_permissions(action.clone(), self.permissions).is_ok() { + self.output.actions.push(action); + self.output.focused = Some(drag.panel); + } + } + return; + } + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, self.id.with("drop-preview"))); + if let Some(proposal) = proposal { + painter.rect( + proposal.preview.shrink(1.0), + 0.0, + self.style.accent.gamma_multiply(0.15), + Stroke::new(2.0, self.style.accent), + StrokeKind::Inside, + ); + if let Some(marker) = proposal.insertion { + painter.rect_filled(marker, 0.0, self.style.accent); + } + } else if (self.permissions)(&drag.panel).floatable { + let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); + painter.rect_stroke(rect, 0.0, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + } + } +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 545bc43285..3d034faf57 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -1,16 +1,11 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Color32, Context, FontId, Id, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, pos2, vec2}; +use egui::{Color32, Context, FontId, Id, Pos2, Rect, Sense, Stroke, Ui, Vec2}; -use crate::{ - layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split_rect}, - tabs, -}; - -use super::{Action, DockError, DropTarget, Layout, Node, Permissions, Placement, resolve_drop}; +use super::{Action, DockError, Layout, Node, Permissions, render::Renderer}; /// Horizontal room around a tab's label, both when measuring its natural width and when cutting it. -const TAB_PADDING: f32 = 24.0; +pub(super) const TAB_PADDING: f32 = 24.0; /// Application-supplied chrome. Body renderers retain their own UI style and contents. #[derive(Clone, Debug)] @@ -59,7 +54,7 @@ impl DockStyle { } } - fn valid(&self) -> bool { + pub(super) fn valid(&self) -> bool { [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size].iter().all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) && self.tab_height > 0.0 && self.font.size > 0.0 @@ -98,7 +93,7 @@ impl Default for PanelLimits { } impl PanelLimits { - fn valid(self) -> bool { + pub(super) fn valid(self) -> bool { self.min.is_finite() && self.max.is_finite() && self.min.x >= 0.0 @@ -111,17 +106,17 @@ impl PanelLimits { } #[derive(Clone)] -struct Drag

{ - panel: P, - origin: Pos2, - source: Rect, - grab: Vec2, +pub(super) struct Drag

{ + pub(super) panel: P, + pub(super) origin: Pos2, + pub(super) source: Rect, + pub(super) grab: Vec2, } #[derive(Clone)] -struct GroupDrag

{ - panel: P, - original: [f32; 4], +pub(super) struct GroupDrag

{ + pub(super) panel: P, + pub(super) original: [f32; 4], } /// Start a docking drag from an application's existing tab/header. Use the same area ID when @@ -335,624 +330,3 @@ impl DockArea

{ renderer.output } } - -struct Renderer<'a, P> { - id: Id, - style: &'a DockStyle, - label: &'a dyn Fn(&P) -> String, - permissions: &'a dyn Fn(&P) -> Permissions, - limits: &'a dyn Fn(&P) -> PanelLimits, - content: &'a mut dyn DockContent

, - activation: Option

, - blockers: Vec, - layout: &'a Layout

, - targets: Vec>, - owned_interactions: Vec, - output: DockOutput

, -} - -impl Renderer<'_, P> { - fn register_interaction(&mut self, ctx: &Context, id: Id) { - // A validated tree has at most 2*MAX_PANELS nodes. Tabs, stack dividers, - // floating grips/corners and splits fit comfortably inside this fixed bound. - const CAP: usize = 8 * super::MAX_PANELS; - if self.owned_interactions.len() < CAP && !self.owned_interactions.contains(&id) { - self.owned_interactions.push(id); - } - // Retain prior-frame controls until return, and publish current controls before - // app callbacks. No Context lock spans a callback or a stop_dragging call. - ctx.data_mut(|d| { - let ids = d.get_temp_mut_or_default::>(self.id.with("owned-interactions")); - if ids.len() < CAP && !ids.contains(&id) { - ids.push(id); - } - }); - } - - fn node(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &mut Vec) { - if !super::targets::usable(rect) { - return; - } - match node { - Node::Split { axis, size, first, second } => { - let Some(wanted) = split_rect(rect, *axis, *size, self.style.gap, 0.0) else { return }; - let (lo, hi) = split_bounds(wanted.available(), *axis, self.node_limits(first), self.node_limits(second)); - let first_size = wanted.first_size().clamp(lo, hi); - let Some(split) = split_rect(rect, *axis, SplitSize::FixedFirst(first_size), self.style.gap, 0.0) else { return }; - path.push(false); - self.node(ui, first, split.first, path); - path.pop(); - path.push(true); - self.node(ui, second, split.second, path); - path.pop(); - // The divider's inner-edge hit margin must win over child scrollbars, just - // as accordion dividers win over the adjacent panel's content. - let response = ResizeHandle::new( - self.id.with(("split", &*path)), - *axis, - split.divider, - &self.style.resize_label, - ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, - ) - .value(split.first_size(), lo..=hi) - .show(ui); - self.register_interaction(ui.ctx(), response.response.id); - if response.delta != 0.0 - && let Some(size) = split.resized(*size, (split.first_size() + response.delta).clamp(lo, hi) - split.first_size(), 0.0) - { - self.output.actions.push(Action::ResizeSplit { path: path.clone(), size }); - } - } - Node::Tabs { panels, active } => self.group(ui, panels, *active, rect, false), - Node::Dock { columns, .. } => { - // Interim rendering: columns side by side, groups stacked evenly. - let total: f32 = columns.iter().map(|c| c.width).sum(); - let mut left = rect.left(); - for column in columns { - let width = if total > 0.0 { rect.width() * column.width / total } else { 0.0 }; - let column_rect = Rect::from_min_max(pos2(left, rect.top()), pos2(left + width, rect.bottom())); - left += width; - self.stacked_groups(ui, &column.groups, column_rect, false); - } - } - Node::Stack { entries } => { - let total_header = (entries.len() as f32 * self.style.tab_height).min(rect.height()); - let remaining = (rect.height() - total_header).max(0.0); - let total_wanted: f64 = entries.iter().filter(|e| e.open).map(|e| f64::from(e.height.unwrap_or(self.style.min_pane).max(1.0))).sum(); - let header = self.style.tab_height.min(rect.height() / entries.len().max(1) as f32); - let mut top = rect.top(); - let mut dividers = Vec::new(); - for (index, entry) in entries.iter().enumerate() { - let share = if entry.open && total_wanted > 0.0 { - (f64::from(remaining) * f64::from(entry.height.unwrap_or(self.style.min_pane).max(1.0)) / total_wanted) as f32 - } else { - 0.0 - }; - let panel_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), (top + header + share).min(rect.bottom()))); - let title_rect = Rect::from_min_max(panel_rect.min, pos2(panel_rect.right(), (top + header).min(panel_rect.bottom()))); - self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect); - let collapse = Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max); - let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click()); - response.widget_info(|| { - egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), entry.open, (self.label)(&entry.panel)) - }); - ui.painter().with_clip_rect(collapse).text( - collapse.center(), - egui::Align2::CENTER_CENTER, - if entry.open { "−" } else { "+" }, - self.style.font.clone(), - self.style.text, - ); - if response.clicked() { - self.output.actions.push(Action::SetStackOpen { panel: entry.panel.clone(), open: !entry.open }); - } - let body_rect = Rect::from_min_max(pos2(rect.left(), title_rect.bottom()), panel_rect.max); - if entry.open { - self.contents(ui, &entry.panel, body_rect); - } - self.targets.push(DropTarget { - anchor: entry.panel.clone(), - rect: panel_rect, - tab_strip: Some(title_rect), - tabs: vec![(entry.panel.clone(), title_rect)], - allow_splits: true, - accepts_tabs: (self.permissions)(&entry.panel).accepts_tabs, - }); - top = panel_rect.bottom(); - if entry.open && remaining > 0.0 { - dividers.push((index, Rect::from_min_max(pos2(rect.left(), top - 1.0), pos2(rect.right(), top + 1.0)).intersect(rect))); - } - } - // Register dividers after the headers so their narrow hit regions win at the - // shared boundary. Closed entries retain their saved sizes and are skipped. - for (index, divider) in dividers { - let Some(first) = entries.get(index) else { continue }; - let Some(second) = entries.iter().skip(index.saturating_add(1)).find(|entry| entry.open) else { continue }; - let a = f64::from(first.height.unwrap_or(self.style.min_pane).max(1.0)); - let b = f64::from(second.height.unwrap_or(self.style.min_pane).max(1.0)); - let scale = f64::from(remaining) / total_wanted; - let first_size = (a * scale) as f32; - let pair_size = ((a + b) * scale) as f32; - let body_limits = |panel: &P| { - let mut limits = (self.limits)(panel); - limits.min.y = limits.min.y.max(self.style.min_pane); - limits.max = limits.max.max(limits.min); - limits - }; - let (lo, hi) = split_bounds(pair_size, SplitAxis::Vertical, body_limits(&first.panel), body_limits(&second.panel)); - let response = ResizeHandle::new( - self.id.with(("stack-resize", &first.panel)), - SplitAxis::Vertical, - divider, - &self.style.resize_label, - ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, - ) - .value(first_size, lo..=hi) - .show(ui); - self.register_interaction(ui.ctx(), response.response.id); - if response.delta != 0.0 && scale > 0.0 { - let delta = f64::from((first_size + response.delta).clamp(lo, hi) - first_size) / scale; - let next_a = (a + delta).clamp((a + b - 1_000_000.0).max(1.0), (a + b - 1.0).min(1_000_000.0)); - self.output.actions.push(Action::ResizeStack { panel: first.panel.clone(), height: Some(next_a as f32) }); - self.output.actions.push(Action::ResizeStack { panel: second.panel.clone(), height: Some((a + b - next_a) as f32) }); - } - } - } - } - } - - /// Groups stacked top to bottom in equal shares of `rect`. - fn stacked_groups(&mut self, ui: &mut Ui, groups: &[super::Group

], rect: Rect, floating: bool) { - let share = rect.height() / groups.len().max(1) as f32; - for (index, group) in groups.iter().enumerate() { - let top = rect.top() + share * index as f32; - let group_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + share)); - self.group(ui, &group.panels, group.active, group_rect, floating); - } - } - - fn node_limits(&self, node: &Node

) -> PanelLimits { - match node { - Node::Dock { .. } => PanelLimits { min: Vec2::splat(self.style.min_pane), ..PanelLimits::default() }, - Node::Tabs { panels, .. } => { - let mut limits = PanelLimits::default(); - for panel in panels { - let policy = (self.limits)(panel); - limits.min = limits.min.max(policy.min).max(Vec2::splat(self.style.min_pane)); - limits.max = limits.max.min(policy.max); - } - limits.max = limits.max.max(limits.min); - if panels.len() != 1 || panels.first().is_some_and(|p| (self.permissions)(p) != Permissions::PROTECTED) { - limits.min.y = (limits.min.y + self.style.tab_height).min(1_000_000.0); - limits.max.y = (limits.max.y + self.style.tab_height).min(1_000_000.0); - } - limits - } - Node::Stack { entries } => { - let mut limits = PanelLimits::default(); - for entry in entries { - let policy = (self.limits)(&entry.panel); - limits.min.x = limits.min.x.max(policy.min.x).max(self.style.min_pane); - limits.min.y += if entry.open { policy.min.y.max(self.style.min_pane) } else { 0.0 } + self.style.tab_height; - limits.max.x = limits.max.x.min(policy.max.x); - } - limits.min = limits.min.min(Vec2::splat(1_000_000.0)); - limits.max = limits.max.max(limits.min); - limits - } - Node::Split { axis, first, second, .. } => { - let a = self.node_limits(first); - let b = self.node_limits(second); - let limits = match axis { - SplitAxis::Horizontal => PanelLimits { - min: vec2(a.min.x + b.min.x + self.style.gap, a.min.y.max(b.min.y)), - max: vec2(a.max.x + b.max.x + self.style.gap, a.max.y.min(b.max.y)), - }, - SplitAxis::Vertical => PanelLimits { - min: vec2(a.min.x.max(b.min.x), a.min.y + b.min.y + self.style.gap), - max: vec2(a.max.x.min(b.max.x), a.max.y + b.max.y + self.style.gap), - }, - }; - PanelLimits { min: limits.min.min(Vec2::splat(1_000_000.0)), max: limits.max.max(limits.min).min(Vec2::splat(1_000_000.0)) } - } - } - } - - fn contents(&mut self, ui: &mut Ui, panel: &P, rect: Rect) { - if !super::targets::usable(rect) { - return; - } - ui.painter().rect_filled(rect, 0.0, self.style.background); - let mut child = - ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); - child.set_clip_rect(rect.intersect(ui.clip_rect())); - self.content.body(&mut child, panel); - if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.primary_pressed()) { - self.output.focused = Some(panel.clone()); - } - } - - fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, rect: Rect, floating: bool) { - let Some(selected) = panels.get(active) else { return }; - let policy = (self.permissions)(selected); - let bare = panels.len() == 1 && policy == Permissions::PROTECTED; - if bare { - self.contents(ui, selected, rect); - self.targets.push(DropTarget { - anchor: selected.clone(), - rect, - tab_strip: None, - tabs: Vec::new(), - allow_splits: !floating, - accepts_tabs: false, - }); - return; - } - let mut strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom()))); - ui.painter().rect_filled(strip, 0.0, self.style.tab_background); - if floating { - let grip = Rect::from_min_max(strip.min, pos2((strip.left() + 12.0).min(strip.right()), strip.bottom())); - let response = ui.interact(grip, self.id.with(("move-group", panels.first())), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); - if panels.iter().all(|p| (self.permissions)(p).movable) - && response.drag_started() - && let Some(first) = panels.first() - { - ui.ctx().data_mut(|d| { - d.insert_temp( - self.id.with("group-drag"), - GroupDrag { panel: first.clone(), original: [rect.left(), rect.top(), rect.width(), rect.height()] }, - ) - }); - } - if panels.iter().all(|p| (self.permissions)(p).movable) - && response.dragged() - && ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))).is_some() - && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) - { - let moved = clamp_float(rect.translate(ui.input(|i| i.pointer.delta())), ui.ctx().content_rect()); - if let Some(first) = panels.first() { - self.output - .actions - .push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); - } - } - ui.painter().line_segment([grip.center() - vec2(0.0, 5.0), grip.center() + vec2(0.0, 5.0)], self.style.border); - strip.min.x = grip.right(); - } - let requested = self.content.group_header_width(panels, selected, floating); - let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 }; - if header_width > 0.0 { - let header = Rect::from_min_max(pos2(strip.right() - header_width, strip.top()), strip.max); - let mut child = ui.new_child(UiBuilder::new().id(self.id.with(("header", selected))).max_rect(header)); - child.set_clip_rect(header.intersect(ui.clip_rect())); - self.content.group_header(&mut child, panels, selected, floating); - } - let widths: Vec = panels - .iter() - .map(|p| { - self.content - .label(ui, p, &(self.label)(p), &self.style.font, self.style.text) - .into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, self.style.font.clone()) - .size() - .x - + TAB_PADDING - }) - .collect(); - let fit = tabs::fit(&widths, active, (strip.width() - header_width).max(0.0), 40.0, 22.0); - let mut x = strip.left(); - let mut targets = Vec::new(); - for (index, width) in &fit.shown { - let Some(panel) = panels.get(*index) else { continue }; - let tab = Rect::from_min_size(pos2(x, strip.top()), vec2(*width, strip.height())); - self.tab(ui, panel, tab, *index == active, rect); - targets.push((panel.clone(), tab)); - x += width; - } - if !fit.overflow.is_empty() && fit.overflow_width > 0.0 { - let overflow = Rect::from_min_size(pos2(x, strip.top()), vec2(fit.overflow_width, strip.height())); - let response = ui.interact(overflow, self.id.with(("overflow", selected)), Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.panels_label)); - ui.painter().with_clip_rect(overflow).text(overflow.center(), egui::Align2::CENTER_CENTER, "…", self.style.font.clone(), self.style.text); - egui::Popup::menu(&response).show(|ui| { - egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { - for index in &fit.overflow { - if let Some(panel) = panels.get(*index) - && self.menu_label(ui, panel).clicked() - { - self.output.actions.push(Action::Activate { panel: panel.clone() }); - self.output.focused = Some(panel.clone()); - ui.close(); - } - } - }); - }); - } - // Include hidden tab identities for source-group detection without creating hit areas. - for panel in panels { - if !targets.iter().any(|(p, _)| p == panel) { - targets.push((panel.clone(), Rect::NOTHING)); - } - } - self.targets.push(DropTarget { - anchor: selected.clone(), - rect, - tab_strip: Some(strip), - tabs: targets, - allow_splits: !floating, - accepts_tabs: policy.accepts_tabs, - }); - self.contents(ui, selected, Rect::from_min_max(pos2(rect.left(), strip.bottom()), rect.max)); - ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); - } - - fn menu_label(&mut self, ui: &mut Ui, panel: &P) -> egui::Response { - let logical = (self.label)(panel); - let text = self.content.label(ui, panel, &logical, &self.style.font, self.style.text); - let response = ui.button(text); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); - response - } - - fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect) { - let policy = (self.permissions)(panel); - let label = (self.label)(panel); - let color = if active { self.style.text } else { self.style.inactive_text }; - // A tab squeezed below its natural width cuts its label with '…' inside the padding its - // natural width was measured with, instead of letting it run under its neighbours. - let galley = self.content.label(ui, panel, &label, &self.style.font, color).into_galley( - ui, - Some(egui::TextWrapMode::Truncate), - (rect.width() - TAB_PADDING).max(0.0), - self.style.font.clone(), - ); - let elided = galley.elided; - let response = tabs::Tab::new(self.id.with(("tab", panel)), &label, active) - .sense(if policy.movable { Sense::click_and_drag() } else { Sense::click() }) - .focus_stroke(Stroke::new(1.0, self.style.accent)) - .show_at(ui, rect, |ui, response| { - let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); - painter.rect_filled(rect, 0.0, if active || response.hovered() { self.style.active_background } else { self.style.tab_background }); - painter.galley(rect.center() - galley.size() * 0.5, galley.clone(), color); - }); - let response = if elided { response.on_hover_text(&label) } else { response }; - self.register_interaction(ui.ctx(), response.id); - if response.clicked() { - self.output.actions.push(Action::Activate { panel: panel.clone() }); - self.output.focused = Some(panel.clone()); - } - if policy.movable && response.drag_started() { - begin_drag(ui.ctx(), self.id, panel.clone(), group); - } - response.context_menu(|ui| { - self.content.panel_menu(ui, panel); - if policy.movable && policy.floatable { - let text = self.content.action_label(ui, &self.style.float_label, &self.style.font, self.style.text); - let response = ui.button(text); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.float_label)); - if response.clicked() { - let rect = clamp_float(group.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); - self.output.actions.push(Action::Float { panel: panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }); - ui.close(); - } - } - if policy.movable && !self.layout.move_targets(panel, self.permissions).is_empty() { - let text = self.content.action_label(ui, &self.style.move_label, &self.style.font, self.style.text); - let response = ui.menu_button(text, |ui| { - egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { - for target in self.layout.move_targets(panel, self.permissions) { - if self.menu_label(ui, target).clicked() { - self.output.actions.push(Action::Move { - panel: panel.clone(), - anchor: target.clone(), - placement: Placement::Tab { before: None }, - }); - ui.close(); - } - } - }); - }); - response.response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); - } - if policy.closable { - let text = self.content.action_label(ui, &self.style.close_label, &self.style.font, self.style.text); - let response = ui.button(text); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.close_label)); - if response.clicked() { - self.output.actions.push(Action::Close { panel: panel.clone() }); - ui.close(); - } - } - }); - } - - fn floating(&mut self, ctx: &Context) { - let screen = ctx.content_rect(); - if !super::targets::usable(screen) { - return; - } - let layers = ctx.memory(|memory| memory.layer_ids().collect::>()); - let mut groups: Vec<_> = self.layout.floating.iter().collect(); - groups.sort_by_key(|group| { - let id = group.panels().next().map(|panel| self.id.with(("floating", panel))); - layers.iter().position(|layer| Some(layer.id) == id).unwrap_or(usize::MAX) - }); - for group in groups { - let Some(first) = group.panels().next() else { continue }; - let [x, y, width, height] = group.rect; - let limits = self.node_limits(&Node::Tabs { panels: group.panels().cloned().collect(), active: 0 }); - let size = vec2(width, height).max(limits.min).min(limits.max); - let rect = clamp_float(Rect::from_min_size(pos2(x, y), size), screen); - let id = self.id.with(("floating", first)); - if self.activation.as_ref().is_some_and(|panel| group.contains(panel)) { - ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); - ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); - self.output.focused = self.activation.clone(); - } - egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).constrain_to(screen).show(ctx, |ui| { - ui.set_min_size(rect.size()); - let rect = Rect::from_min_size(ui.min_rect().min, rect.size()); - ui.allocate_rect(rect, Sense::hover()); - self.stacked_groups(ui, &group.groups, rect, true); - let corner = Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max); - let response = ui.interact(corner, id.with("resize"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeNwSe); - self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.resize_window_label)); - if response.drag_started() { - response.request_focus(); - } - let mut delta = if response.dragged() { ui.input(|i| i.pointer.delta()) } else { Vec2::ZERO }; - if response.has_focus() { - ui.memory_mut(|memory| { - memory.set_focus_lock_filter( - response.id, - egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }, - ) - }); - ui.input_mut(|input| { - if input.consume_key(egui::Modifiers::NONE, Key::ArrowLeft) { - delta.x -= 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowRight) { - delta.x += 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowUp) { - delta.y -= 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowDown) { - delta.y += 8.0; - } - }); - } - if response.enabled() && delta != Vec2::ZERO { - let size = (rect.size() + delta).max(limits.min.max(vec2(40.0, self.style.tab_height + 20.0))).min(limits.max).min(screen.size()); - self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [rect.left(), rect.top(), size.x, size.y] }); - } - if response.hovered() || response.dragged() || response.has_focus() { - ui.painter().line_segment([corner.left_bottom(), corner.right_top()], Stroke::new(2.0, self.style.accent)); - } - }); - } - } - - fn finish_group_drag(&mut self, ctx: &Context) { - let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("group-drag"))) else { return }; - if !self.layout.floating.iter().any(|g| g.contains(&drag.panel) && g.panels().all(|p| (self.permissions)(p).movable)) { - ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); - return; - } - let (escape, focused, down, released, pointer) = - ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); - // A button release outside the window may never reach egui. - let has_pointer = ctx.input(|i| i.pointer.has_pointer()); - // Touch-up also removes the pointer, but still completes a drop. - let touch_ended = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::End, .. }))); - if escape || !focused || !down || !has_pointer { - cancel_drag::

(ctx, self.id); - if escape || !focused { - self.output.actions.push(Action::MoveFloating { panel: drag.panel, rect: drag.original }); - } else if released - && (has_pointer || touch_ended) - && let Some(pointer) = pointer.filter(|p| p.is_finite()) - && !self.blockers.iter().any(|r| r.contains(pointer)) - { - self.output.group_drop = Some((drag.panel, pointer)); - } - } else if pointer.is_some_and(|p| !self.blockers.iter().any(|r| r.contains(p))) { - self.output.group_drag = Some(drag.panel); - } - } - - fn finish_drag(&mut self, ctx: &Context) { - let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("drag"))) else { return }; - let (pointer, down, released, focused, gone) = - ctx.input(|i| (i.pointer.interact_pos(), i.pointer.primary_down(), i.pointer.primary_released(), i.focused, !i.pointer.has_pointer())); - // Leaving the window is the drop: on X11 and Windows the release outside never reaches - // egui, so the drag would otherwise stay on the pointer. `interact_pos` still holds the - // last position this frame, and the panel floats there rather than docking at the edge. - let released = released || gone; - let escape = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)); - if escape || !focused || !self.layout.contains(&drag.panel) || (!down && !released) { - cancel_drag::

(ctx, self.id); - return; - } - let Some(pointer) = pointer.filter(|p| p.is_finite()) else { - if released { - cancel_drag::

(ctx, self.id); - } - return; - }; - if self.blockers.iter().any(|rect| rect.contains(pointer)) { - if released { - cancel_drag::

(ctx, self.id); - } - return; - } - let proposal = resolve_drop(&drag.panel, pointer, &self.targets); - if released { - cancel_drag::

(ctx, self.id); - if pointer.distance(drag.origin) < 2.0 { - return; - } - let action = if let Some(proposal) = proposal.filter(|_| !gone) { - Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) - } else if (self.permissions)(&drag.panel).floatable - && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))) - { - let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); - Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }) - } else { - None - }; - if let Some(action) = action { - // Validate the proposed gesture against the same complete snapshot. The app - // still applies it via its own command path after body rendering finishes. - let mut candidate = self.layout.clone(); - if candidate.apply_with_permissions(action.clone(), self.permissions).is_ok() { - self.output.actions.push(action); - self.output.focused = Some(drag.panel); - } - } - return; - } - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, self.id.with("drop-preview"))); - if let Some(proposal) = proposal { - painter.rect( - proposal.preview.shrink(1.0), - 0.0, - self.style.accent.gamma_multiply(0.15), - Stroke::new(2.0, self.style.accent), - StrokeKind::Inside, - ); - if let Some(marker) = proposal.insertion { - painter.rect_filled(marker, 0.0, self.style.accent); - } - } else if (self.permissions)(&drag.panel).floatable { - let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); - painter.rect_stroke(rect, 0.0, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); - } - } -} - -fn clamp_float(rect: Rect, screen: Rect) -> Rect { - if !super::targets::usable(screen) { - return rect; - } - let size = rect.size().max(vec2(1.0, 1.0)).min(screen.size()); - let min = rect.min.max(screen.min).min(screen.max - size); - Rect::from_min_size(min, size) -} - -fn split_bounds(available: f32, axis: SplitAxis, first: PanelLimits, second: PanelLimits) -> (f32, f32) { - let (a_min, a_max, b_min, b_max) = match axis { - SplitAxis::Horizontal => (first.min.x, first.max.x, second.min.x, second.max.x), - SplitAxis::Vertical => (first.min.y, first.max.y, second.min.y, second.max.y), - }; - let scale = if a_min + b_min > available { available / (a_min + b_min).max(1.0) } else { 1.0 }; - let lo = (a_min * scale).min(available); - let hi = (available - b_min * scale).max(lo).min(available); - let constrained_lo = lo.max(available - b_max); - let constrained_hi = hi.min(a_max); - if constrained_lo <= constrained_hi { (constrained_lo, constrained_hi) } else { (lo, hi) } -} From 0784873c068d841b87bae83893e95043ef2b5240 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:42:49 +0000 Subject: [PATCH 09/94] docking: per-panel policy on DockContent and DockArea::show_content DockContent gains default methods for the logical label, permissions, limits, floating size, icon, native-window permission, bare panels and a host drop hook. show_content reads all of them from the content; the closures passed to the older show functions override the label, permission and limit defaults. floating_size, resolve_drag, DropRequest and DropFeedback are ported from storytold/craft-libs#110 by @Zenodeon. Co-authored-by: Zenodeon --- crates/ui/src/docking/mod.rs | 2 +- crates/ui/src/docking/render/group.rs | 20 ++-- crates/ui/src/docking/render/mod.rs | 29 ++++-- crates/ui/src/docking/render/preview.rs | 8 +- crates/ui/src/docking/surface.rs | 126 ++++++++++++++++++++++-- 5 files changed, 155 insertions(+), 30 deletions(-) diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index b47dd39d25..b08872b954 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -14,7 +14,7 @@ mod workspace; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; -pub use surface::{DockArea, DockContent, DockOutput, DockStyle, PanelLimits, begin_drag, cancel_drag}; +pub use surface::{DockArea, DockContent, DockOutput, DockStyle, DropFeedback, DropRequest, PanelLimits, begin_drag, cancel_drag}; pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect}; pub use workspace::Workspace; diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 850a22aaa9..3dca5511ef 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -19,7 +19,7 @@ impl Renderer<'_, P> { pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, rect: Rect, floating: bool) { let Some(selected) = panels.get(active) else { return }; - let policy = (self.permissions)(selected); + let policy = self.permissions(selected); let bare = panels.len() == 1 && policy == Permissions::PROTECTED; if bare { self.contents(ui, selected, rect); @@ -40,7 +40,7 @@ impl Renderer<'_, P> { let response = ui.interact(grip, self.id.with(("move-group", panels.first())), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); self.register_interaction(ui.ctx(), response.id); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); - if panels.iter().all(|p| (self.permissions)(p).movable) + if panels.iter().all(|p| self.permissions(p).movable) && response.drag_started() && let Some(first) = panels.first() { @@ -51,7 +51,7 @@ impl Renderer<'_, P> { ) }); } - if panels.iter().all(|p| (self.permissions)(p).movable) + if panels.iter().all(|p| self.permissions(p).movable) && response.dragged() && ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))).is_some() && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) @@ -78,7 +78,7 @@ impl Renderer<'_, P> { .iter() .map(|p| { self.content - .label(ui, p, &(self.label)(p), &self.style.font, self.style.text) + .label(ui, p, &self.label_of(p), &self.style.font, self.style.text) .into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, self.style.font.clone()) .size() .x @@ -133,7 +133,7 @@ impl Renderer<'_, P> { } pub(super) fn menu_label(&mut self, ui: &mut Ui, panel: &P) -> egui::Response { - let logical = (self.label)(panel); + let logical = self.label_of(panel); let text = self.content.label(ui, panel, &logical, &self.style.font, self.style.text); let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); @@ -141,8 +141,8 @@ impl Renderer<'_, P> { } pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect) { - let policy = (self.permissions)(panel); - let label = (self.label)(panel); + let policy = self.permissions(panel); + let label = self.label_of(panel); let color = if active { self.style.text } else { self.style.inactive_text }; // A tab squeezed below its natural width cuts its label with '…' inside the padding its // natural width was measured with, instead of letting it run under its neighbours. @@ -182,11 +182,13 @@ impl Renderer<'_, P> { ui.close(); } } - if policy.movable && !self.layout.move_targets(panel, self.permissions).is_empty() { + let targets: Vec

= + if policy.movable { self.layout.move_targets(panel, |p| self.permissions(p)).into_iter().cloned().collect() } else { Vec::new() }; + if !targets.is_empty() { let text = self.content.action_label(ui, &self.style.move_label, &self.style.font, self.style.text); let response = ui.menu_button(text, |ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { - for target in self.layout.move_targets(panel, self.permissions) { + for target in &targets { if self.menu_label(ui, target).clicked() { self.output.actions.push(Action::Move { panel: panel.clone(), diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index c5a031f942..b0c62a5273 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -13,19 +13,30 @@ mod preview; pub(super) struct Renderer<'a, P> { pub(super) id: Id, pub(super) style: &'a DockStyle, - pub(super) label: &'a dyn Fn(&P) -> String, - pub(super) permissions: &'a dyn Fn(&P) -> Permissions, - pub(super) limits: &'a dyn Fn(&P) -> PanelLimits, pub(super) content: &'a mut dyn DockContent

, pub(super) activation: Option

, pub(super) blockers: Vec, pub(super) layout: &'a Layout

, + /// The docked area, for host drop requests. + pub(super) workspace: Rect, pub(super) targets: Vec>, pub(super) owned_interactions: Vec, pub(super) output: DockOutput

, } impl Renderer<'_, P> { + pub(super) fn label_of(&self, panel: &P) -> String { + self.content.logical_label(panel) + } + + pub(super) fn permissions(&self, panel: &P) -> Permissions { + self.content.permissions(panel) + } + + pub(super) fn limits(&self, panel: &P) -> PanelLimits { + self.content.limits(panel) + } + pub(super) fn register_interaction(&mut self, ctx: &Context, id: Id) { // A validated tree has at most 2*MAX_PANELS nodes. Tabs, stack dividers, // floating grips/corners and splits fit comfortably inside this fixed bound. @@ -108,7 +119,7 @@ impl Renderer<'_, P> { let collapse = Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max); let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click()); response.widget_info(|| { - egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), entry.open, (self.label)(&entry.panel)) + egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), entry.open, self.label_of(&entry.panel)) }); ui.painter().with_clip_rect(collapse).text( collapse.center(), @@ -130,7 +141,7 @@ impl Renderer<'_, P> { tab_strip: Some(title_rect), tabs: vec![(entry.panel.clone(), title_rect)], allow_splits: true, - accepts_tabs: (self.permissions)(&entry.panel).accepts_tabs, + accepts_tabs: self.permissions(&entry.panel).accepts_tabs, }); top = panel_rect.bottom(); if entry.open && remaining > 0.0 { @@ -148,7 +159,7 @@ impl Renderer<'_, P> { let first_size = (a * scale) as f32; let pair_size = ((a + b) * scale) as f32; let body_limits = |panel: &P| { - let mut limits = (self.limits)(panel); + let mut limits = self.limits(panel); limits.min.y = limits.min.y.max(self.style.min_pane); limits.max = limits.max.max(limits.min); limits @@ -181,12 +192,12 @@ impl Renderer<'_, P> { Node::Tabs { panels, .. } => { let mut limits = PanelLimits::default(); for panel in panels { - let policy = (self.limits)(panel); + let policy = self.limits(panel); limits.min = limits.min.max(policy.min).max(Vec2::splat(self.style.min_pane)); limits.max = limits.max.min(policy.max); } limits.max = limits.max.max(limits.min); - if panels.len() != 1 || panels.first().is_some_and(|p| (self.permissions)(p) != Permissions::PROTECTED) { + if panels.len() != 1 || panels.first().is_some_and(|p| self.permissions(p) != Permissions::PROTECTED) { limits.min.y = (limits.min.y + self.style.tab_height).min(1_000_000.0); limits.max.y = (limits.max.y + self.style.tab_height).min(1_000_000.0); } @@ -195,7 +206,7 @@ impl Renderer<'_, P> { Node::Stack { entries } => { let mut limits = PanelLimits::default(); for entry in entries { - let policy = (self.limits)(&entry.panel); + let policy = self.limits(&entry.panel); limits.min.x = limits.min.x.max(policy.min.x).max(self.style.min_pane); limits.min.y += if entry.open { policy.min.y.max(self.style.min_pane) } else { 0.0 } + self.style.tab_height; limits.max.x = limits.max.x.min(policy.max.x); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index e4e427eda5..0fb075e1c9 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -8,7 +8,7 @@ use crate::docking::{Action, Drag, GroupDrag, cancel_drag, resolve_drop}; impl Renderer<'_, P> { pub(in crate::docking) fn finish_group_drag(&mut self, ctx: &Context) { let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("group-drag"))) else { return }; - if !self.layout.floating.iter().any(|g| g.contains(&drag.panel) && g.panels().all(|p| (self.permissions)(p).movable)) { + if !self.layout.floating.iter().any(|g| g.contains(&drag.panel) && g.panels().all(|p| self.permissions(p).movable)) { ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); return; } @@ -67,7 +67,7 @@ impl Renderer<'_, P> { } let action = if let Some(proposal) = proposal.filter(|_| !gone) { Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) - } else if (self.permissions)(&drag.panel).floatable + } else if self.permissions(&drag.panel).floatable && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))) { let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); @@ -79,7 +79,7 @@ impl Renderer<'_, P> { // Validate the proposed gesture against the same complete snapshot. The app // still applies it via its own command path after body rendering finishes. let mut candidate = self.layout.clone(); - if candidate.apply_with_permissions(action.clone(), self.permissions).is_ok() { + if candidate.apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() { self.output.actions.push(action); self.output.focused = Some(drag.panel); } @@ -98,7 +98,7 @@ impl Renderer<'_, P> { if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); } - } else if (self.permissions)(&drag.panel).floatable { + } else if self.permissions(&drag.panel).floatable { let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); painter.rect_stroke(rect, 0.0, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 3d034faf57..3578579b9a 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -2,7 +2,7 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Color32, Context, FontId, Id, Pos2, Rect, Sense, Stroke, Ui, Vec2}; -use super::{Action, DockError, Layout, Node, Permissions, render::Renderer}; +use super::{Action, DockError, DropTarget, Layout, Node, Permissions, render::Renderer}; /// Horizontal room around a tab's label, both when measuring its natural width and when cutting it. pub(super) const TAB_PADDING: f32 = 24.0; @@ -149,10 +149,47 @@ pub fn cancel_drag(ctx: &Context, area_id: Id) } } -/// One mutable application adapter owns bodies, menus and shaped text, avoiding competing -/// mutable closures. Logical labels remain separate and are used for tab accessibility. +/// One mutable application adapter owns bodies, menus, shaped text and per-panel policy, +/// avoiding competing mutable closures. Logical labels are used for tab accessibility. +/// [`DockArea::show_content`] reads every policy from here; the closures passed to the older +/// `show*` functions override `logical_label`, `permissions` and `limits`. pub trait DockContent

{ fn body(&mut self, ui: &mut Ui, panel: &P); + /// Plain text name for accessibility, menus and the default visual label. + fn logical_label(&self, panel: &P) -> String + where + P: Debug, + { + format!("{panel:?}") + } + fn permissions(&self, _panel: &P) -> Permissions { + Permissions::default() + } + fn limits(&self, _panel: &P) -> PanelLimits { + PanelLimits::default() + } + /// Preferred floating size, independent of the current dock geometry. `None` falls back + /// to the panel limits. + fn floating_size(&self, _panel: &P) -> Option { + None + } + fn icon(&self, _panel: &P) -> Option> { + None + } + /// Whether the panel may move to a native OS window (feature `native-windows`). + fn allow_native(&self, _panel: &P) -> bool { + false + } + /// A lone bare panel draws no tab strip and no drag bar, like a lone protected panel. It + /// still moves by command and menu. + fn bare(&self, _panel: &P) -> bool { + false + } + /// Host-owned drop resolution for targets the renderer cannot know about. Returning + /// feedback consumes the gesture, including no-op targets; the renderer then emits no move. + fn resolve_drag(&mut self, _ctx: &Context, _style: &DockStyle, _request: &DropRequest<'_, P>) -> Option { + None + } fn label(&mut self, _ui: &Ui, _panel: &P, logical: &str, _font: &FontId, _color: Color32) -> egui::WidgetText { logical.into() } @@ -168,6 +205,24 @@ pub trait DockContent

{ fn group_header(&mut self, _ui: &mut Ui, _panels: &[P], _active: &P, _floating: bool) {} } +/// Host-owned drop resolution request, see [`DockContent::resolve_drag`]. +pub struct DropRequest<'a, P> { + pub panel: &'a P, + pub pointer: Pos2, + pub targets: &'a [DropTarget

], + pub floating_rect: Option, + pub whole_group: bool, + pub released: bool, + pub workspace: Rect, + pub screen: Rect, +} + +#[derive(Clone, Debug, Default)] +pub struct DropFeedback { + pub preview: Option, + pub insertion: Option, +} + struct BodyContent(F); impl DockContent

for BodyContent { fn body(&mut self, ui: &mut Ui, panel: &P) { @@ -175,6 +230,59 @@ impl DockContent

for BodyContent { } } +/// The older `show*` closures in front of an application's content. +struct Overrides<'a, P, C: ?Sized> { + label: &'a dyn Fn(&P) -> String, + permissions: &'a dyn Fn(&P) -> Permissions, + limits: &'a dyn Fn(&P) -> PanelLimits, + inner: &'a mut C, +} + +impl + ?Sized> DockContent

for Overrides<'_, P, C> { + fn body(&mut self, ui: &mut Ui, panel: &P) { + self.inner.body(ui, panel); + } + fn logical_label(&self, panel: &P) -> String { + (self.label)(panel) + } + fn permissions(&self, panel: &P) -> Permissions { + (self.permissions)(panel) + } + fn limits(&self, panel: &P) -> PanelLimits { + (self.limits)(panel) + } + fn floating_size(&self, panel: &P) -> Option { + self.inner.floating_size(panel) + } + fn icon(&self, panel: &P) -> Option> { + self.inner.icon(panel) + } + fn allow_native(&self, panel: &P) -> bool { + self.inner.allow_native(panel) + } + fn bare(&self, panel: &P) -> bool { + self.inner.bare(panel) + } + fn resolve_drag(&mut self, ctx: &Context, style: &DockStyle, request: &DropRequest<'_, P>) -> Option { + self.inner.resolve_drag(ctx, style, request) + } + fn label(&mut self, ui: &Ui, panel: &P, logical: &str, font: &FontId, color: Color32) -> egui::WidgetText { + self.inner.label(ui, panel, logical, font, color) + } + fn action_label(&mut self, ui: &Ui, logical: &str, font: &FontId, color: Color32) -> egui::WidgetText { + self.inner.action_label(ui, logical, font, color) + } + fn panel_menu(&mut self, ui: &mut Ui, panel: &P) { + self.inner.panel_menu(ui, panel); + } + fn group_header_width(&self, panels: &[P], active: &P, floating: bool) -> f32 { + self.inner.group_header_width(panels, active, floating) + } + fn group_header(&mut self, ui: &mut Ui, panels: &[P], active: &P, floating: bool) { + self.inner.group_header(ui, panels, active, floating); + } +} + /// Optional renderer for applications without an existing docking surface. Apps with custom /// chrome can instead use the model, target resolver and resize/tab primitives independently. pub struct DockArea

{ @@ -296,25 +404,29 @@ impl DockArea

{ limits: impl Fn(&P) -> PanelLimits, content: &mut impl DockContent

, ) -> DockOutput

{ + let mut content = Overrides { label: &label, permissions: &permissions, limits: &limits, inner: content }; + self.show_content(ui, layout, style, &mut content) + } + + /// Render with every label, policy and size from `content`. + pub fn show_content(self, ui: &mut Ui, layout: &Layout

, style: &DockStyle, content: &mut dyn DockContent

) -> DockOutput

{ let rect = ui.available_rect_before_wrap(); if let Err(error) = layout.validate() { cancel_drag::

(ui.ctx(), self.id); return DockOutput { error: Some(error), ..Default::default() }; } - if !style.valid() || !super::targets::usable(rect) || layout.panels().into_iter().any(|p| !limits(p).valid()) { + if !style.valid() || !super::targets::usable(rect) || layout.panels().into_iter().any(|p| !content.limits(p).valid()) { cancel_drag::

(ui.ctx(), self.id); return DockOutput { error: Some(DockError::InvalidGeometry), ..Default::default() }; } let mut renderer = Renderer { id: self.id, style, - label: &label, - permissions: &permissions, - limits: &limits, content, activation: self.activation, blockers: self.blockers, layout, + workspace: rect, targets: Vec::new(), owned_interactions: Vec::new(), output: DockOutput::default(), From 9777c291c354ce6f696922532d38101e65021d67 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:45:52 +0000 Subject: [PATCH 10/94] docking: anchored floating resize, no-op drops and the host drop hook Floating windows resize from both side edges, the bottom edge and both bottom corners; the opposite edges stay fixed and a resize past the viewport waits for the pointer to come back. A release over a tab's current slot or its own group body is a no-op instead of a float. Insertion markers stay inside their strip. Previews paint on the Tooltip layer, and a reorder inside the source strip shows only the insertion line. resolve_drag lets the host own a gesture. A panel floated from a dock uses floating_size or its limits instead of the column height. ResizeHandle gives focus back after a pointer drag. node_limits is a free function for the render modules. is_dragging and tab_insertion_marker are public. Ported from storytold/craft-libs#110 by @Zenodeon. Co-authored-by: Zenodeon --- crates/ui/src/docking/mod.rs | 5 +- crates/ui/src/docking/render/floating.rs | 189 +++++++++++---- crates/ui/src/docking/render/group.rs | 3 +- crates/ui/src/docking/render/mod.rs | 95 ++++---- crates/ui/src/docking/render/preview.rs | 122 ++++++++-- crates/ui/src/docking/resize.rs | 147 ++++++++++++ crates/ui/src/docking/surface.rs | 23 +- crates/ui/src/docking/targets.rs | 68 +++++- crates/ui/src/docking/tests.rs | 293 ++++++++++++++++++++++- crates/ui/src/layout/resize.rs | 5 + crates/ui/src/layout/tests.rs | 8 + 11 files changed, 831 insertions(+), 127 deletions(-) create mode 100644 crates/ui/src/docking/resize.rs diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index b08872b954..1be249d6c2 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -8,14 +8,15 @@ mod dock_model; mod model; mod render; +mod resize; mod surface; mod targets; mod workspace; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; -pub use surface::{DockArea, DockContent, DockOutput, DockStyle, DropFeedback, DropRequest, PanelLimits, begin_drag, cancel_drag}; -pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, zone_rect}; +pub use surface::{DockArea, DockContent, DockOutput, DockStyle, DropFeedback, DropRequest, PanelLimits, begin_drag, cancel_drag, is_dragging}; +pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect}; pub use workspace::Workspace; use surface::{Drag, GroupDrag}; diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 64ca2da441..cd55820bdd 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -1,9 +1,42 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Context, Key, Rect, Sense, Stroke, Vec2, pos2, vec2}; +use egui::{Context, Id, Key, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; use super::{Renderer, clamp_float}; -use crate::docking::{Action, Node}; +use crate::docking::{Action, Floating, Node, PanelLimits, resize::AnchoredResize}; + +/// Floating window resize handles: id suffix, hit rect and the edges they move. +fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 5] { + [ + ("resize", Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max), vec2(1.0, 1.0)), + ( + "resize-left", + Rect::from_min_max(pos2(rect.left(), rect.top() + 12.0), pos2((rect.left() + 4.0).min(rect.right()), rect.bottom() - 12.0)), + vec2(-1.0, 0.0), + ), + ( + "resize-right", + Rect::from_min_max(pos2((rect.right() - 4.0).max(rect.left()), rect.top() + 12.0), pos2(rect.right(), rect.bottom() - 12.0)), + vec2(1.0, 0.0), + ), + ( + "resize-bottom", + Rect::from_min_max(pos2(rect.left() + 12.0, (rect.bottom() - 4.0).max(rect.top())), pos2(rect.right() - 12.0, rect.bottom())), + vec2(0.0, 1.0), + ), + ( + "resize-bottom-left", + Rect::from_min_max( + pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), + pos2((rect.left() + 12.0).min(rect.right()), rect.bottom()), + ), + vec2(-1.0, 1.0), + ), + ] +} + +/// Names of every floating window resize handle, for focus classification. +pub(in crate::docking) const RESIZE_HANDLES: [&str; 5] = ["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left"]; impl Renderer<'_, P> { pub(in crate::docking) fn floating(&mut self, ctx: &Context) { @@ -12,19 +45,19 @@ impl Renderer<'_, P> { return; } let layers = ctx.memory(|memory| memory.layer_ids().collect::>()); - let mut groups: Vec<_> = self.layout.floating.iter().collect(); - groups.sort_by_key(|group| { - let id = group.panels().next().map(|panel| self.id.with(("floating", panel))); + let mut windows: Vec<_> = self.layout.floating.iter().collect(); + windows.sort_by_key(|window| { + let id = window.panels().next().map(|panel| self.id.with(("floating", panel))); layers.iter().position(|layer| Some(layer.id) == id).unwrap_or(usize::MAX) }); - for group in groups { - let Some(first) = group.panels().next() else { continue }; - let [x, y, width, height] = group.rect; - let limits = self.node_limits(&Node::Tabs { panels: group.panels().cloned().collect(), active: 0 }); + for window in windows { + let Some(first) = window.panels().next() else { continue }; + let [x, y, width, height] = window.rect; + let limits = self.node_limits(&Node::Tabs { panels: window.panels().cloned().collect(), active: 0 }); let size = vec2(width, height).max(limits.min).min(limits.max); let rect = clamp_float(Rect::from_min_size(pos2(x, y), size), screen); let id = self.id.with(("floating", first)); - if self.activation.as_ref().is_some_and(|panel| group.contains(panel)) { + if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); self.output.focused = self.activation.clone(); @@ -33,45 +66,105 @@ impl Renderer<'_, P> { ui.set_min_size(rect.size()); let rect = Rect::from_min_size(ui.min_rect().min, rect.size()); ui.allocate_rect(rect, Sense::hover()); - self.stacked_groups(ui, &group.groups, rect, true); - let corner = Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max); - let response = ui.interact(corner, id.with("resize"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeNwSe); - self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.resize_window_label)); - if response.drag_started() { - response.request_focus(); - } - let mut delta = if response.dragged() { ui.input(|i| i.pointer.delta()) } else { Vec2::ZERO }; - if response.has_focus() { - ui.memory_mut(|memory| { - memory.set_focus_lock_filter( - response.id, - egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }, - ) - }); - ui.input_mut(|input| { - if input.consume_key(egui::Modifiers::NONE, Key::ArrowLeft) { - delta.x -= 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowRight) { - delta.x += 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowUp) { - delta.y -= 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowDown) { - delta.y += 8.0; - } - }); - } - if response.enabled() && delta != Vec2::ZERO { - let size = (rect.size() + delta).max(limits.min.max(vec2(40.0, self.style.tab_height + 20.0))).min(limits.max).min(screen.size()); - self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [rect.left(), rect.top(), size.x, size.y] }); - } - if response.hovered() || response.dragged() || response.has_focus() { - ui.painter().line_segment([corner.left_bottom(), corner.right_top()], Stroke::new(2.0, self.style.accent)); - } + self.stacked_groups(ui, &window.groups, rect, true); + self.resize_handles(ui, window, id, rect, limits, screen); }); } } + + /// Anchored resize from the side edges, the bottom edge and both bottom corners: the + /// opposite edges stay where they are. + fn resize_handles(&mut self, ui: &mut Ui, window: &Floating

, id: Id, rect: Rect, limits: PanelLimits, screen: Rect) { + let Some(first) = window.panels().next() else { return }; + for (name, handle, direction) in handles(rect) { + if !crate::docking::targets::usable(handle) { + continue; + } + let cursor = if direction.x == 0.0 { + egui::CursorIcon::ResizeVertical + } else if direction.y == 0.0 { + egui::CursorIcon::ResizeHorizontal + } else if direction.x == direction.y { + egui::CursorIcon::ResizeNwSe + } else { + egui::CursorIcon::ResizeNeSw + }; + let response = ui.interact(handle, id.with(name), Sense::drag()).on_hover_cursor(cursor); + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.resize_window_label)); + let anchor_id = response.id.with("pointer-anchor"); + if response.drag_started() { + response.request_focus(); + if let Some(origin) = ui.input(|i| i.pointer.press_origin()) + && let Some(anchor) = AnchoredResize::new(rect, origin, direction) + { + ui.ctx().data_mut(|data| { + if let Some(previous) = data.get_temp::(self.id.with("pointer-resize")) { + data.remove::(previous.with("pointer-anchor")); + } + data.insert_temp(self.id.with("pointer-resize"), response.id); + data.insert_temp(anchor_id, anchor); + }); + } + } + let cancelled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused); + let mut delta = Vec2::ZERO; + if response.has_focus() { + ui.memory_mut(|memory| { + memory.set_focus_lock_filter( + response.id, + egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }, + ) + }); + ui.input_mut(|input| { + if input.consume_key(egui::Modifiers::NONE, Key::ArrowLeft) { + delta.x -= 8.0; + } + if input.consume_key(egui::Modifiers::NONE, Key::ArrowRight) { + delta.x += 8.0; + } + if input.consume_key(egui::Modifiers::NONE, Key::ArrowUp) { + delta.y -= 8.0; + } + if input.consume_key(egui::Modifiers::NONE, Key::ArrowDown) { + delta.y += 8.0; + } + }); + } + let pointer_resize = response.dragged() || response.drag_stopped(); + let limits = PanelLimits { min: limits.min.max(vec2(40.0, self.style.tab_height + 20.0)).min(limits.max), ..limits }; + let next = if pointer_resize { + ui.ctx() + .data(|data| data.get_temp::(anchor_id)) + .and_then(|anchor| ui.ctx().pointer_interact_pos().and_then(|pointer| anchor.rect(pointer, screen, limits))) + } else if delta != Vec2::ZERO { + AnchoredResize::new(rect, rect.max, direction).and_then(|anchor| anchor.rect(rect.max + delta, screen, limits)) + } else { + None + }; + let permitted = response.enabled() && window.panels().all(|panel| self.permissions(panel).movable); + if permitted + && !cancelled + && let Some(resized) = next.filter(|next| *next != rect) + { + self.output + .actions + .push(Action::MoveFloating { panel: first.clone(), rect: [resized.left(), resized.top(), resized.width(), resized.height()] }); + } + if response.drag_stopped() { + response.surrender_focus(); + } + if cancelled || !permitted || !ui.input(|input| input.pointer.primary_down()) { + ui.ctx().data_mut(|data| { + data.remove::(anchor_id); + if data.get_temp::(self.id.with("pointer-resize")) == Some(response.id) { + data.remove::(self.id.with("pointer-resize")); + } + }); + } + if name == "resize" && (response.hovered() || response.dragged() || response.has_focus()) { + ui.painter().line_segment([handle.left_bottom(), handle.right_top()], Stroke::new(2.0, self.style.accent)); + } + } + } } diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 3dca5511ef..0c80d634c6 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -177,7 +177,8 @@ impl Renderer<'_, P> { let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.float_label)); if response.clicked() { - let rect = clamp_float(group.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); + let size = self.float_size(panel, group.size()); + let rect = clamp_float(Rect::from_min_size(group.min + vec2(24.0, 24.0), size), ui.ctx().content_rect()); self.output.actions.push(Action::Float { panel: panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }); ui.close(); } diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index b0c62a5273..9ed2e9c856 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -7,6 +7,8 @@ use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions}; mod floating; + +pub(in crate::docking) use floating::RESIZE_HANDLES; mod group; mod preview; @@ -187,50 +189,7 @@ impl Renderer<'_, P> { } pub(super) fn node_limits(&self, node: &Node

) -> PanelLimits { - match node { - Node::Dock { .. } => PanelLimits { min: Vec2::splat(self.style.min_pane), ..PanelLimits::default() }, - Node::Tabs { panels, .. } => { - let mut limits = PanelLimits::default(); - for panel in panels { - let policy = self.limits(panel); - limits.min = limits.min.max(policy.min).max(Vec2::splat(self.style.min_pane)); - limits.max = limits.max.min(policy.max); - } - limits.max = limits.max.max(limits.min); - if panels.len() != 1 || panels.first().is_some_and(|p| self.permissions(p) != Permissions::PROTECTED) { - limits.min.y = (limits.min.y + self.style.tab_height).min(1_000_000.0); - limits.max.y = (limits.max.y + self.style.tab_height).min(1_000_000.0); - } - limits - } - Node::Stack { entries } => { - let mut limits = PanelLimits::default(); - for entry in entries { - let policy = self.limits(&entry.panel); - limits.min.x = limits.min.x.max(policy.min.x).max(self.style.min_pane); - limits.min.y += if entry.open { policy.min.y.max(self.style.min_pane) } else { 0.0 } + self.style.tab_height; - limits.max.x = limits.max.x.min(policy.max.x); - } - limits.min = limits.min.min(Vec2::splat(1_000_000.0)); - limits.max = limits.max.max(limits.min); - limits - } - Node::Split { axis, first, second, .. } => { - let a = self.node_limits(first); - let b = self.node_limits(second); - let limits = match axis { - SplitAxis::Horizontal => PanelLimits { - min: vec2(a.min.x + b.min.x + self.style.gap, a.min.y.max(b.min.y)), - max: vec2(a.max.x + b.max.x + self.style.gap, a.max.y.min(b.max.y)), - }, - SplitAxis::Vertical => PanelLimits { - min: vec2(a.min.x.max(b.min.x), a.min.y + b.min.y + self.style.gap), - max: vec2(a.max.x.min(b.max.x), a.max.y + b.max.y + self.style.gap), - }, - }; - PanelLimits { min: limits.min.min(Vec2::splat(1_000_000.0)), max: limits.max.max(limits.min).min(Vec2::splat(1_000_000.0)) } - } - } + node_limits(node, self.style, &*self.content) } pub(super) fn contents(&mut self, ui: &mut Ui, panel: &P, rect: Rect) { @@ -248,6 +207,54 @@ impl Renderer<'_, P> { } } +/// Size policy of a subtree, shared by the renderer and its measurements. +pub(in crate::docking) fn node_limits

(node: &Node

, style: &DockStyle, content: &dyn DockContent

) -> PanelLimits { + match node { + Node::Dock { .. } => PanelLimits { min: Vec2::splat(style.min_pane), ..PanelLimits::default() }, + Node::Tabs { panels, .. } => { + let mut limits = PanelLimits::default(); + for panel in panels { + let policy = content.limits(panel); + limits.min = limits.min.max(policy.min).max(Vec2::splat(style.min_pane)); + limits.max = limits.max.min(policy.max); + } + limits.max = limits.max.max(limits.min); + if panels.len() != 1 || panels.first().is_some_and(|p| content.permissions(p) != Permissions::PROTECTED) { + limits.min.y = (limits.min.y + style.tab_height).min(1_000_000.0); + limits.max.y = (limits.max.y + style.tab_height).min(1_000_000.0); + } + limits + } + Node::Stack { entries } => { + let mut limits = PanelLimits::default(); + for entry in entries { + let policy = content.limits(&entry.panel); + limits.min.x = limits.min.x.max(policy.min.x).max(style.min_pane); + limits.min.y += if entry.open { policy.min.y.max(style.min_pane) } else { 0.0 } + style.tab_height; + limits.max.x = limits.max.x.min(policy.max.x); + } + limits.min = limits.min.min(Vec2::splat(1_000_000.0)); + limits.max = limits.max.max(limits.min); + limits + } + Node::Split { axis, first, second, .. } => { + let a = node_limits(first, style, content); + let b = node_limits(second, style, content); + let limits = match axis { + SplitAxis::Horizontal => PanelLimits { + min: vec2(a.min.x + b.min.x + style.gap, a.min.y.max(b.min.y)), + max: vec2(a.max.x + b.max.x + style.gap, a.max.y.min(b.max.y)), + }, + SplitAxis::Vertical => PanelLimits { + min: vec2(a.min.x.max(b.min.x), a.min.y + b.min.y + style.gap), + max: vec2(a.max.x.min(b.max.x), a.max.y + b.max.y + style.gap), + }, + }; + PanelLimits { min: limits.min.min(Vec2::splat(1_000_000.0)), max: limits.max.max(limits.min).min(Vec2::splat(1_000_000.0)) } + } + } +} + pub(super) fn clamp_float(rect: Rect, screen: Rect) -> Rect { if !crate::docking::targets::usable(screen) { return rect; diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 0fb075e1c9..9b6214f933 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -1,9 +1,12 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Context, Key, Rect, Stroke, StrokeKind}; +use egui::{Context, Key, Pos2, Rect, Stroke, StrokeKind, Vec2, vec2}; use super::{Renderer, clamp_float}; -use crate::docking::{Action, Drag, GroupDrag, cancel_drag, resolve_drop}; +use crate::docking::{Action, Drag, DropRequest, GroupDrag, cancel_drag, dock_model::Place, resolve_drop}; + +/// Height of a panel floated out of a dock column when the host gives no floating size. +const DOCKED_FLOAT_HEIGHT: f32 = 320.0; impl Renderer<'_, P> { pub(in crate::docking) fn finish_group_drag(&mut self, ctx: &Context) { @@ -14,6 +17,18 @@ impl Renderer<'_, P> { } let (escape, focused, down, released, pointer) = ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); + if !escape + && focused + && (down || released) + && let Some(pointer) = pointer.filter(|p| p.is_finite()) + && !self.blockers.iter().any(|r| r.contains(pointer)) + && self.host_drop(ctx, &drag.panel, pointer, true, released, None) + { + if released { + ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); + } + return; + } // A button release outside the window may never reach egui. let has_pointer = ctx.input(|i| i.pointer.has_pointer()); // Touch-up also removes the pointer, but still completes a drop. @@ -59,18 +74,24 @@ impl Renderer<'_, P> { } return; } + let floatable = self.permissions(&drag.panel).floatable + && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); + let floating_rect = floatable.then(|| self.tab_float_rect(ctx, &drag, pointer)); + if self.host_drop(ctx, &drag.panel, pointer, false, released, floating_rect) { + if released { + cancel_drag::

(ctx, self.id); + } + return; + } let proposal = resolve_drop(&drag.panel, pointer, &self.targets); if released { cancel_drag::

(ctx, self.id); - if pointer.distance(drag.origin) < 2.0 { + if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !gone) { return; } let action = if let Some(proposal) = proposal.filter(|_| !gone) { Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) - } else if self.permissions(&drag.panel).floatable - && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))) - { - let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); + } else if let Some(rect) = floating_rect { Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }) } else { None @@ -86,21 +107,88 @@ impl Renderer<'_, P> { } return; } - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, self.id.with("drop-preview"))); + let painter = self.preview_painter(ctx); if let Some(proposal) = proposal { - painter.rect( - proposal.preview.shrink(1.0), - 0.0, - self.style.accent.gamma_multiply(0.15), - Stroke::new(2.0, self.style.accent), - StrokeKind::Inside, - ); + // Reordering inside the source strip shows only the insertion line. + let same_group = proposal.insertion.is_some() + && self.targets.iter().any(|target| target.rect == proposal.preview && target.tabs.iter().any(|(panel, _)| panel == &drag.panel)); + if !same_group && !proposal.noop { + painter.rect( + proposal.preview.shrink(1.0), + 0.0, + self.style.accent.gamma_multiply(0.15), + Stroke::new(2.0, self.style.accent), + StrokeKind::Inside, + ); + } if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); } - } else if self.permissions(&drag.panel).floatable { - let rect = clamp_float(Rect::from_min_size(pointer - drag.grab, drag.source.size()), ctx.content_rect()); + } else if let Some(rect) = floating_rect { painter.rect_stroke(rect, 0.0, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); } } + + /// The single drop preview layer, above every floating window. + pub(super) fn preview_painter(&self, ctx: &Context) -> egui::Painter { + let layer = egui::LayerId::new(egui::Order::Tooltip, self.id.with("drop-preview")); + ctx.move_to_top(layer); + ctx.layer_painter(layer) + } + + /// Size of a panel floated by a drag or the Float menu: the host's floating size, else the + /// source size within the panel limits. A panel leaving a dock column does not take the + /// column's height. + pub(super) fn float_size(&self, panel: &P, source: Vec2) -> Vec2 { + if let Some(size) = self.content.floating_size(panel).filter(|s| s.is_finite() && s.x > 0.0 && s.y > 0.0) { + return size; + } + let mut size = source; + if matches!(self.layout.place(panel), Some(Place::Dock { .. })) { + size.y = size.y.min(DOCKED_FLOAT_HEIGHT); + } + let limits = self.limits(panel); + let header = vec2(0.0, self.style.tab_height); + size.max(limits.min + header).min(limits.max + header) + } + + fn tab_float_rect(&self, ctx: &Context, drag: &Drag

, pointer: Pos2) -> Rect { + let size = self.float_size(&drag.panel, drag.source.size()); + let grab = drag.grab.min(vec2(size.x, self.style.tab_height)); + clamp_float(Rect::from_min_size(pointer - grab, size), ctx.content_rect()) + } + + /// Offer the gesture to [`crate::docking::DockContent::resolve_drag`]. True when the host + /// owns it; its feedback replaces the renderer's preview. + pub(super) fn host_drop( + &mut self, + ctx: &Context, + panel: &P, + pointer: Pos2, + whole_group: bool, + released: bool, + floating_rect: Option, + ) -> bool { + let request = DropRequest { + panel, + pointer, + targets: &self.targets, + floating_rect, + whole_group, + released, + workspace: self.workspace, + screen: ctx.content_rect(), + }; + let Some(feedback) = self.content.resolve_drag(ctx, self.style, &request) else { return false }; + if !released { + let painter = self.preview_painter(ctx); + if let Some(rect) = feedback.preview.filter(|rect| crate::docking::targets::usable(*rect)) { + painter.rect(rect, 0.0, self.style.accent.gamma_multiply(0.15), Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + } + if let Some(rect) = feedback.insertion.filter(|rect| crate::docking::targets::usable(*rect)) { + painter.rect_filled(rect, 0.0, self.style.accent); + } + } + true + } } diff --git a/crates/ui/src/docking/resize.rs b/crates/ui/src/docking/resize.rs new file mode 100644 index 0000000000..48e50f4e52 --- /dev/null +++ b/crates/ui/src/docking/resize.rs @@ -0,0 +1,147 @@ +use egui::{Pos2, Rect, Vec2}; + +use super::PanelLimits; + +/// A pointer-anchored resize. The opposite edges and handle grab offset stay fixed +/// through boundary overshoot; viewport constraints never translate the window. +#[derive(Clone, Copy, Debug)] +pub struct AnchoredResize { + start: Rect, + offset: Vec2, + direction: Vec2, +} + +impl AnchoredResize { + pub fn new(start: Rect, pointer: Pos2, direction: Vec2) -> Option { + if !start.is_finite() + || !start.is_positive() + || !pointer.is_finite() + || ![-1.0, 0.0, 1.0].contains(&direction.x) + || ![-1.0, 0.0, 1.0].contains(&direction.y) + || direction == Vec2::ZERO + { + return None; + } + let edge = + egui::pos2(if direction.x < 0.0 { start.left() } else { start.right() }, if direction.y < 0.0 { start.top() } else { start.bottom() }); + Some(Self { start, offset: pointer - edge, direction }) + } + + /// None suspends resizing when the fixed anchor cannot accommodate the minimum. + pub fn rect(self, pointer: Pos2, viewport: Rect, limits: PanelLimits) -> Option { + if !pointer.is_finite() + || !viewport.is_finite() + || !viewport.is_positive() + || !limits.min.is_finite() + || !limits.max.is_finite() + || limits.min.x <= 0.0 + || limits.min.y <= 0.0 + || limits.max.x < limits.min.x + || limits.max.y < limits.min.y + || !viewport.contains_rect(self.start) + || self.start.width() < limits.min.x + || self.start.height() < limits.min.y + { + return None; + } + let desired = pointer - self.offset; + if !desired.is_finite() { + return None; + } + let mut rect = self.start; + for (axis, direction) in [(0, self.direction.x), (1, self.direction.y)] { + if direction == 0.0 { + continue; + } + let (lo, hi) = if direction < 0.0 { + ((self.start.max[axis] - limits.max[axis]).max(viewport.min[axis]), self.start.max[axis] - limits.min[axis]) + } else { + (self.start.min[axis] + limits.min[axis], (self.start.min[axis] + limits.max[axis]).min(viewport.max[axis])) + }; + if !lo.is_finite() || !hi.is_finite() || lo > hi { + return None; + } + if direction < 0.0 { + rect.min[axis] = desired[axis].clamp(lo, hi); + } else { + rect.max[axis] = desired[axis].clamp(lo, hi); + } + } + Some(rect) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{pos2, vec2}; + + #[test] + fn every_handle_tracks_absolute_pointer_and_keeps_opposite_edges() { + let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0)); + let viewport = Rect::from_min_max(Pos2::ZERO, pos2(800.0, 600.0)); + let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(500.0, 400.0) }; + for direction in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0)] { + let edge = pos2(if direction.x < 0.0 { start.left() } else { start.right() }, start.bottom()); + let pointer = edge + vec2(2.0, -3.0); + let resize = AnchoredResize::new(start, pointer, direction).unwrap(); + let rect = resize.rect(pointer + vec2(20.0, 25.0), viewport, limits).unwrap(); + assert_eq!(rect.top(), start.top()); + if direction.x < 0.0 { + assert_eq!(rect.right(), start.right()); + assert_eq!(rect.left(), start.left() + 20.0); + } else { + assert_eq!(rect.left(), start.left()); + } + if direction.x > 0.0 { + assert_eq!(rect.right(), start.right() + 20.0); + } + if direction.y > 0.0 { + assert_eq!(rect.bottom(), start.bottom() + 25.0); + } else { + assert_eq!(rect.bottom(), start.bottom()); + } + } + } + + #[test] + fn overshoot_requires_pointer_to_return_to_the_valid_range() { + let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0)); + let viewport = Rect::from_min_max(Pos2::ZERO, pos2(600.0, 500.0)); + let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(1000.0, 1000.0) }; + let resize = AnchoredResize::new(start, pos2(398.0, 200.0), vec2(1.0, 0.0)).unwrap(); + for x in [800.0, 750.0, 598.0] { + let rect = resize.rect(pos2(x, 200.0), viewport, limits).unwrap(); + assert_eq!((rect.left(), rect.right()), (100.0, 600.0)); + } + for x in [120.0, 200.0, 258.0] { + assert_eq!(resize.rect(pos2(x, 200.0), viewport, limits).unwrap().right(), 260.0); + } + assert_eq!(resize.rect(pos2(278.0, 200.0), viewport, limits).unwrap().right(), 280.0); + let left = AnchoredResize::new(start, pos2(102.0, 200.0), vec2(-1.0, 0.0)).unwrap(); + assert_eq!(left.rect(pos2(-300.0, 200.0), viewport, limits).unwrap().min.x, 0.0); + assert_eq!(left.rect(pos2(350.0, 200.0), viewport, limits).unwrap().min.x, 240.0); + assert_eq!(left.rect(pos2(300.0, 200.0), viewport, limits).unwrap().min.x, 240.0); + assert_eq!(left.rect(pos2(222.0, 200.0), viewport, limits).unwrap().min.x, 220.0); + } + + #[test] + fn panel_maximum_caps_edges_without_losing_the_absolute_anchor() { + let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0)); + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(320.0, 240.0) }; + let resize = AnchoredResize::new(start, start.max, Vec2::splat(1.0)).unwrap(); + for pointer in [pos2(700.0, 550.0), pos2(600.0, 450.0)] { + assert_eq!(resize.rect(pointer, viewport, limits).unwrap(), Rect::from_min_max(start.min, pos2(420.0, 320.0))); + } + assert_eq!(resize.rect(pos2(410.0, 310.0), viewport, limits).unwrap(), Rect::from_min_max(start.min, pos2(410.0, 310.0))); + } + + #[test] + fn constrained_viewports_and_invalid_geometry_suspend_resize() { + let start = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 90.0)); + let resize = AnchoredResize::new(start, start.max, Vec2::splat(1.0)).unwrap(); + assert!(resize.rect(start.max, start, PanelLimits { min: vec2(160.0, 120.0), ..Default::default() }).is_none()); + assert!(AnchoredResize::new(start, pos2(f32::NAN, 0.0), Vec2::splat(1.0)).is_none()); + } +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 3578579b9a..5321fb2531 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -2,7 +2,11 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Color32, Context, FontId, Id, Pos2, Rect, Sense, Stroke, Ui, Vec2}; -use super::{Action, DockError, DropTarget, Layout, Node, Permissions, render::Renderer}; +use super::{ + Action, DockError, DropTarget, Layout, Node, Permissions, + render::{RESIZE_HANDLES, Renderer}, + resize::AnchoredResize, +}; /// Horizontal room around a tab's label, both when measuring its natural width and when cutting it. pub(super) const TAB_PADDING: f32 = 24.0; @@ -131,6 +135,11 @@ pub fn begin_drag(ctx: &Context, area_id: Id, true } +/// Whether this area's tab or group gesture is active. +pub fn is_dragging(ctx: &Context, area_id: Id) -> bool { + ctx.data(|data| data.get_temp::>(area_id.with("drag")).is_some() || data.get_temp::>(area_id.with("group-drag")).is_some()) +} + /// Discard pending tab/group gestures and an actively dragged renderer-owned control before /// replacing a workspace. Body/custom-header/menu gestures and other areas are untouched. /// Ownership is recorded as controls render; before an initial render or drag threshold there @@ -142,7 +151,12 @@ pub fn cancel_drag(ctx: &Context, area_id: Id) d.remove::>(area_id.with("drag")); d.remove::>(area_id.with("group-drag")); let ids = d.remove_temp::>(area_id.with("owned-interactions")); - dragged.is_some_and(|id| ids.is_some_and(|ids| ids.contains(&id))) + let resize = d.get_temp::(area_id.with("pointer-resize")); + d.remove::(area_id.with("pointer-resize")); + for id in resize.iter().chain(ids.iter().flatten()) { + d.remove::(id.with("pointer-anchor")); + } + dragged.is_some_and(|id| resize == Some(id) || ids.is_some_and(|ids| ids.contains(&id))) }); if owned { ctx.stop_dragging(); @@ -312,7 +326,10 @@ impl DockArea

{ }; for floating in &layout.floating { if floating.groups.iter().any(|g| group(&g.panels)) - || floating.panels().next().is_some_and(|first| matches(self.id.with(("floating", first)).with("resize"))) + || floating + .panels() + .next() + .is_some_and(|first| RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name)))) { return true; } diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index 515b9c651a..a4c8b63182 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -20,6 +20,8 @@ pub struct DropProposal

{ pub placement: Placement

, pub preview: Rect, pub insertion: Option, + /// The pointer addresses the tab's current insertion slot. + pub noop: bool, } pub(super) fn usable(rect: Rect) -> bool { @@ -57,6 +59,28 @@ pub fn zone_rect(rect: Rect, zone: Zone) -> Option { }) } +/// Bounded insertion marker for a logical slot in a measured tab strip. Hidden tabs +/// retain their order; their slot uses the next visible boundary or the visible strip end. +pub fn tab_insertion_marker(target: &DropTarget

, before: Option<&P>) -> Option { + if target.tabs.len() > super::MAX_PANELS || !target.accepts_tabs || !usable(target.rect) { + return None; + } + let strip = target.tab_strip?.intersect(target.rect); + if !usable(strip) { + return None; + } + let index = before.and_then(|before| target.tabs.iter().position(|(panel, _)| panel == before)); + let x = index + .and_then(|index| target.tabs.get(index..)) + .and_then(|tabs| tabs.iter().find(|(_, rect)| usable(*rect)).map(|(_, rect)| rect.left())) + .unwrap_or_else(|| { + target.tabs.iter().filter(|(_, rect)| usable(*rect)).map(|(_, rect)| rect.right()).fold(strip.left(), f32::max).min(strip.right()) + }); + let width = strip.width().min(2.0); + let left = (x - width * 0.5).max(strip.left()).min((strip.right() - width).max(strip.left())); + Some(Rect::from_min_max(pos2(left, strip.top()), pos2((left + width).min(strip.right()), strip.bottom()))) +} + /// Resolve a pointer against visible groups. The frontmost containing group occludes groups /// behind it even if it rejects the drop. A strip reorders by midpoint; the body of the source /// group is a no-op at center. Floating groups normally set `allow_splits` to false. @@ -68,26 +92,48 @@ pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarg if target.tabs.len() > super::MAX_PANELS { return None; } - let anchor = if &target.anchor == panel { target.tabs.iter().find(|(p, _)| p != panel).map(|(p, _)| p)? } else { &target.anchor }; - let strip = target.tab_strip.filter(|r| usable(*r) && r.contains(pointer)); - if let Some(strip) = strip { + let anchor = if &target.anchor == panel { target.tabs.iter().find(|(p, _)| p != panel).map(|(p, _)| p).unwrap_or(panel) } else { &target.anchor }; + let strip = target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|r| usable(*r) && r.contains(pointer)); + if strip.is_some() { if !target.accepts_tabs { return None; } let before = target.tabs.iter().filter(|(_, r)| usable(*r)).find(|(_, r)| pointer.x < r.center().x); let before_panel = before.map(|(p, _)| p.clone()); - let x = before.map(|(_, r)| r.left()).unwrap_or_else(|| { - target.tabs.iter().filter(|(_, r)| usable(*r)).map(|(_, r)| r.right()).fold(strip.left(), f32::max).min(strip.right()) - }); - let insertion = Rect::from_min_max(pos2((x - 1.0).max(strip.left()), strip.top()), pos2((x + 1.0).min(strip.right()), strip.bottom())); + let insertion = tab_insertion_marker(target, before_panel.as_ref())?; + let old_order: Vec<_> = target.tabs.iter().map(|(p, _)| p).collect(); + let mut order = old_order.clone(); + let noop = if before_panel.as_ref() == Some(panel) { + old_order.contains(&panel) + } else if old_order.contains(&panel) { + order.retain(|p| *p != panel); + let at = before_panel.as_ref().and_then(|before| order.iter().position(|p| *p == before)).unwrap_or(order.len()); + order.insert(at, panel); + order == old_order + } else { + false + }; return Some(DropProposal { anchor: anchor.clone(), placement: Placement::Tab { before: before_panel }, preview: target.rect, insertion: Some(insertion), + noop, }); } let zone = if target.allow_splits { drop_zone(target.rect, 0.0, pointer)? } else { Zone::Center }; + if zone == Zone::Center && target.accepts_tabs && target.tabs.iter().any(|(p, _)| p == panel) { + return Some(DropProposal { + anchor: anchor.clone(), + placement: Placement::Tab { before: Some(panel.clone()) }, + preview: target.rect, + insertion: None, + noop: true, + }); + } + if anchor == panel { + return None; + } if zone == Zone::Center { if !target.accepts_tabs || target.tabs.iter().any(|(p, _)| p == panel) { return None; @@ -95,5 +141,11 @@ pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarg } else if !target.allow_splits { return None; } - Some(DropProposal { anchor: anchor.clone(), placement: Placement::Split(zone), preview: zone_rect(target.rect, zone)?, insertion: None }) + Some(DropProposal { + anchor: anchor.clone(), + placement: Placement::Split(zone), + preview: zone_rect(target.rect, zone)?, + insertion: None, + noop: false, + }) } diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 5180b76deb..cd5adafc8d 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::layout::{SplitAxis, SplitSize}; -use egui::{Context, Event, Id, Modifiers, PointerButton, RawInput, Rect, pos2, vec2}; +use egui::{Context, Event, Id, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; fn tabs(panels: &[u32], active: usize) -> Node { Node::Tabs { panels: panels.to_vec(), active } @@ -241,7 +241,7 @@ fn pointer_targets_distinguish_reorder_center_split_and_occlusion() { assert!(placement.insertion.unwrap().is_finite()); assert_eq!(resolve_drop(&5, rect.center(), std::slice::from_ref(&group)).unwrap().placement, Placement::Split(Zone::Center)); assert_eq!(resolve_drop(&5, pos2(11.0, 90.0), std::slice::from_ref(&group)).unwrap().placement, Placement::Split(Zone::Left)); - assert!(resolve_drop(&3, rect.center(), std::slice::from_ref(&group)).is_none()); + assert!(resolve_drop(&3, rect.center(), std::slice::from_ref(&group)).unwrap().noop); assert!(resolve_drop(&3, pos2(11.0, 90.0), std::slice::from_ref(&group)).is_some()); let mut overlay = target(5, &[5], rect); overlay.accepts_tabs = false; @@ -355,6 +355,8 @@ fn frame(ctx: &Context, layout: &Layout, events: Vec, focused: bool) ui.label("Actual panel content"); }, ); + let cursor = ctx.output(|o| o.cursor_icon); + ctx.data_mut(|d| d.insert_temp(Id::new("test-cursor"), cursor)); }) .textures_delta .clear(); @@ -699,8 +701,10 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() { let tab = ctx.read_response(Id::new("test-area").with(("tab", &5u32))).unwrap().rect.center(); step(&ctx, &mut layout, vec![Event::PointerMoved(tab), pointer_button(tab, true)]); step(&ctx, &mut layout, vec![Event::PointerMoved(tab + vec2(8.0, 0.0))]); - step(&ctx, &mut layout, vec![Event::PointerMoved(tab + vec2(100.0, 100.0))]); - let detached = step(&ctx, &mut layout, vec![pointer_button(tab + vec2(100.0, 100.0), false)]); + // Inside the source window the release is a no-op; outside it floats. + let outside = pos2(780.0, 650.0); + step(&ctx, &mut layout, vec![Event::PointerMoved(outside)]); + let detached = step(&ctx, &mut layout, vec![pointer_button(outside, false)]); assert!(detached.iter().any(|a| matches!(a, Action::Float { panel: 5, .. }))); assert_eq!(layout.floating.len(), 2); assert_eq!(layout.floating[0].groups[0].panels, vec![6]); @@ -1304,3 +1308,284 @@ fn tab_labels_that_do_not_fit_are_truncated_inside_their_tab_and_named_in_a_tool "a truncated tab names its panel in full on hover" ); } + +// Ported from storytold/craft-libs#110 by @Zenodeon. + +#[test] +fn resize_cancellation_retains_ownership_across_other_host_rendering() { + let ctx = Context::default(); + let area = Id::new("test-area"); + let mut layout = sample(); + for _ in 0..3 { + step(&ctx, &mut layout, vec![]); + } + let id = area.with(("floating", &5u32)).with("resize-right"); + let start = ctx.read_response(id).unwrap().rect.center(); + step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); + step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(20.0, 0.0))]); + assert_eq!(ctx.dragged_id(), Some(id)); + ctx.data_mut(|data| data.insert_temp(area.with("owned-interactions"), vec![Id::new("another-host-control")])); + cancel_drag::(&ctx, area); + assert!(ctx.dragged_id().is_none()); + let before = layout.clone(); + assert!(step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(100.0, 0.0))]).is_empty()); + assert_eq!(layout, before); +} + +#[test] +fn collapsed_floating_height_cap_does_not_disable_keyboard_width_resizing() { + let ctx = Context::default(); + let mut layout = Layout { root: None, floating: vec![Floating::single(vec![1u32], 0, [80.0, 70.0, 300.0, 26.0])] }; + let id = Id::new("collapsed-resize").with(("floating", &1u32)).with("resize-right"); + let mut frame = |events| { + let mut actions = Vec::new(); + ctx.run_ui( + RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), focused: true, events, ..Default::default() }, + |ui| { + let mut style = DockStyle::from_ui(ui); + style.min_pane = 0.0; + actions = DockArea::new(Id::new("collapsed-resize")) + .show_with_limits( + ui, + &layout, + &style, + |p| p.to_string(), + |_| Permissions::default(), + |_| PanelLimits { min: vec2(220.0, 0.0), max: vec2(1000.0, 0.0) }, + |_, _| {}, + ) + .actions; + }, + ) + .textures_delta + .clear(); + for action in actions { + layout.apply(action).unwrap(); + } + }; + for _ in 0..3 { + frame(vec![]); + } + ctx.memory_mut(|memory| memory.request_focus(id)); + frame(vec![Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + assert_eq!(layout.floating[0].rect, [80.0, 70.0, 308.0, 26.0]); +} + +#[test] +fn returning_to_a_singleton_or_floating_source_body_is_an_explicit_noop() { + for panels in [vec![1u32], vec![1, 2, 3]] { + for allow_splits in [false, true] { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(300.0, 300.0)); + let target = DropTarget { + anchor: 1, + rect, + tab_strip: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 26.0))), + tabs: panels.iter().map(|id| (*id, Rect::NOTHING)).collect(), + allow_splits, + accepts_tabs: true, + }; + let proposal = resolve_drop(&1, rect.center(), &[target]).unwrap(); + assert!(proposal.noop); + assert!(proposal.insertion.is_none()); + } + } +} + +#[test] +fn pointer_floating_resize_stops_at_edges_and_waits_for_cursor_to_return() { + for name in ["resize-right", "resize-left", "resize-bottom", "resize", "resize-bottom-left"] { + let ctx = Context::default(); + let mut layout = sample(); + for _ in 0..3 { + step(&ctx, &mut layout, vec![]); + } + let id = Id::new("test-area").with(("floating", &5u32)).with(name); + let start = ctx.read_response(id).unwrap().rect.center(); + let original = layout.floating[0].rect; + let horizontal = name != "resize-bottom"; + let left = name.contains("left"); + step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); + let outside = if horizontal { pos2(if left { -200.0 } else { 1100.0 }, start.y) } else { pos2(start.x, 1000.0) }; + step(&ctx, &mut layout, vec![Event::PointerMoved(outside)]); + let stopped = layout.floating[0].rect; + if horizontal { + if left { + assert_eq!(stopped[0] + stopped[2], original[0] + original[2]); + } else { + assert_eq!(stopped[0], original[0]); + assert_eq!(stopped[0] + stopped[2], 800.0); + } + } else { + assert_eq!(stopped[1], original[1]); + assert_eq!(stopped[1] + stopped[3], 600.0); + } + let still_outside = if horizontal { outside + vec2(if left { 100.0 } else { -100.0 }, 0.0) } else { outside - vec2(0.0, 100.0) }; + step(&ctx, &mut layout, vec![Event::PointerMoved(still_outside)]); + assert_eq!(layout.floating[0].rect, stopped, "{name}: reversal outside the edge must not resize"); + step(&ctx, &mut layout, vec![Event::PointerMoved(start)]); + assert_eq!(layout.floating[0].rect, original, "{name}: returning to the original handle restores its geometry"); + step(&ctx, &mut layout, vec![pointer_button(start, false)]); + assert!(!ctx.memory(|memory| memory.has_focus(id))); + } +} + +#[test] +fn unchanged_tab_slots_are_explicit_noops_with_bounded_insertion_markers() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 200.0)); + let target = DropTarget { + anchor: 1, + rect, + tab_strip: Some(Rect::from_min_size(rect.min, vec2(300.0, 30.0))), + tabs: vec![ + (1, Rect::from_min_size(pos2(0.0, 0.0), vec2(60.0, 30.0))), + (2, Rect::from_min_size(pos2(60.0, 0.0), vec2(60.0, 30.0))), + (3, Rect::from_min_size(pos2(120.0, 0.0), vec2(60.0, 30.0))), + ], + allow_splits: true, + accepts_tabs: true, + }; + for (panel, positions) in [(1, [10.0, 50.0]), (2, [70.0, 110.0]), (3, [130.0, 210.0])] { + for x in positions { + let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target)).unwrap(); + assert!(proposal.noop, "{panel}/{x}"); + assert!(target.tab_strip.unwrap().contains_rect(proposal.insertion.unwrap())); + } + } + for (panel, x) in [(1, 140.0), (3, 10.0), (2, 210.0)] { + let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target)).unwrap(); + assert!(!proposal.noop); + assert!(proposal.insertion.is_some()); + } +} + +#[test] +fn host_owned_noop_consumes_release_without_a_fallback_float() { + struct Content(usize); + impl DockContent for Content { + fn body(&mut self, _ui: &mut egui::Ui, _panel: &u32) {} + fn resolve_drag(&mut self, _ctx: &Context, _style: &DockStyle, request: &DropRequest<'_, u32>) -> Option { + if request.released { + self.0 += 1; + } + Some(DropFeedback::default()) + } + } + let ctx = Context::default(); + let area = Id::new("host-owned"); + let layout = sample(); + let mut content = Content(0); + let from = pos2(30.0, 20.0); + let to = pos2(400.0, 300.0); + let render = |events: Vec, content: &mut Content| { + let mut output = DockOutput::default(); + ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }, |ui| { + output = DockArea::new(area).show_customized( + ui, + &layout, + &DockStyle::from_ui(ui), + |p| p.to_string(), + |_| Permissions::default(), + |_| PanelLimits::default(), + content, + ); + }) + .textures_delta + .clear(); + output + }; + render( + vec![ + Event::PointerMoved(from), + Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ], + &mut content, + ); + assert!(begin_drag(&ctx, area, 1u32, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)))); + render(vec![Event::PointerMoved(to)], &mut content); + let output = render( + vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + &mut content, + ); + assert_eq!(content.0, 1); + assert!(output.actions.iter().all(|action| !matches!(action, Action::Move { .. } | Action::Float { .. }))); +} + +#[test] +fn overflow_noop_detection_uses_logical_order_including_hidden_tabs() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(140.0, 200.0)); + let target = DropTarget { + anchor: 1, + rect, + tab_strip: Some(Rect::from_min_size(Pos2::ZERO, vec2(140.0, 30.0))), + tabs: vec![ + (1, Rect::from_min_size(Pos2::ZERO, vec2(60.0, 30.0))), + (2, Rect::NOTHING), + (3, Rect::from_min_size(pos2(60.0, 0.0), vec2(60.0, 30.0))), + ], + allow_splits: true, + accepts_tabs: true, + }; + assert!(resolve_drop(&1, pos2(10.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); + // Before the next visible tab crosses hidden tab 2 and really changes the order. + assert!(!resolve_drop(&1, pos2(65.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); + assert!(resolve_drop(&3, pos2(130.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); +} + +#[test] +fn insertion_markers_stay_inside_clipped_and_singleton_strips() { + for width in [0.5, 1.0, 20.0, 140.0] { + let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(width, 200.0)); + let strip = Rect::from_min_size(rect.min, vec2(width, 30.0)); + for tab_left in [-100.0, 10.0, 300.0] { + let target = DropTarget { + anchor: 1, + rect, + tab_strip: Some(strip.expand(5.0)), + tabs: vec![(1, Rect::from_min_size(pos2(tab_left, 20.0), vec2(60.0, 30.0)))], + allow_splits: true, + accepts_tabs: true, + }; + for x in [rect.left(), rect.center().x, rect.right()] { + let proposal = resolve_drop(&1, pos2(x, 25.0), std::slice::from_ref(&target)).unwrap(); + assert!(proposal.noop); + let marker = proposal.insertion.unwrap(); + assert!(rect.intersect(target.tab_strip.unwrap()).contains_rect(marker)); + assert!(marker.width() > 0.0 && marker.width() <= 2.0); + } + } + } +} + +#[test] +fn insertion_marker_handles_subpixel_strip_crossing_zero_without_panicking() { + let rect = Rect::from_min_max(pos2(-0.001, 0.0), pos2(0.002, 30.0)); + let target = DropTarget { anchor: 1, rect, tab_strip: Some(rect), tabs: vec![(1, rect)], allow_splits: true, accepts_tabs: true }; + let proposal = resolve_drop(&1, pos2(0.0, 12.0), &[target]).unwrap(); + assert!(proposal.noop); + assert!(rect.contains_rect(proposal.insertion.unwrap())); +} + +#[test] +fn overflowing_strip_paints_a_single_ellipsis_symbol() { + use egui_kittest::Harness; + fn paints(shape: &egui::Shape, text: &str) -> bool { + match shape { + egui::Shape::Text(shape) => shape.galley.text() == text, + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| paints(shape, text)), + _ => false, + } + } + let layout = Layout { root: Some(tabs(&[1, 2, 3, 4, 5, 6], 0)), floating: vec![] }; + let mut h = Harness::builder().with_size(vec2(150.0, 240.0)).build_ui(move |ui| { + DockArea::new(Id::new("overflow-symbol")).show( + ui, + &layout, + &DockStyle::from_ui(ui), + |panel| format!("Panel {panel}"), + |_| Permissions::default(), + |_ui: &mut egui::Ui, _panel: &u32| {}, + ); + }); + h.run_steps(2); + assert!(h.output().shapes.iter().any(|shape| paints(&shape.shape, "\u{2026}"))); +} diff --git a/crates/ui/src/layout/resize.rs b/crates/ui/src/layout/resize.rs index e8a2a820af..c0de628fbf 100644 --- a/crates/ui/src/layout/resize.rs +++ b/crates/ui/src/layout/resize.rs @@ -82,6 +82,11 @@ impl<'a> ResizeHandle<'a> { let mut response = ui.interact(if valid { hit } else { inert }, self.id, if valid { Sense::drag() } else { Sense::hover() }); let enabled = valid && response.enabled(); let mut delta = 0.0; + // Pointer resizing borrows focus only for the gesture. Keyboard focus acquired + // through traversal remains intact until the user chooses another control. + if response.drag_stopped() { + response.surrender_focus(); + } if enabled { if response.drag_started() { response.request_focus(); diff --git a/crates/ui/src/layout/tests.rs b/crates/ui/src/layout/tests.rs index 3791465289..1a23ac02d3 100644 --- a/crates/ui/src/layout/tests.rs +++ b/crates/ui/src/layout/tests.rs @@ -171,6 +171,14 @@ fn resize_handle_preserves_pointer_drag_lifecycle_and_reports_per_frame_delta() let (response, _) = h.frame(vec![pointer(center + vec2(16.0, 0.0), false)]); assert!(response.response.drag_stopped()); assert_eq!(response.delta, 0.0); + assert!(!response.response.has_focus(), "pointer release must not leave a sticky focus highlight"); + let (_, output) = h.frame(vec![Event::PointerMoved(pos2(300.0, 180.0))]); + assert!( + !output + .shapes + .iter() + .any(|shape| { matches!(&shape.shape, egui::epaint::Shape::Rect(rect) if rect.rect == h.rect && rect.fill == Color32::BLUE) }) + ); assert_eq!(h.value, 100.0, "the component never owns pane state"); } From 1b091edefbd1d450d9b82ccc3736ba784be80ade Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:55:27 +0000 Subject: [PATCH 11/94] docking: drag tab groups by their drag bar and top border Every group with a tab strip has a drag bar between its tabs and the host's header, at least drag_bar_width wide: tabs shrink and overflow before it narrows. The bar and the 4 pt top border move the whole group with its order and active tab. While dragging, a ghost outline follows the pointer and one destination preview paints on the Tooltip layer. On release DockArea resolves the target and emits one MoveGroup: joined as tabs, split beside a frame, or floated at the group's own size. group_drop is filled only for releases without a target. Ctrl or Cmd held at release always floats, for tab drags too. Escape, focus loss, leaving the window and cancel_drag end the drag without a change. A release over the group's own docked position is a no-op; a floating group released over itself moves there. Double-clicking a tab or the bar of a floating or dock-column group minimizes it to its strip; clicking another tab expands it. The bar is focusable; its menu (right-click, Enter or Space) and the tab menu end with Close Tab Group, Minimize or Expand, Float Tab Group and Group with. Floating windows paint floating_background and floating_stroke under their groups, so they stay opaque over a transparent host. A lone bare panel, like a lone protected one, draws no strip and no bar. The group handles and their tests build on storytold/craft-libs#110 by @Zenodeon. Co-authored-by: Zenodeon --- crates/ui/src/docking/group_tests.rs | 521 +++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 4 +- crates/ui/src/docking/render/floating.rs | 14 +- crates/ui/src/docking/render/group.rs | 306 ++++++++++--- crates/ui/src/docking/render/mod.rs | 18 +- crates/ui/src/docking/render/preview.rs | 125 +++++- crates/ui/src/docking/surface.rs | 44 +- 7 files changed, 944 insertions(+), 88 deletions(-) create mode 100644 crates/ui/src/docking/group_tests.rs diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs new file mode 100644 index 0000000000..584fff2e31 --- /dev/null +++ b/crates/ui/src/docking/group_tests.rs @@ -0,0 +1,521 @@ +//! Whole-group gestures: drag bar, top border, drop resolution, minimize and the floating frame. + +use super::*; +use crate::layout::{SplitAxis, SplitSize}; +use egui::{Color32, Context, Event, Id, Modifiers, PointerButton, RawInput, Rect, UiBuilder, Vec2, pos2, vec2}; + +const AREA: &str = "group-area"; + +fn tabs(panels: &[u32], active: usize) -> Node { + Node::Tabs { panels: panels.to_vec(), active } +} + +/// `[1] | [2, 3]` with panel 3 selected. +fn frames() -> Layout { + Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(300.0), + first: Box::new(tabs(&[1], 0)), + second: Box::new(tabs(&[2, 3], 1)), + }), + floating: Vec::new(), + } +} + +/// A start dock with one column holding `[2, 3]` (3 selected) above `[4]`, beside canvas 0. +fn docked() -> Layout { + Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(240.0), + first: Box::new(Node::Dock { + side: Side::Start, + columns: vec![Column::new(vec![Group::new(vec![2, 3], 1), Group::new(vec![4], 0)], 240.0)], + }), + second: Box::new(tabs(&[0], 0)), + }), + floating: Vec::new(), + } +} + +#[derive(Default)] +struct TestContent { + protected: Vec, + header: f32, + header_clicks: usize, + floating_size: Option, + host_owned: bool, + whole_group: bool, +} + +impl DockContent for TestContent { + fn body(&mut self, ui: &mut egui::Ui, _: &u32) { + ui.label("Body"); + } + fn logical_label(&self, panel: &u32) -> String { + format!("Panel {panel}") + } + fn permissions(&self, panel: &u32) -> Permissions { + if self.protected.contains(panel) { Permissions::PROTECTED } else { Permissions::default() } + } + fn floating_size(&self, _: &u32) -> Option { + self.floating_size + } + fn resolve_drag(&mut self, _: &Context, _: &DockStyle, request: &DropRequest<'_, u32>) -> Option { + self.whole_group |= request.whole_group; + self.host_owned.then(DropFeedback::default) + } + fn group_header_width(&self, _: &[u32], _: &u32, _: bool) -> f32 { + self.header + } + fn group_header(&mut self, ui: &mut egui::Ui, _: &[u32], _: &u32, _: bool) { + if ui.button("≡").clicked() { + self.header_clicks += 1; + } + } +} + +/// Renders a layout through `show_content` in `area` of an 800x600 window and applies what +/// it emits, the way an application's command handler would. +struct Driver { + ctx: Context, + layout: Layout, + content: TestContent, + area: Rect, + modifiers: Modifiers, + focused: bool, + transparent: bool, + shapes: Vec, + time: f64, +} + +impl Driver { + fn new(layout: Layout) -> Self { + Self::with(layout, TestContent::default(), Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))) + } + + fn with(layout: Layout, content: TestContent, area: Rect) -> Self { + let mut driver = Self { + ctx: Context::default(), + layout, + content, + area, + modifiers: Modifiers::NONE, + focused: true, + transparent: false, + shapes: Vec::new(), + time: 0.0, + }; + driver.step(vec![]); + driver.step(vec![]); + driver + } + + fn frame(&mut self, mut events: Vec) -> DockOutput { + let mut output = DockOutput::default(); + events.insert(0, Event::ModifiersChanged(self.modifiers)); + self.time += 1.0 / 60.0; + let input = RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), + events, + focused: self.focused, + time: Some(self.time), + ..Default::default() + }; + let (layout, content, area, transparent) = (&self.layout, &mut self.content, self.area, self.transparent); + let mut full = self.ctx.run_ui(input, |ui| { + let mut style = DockStyle::from_ui(ui); + if transparent { + style.background = Color32::TRANSPARENT; + style.tab_background = Color32::TRANSPARENT; + } + ui.scope_builder(UiBuilder::new().max_rect(area), |ui| { + output = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content); + }); + }); + full.textures_delta.clear(); + self.shapes = full.shapes; + output + } + + fn step(&mut self, events: Vec) -> DockOutput { + let output = self.frame(events); + assert!(output.error.is_none(), "{output:?}"); + let permissions = |p: &u32| self.content.permissions(p); + for action in &output.actions { + self.layout.apply_with_permissions(action.clone(), permissions).unwrap(); + } + output + } + + fn rect(&self, name: &str, panel: u32) -> Rect { + self.ctx.read_response(Id::new(AREA).with((name, Some(&panel)))).unwrap().rect + } + + fn tab(&self, panel: u32) -> Rect { + self.ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect + } + + /// Press at `from`, pass the drag threshold, move to `to`; returns the last move's output. + fn hold(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput { + self.step(vec![Event::PointerMoved(from), button(from, true)]); + self.step(vec![Event::PointerMoved(from + vec2(8.0, 6.0))]); + self.step(vec![Event::PointerMoved(to)]) + } + + /// A full drag; returns the release frame's output. + fn drag(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput { + self.hold(from, to); + self.step(vec![button(to, false)]) + } + + /// Lets egui's double- and triple-click windows pass. + fn wait(&mut self) { + for _ in 0..45 { + self.step(vec![]); + } + } + + fn click(&mut self, at: egui::Pos2) -> DockOutput { + self.step(vec![Event::PointerMoved(at), button(at, true)]); + self.step(vec![button(at, false)]) + } +} + +fn button(pos: egui::Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } +} + +fn key(key: egui::Key) -> Event { + Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE } +} + +fn moved_group(actions: &[Action]) -> Option<&Target> { + actions.iter().find_map(|a| match a { + Action::MoveGroup { to, .. } => Some(to), + _ => None, + }) +} + +#[test] +fn docked_two_tab_group_drags_by_its_bar_and_keeps_order_and_active_tab() { + // Onto another group's strip: one MoveGroup, both panels in order, 3 still selected. + let mut d = Driver::new(frames()); + let bar = d.rect("drag-bar", 2); + assert!(bar.width() >= 40.0); + let out = d.drag(bar.center(), d.tab(1).center()); + assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, placement: Placement::Tab { .. } })), "{:?}", out.actions); + assert_eq!(out.actions.len(), 1); + assert!(out.group_drop.is_none(), "a resolved target leaves group_drop empty"); + assert_eq!(d.layout.root, Some(tabs(&[1, 2, 3], 2))); + + // Onto empty space: a floating window at the group's docked size. + let mut d = Driver::new(frames()); + let border = d.rect("drag-border", 2); + let bar = d.rect("drag-bar", 2); + let out = d.drag(bar.center(), pos2(700.0, 200.0)); + let Some(Target::Float { rect: Some([_, _, width, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) }; + assert_eq!((*width, *height), (border.width(), 600.0)); + assert_eq!(out.group_drop, Some((2, pos2(700.0, 200.0)))); + assert_eq!(d.layout.root, Some(tabs(&[1], 0))); + assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![2, 3], 1)]); + + // The same group in a dock column joins the group below it. + let mut d = Driver::new(docked()); + let bar = d.rect("drag-bar", 2); + let out = d.drag(bar.center(), d.tab(4).center()); + assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 4, .. })), "{:?}", out.actions); + let Some(Node::Split { first, .. }) = &d.layout.root else { panic!() }; + let Node::Dock { columns, .. } = first.as_ref() else { panic!() }; + assert_eq!(columns[0].groups.len(), 1); + assert_eq!(columns[0].groups[0].panels, vec![4, 2, 3]); + assert_eq!(columns[0].groups[0].active_panel(), Some(&3)); +} + +#[test] +fn drag_bar_survives_a_strip_full_of_tabs() { + let layout = Layout { root: Some(tabs(&[1, 2, 3, 4, 5, 6, 7, 8], 0)), floating: Vec::new() }; + let content = TestContent { header: 24.0, ..Default::default() }; + let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 400.0))); + let bar = d.rect("drag-bar", 1); + assert!(bar.width() >= 40.0, "{bar:?}"); + assert_eq!(bar.right(), 300.0 - 24.0, "the bar ends at the header"); + assert!(d.ctx.read_response(Id::new(AREA).with(("overflow", &1u32))).is_some(), "tabs overflow before the bar narrows"); + let out = d.drag(bar.center(), pos2(500.0, 300.0)); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); + assert_eq!(d.layout.floating[0].groups[0].panels.len(), 8); +} + +#[test] +fn top_border_drags_the_group_and_the_menu_button_only_clicks() { + let content = TestContent { header: 30.0, ..Default::default() }; + let mut d = Driver::with(frames(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let border = d.rect("drag-border", 2); + assert!(border.height() <= 4.0); + // The band lies over the tabs and wins there. + let over_tab = pos2(d.tab(2).center().x, border.center().y); + let menu = pos2(576.0, d.tab(2).center().y); + + // Pressing ≡ and dragging moves nothing; clicking it reaches the host. + let held = d.hold(menu, menu + vec2(0.0, 200.0)); + assert!(held.group_drag.is_none()); + let out = d.step(vec![button(menu + vec2(0.0, 200.0), false)]); + assert!(out.actions.iter().all(|a| !matches!(a, Action::MoveGroup { .. } | Action::Move { .. } | Action::Float { .. })), "{:?}", out.actions); + d.click(menu); + assert_eq!(d.content.header_clicks, 1); + + let out = d.drag(over_tab, d.tab(1).center()); + assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, .. })), "{:?}", out.actions); + assert_eq!(d.layout.root, Some(tabs(&[1, 2, 3], 2))); +} + +#[test] +fn group_drop_on_a_frame_edge_splits_and_on_a_protected_canvas_centre_floats() { + let canvas = || TestContent { protected: vec![1], ..Default::default() }; + let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)); + let mut d = Driver::with(frames(), canvas(), area); + let out = d.drag(d.rect("drag-bar", 2).center(), pos2(20.0, 300.0)); + assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, placement: Placement::Split(Zone::Left) })), "{:?}", out.actions); + let Some(Node::Split { first, second, .. }) = &d.layout.root else { panic!() }; + assert_eq!(**first, tabs(&[2, 3], 1)); + assert_eq!(**second, tabs(&[1], 0)); + + // The canvas centre takes nothing: no join, no preview; the group floats there. + let mut d = Driver::with(frames(), canvas(), area); + let out = d.drag(d.rect("drag-bar", 2).center(), pos2(150.0, 300.0)); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); + assert_eq!(d.layout.root, Some(tabs(&[1], 0))); +} + +#[test] +fn ctrl_or_cmd_held_at_release_always_floats() { + for modifiers in [Modifiers::CTRL, Modifiers::MAC_CMD, Modifiers::COMMAND] { + let mut d = Driver::new(frames()); + let target = d.tab(1).center(); + d.hold(d.rect("drag-bar", 2).center(), target); + d.modifiers = modifiers; + let out = d.step(vec![button(target, false)]); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{modifiers:?}: {:?}", out.actions); + assert_eq!(d.layout.root, Some(tabs(&[1], 0))); + + // A tab drag floats the same way. + let mut d = Driver::new(frames()); + let target = d.tab(1).center(); + d.hold(d.tab(3).center(), target); + d.modifiers = modifiers; + let out = d.step(vec![button(target, false)]); + assert!(out.actions.iter().any(|a| matches!(a, Action::Float { panel: 3, .. })), "{modifiers:?}: {:?}", out.actions); + } +} + +#[test] +fn group_drag_escape_focus_loss_pointer_exit_and_cancel_drag_leave_the_layout_unchanged() { + for case in ["escape", "focus", "exit", "cancel"] { + let mut d = Driver::new(frames()); + let target = d.tab(1).center(); + let held = d.hold(d.rect("drag-bar", 2).center(), target); + assert_eq!(held.group_drag, Some(2)); + let out = match case { + "escape" => d.step(vec![key(egui::Key::Escape)]), + "focus" => { + d.focused = false; + let out = d.step(vec![]); + d.focused = true; + out + } + "exit" => d.step(vec![Event::PointerGone]), + _ => { + cancel_drag::(&d.ctx, Id::new(AREA)); + d.step(vec![Event::PointerMoved(target + vec2(1.0, 0.0))]) + } + }; + assert!(out.actions.is_empty() && out.group_drop.is_none(), "{case}: {out:?}"); + let out = d.step(vec![Event::PointerMoved(target), button(target, false)]); + assert!(out.actions.is_empty() && out.group_drop.is_none() && out.group_drag.is_none(), "{case}: {out:?}"); + assert_eq!(d.layout, frames(), "{case}"); + assert!(!is_dragging::(&d.ctx, Id::new(AREA)), "{case}"); + } +} + +#[test] +fn floated_panel_uses_floating_size_not_the_column_height() { + for size in [Some(vec2(200.0, 150.0)), None] { + let mut layout = docked(); + let Some(Node::Split { first, .. }) = &mut layout.root else { panic!() }; + **first = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![2, 3], 1)], 240.0)] }; + let content = TestContent { protected: vec![0], floating_size: size, ..Default::default() }; + let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let out = d.drag(d.tab(3).center(), pos2(700.0, 100.0)); + let Some([_, _, width, height]) = out.actions.iter().find_map(|a| match a { + Action::Float { panel: 3, rect } => Some(*rect), + _ => None, + }) else { + panic!("{:?}", out.actions) + }; + match size { + Some(size) => assert_eq!((width, height), (size.x, size.y)), + None => assert!(height <= 320.0, "{height}"), + } + } +} + +#[test] +fn floating_window_is_opaque_with_a_transparent_host_background() { + let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; + let mut d = Driver::new(layout); + d.transparent = true; + d.step(vec![]); + let window = Rect::from_min_size(pos2(80.0, 70.0), vec2(300.0, 220.0)); + let fill = d.ctx.global_style().visuals.window_fill; + assert_ne!(fill, Color32::TRANSPARENT); + fn filled(shape: &egui::Shape, rect: Rect, fill: Color32) -> bool { + match shape { + egui::Shape::Rect(shape) => shape.rect == rect && shape.fill == fill, + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| filled(shape, rect, fill)), + _ => false, + } + } + assert!(d.shapes.iter().any(|clipped| filled(&clipped.shape, window, fill)), "no opaque fill under the floating window"); +} + +#[test] +fn double_click_on_a_floating_tab_or_bar_minimizes_and_another_tab_expands() { + let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; + let mut d = Driver::new(layout); + let minimized = |d: &Driver| d.layout.floating[0].groups[0].minimized; + let tab = d.tab(6).center(); + d.click(tab); + let out = d.click(tab); + assert!(out.actions.contains(&Action::SetMinimized { panel: 6, minimized: true }), "{:?}", out.actions); + assert!(minimized(&d)); + d.wait(); + + // Another tab of the minimized group expands it and selects that tab. + let other = d.tab(5).center(); + d.click(other); + assert!(!minimized(&d)); + assert_eq!(d.layout.floating[0].groups[0].active_panel(), Some(&5)); + + d.wait(); + let bar = d.rect("drag-bar", 5).center(); + d.click(bar); + d.click(bar); + assert!(minimized(&d)); + d.wait(); + d.click(bar); + d.click(bar); + assert!(!minimized(&d)); +} + +#[test] +fn release_over_own_position_is_a_noop() { + let mut d = Driver::new(frames()); + let bar = d.rect("drag-bar", 2); + let out = d.drag(bar.center(), bar.center() + vec2(0.0, 200.0)); + assert!(out.actions.is_empty() && out.group_drop.is_none(), "{out:?}"); + assert_eq!(d.layout, frames()); +} + +#[test] +fn floating_border_and_drag_bar_move_and_cancel_as_a_group() { + for name in ["drag-border", "drag-bar"] { + let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; + let mut d = Driver::new(layout.clone()); + let from = d.rect(name, 5).center(); + d.hold(from, from + vec2(50.0, 40.0)); + assert_eq!(d.layout, layout, "{name}: a ghost moves, not the window"); + d.step(vec![key(egui::Key::Escape)]); + d.step(vec![button(from + vec2(50.0, 40.0), false)]); + assert_eq!(d.layout, layout, "{name}"); + + let out = d.drag(from, from + vec2(50.0, 40.0)); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{name}: {:?}", out.actions); + let [x, y, w, h] = d.layout.floating[0].rect; + assert_eq!([x, y, w, h], [130.0, 110.0, 300.0, 220.0], "{name}"); + assert_eq!(d.layout.floating[0].groups[0], Group::new(vec![5, 6], 1)); + } +} + +#[test] +fn floating_border_movement_does_not_accumulate_fractional_step_rounding() { + let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; + let mut d = Driver::new(layout); + let from = d.rect("drag-border", 5).center(); + d.step(vec![Event::PointerMoved(from), button(from, true)]); + for index in 1..=8 { + d.step(vec![Event::PointerMoved(from + vec2(80.3, 60.7) * (index as f32 / 8.0))]); + } + d.step(vec![button(from + vec2(80.3, 60.7), false)]); + let [x, y, ..] = d.layout.floating[0].rect; + assert!((x - 160.3).abs() <= 1.0 && (y - 130.7).abs() <= 1.0, "{x} {y}"); +} + +#[test] +fn docked_header_drag_reaches_the_host_hook_and_preserves_the_group() { + for name in ["drag-border", "drag-bar"] { + let content = TestContent { host_owned: true, ..Default::default() }; + let mut d = Driver::with(frames(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let out = d.drag(d.rect(name, 2).center(), pos2(70.0, 300.0)); + assert!(d.content.whole_group, "{name}"); + assert!(out.actions.is_empty() && out.group_drop.is_none(), "{name}: the host owns the release"); + assert_eq!(d.layout, frames()); + } +} + +#[test] +fn lone_bare_or_protected_panels_draw_no_strip_and_no_bar() { + struct Bare; + impl DockContent for Bare { + fn body(&mut self, _: &mut egui::Ui, _: &u32) {} + fn bare(&self, panel: &u32) -> bool { + *panel == 1 + } + } + let ctx = Context::default(); + for _ in 0..2 { + ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, |ui| { + DockArea::new(Id::new(AREA)).show_content(ui, &frames(), &DockStyle::from_ui(ui), &mut Bare); + }) + .textures_delta + .clear(); + } + assert!(ctx.read_response(Id::new(AREA).with(("drag-bar", Some(&1u32)))).is_none()); + assert!(ctx.read_response(Id::new(AREA).with(("tab", &1u32))).is_none()); + assert!(ctx.read_response(Id::new(AREA).with(("drag-bar", Some(&2u32)))).is_some()); +} + +#[test] +fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, (content, actions): &mut (TestContent, Vec>)| { + let out = DockArea::new(Id::new(AREA)).show_content(ui, &docked(), &DockStyle::from_ui(ui), content); + actions.extend(out.actions); + }, + (TestContent { protected: vec![0], ..Default::default() }, Vec::new()), + ); + h.run_steps(2); + let bar_id = Id::new(AREA).with(("drag-bar", Some(&2u32))); + let at = h.ctx.read_response(bar_id).unwrap().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); + for label in ["Close Tab Group", "Minimize", "Float Tab Group", "Group with"] { + assert_eq!(h.query_all_by_label(label).count(), 1, "{label}"); + } + h.get_by_label("Close Tab Group").click(); + h.run_steps(2); + assert!(h.state().1.contains(&Action::CloseGroup { panel: 3 }), "{:?}", h.state().1); + + h.ctx.memory_mut(|memory| memory.request_focus(bar_id)); + h.run_steps(1); + assert!(DockArea::::new(Id::new(AREA)).chrome_has_focus(&h.ctx, &docked())); + h.input_mut().events.push(key(egui::Key::Enter)); + h.run_steps(2); + assert!(egui::Popup::is_any_open(&h.ctx)); +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 1be249d6c2..849a5e593b 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -19,8 +19,10 @@ pub use surface::{DockArea, DockContent, DockOutput, DockStyle, DropFeedback, Dr pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect}; pub use workspace::Workspace; -use surface::{Drag, GroupDrag}; +use surface::{Drag, GroupDrag, GroupGesture}; +#[cfg(test)] +mod group_tests; #[cfg(test)] mod model_tests; #[cfg(test)] diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index cd55820bdd..43d18e2589 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -2,7 +2,7 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Context, Id, Key, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; -use super::{Renderer, clamp_float}; +use super::{GroupKind, Renderer, clamp_float}; use crate::docking::{Action, Floating, Node, PanelLimits, resize::AnchoredResize}; /// Floating window resize handles: id suffix, hit rect and the edges they move. @@ -54,7 +54,10 @@ impl Renderer<'_, P> { let Some(first) = window.panels().next() else { continue }; let [x, y, width, height] = window.rect; let limits = self.node_limits(&Node::Tabs { panels: window.panels().cloned().collect(), active: 0 }); - let size = vec2(width, height).max(limits.min).min(limits.max); + let mut size = vec2(width, height).max(limits.min).min(limits.max); + if window.groups.iter().all(|group| group.minimized) { + size.y = size.y.min(window.groups.len() as f32 * self.style.tab_height); + } let rect = clamp_float(Rect::from_min_size(pos2(x, y), size), screen); let id = self.id.with(("floating", first)); if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { @@ -62,11 +65,14 @@ impl Renderer<'_, P> { ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); self.output.focused = self.activation.clone(); } - egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).constrain_to(screen).show(ctx, |ui| { + egui::Area::new(id).fade_in(false).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).constrain_to(screen).show(ctx, |ui| { ui.set_min_size(rect.size()); let rect = Rect::from_min_size(ui.min_rect().min, rect.size()); ui.allocate_rect(rect, Sense::hover()); - self.stacked_groups(ui, &window.groups, rect, true); + // Opaque even when the host's panel colours are transparent. + ui.painter().rect_filled(rect, 0.0, self.style.floating_background); + self.stacked_groups(ui, &window.groups, rect, GroupKind::Floating { window: rect }); + ui.painter().rect_stroke(rect, 0.0, self.style.floating_stroke, egui::StrokeKind::Outside); self.resize_handles(ui, window, id, rect, limits, screen); }); } diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 0c80d634c6..3b80dfb3e9 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -2,70 +2,77 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Key, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; -use super::{Renderer, clamp_float}; -use crate::docking::{Action, DropTarget, GroupDrag, Permissions, Placement, begin_drag, surface::TAB_PADDING}; +use super::{Renderer, clamp_float, stripless}; +use crate::docking::{Action, DropTarget, Group, GroupDrag, GroupGesture, Placement, Target, begin_drag, surface::TAB_PADDING}; use crate::tabs; +/// Where a group is drawn. It decides the drop targets the group offers and its gestures. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::docking) enum GroupKind { + /// A `Tabs` node of the split tree: side drops split it. + Frame, + /// A group in a dock column. + Dock, + /// A group in the floating window drawn at `window`. + Floating { window: Rect }, +} + +/// The group a tab belongs to, for its menu and minimize gestures. +pub(super) struct TabGroup<'a, P> { + pub(super) panels: &'a [P], + pub(super) selected: &'a P, + pub(super) minimized: bool, + pub(super) kind: GroupKind, + pub(super) rect: Rect, +} + +/// Width of a floating window's move grip at the left of each strip. +const GRIP_WIDTH: f32 = 12.0; +/// The top band of a strip that drags the whole group. +const BORDER_BAND: f32 = 4.0; + impl Renderer<'_, P> { - /// Groups stacked top to bottom in equal shares of `rect`. - pub(super) fn stacked_groups(&mut self, ui: &mut Ui, groups: &[crate::docking::Group

], rect: Rect, floating: bool) { - let share = rect.height() / groups.len().max(1) as f32; - for (index, group) in groups.iter().enumerate() { - let top = rect.top() + share * index as f32; - let group_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + share)); - self.group(ui, &group.panels, group.active, group_rect, floating); + /// Groups stacked top to bottom. Minimized groups take their strip; the others share the + /// rest equally. + pub(super) fn stacked_groups(&mut self, ui: &mut Ui, groups: &[Group

], rect: Rect, kind: GroupKind) { + let strip = self.style.tab_height; + let open = groups.iter().filter(|g| !g.minimized).count(); + let fixed = groups.len().saturating_sub(open) as f32 * strip; + let share = if open > 0 { (rect.height() - fixed).max(0.0) / open as f32 } else { 0.0 }; + let mut top = rect.top(); + for group in groups { + let bottom = (top + if group.minimized { strip } else { share }).min(rect.bottom()); + let group_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), bottom)); + self.group(ui, &group.panels, group.active, group.minimized, group_rect, kind); + top = bottom; } } - pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, rect: Rect, floating: bool) { + pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, minimized: bool, rect: Rect, kind: GroupKind) { let Some(selected) = panels.get(active) else { return }; let policy = self.permissions(selected); - let bare = panels.len() == 1 && policy == Permissions::PROTECTED; - if bare { + let splits = kind == GroupKind::Frame; + if stripless(panels, &*self.content) { self.contents(ui, selected, rect); self.targets.push(DropTarget { anchor: selected.clone(), rect, tab_strip: None, - tabs: Vec::new(), - allow_splits: !floating, - accepts_tabs: false, + tabs: vec![(selected.clone(), Rect::NOTHING)], + allow_splits: splits, + accepts_tabs: policy.accepts_tabs, }); return; } + let movable = panels.iter().all(|p| self.permissions(p).movable); let mut strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom()))); ui.painter().rect_filled(strip, 0.0, self.style.tab_background); - if floating { - let grip = Rect::from_min_max(strip.min, pos2((strip.left() + 12.0).min(strip.right()), strip.bottom())); - let response = ui.interact(grip, self.id.with(("move-group", panels.first())), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); - if panels.iter().all(|p| self.permissions(p).movable) - && response.drag_started() - && let Some(first) = panels.first() - { - ui.ctx().data_mut(|d| { - d.insert_temp( - self.id.with("group-drag"), - GroupDrag { panel: first.clone(), original: [rect.left(), rect.top(), rect.width(), rect.height()] }, - ) - }); - } - if panels.iter().all(|p| self.permissions(p).movable) - && response.dragged() - && ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))).is_some() - && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) - { - let moved = clamp_float(rect.translate(ui.input(|i| i.pointer.delta())), ui.ctx().content_rect()); - if let Some(first) = panels.first() { - self.output - .actions - .push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); - } - } - ui.painter().line_segment([grip.center() - vec2(0.0, 5.0), grip.center() + vec2(0.0, 5.0)], self.style.border); + if let GroupKind::Floating { window } = kind { + let grip = Rect::from_min_max(strip.min, pos2((strip.left() + GRIP_WIDTH).min(strip.right()), strip.bottom())); + self.window_grip(ui, panels, grip, window, movable); strip.min.x = grip.right(); } + let floating = matches!(kind, GroupKind::Floating { .. }); let requested = self.content.group_header_width(panels, selected, floating); let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 }; if header_width > 0.0 { @@ -74,6 +81,9 @@ impl Renderer<'_, P> { child.set_clip_rect(header.intersect(ui.clip_rect())); self.content.group_header(&mut child, panels, selected, floating); } + // The drag bar keeps its reserved width: tabs shrink, then overflow, before it narrows. + let bar_width = self.style.drag_bar_width.clamp(0.0, (strip.width() - header_width).max(0.0)); + let tabs_width = (strip.width() - header_width - bar_width).max(0.0); let widths: Vec = panels .iter() .map(|p| { @@ -85,19 +95,21 @@ impl Renderer<'_, P> { + TAB_PADDING }) .collect(); - let fit = tabs::fit(&widths, active, (strip.width() - header_width).max(0.0), 40.0, 22.0); + let fit = tabs::fit(&widths, active, tabs_width, 40.0, 22.0); + let owner = TabGroup { panels, selected, minimized, kind, rect }; let mut x = strip.left(); - let mut targets = Vec::new(); + let mut shown = Vec::new(); for (index, width) in &fit.shown { let Some(panel) = panels.get(*index) else { continue }; let tab = Rect::from_min_size(pos2(x, strip.top()), vec2(*width, strip.height())); - self.tab(ui, panel, tab, *index == active, rect); - targets.push((panel.clone(), tab)); + self.tab(ui, panel, tab, *index == active, rect, Some(&owner)); + shown.push((panel.clone(), tab)); x += width; } if !fit.overflow.is_empty() && fit.overflow_width > 0.0 { let overflow = Rect::from_min_size(pos2(x, strip.top()), vec2(fit.overflow_width, strip.height())); let response = ui.interact(overflow, self.id.with(("overflow", selected)), Sense::click()); + self.register_interaction(ui.ctx(), response.id); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.panels_label)); ui.painter().with_clip_rect(overflow).text(overflow.center(), egui::Align2::CENTER_CENTER, "…", self.style.font.clone(), self.style.text); egui::Popup::menu(&response).show(|ui| { @@ -113,25 +125,190 @@ impl Renderer<'_, P> { } }); }); + x += fit.overflow_width; } - // Include hidden tab identities for source-group detection without creating hit areas. - for panel in panels { - if !targets.iter().any(|(p, _)| p == panel) { - targets.push((panel.clone(), Rect::NOTHING)); - } - } + let bar = Rect::from_min_max(pos2(x.min(strip.right() - header_width), strip.top()), pos2(strip.right() - header_width, strip.bottom())); + self.group_handle(ui, "drag-bar", bar, &owner, movable); + // Registered last, so the band wins over the tabs below it. + let border = Rect::from_min_max(strip.min, pos2(strip.right() - header_width, (strip.top() + BORDER_BAND).min(strip.bottom()))); + self.group_handle(ui, "drag-border", border, &owner, movable); + // Logical order, hidden tabs included without a hit area, for no-op detection. + let tabs = + panels.iter().map(|panel| (panel.clone(), shown.iter().find(|(p, _)| p == panel).map_or(Rect::NOTHING, |(_, rect)| *rect))).collect(); self.targets.push(DropTarget { anchor: selected.clone(), rect, tab_strip: Some(strip), - tabs: targets, - allow_splits: !floating, + tabs, + allow_splits: splits, accepts_tabs: policy.accepts_tabs, }); - self.contents(ui, selected, Rect::from_min_max(pos2(rect.left(), strip.bottom()), rect.max)); + if !minimized { + self.contents(ui, selected, Rect::from_min_max(pos2(rect.left(), strip.bottom()), rect.max)); + } ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); } + /// The floating window's own move: the window follows the pointer, every group included. + fn window_grip(&mut self, ui: &mut Ui, panels: &[P], grip: Rect, window: Rect, movable: bool) { + let Some(first) = panels.first() else { return }; + let response = ui.interact(grip, self.id.with(("move-group", Some(first))), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); + if movable && response.drag_started() { + let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center()); + let drag = GroupDrag { + panel: first.clone(), + original: [window.left(), window.top(), window.width(), window.height()], + gesture: GroupGesture::Window, + members: panels.to_vec(), + origin, + source: window, + }; + ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag)); + } + if movable + && response.dragged() + && let Some(drag) = ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))) + && drag.gesture == GroupGesture::Window + && let Some(pointer) = ui.ctx().pointer_interact_pos() + && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) + { + // From the press origin, so fractional pointer steps do not accumulate rounding. + let moved = clamp_float(drag.source.translate(pointer - drag.origin), ui.ctx().content_rect()); + self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); + } + ui.painter().line_segment([grip.center() - vec2(0.0, 5.0), grip.center() + vec2(0.0, 5.0)], self.style.border); + } + + /// The drag bar (`drag-bar`: click, double-click, menu and drag) or the top border band + /// (`drag-border`: drag only). Both move the whole group. + fn group_handle(&mut self, ui: &mut Ui, name: &'static str, hit: Rect, owner: &TabGroup<'_, P>, movable: bool) { + if !crate::docking::targets::usable(hit) { + return; + } + let bar = name == "drag-bar"; + let sense = if bar { Sense::click_and_drag() } else { Sense::drag() }; + let response = ui.interact(hit, self.id.with((name, owner.panels.first())), sense); + let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response }; + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label)); + if movable && response.drag_started() { + self.start_group_drag(ui, owner.panels, owner.rect); + } + if !bar { + return; + } + if owner.kind != GroupKind::Frame && response.double_clicked() { + self.output.actions.push(Action::SetMinimized { panel: owner.selected.clone(), minimized: !owner.minimized }); + } + if response.has_focus() || response.hovered() { + ui.painter().with_clip_rect(hit).rect_stroke( + hit.shrink(1.0), + 0.0, + Stroke::new(1.0, self.style.accent.gamma_multiply(0.5)), + StrokeKind::Inside, + ); + } + let keyboard = response.has_focus() && ui.input(|i| i.key_pressed(Key::Enter) || i.key_pressed(Key::Space)); + let command = if response.secondary_clicked() || keyboard { + Some(egui::SetOpenCommand::Bool(true)) + } else if response.clicked() { + Some(egui::SetOpenCommand::Bool(false)) + } else { + None + }; + egui::Popup::menu(&response).open_memory(command).show(|ui| self.group_menu(ui, owner, owner.selected)); + } + + fn start_group_drag(&mut self, ui: &Ui, panels: &[P], rect: Rect) { + let Some(first) = panels.first() else { return }; + let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(rect.center()); + let drag = GroupDrag { + panel: first.clone(), + original: [rect.left(), rect.top(), rect.width(), rect.height()], + gesture: GroupGesture::Group, + members: panels.to_vec(), + origin, + source: rect, + }; + ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag)); + } + + /// The group items of the menu tail: Close Tab Group, Minimize or Expand, Float Tab Group + /// and Group with. `panel` is the panel whose menu this is. + fn group_menu(&mut self, ui: &mut Ui, owner: &TabGroup<'_, P>, panel: &P) { + let all = |check: &dyn Fn(crate::docking::Permissions) -> bool| owner.panels.iter().all(|p| check(self.permissions(p))); + let closable = all(&|p| p.closable); + let movable = all(&|p| p.movable); + let floatable = movable && all(&|p| p.floatable); + if closable && self.menu_action(ui, &self.style.close_group_label.clone()) { + self.output.actions.push(Action::CloseGroup { panel: panel.clone() }); + } + if owner.kind != GroupKind::Frame { + let label = if owner.minimized { self.style.expand_label.clone() } else { self.style.minimize_label.clone() }; + if self.menu_action(ui, &label) { + self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !owner.minimized }); + } + } + if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.style.float_group_label.clone()) { + let rect = clamp_float(owner.rect.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); + self.output.actions.push(Action::MoveGroup { + panel: panel.clone(), + to: Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) }, + }); + } + let targets = if movable { self.group_targets(owner.panels) } else { Vec::new() }; + if !targets.is_empty() { + let logical = self.style.group_with_label.clone(); + let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text); + let response = ui.menu_button(text, |ui| { + egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { + for target in &targets { + if self.menu_label(ui, target).clicked() { + self.output.actions.push(Action::MoveGroup { + panel: panel.clone(), + to: Target::At { anchor: target.clone(), placement: Placement::Tab { before: None } }, + }); + ui.close(); + } + } + }); + }); + response.response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); + } + } + + /// A stock menu button with shaped text and its logical accessibility label; true when + /// clicked, after closing the menu. + fn menu_action(&mut self, ui: &mut Ui, logical: &str) -> bool { + let text = self.content.action_label(ui, logical, &self.style.font, self.style.text); + let response = ui.button(text); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), logical)); + if response.clicked() { + ui.close(); + } + response.clicked() + } + + /// One anchor per other group that accepts a whole group as tabs, in layout order. + fn group_targets(&self, members: &[P]) -> Vec

{ + let Some(first) = members.first() else { return Vec::new() }; + let mut places = Vec::new(); + let mut anchors = Vec::new(); + for anchor in self.layout.move_targets(first, |p| self.permissions(p)) { + if members.contains(anchor) { + continue; + } + let Some(place) = self.layout.place(anchor) else { continue }; + if !places.contains(&place) { + places.push(place); + anchors.push(anchor.clone()); + } + } + anchors + } + pub(super) fn menu_label(&mut self, ui: &mut Ui, panel: &P) -> egui::Response { let logical = self.label_of(panel); let text = self.content.label(ui, panel, &logical, &self.style.font, self.style.text); @@ -140,7 +317,8 @@ impl Renderer<'_, P> { response } - pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect) { + pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect, owner: Option<&TabGroup<'_, P>>) { + let minimized = owner.filter(|owner| owner.kind != GroupKind::Frame).map(|owner| owner.minimized); let policy = self.permissions(panel); let label = self.label_of(panel); let color = if active { self.style.text } else { self.style.inactive_text }; @@ -166,6 +344,14 @@ impl Renderer<'_, P> { if response.clicked() { self.output.actions.push(Action::Activate { panel: panel.clone() }); self.output.focused = Some(panel.clone()); + if minimized == Some(true) && !active { + self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: false }); + } + } + if let Some(minimized) = minimized + && response.double_clicked() + { + self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized }); } if policy.movable && response.drag_started() { begin_drag(ui.ctx(), self.id, panel.clone(), group); @@ -212,6 +398,10 @@ impl Renderer<'_, P> { ui.close(); } } + if let Some(owner) = owner { + ui.separator(); + self.group_menu(ui, owner, panel); + } }); } } diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 9ed2e9c856..7539a1c0c5 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -8,6 +8,8 @@ use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node mod floating; +pub(in crate::docking) use group::GroupKind; + pub(in crate::docking) use floating::RESIZE_HANDLES; mod group; mod preview; @@ -90,7 +92,7 @@ impl Renderer<'_, P> { self.output.actions.push(Action::ResizeSplit { path: path.clone(), size }); } } - Node::Tabs { panels, active } => self.group(ui, panels, *active, rect, false), + Node::Tabs { panels, active } => self.group(ui, panels, *active, false, rect, GroupKind::Frame), Node::Dock { columns, .. } => { // Interim rendering: columns side by side, groups stacked evenly. let total: f32 = columns.iter().map(|c| c.width).sum(); @@ -99,7 +101,7 @@ impl Renderer<'_, P> { let width = if total > 0.0 { rect.width() * column.width / total } else { 0.0 }; let column_rect = Rect::from_min_max(pos2(left, rect.top()), pos2(left + width, rect.bottom())); left += width; - self.stacked_groups(ui, &column.groups, column_rect, false); + self.stacked_groups(ui, &column.groups, column_rect, GroupKind::Dock); } } Node::Stack { entries } => { @@ -117,7 +119,7 @@ impl Renderer<'_, P> { }; let panel_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), (top + header + share).min(rect.bottom()))); let title_rect = Rect::from_min_max(panel_rect.min, pos2(panel_rect.right(), (top + header).min(panel_rect.bottom()))); - self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect); + self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect, None); let collapse = Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max); let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click()); response.widget_info(|| { @@ -207,6 +209,14 @@ impl Renderer<'_, P> { } } +/// A lone protected or bare panel draws no tab strip and no drag bar. +pub(in crate::docking) fn stripless

(panels: &[P], content: &dyn DockContent

) -> bool { + match panels { + [panel] => content.permissions(panel) == Permissions::PROTECTED || content.bare(panel), + _ => false, + } +} + /// Size policy of a subtree, shared by the renderer and its measurements. pub(in crate::docking) fn node_limits

(node: &Node

, style: &DockStyle, content: &dyn DockContent

) -> PanelLimits { match node { @@ -219,7 +229,7 @@ pub(in crate::docking) fn node_limits

(node: &Node

, style: &DockStyle, cont limits.max = limits.max.min(policy.max); } limits.max = limits.max.max(limits.min); - if panels.len() != 1 || panels.first().is_some_and(|p| content.permissions(p) != Permissions::PROTECTED) { + if !stripless(panels, content) { limits.min.y = (limits.min.y + style.tab_height).min(1_000_000.0); limits.max.y = (limits.max.y + style.tab_height).min(1_000_000.0); } diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 9b6214f933..de2aa4452b 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -1,31 +1,41 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Context, Key, Pos2, Rect, Stroke, StrokeKind, Vec2, vec2}; +use egui::{Color32, Context, Key, Pos2, Rect, Stroke, StrokeKind, Vec2, vec2}; use super::{Renderer, clamp_float}; -use crate::docking::{Action, Drag, DropRequest, GroupDrag, cancel_drag, dock_model::Place, resolve_drop}; +use crate::docking::{ + Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Placement, Target, Zone, cancel_drag, dock_model::Place, resolve_drop, +}; + +/// Ctrl (Windows, Linux) or Cmd (macOS) held: the drop floats and no target is offered. +fn float_only(ctx: &Context) -> bool { + ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.mac_cmd) +} /// Height of a panel floated out of a dock column when the host gives no floating size. const DOCKED_FLOAT_HEIGHT: f32 = 320.0; impl Renderer<'_, P> { pub(in crate::docking) fn finish_group_drag(&mut self, ctx: &Context) { - let Some(drag) = ctx.data(|d| d.get_temp::>(self.id.with("group-drag"))) else { return }; - if !self.layout.floating.iter().any(|g| g.contains(&drag.panel) && g.panels().all(|p| self.permissions(p).movable)) { - ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); + let key = self.id.with("group-drag"); + let Some(drag) = ctx.data(|d| d.get_temp::>(key)) else { return }; + if !drag.members.iter().all(|p| self.layout.contains(p) && self.permissions(p).movable) { + ctx.data_mut(|d| d.remove::>(key)); return; } let (escape, focused, down, released, pointer) = ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); + let pointer = pointer.filter(|p| p.is_finite()); + let ghost = pointer.map(|pointer| clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect())); if !escape && focused && (down || released) - && let Some(pointer) = pointer.filter(|p| p.is_finite()) + && let Some(pointer) = pointer && !self.blockers.iter().any(|r| r.contains(pointer)) - && self.host_drop(ctx, &drag.panel, pointer, true, released, None) + && self.host_drop(ctx, &drag.panel, pointer, true, released, ghost.filter(|_| drag.gesture == GroupGesture::Group)) { if released { - ctx.data_mut(|d| d.remove::>(self.id.with("group-drag"))); + ctx.data_mut(|d| d.remove::>(key)); } return; } @@ -33,19 +43,95 @@ impl Renderer<'_, P> { let has_pointer = ctx.input(|i| i.pointer.has_pointer()); // Touch-up also removes the pointer, but still completes a drop. let touch_ended = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::End, .. }))); + let float_only = float_only(ctx); if escape || !focused || !down || !has_pointer { cancel_drag::

(ctx, self.id); if escape || !focused { - self.output.actions.push(Action::MoveFloating { panel: drag.panel, rect: drag.original }); - } else if released - && (has_pointer || touch_ended) - && let Some(pointer) = pointer.filter(|p| p.is_finite()) - && !self.blockers.iter().any(|r| r.contains(pointer)) - { - self.output.group_drop = Some((drag.panel, pointer)); + if drag.gesture == GroupGesture::Window { + self.output.actions.push(Action::MoveFloating { panel: drag.panel, rect: drag.original }); + } + return; + } + // Leaving the window ends a group drag where it is, with no drop. + if !released || !(has_pointer || touch_ended) { + return; + } + let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return }; + match drag.gesture { + GroupGesture::Window => self.output.group_drop = Some((drag.panel, pointer)), + GroupGesture::Group => self.drop_group(ctx, &drag, pointer, float_only), + } + } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { + self.output.group_drag = Some(drag.panel.clone()); + if drag.gesture == GroupGesture::Group { + self.paint_group_drag(ctx, &drag, pointer, float_only); + } + } + } + + /// The valid target under the pointer for a whole group. A target holding the group + /// itself is a no-op proposal; a target the model would reject is no target. + fn group_proposal(&self, drag: &GroupDrag

, pointer: Pos2) -> Option> { + let target = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer))?; + if target.tabs.iter().any(|(p, _)| drag.members.contains(p)) { + return Some(DropProposal { + anchor: drag.panel.clone(), + placement: Placement::Tab { before: None }, + preview: target.rect, + insertion: None, + noop: true, + }); + } + let proposal = resolve_drop(&drag.panel, pointer, std::slice::from_ref(target))?; + let action = Action::MoveGroup { + panel: drag.panel.clone(), + to: Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }, + }; + self.layout.clone().apply_with_permissions(action, |p| self.permissions(p)).is_ok().then_some(proposal) + } + + /// Release of a group drag: join or split at the target, or float at the ghost with the + /// group's size. Over its own docked position nothing changes; a floating group released + /// over itself moves there. + fn drop_group(&mut self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + if pointer.distance(drag.origin) < 2.0 { + return; + } + let floating = matches!(self.layout.place(&drag.panel), Some(Place::Floating { .. })); + let proposal = if float_only { None } else { self.group_proposal(drag, pointer) }; + if let Some(proposal) = proposal.as_ref().filter(|p| !p.noop) { + let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; + self.output.actions.push(Action::MoveGroup { panel: drag.panel.clone(), to }); + return; + } + if proposal.is_some() && !floating { + return; + } + // No target: hosts that still apply their own policy for a whole-group release get it. + self.output.group_drop = Some((drag.panel.clone(), pointer)); + let rect = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); + let action = + Action::MoveGroup { panel: drag.panel.clone(), to: Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) } }; + if self.layout.clone().apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() { + self.output.actions.push(action); + } + } + + /// Ghost outline at the pointer and one destination preview. + fn paint_group_drag(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + let painter = self.preview_painter(ctx); + let ghost = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); + painter.rect_stroke(ghost, 0.0, Stroke::new(1.0, self.style.accent.gamma_multiply(0.6)), StrokeKind::Inside); + if float_only { + return; + } + if let Some(proposal) = self.group_proposal(drag, pointer).filter(|p| !p.noop) { + let split = matches!(proposal.placement, Placement::Split(zone) if zone != Zone::Center); + let fill = if split { self.style.accent.gamma_multiply(0.15) } else { Color32::TRANSPARENT }; + painter.rect(proposal.preview.shrink(1.0), 0.0, fill, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + if let Some(marker) = proposal.insertion { + painter.rect_filled(marker, 0.0, self.style.accent); } - } else if pointer.is_some_and(|p| !self.blockers.iter().any(|r| r.contains(p))) { - self.output.group_drag = Some(drag.panel); } } @@ -74,8 +160,9 @@ impl Renderer<'_, P> { } return; } + let float_only = float_only(ctx); let floatable = self.permissions(&drag.panel).floatable - && (gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); + && (float_only || gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); let floating_rect = floatable.then(|| self.tab_float_rect(ctx, &drag, pointer)); if self.host_drop(ctx, &drag.panel, pointer, false, released, floating_rect) { if released { @@ -83,7 +170,7 @@ impl Renderer<'_, P> { } return; } - let proposal = resolve_drop(&drag.panel, pointer, &self.targets); + let proposal = if float_only { None } else { resolve_drop(&drag.panel, pointer, &self.targets) }; if released { cancel_drag::

(ctx, self.id); if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !gone) { diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 5321fb2531..901fc27312 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -32,6 +32,19 @@ pub struct DockStyle { pub panels_label: String, pub resize_label: String, pub resize_window_label: String, + /// Accessibility label of a group's drag bar and top border. + pub move_group_label: String, + pub close_group_label: String, + pub minimize_label: String, + pub expand_label: String, + pub float_group_label: String, + pub group_with_label: String, + /// Minimum width of the drag bar left of the group header. Tabs shrink, then overflow, + /// before the bar narrows. + pub drag_bar_width: f32, + /// Painted under every floating window, so it stays opaque when the panel colours are not. + pub floating_background: Color32, + pub floating_stroke: Stroke, } impl DockStyle { @@ -55,11 +68,22 @@ impl DockStyle { panels_label: "Panels".into(), resize_label: "Resize panels".into(), resize_window_label: "Resize panel window".into(), + move_group_label: "Move tab group".into(), + close_group_label: "Close Tab Group".into(), + minimize_label: "Minimize".into(), + expand_label: "Expand".into(), + float_group_label: "Float Tab Group".into(), + group_with_label: "Group with".into(), + drag_bar_width: 40.0, + floating_background: visuals.window_fill, + floating_stroke: visuals.window_stroke, } } pub(super) fn valid(&self) -> bool { - [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size].iter().all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) + [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size, self.drag_bar_width, self.floating_stroke.width] + .iter() + .all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) && self.tab_height > 0.0 && self.font.size > 0.0 } @@ -117,10 +141,26 @@ pub(super) struct Drag

{ pub(super) grab: Vec2, } +/// What a group gesture moves. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum GroupGesture { + /// A floating window's grip: the window follows the pointer. + Window, + /// A drag bar or top border: a ghost follows the pointer, the release picks the target. + Group, +} + #[derive(Clone)] pub(super) struct GroupDrag

{ + /// The first member; identifies the gesture. pub(super) panel: P, + /// The floating window rect at the press, restored when a window move is cancelled. pub(super) original: [f32; 4], + pub(super) gesture: GroupGesture, + pub(super) members: Vec

, + pub(super) origin: Pos2, + /// The group (or window) rect at the press. A floated group keeps this size. + pub(super) source: Rect, } /// Start a docking drag from an application's existing tab/header. Use the same area ID when @@ -322,7 +362,7 @@ impl DockArea

{ let matches = |id: Id| id == focused; let group = |panels: &[P]| { panels.iter().any(|panel| matches(self.id.with(("tab", panel))) || matches(self.id.with(("overflow", panel)))) - || matches(self.id.with(("move-group", panels.first()))) + || ["move-group", "drag-bar", "drag-border"].iter().any(|name| matches(self.id.with((*name, panels.first())))) }; for floating in &layout.floating { if floating.groups.iter().any(|g| group(&g.panels)) From 4bf11647adb05e1b6f5a49c1ae5f7105bf746c71 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:56:52 +0000 Subject: [PATCH 12/94] docking: test tearing a group out of a floating stack --- crates/ui/src/docking/group_tests.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 584fff2e31..7edcf28fa4 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -519,3 +519,16 @@ fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() { h.run_steps(2); assert!(egui::Popup::is_any_open(&h.ctx)); } + +#[test] +fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() { + let stack = Floating { groups: vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], rect: [80.0, 70.0, 300.0, 400.0], native: None }; + let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![stack] }; + let mut d = Driver::new(layout); + let from = d.rect("drag-bar", 6).center(); + let out = d.drag(from, pos2(700.0, 300.0)); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 200.0]) })), "{:?}", out.actions); + assert_eq!(d.layout.floating.len(), 2); + assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![5], 0)]); + assert_eq!(d.layout.floating[1].groups, vec![Group::new(vec![6, 7], 1)]); +} From 954ad06d250399e3ebc18ac9a0fad785eb7d7445 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:05:42 +0000 Subject: [PATCH 13/94] docking: Placement::Edge splits the layout's outer edge A frame along one edge of the docked layout, a quarter of its size. In a layout with docks the split wraps the part between them, so a bottom Timeline or top bar stays inside the docks. Behaviour follows filmcraft dock_ui.rs (workspace_edge). --- crates/ui/src/docking/dock_model.rs | 39 +++++++++++++++++++++++++++- crates/ui/src/docking/model.rs | 8 +++++- crates/ui/src/docking/model_tests.rs | 23 ++++++++++++++++ 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index d4200fe3b3..05b3409fce 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -6,7 +6,7 @@ use std::hash::Hash; -use super::model::{DockError, Floating, Layout, MAX_NODES, Node, Placement, Zone, valid_rect, valid_width}; +use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, Node, Placement, Zone, valid_rect, valid_width}; use crate::layout::{SplitAxis, SplitSize}; /// Width of a new column when nothing better is known. @@ -242,6 +242,25 @@ impl Layout

{ None } + /// The node an edge split wraps: the root, or the part between the docks. + pub(in crate::docking) fn edge_path(&self) -> Vec { + let mut path = Vec::new(); + let mut node = self.root.as_ref(); + while let Some(Node::Split { axis: SplitAxis::Horizontal, first, second, .. }) = node { + if path.len() > MAX_DEPTH { + break; + } + let second_side = match (&**first, &**second) { + (Node::Dock { .. }, _) => true, + (_, Node::Dock { .. }) => false, + _ => break, + }; + path.push(second_side); + node = Some(if second_side { second } else { first }); + } + path + } + pub(super) fn columns_mut(&mut self, path: &[bool]) -> Option<&mut Vec>> { match self.root.as_mut().and_then(|root| node_at_mut(root, path)) { Some(Node::Dock { columns, .. }) => Some(columns), @@ -494,6 +513,24 @@ impl Layout

{ groups.splice(index..index, moving.groups); Ok(()) } + Placement::Edge(zone) => { + if zone == Zone::Center || matches!(place, Place::Floating { .. }) { + return Err(DockError::InvalidPlacement); + } + let path = self.edge_path(); + let node = self.root.as_mut().and_then(|root| node_at_mut(root, &path)).ok_or(DockError::MissingTarget)?; + if matches!(node, Node::Dock { .. }) { + return Err(DockError::InvalidPlacement); + } + let (panels, active) = flatten(moving.groups); + let new = Node::Tabs { panels, active }; + let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); + let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; + let (first, second, size) = + if matches!(zone, Zone::Top | Zone::Left) { (new, old, 0.25) } else { (old, new, 0.75) }; + *node = Node::Split { axis, size: SplitSize::Ratio(size), first: Box::new(first), second: Box::new(second) }; + Ok(()) + } Placement::Column { after } => { let Place::Dock { path, column, .. } = &place else { return Err(DockError::InvalidPlacement) }; let columns = self.columns_mut(path).ok_or(DockError::MissingTarget)?; diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 92eeedbb78..952092ea93 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -169,6 +169,10 @@ pub enum Placement

{ Group { below: bool }, /// A new column before (towards the window edge) or after the anchor's column. Column { after: bool }, + /// A new frame along one edge of the docked layout, a quarter of its width or height: the + /// root is split, or in a layout with docks, the part between them. The anchor names any + /// docked panel. `Center` is invalid. + Edge(Zone), } /// A closed panel's former placement. Applications may retain this beside visibility flags. @@ -970,7 +974,9 @@ impl Layout

{ fn insert(&mut self, entry: StackEntry

, anchor: &P, placement: Placement

) -> Result<(), DockError> { let place = self.place(anchor).ok_or(DockError::MissingTarget)?; - if matches!(place, Place::Dock { .. } | Place::Floating { .. }) || matches!(placement, Placement::Group { .. } | Placement::Column { .. }) { + if matches!(place, Place::Dock { .. } | Place::Floating { .. }) + || matches!(placement, Placement::Group { .. } | Placement::Column { .. } | Placement::Edge(_)) + { let group = Group::new(vec![entry.panel], 0); return self.insert_moving(Moving::group(group), Target::At { anchor: anchor.clone(), placement }); } diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index bbd9ae0570..88ca72f610 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -470,3 +470,26 @@ mod serde_tests { } } } + +#[test] +fn edge_placement_splits_the_part_between_the_docks_or_the_root() { + // Dock layout: a floating window lands under the frames, beside the end dock. + let mut layout = docked(); + layout.apply(Action::MoveWindow { panel: 6, to: Target::At { anchor: 1, placement: Placement::Edge(Zone::Bottom) } }).unwrap(); + let Some(Node::Split { first, second, .. }) = &layout.root else { panic!("{layout:?}") }; + assert!(matches!(&**second, Node::Dock { .. })); + let Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(size), second: bottom, .. } = &**first else { panic!("{first:?}") }; + assert_eq!(*size, 0.75); + assert_eq!(**bottom, tabs(&[6, 7, 8], 1)); + assert!(layout.floating.is_empty()); + + // Frame layout: one panel takes the whole left edge. + let mut frames = Layout { root: Some(hsplit(SplitSize::Ratio(0.5), tabs(&[1], 0), tabs(&[2, 3], 0))), floating: Vec::new() }; + frames.apply(Action::Move { panel: 3, anchor: 1, placement: Placement::Edge(Zone::Left) }).unwrap(); + let Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(size), first, .. }) = &frames.root else { panic!() }; + assert_eq!((*size, &**first), (0.25, &tabs(&[3], 0))); + + let before = frames.clone(); + assert_eq!(frames.apply(Action::Move { panel: 2, anchor: 1, placement: Placement::Edge(Zone::Center) }), Err(DockError::InvalidPlacement)); + assert_eq!(frames, before); +} From f1a3683cc996bb5dbe3e964de7f0ab61e60143f4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:15:14 +0000 Subject: [PATCH 14/94] docking: dock profile with columns, column bars, seams and dock targets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Node::Dock renders as side docks: columns from the window edge inwards, each with a column bar (drag, »/« button, double-click and menu toggle iconic) above stacked groups. A split beside a dock gives the dock its columns' width. Every column's inner edge resizes it; dividers between open groups save both heights; minimized groups keep theirs. A column whose groups' minimum heights do not fit scrolls. Drops resolve dock targets before group targets: column edges (new column), seams and the top or bottom quarter of a group body (new group), the room under a minimized column (below its last group) and the left or right edge of the docked area without a dock (new dock, offered once the layout has a dock). They show a horizontal or full-height vertical line. Floating windows and host overlays occlude them. Tab drags use the same targets with Move. A column bar drag moves the column with a ghost and floats its groups away from a dock; Escape, focus loss, pointer exit and cancel_drag cancel it like a group drag. Side::Start maps to the left edge, or the right with DockStyle::right_to_left. New DockStyle fields: column_bar_height, seam_band, edge_band, right_to_left and the column labels. Behaviour follows vectorcraft crates/ui-egui/src/floating.rs (drop geometry, column layout and scrolling) and photocraft crates/ui-egui/src/dock.rs (group heights). --- crates/ui/src/docking/render/dock.rs | 505 ++++++++++++++++++++++++ crates/ui/src/docking/render/group.rs | 5 +- crates/ui/src/docking/render/mod.rs | 21 +- crates/ui/src/docking/render/preview.rs | 41 +- crates/ui/src/docking/surface.rs | 35 +- crates/ui/src/docking/targets.rs | 76 +++- 6 files changed, 656 insertions(+), 27 deletions(-) create mode 100644 crates/ui/src/docking/render/dock.rs diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs new file mode 100644 index 0000000000..c3e399667a --- /dev/null +++ b/crates/ui/src/docking/render/dock.rs @@ -0,0 +1,505 @@ +//! [D] The dock profile: side docks of columns, each a column bar above stacked groups. +//! +//! Columns run from the window edge inwards. Every column's inner edge resizes it; the last +//! column's inner edge is the dock's inner edge. Behaviour follows VectorCraft `floating.rs` +//! (column layout, drop geometry) and PhotoCraft `dock.rs` (group heights). + +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; + +use super::{GroupKind, Renderer}; +use crate::docking::{ + Action, Column, Group, GroupDrag, GroupGesture, Node, Side, Target, + targets::{DockDrop, DockTarget, column_edge, horizontal_line, resolve_dock, usable, vertical_line}, +}; +use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; + +/// Width of an iconic column without a saved width. +const ICONIC_WIDTH: f32 = 36.0; +/// Widest an iconic column gets by dragging its inner edge. +const ICONIC_MAX: f32 = 240.0; +/// Width of the »/« button at the outer end of a column bar. +const COLLAPSE_WIDTH: f32 = 18.0; + +/// The physical window edge a dock sits on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::docking) enum Edge { + Left, + Right, +} + +/// `Start` is the left edge in a left-to-right layout and the right edge in a right-to-left one. +pub(in crate::docking) fn edge_of(side: Side, right_to_left: bool) -> Edge { + match (side, right_to_left) { + (Side::Start, false) | (Side::End, true) => Edge::Left, + (Side::Start, true) | (Side::End, false) => Edge::Right, + } +} + +fn side_at(edge: Edge, right_to_left: bool) -> Side { + match (edge, right_to_left) { + (Edge::Left, false) | (Edge::Right, true) => Side::Start, + (Edge::Left, true) | (Edge::Right, false) => Side::End, + } +} + +pub(in crate::docking) fn column_width

(column: &Column

) -> f32 { + if column.iconic { column.iconic_width.unwrap_or(ICONIC_WIDTH) } else { column.width } +} + +/// Heights of stacked groups in a column body `room` high. Each entry is (minimized, saved +/// height, minimum). Minimized groups take `strip`, groups with a saved height keep it, and the +/// rest share what is left; when every open group has a height, the last one takes the rest. +/// Saved heights shrink towards their minimums before the column overflows and scrolls. +pub(in crate::docking) fn group_heights(groups: &[(bool, Option, f32)], strip: f32, room: f32) -> Vec { + let open: Vec = (0..groups.len()).filter(|i| groups.get(*i).is_some_and(|g| !g.0)).collect(); + let mut shared: Vec = open.iter().copied().filter(|i| groups.get(*i).is_some_and(|g| g.1.is_none_or(|h| !h.is_finite()))).collect(); + if shared.is_empty() { + shared.extend(open.last()); + } + let mut heights: Vec = groups + .iter() + .enumerate() + .map(|(i, (minimized, height, min))| { + if *minimized { + strip + } else if shared.contains(&i) { + 0.0 + } else { + height.unwrap_or(*min).max(*min) + } + }) + .collect(); + let mins: Vec = groups.iter().map(|g| if g.0 { strip } else { g.2 }).collect(); + let shared_min: f32 = shared.iter().filter_map(|i| mins.get(*i)).sum(); + let deficit = heights.iter().sum::() + shared_min - room; + let slack: f32 = open.iter().filter(|i| !shared.contains(i)).filter_map(|i| Some(heights.get(*i)? - mins.get(*i)?)).sum(); + if deficit > 0.0 && slack > 0.0 { + let take = deficit.min(slack) / slack; + for i in open.iter().filter(|i| !shared.contains(i)) { + if let (Some(height), Some(min)) = (heights.get_mut(*i), mins.get(*i)) { + *height -= (*height - min) * take; + } + } + } + let free = (room - heights.iter().sum::()).max(0.0); + let share = free / shared.len().max(1) as f32; + for i in &shared { + if let (Some(height), Some(min)) = (heights.get_mut(*i), mins.get(*i)) { + *height = share.max(*min); + } + } + heights +} + +impl Renderer<'_, P> { + /// A horizontal split with a dock child: the dock takes its columns' width on its physical + /// edge, the sibling the rest. False when neither child is a dock. + pub(super) fn dock_split(&mut self, ui: &mut Ui, first: &Node

, second: &Node

, rect: Rect, path: &mut Vec) -> bool { + let (dock_first, side, columns, other) = match (first, second) { + (Node::Dock { side, columns }, other) => (true, *side, columns, other), + (other, Node::Dock { side, columns }) => (false, *side, columns, other), + _ => return false, + }; + let gap = self.style.gap; + let room = (rect.width() - gap - self.node_limits(other).min.x).clamp(0.0, rect.width()); + let width = columns.iter().map(column_width).sum::().clamp(0.0, room); + let (dock, rest) = match edge_of(side, self.style.right_to_left) { + Edge::Left => ( + Rect::from_min_max(rect.min, pos2(rect.left() + width, rect.bottom())), + Rect::from_min_max(pos2((rect.left() + width + gap).min(rect.right()), rect.top()), rect.max), + ), + Edge::Right => ( + Rect::from_min_max(pos2(rect.right() - width, rect.top()), rect.max), + Rect::from_min_max(rect.min, pos2((rect.right() - width - gap).max(rect.left()), rect.bottom())), + ), + }; + self.dock(ui, side, columns, dock, room); + path.push(dock_first); + self.node(ui, other, rest, path); + path.pop(); + true + } + + /// One dock in `rect`, columns from its outer edge. `room` is the widest the dock may get. + pub(super) fn dock(&mut self, ui: &mut Ui, side: Side, columns: &[Column

], rect: Rect, room: f32) { + let edge = edge_of(side, self.style.right_to_left); + let (outer, inward) = match edge { + Edge::Left => (rect.left(), 1.0), + Edge::Right => (rect.right(), -1.0), + }; + if columns.is_empty() { + let (band, line) = column_edge(outer, inward, rect.y_range()); + let band = band.union(Rect::from_x_y_ranges( + outer.min(outer + inward * self.style.edge_band)..=outer.max(outer + inward * self.style.edge_band), + rect.y_range(), + )); + self.dock_targets.push(DockDrop { target: DockTarget::NewDock { side }, band, line }); + return; + } + if usable(rect) { + ui.painter().rect_filled(rect, 0.0, self.style.background); + } + let total: f32 = columns.iter().map(column_width).sum(); + let mut x = outer; + let mut drawn = Vec::new(); + for (index, column) in columns.iter().enumerate() { + let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { continue }; + let width = column_width(column).min((rect.width() - (x - outer).abs()).max(0.0)); + let inner = x + inward * width; + let column_rect = Rect::from_x_y_ranges(x.min(inner)..=x.max(inner), rect.y_range()); + self.column(ui, column, first, column_rect, edge); + if index == 0 { + let (band, line) = column_edge(x, inward, rect.y_range()); + self.dock_targets.push(DockDrop { target: DockTarget::ColumnEdge { anchor: first.clone(), after: false }, band, line }); + } + let (band, line) = column_edge(inner, -inward, rect.y_range()); + self.dock_targets.push(DockDrop { target: DockTarget::ColumnEdge { anchor: first.clone(), after: true }, band, line }); + drawn.push((column, first, width, inner)); + x = inner; + } + // Registered after the columns, so the narrow hit areas win at the edges. + for (column, first, width, inner) in drawn { + let others = total - column_width(column); + let (lo, hi) = if column.iconic { (ICONIC_WIDTH, ICONIC_MAX) } else { self.column_bounds(column) }; + let hi = hi.min(room - others).max(lo.min(room - others).max(0.0)); + let lo = lo.min(hi); + let divider = Rect::from_x_y_ranges((inner - 1.0)..=(inner + 1.0), rect.y_range()); + let response = ResizeHandle::new( + self.id.with(("column-resize", Some(first))), + SplitAxis::Horizontal, + divider, + &self.style.resize_label, + self.handle_style(), + ) + .value(width, lo..=hi) + .show(ui); + self.register_interaction(ui.ctx(), response.response.id); + let next = (width + inward * response.delta).clamp(lo, hi); + if response.delta != 0.0 && next != width { + self.output.actions.push(if column.iconic { + Action::ResizeIconic { panel: first.clone(), width: Some(next) } + } else { + Action::ResizeColumn { panel: first.clone(), width: next } + }); + } + } + } + + fn handle_style(&self) -> ResizeHandleStyle { + ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent } + } + + /// Width bounds of an expanded column from its panels' limits. + fn column_bounds(&self, column: &Column

) -> (f32, f32) { + let mut lo = self.style.min_pane; + let mut hi = f32::INFINITY; + for panel in column.groups.iter().flat_map(|g| g.panels.iter()) { + let limits = self.limits(panel); + lo = lo.max(limits.min.x); + hi = hi.min(limits.max.x); + } + (lo, hi.max(lo)) + } + + /// Least height of an open group: its strip and the tallest minimum of its panels. + fn group_min(&self, group: &Group

) -> f32 { + let body = group.panels.iter().map(|p| self.limits(p).min.y).fold(self.style.min_pane, f32::max); + self.style.tab_height + body + } + + fn column(&mut self, ui: &mut Ui, column: &Column

, first: &P, rect: Rect, edge: Edge) { + if !usable(rect) { + return; + } + let bar = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.column_bar_height).min(rect.bottom()))); + self.column_bar(ui, column, first, bar, rect, edge); + let body = Rect::from_min_max(pos2(rect.left(), bar.bottom()), rect.max); + if column.iconic || !usable(body) { + ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); + return; + } + let sizes: Vec<_> = column.groups.iter().map(|g| (g.minimized, g.height, self.group_min(g))).collect(); + let heights = group_heights(&sizes, self.style.tab_height, body.height()); + let total: f32 = heights.iter().sum(); + let start = self.targets.len(); + if total > body.height() + 0.5 { + let mut child = + ui.new_child(UiBuilder::new().id_salt(("dock-column", first)).max_rect(body).layout(egui::Layout::top_down(egui::Align::Min))); + child.set_clip_rect(body.intersect(ui.clip_rect())); + egui::ScrollArea::vertical() + .id_salt(self.id.with(("column-scroll", first))) + .auto_shrink([false, false]) + .scroll_source(egui::scroll_area::ScrollSource::SCROLL_BAR | egui::scroll_area::ScrollSource::MOUSE_WHEEL) + .show(&mut child, |ui| { + let (content, _) = ui.allocate_exact_size(vec2(ui.available_width(), total), Sense::hover()); + self.column_groups(ui, column, &heights, content, body); + }); + } else { + self.column_groups(ui, column, &heights, body, body); + } + // A group scrolled out of view takes nothing. + for target in self.targets.iter_mut().skip(start) { + target.rect = target.rect.intersect(body); + target.tab_strip = target.tab_strip.map(|strip| strip.intersect(body)); + for (_, tab) in &mut target.tabs { + *tab = tab.intersect(body); + } + } + ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); + } + + /// Groups top to bottom in `area` (the scrolled content when the column scrolls), their + /// seams and bands clipped to the visible `view`, and the height dividers. + fn column_groups(&mut self, ui: &mut Ui, column: &Column

, heights: &[f32], area: Rect, view: Rect) { + let mut top = area.top(); + let mut rects = Vec::new(); + for (group, height) in column.groups.iter().zip(heights) { + let rect = Rect::from_min_max(pos2(area.left(), top), pos2(area.right(), top + height)); + self.group(ui, &group.panels, group.active, group.minimized, rect, GroupKind::Dock); + rects.push(rect); + top += height; + } + let xs = view.x_range(); + let half = self.style.seam_band * 0.5; + let push = |targets: &mut Vec>, target: DockTarget

, band: Rect, line: Rect| { + let band = band.intersect(view); + if usable(band) { + targets.push(DockDrop { target, band, line: line.intersect(view.expand(2.0)) }); + } + }; + let mut previous: Option<&P> = None; + for (group, rect) in column.groups.iter().zip(&rects) { + let Some(anchor) = group.panels.first() else { continue }; + if let Some(above) = previous { + let band = Rect::from_x_y_ranges(xs, (rect.top() - half)..=(rect.top() + half)); + push(&mut self.dock_targets, DockTarget::Seam { anchor: above.clone() }, band, horizontal_line(rect.top(), xs)); + } + if !group.minimized { + let body = Rect::from_min_max(pos2(rect.left(), (rect.top() + self.style.tab_height).min(rect.bottom())), rect.max); + let quarter = body.height() * 0.25; + let upper = Rect::from_x_y_ranges(xs, body.top()..=(body.top() + quarter)); + let lower = Rect::from_x_y_ranges(xs, (body.bottom() - quarter)..=body.bottom()); + push(&mut self.dock_targets, DockTarget::GroupBand { anchor: anchor.clone(), below: false }, upper, horizontal_line(rect.top(), xs)); + push( + &mut self.dock_targets, + DockTarget::GroupBand { anchor: anchor.clone(), below: true }, + lower, + horizontal_line(rect.bottom(), xs), + ); + } + previous = Some(anchor); + } + // The room under the last group, when every group is minimized, stacks below it. + if let Some(last) = previous + && top < view.bottom() + { + let band = Rect::from_x_y_ranges(xs, top..=view.bottom()); + push(&mut self.dock_targets, DockTarget::GroupBand { anchor: last.clone(), below: true }, band, horizontal_line(top, xs)); + } + // Height dividers between an open group and the next open one, after the groups so + // their hit areas win at the boundary. Both groups' heights are saved. + let open: Vec = (0..column.groups.len()).filter(|i| column.groups.get(*i).is_some_and(|g| !g.minimized)).collect(); + for pair in open.windows(2) { + let &[i, j] = pair else { continue }; + let (Some(upper), Some(lower), Some(rect)) = (column.groups.get(i), column.groups.get(j), rects.get(i)) else { continue }; + let (Some(a), Some(b), Some(first), Some(second)) = (heights.get(i), heights.get(j), upper.panels.first(), lower.panels.first()) else { + continue; + }; + let (lo, hi) = (self.group_min(upper), a + b - self.group_min(lower)); + let hi = hi.max(lo); + let divider = Rect::from_x_y_ranges(rect.x_range(), (rect.bottom() - 1.0)..=(rect.bottom() + 1.0)); + let response = ResizeHandle::new( + self.id.with(("group-resize", Some(first))), + SplitAxis::Vertical, + divider, + &self.style.resize_label, + self.handle_style(), + ) + .value(*a, lo..=hi) + .show(ui); + self.register_interaction(ui.ctx(), response.response.id); + let next = (a + response.delta).clamp(lo, hi); + if response.delta != 0.0 && next != *a { + self.output.actions.push(Action::ResizeGroup { panel: first.clone(), height: Some(next) }); + self.output.actions.push(Action::ResizeGroup { panel: second.clone(), height: Some(a + b - next) }); + } + } + } + + /// The column bar: the »/« button at its outer end, the rest drags the column (S6), + /// toggles iconic on double-click (M2) and opens the column menu (U1). + fn column_bar(&mut self, ui: &mut Ui, column: &Column

, first: &P, bar: Rect, rect: Rect, edge: Edge) { + ui.painter().rect_filled(bar, 0.0, self.style.tab_background); + let width = COLLAPSE_WIDTH.min(bar.width()); + let (button, grip) = match edge { + Edge::Left => ( + Rect::from_min_max(bar.min, pos2(bar.left() + width, bar.bottom())), + Rect::from_min_max(pos2(bar.left() + width, bar.top()), bar.max), + ), + Edge::Right => ( + Rect::from_min_max(pos2(bar.right() - width, bar.top()), bar.max), + Rect::from_min_max(bar.min, pos2(bar.right() - width, bar.bottom())), + ), + }; + let label = if column.iconic { self.style.expand_panels_label.clone() } else { self.style.collapse_to_icons_label.clone() }; + if usable(button) { + let response = ui.interact(button, self.id.with(("column-collapse", Some(first))), Sense::click()); + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &label)); + // The arrows point where the column goes: towards the window edge when it collapses. + let glyph = if (edge == Edge::Left) != column.iconic { "«" } else { "»" }; + let color = if response.hovered() || response.has_focus() { self.style.text } else { self.style.inactive_text }; + ui.painter().with_clip_rect(button).text(button.center(), egui::Align2::CENTER_CENTER, glyph, self.style.font.clone(), color); + if response.clicked() { + self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic }); + } + } + if !usable(grip) { + return; + } + let movable = column.groups.iter().flat_map(|g| g.panels.iter()).all(|p| self.permissions(p).movable); + let response = ui.interact(grip, self.id.with(("column-bar", Some(first))), Sense::click_and_drag()); + let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response }; + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_column_label)); + if movable && response.drag_started() { + let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center()); + let drag = GroupDrag { + panel: first.clone(), + original: [rect.left(), rect.top(), rect.width(), rect.height()], + gesture: GroupGesture::Column, + members: column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect(), + origin, + source: rect, + }; + ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag)); + } + if response.double_clicked() { + self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic }); + } + for k in 0..2 { + let y = grip.center().y - 1.5 + k as f32 * 3.0; + let x = grip.center().x; + ui.painter().with_clip_rect(grip).line_segment([pos2(x - 9.0, y), pos2(x + 9.0, y)], Stroke::new(1.0, self.style.inactive_text)); + } + if response.has_focus() || response.hovered() { + ui.painter().with_clip_rect(grip).rect_stroke( + grip.shrink(1.0), + 0.0, + Stroke::new(1.0, self.style.accent.gamma_multiply(0.5)), + StrokeKind::Inside, + ); + } + let keyboard = response.has_focus() && ui.input(|i| i.key_pressed(Key::Enter) || i.key_pressed(Key::Space)); + let command = if response.secondary_clicked() || keyboard { + Some(egui::SetOpenCommand::Bool(true)) + } else if response.clicked() { + Some(egui::SetOpenCommand::Bool(false)) + } else { + None + }; + egui::Popup::menu(&response).open_memory(command).show(|ui| { + if self.menu_action(ui, &label) { + self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic }); + } + }); + } + + /// Whether a floating window (other than the one following the pointer) or a host overlay + /// covers `pointer`. Covered dock targets take nothing. + fn dock_covered(&self, ctx: &Context, pointer: Pos2, moving: Option<&P>) -> bool { + self.blockers.iter().any(|r| r.contains(pointer)) + || self.layout.floating.iter().any(|window| { + let Some(first) = window.panels().next() else { return false }; + !moving.is_some_and(|p| window.contains(p)) + && ctx.memory(|m| m.area_rect(self.id.with(("floating", first)))).is_some_and(|r| r.contains(pointer)) + }) + } + + /// New docks are offered only where the dock profile is in use: in a layout with a dock. + fn has_dock(&self) -> bool { + self.layout.dock_path(Side::Start).is_some() || self.layout.dock_path(Side::End).is_some() + } + + /// Dock targets, with the new-dock bands along the docked area's left and right edges that + /// have no dock yet. + fn dock_candidates(&self) -> Vec> { + let mut candidates = self.dock_targets.clone(); + if !self.has_dock() || !usable(self.workspace) { + return candidates; + } + let rtl = self.style.right_to_left; + let ys = self.workspace.y_range(); + for edge in [Edge::Left, Edge::Right] { + let side = side_at(edge, rtl); + if self.layout.dock_path(side).is_some() { + continue; + } + let (x, inward) = match edge { + Edge::Left => (self.workspace.left(), self.style.edge_band), + Edge::Right => (self.workspace.right(), -self.style.edge_band), + }; + let band = Rect::from_x_y_ranges(x.min(x + inward)..=x.max(x + inward), ys); + let line = vertical_line(x + inward.signum() * 2.0, ys); + candidates.push(DockDrop { target: DockTarget::NewDock { side }, band, line }); + } + candidates + } + + /// The dock target a whole group or column drag would take at `pointer`, with the action + /// and its line. A target that leaves the layout unchanged is a no-op: `None` action. + pub(super) fn dock_group_proposal(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2) -> Option<(Option>, Rect)> { + let moving = (drag.gesture == GroupGesture::Window).then_some(&drag.panel); + if self.dock_covered(ctx, pointer, moving) { + return None; + } + let candidates = self.dock_candidates(); + let drop = resolve_dock(pointer, &candidates)?; + let action = group_action(drag, drop.target.to()); + self.checked(action).map(|action| (action, drop.line)) + } + + /// The dock target a single tab drag would take: a new group or column of that panel. A new + /// dock only takes a panel that is alone in its group. + pub(super) fn dock_tab_proposal(&self, ctx: &Context, panel: &P, pointer: Pos2) -> Option<(Option>, Rect)> { + if self.dock_covered(ctx, pointer, None) { + return None; + } + let candidates = self.dock_candidates(); + let drop = resolve_dock(pointer, &candidates)?; + let action = match drop.target.to() { + Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, + to @ Target::NewDock { .. } + if self.layout.place(panel).and_then(|place| self.layout.group(&place)).is_some_and(|g| g.panels.len() == 1) => + { + Action::MoveGroup { panel: panel.clone(), to } + } + Target::NewDock { .. } | Target::Float { .. } => return None, + }; + self.checked(action).map(|action| (action, drop.line)) + } + + /// `Some(None)` when the action is valid but changes nothing, `None` when it is invalid. + fn checked(&self, action: Action

) -> Option>> { + let mut candidate = self.layout.clone(); + candidate.apply_with_permissions(action.clone(), |p| self.permissions(p)).ok()?; + Some((candidate != *self.layout).then_some(action)) + } + + /// The insertion line of a dock target. + pub(super) fn paint_dock_line(&self, ctx: &Context, line: Rect) { + if usable(line) { + self.preview_painter(ctx).rect_filled(line, 1.0, self.style.accent); + } + } +} + +/// The move a group gesture makes: the column for a column bar, else the group. +pub(super) fn group_action(drag: &GroupDrag

, to: Target

) -> Action

{ + match drag.gesture { + GroupGesture::Column => Action::MoveColumn { panel: drag.panel.clone(), to }, + GroupGesture::Window | GroupGesture::Group => Action::MoveGroup { panel: drag.panel.clone(), to }, + } +} diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 3b80dfb3e9..3c5d33ce69 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -251,6 +251,9 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !owner.minimized }); } } + if owner.kind == GroupKind::Dock && self.menu_action(ui, &self.style.collapse_to_icons_label.clone()) { + self.output.actions.push(Action::SetIconic { panel: panel.clone(), iconic: true }); + } if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.style.float_group_label.clone()) { let rect = clamp_float(owner.rect.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); self.output.actions.push(Action::MoveGroup { @@ -281,7 +284,7 @@ impl Renderer<'_, P> { /// A stock menu button with shaped text and its logical accessibility label; true when /// clicked, after closing the menu. - fn menu_action(&mut self, ui: &mut Ui, logical: &str) -> bool { + pub(super) fn menu_action(&mut self, ui: &mut Ui, logical: &str) -> bool { let text = self.content.action_label(ui, logical, &self.style.font, self.style.text); let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), logical)); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 7539a1c0c5..3b16feed07 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -6,6 +6,7 @@ use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions}; +mod dock; mod floating; pub(in crate::docking) use group::GroupKind; @@ -24,6 +25,8 @@ pub(super) struct Renderer<'a, P> { /// The docked area, for host drop requests. pub(super) workspace: Rect, pub(super) targets: Vec>, + /// [D] Seams, group bands, column edges and new-dock bands, see [`crate::docking::targets::DockDrop`]. + pub(super) dock_targets: Vec>, pub(super) owned_interactions: Vec, pub(super) output: DockOutput

, } @@ -63,6 +66,7 @@ impl Renderer<'_, P> { return; } match node { + Node::Split { axis: SplitAxis::Horizontal, first, second, .. } if self.dock_split(ui, first, second, rect, path) => {} Node::Split { axis, size, first, second } => { let Some(wanted) = split_rect(rect, *axis, *size, self.style.gap, 0.0) else { return }; let (lo, hi) = split_bounds(wanted.available(), *axis, self.node_limits(first), self.node_limits(second)); @@ -93,17 +97,7 @@ impl Renderer<'_, P> { } } Node::Tabs { panels, active } => self.group(ui, panels, *active, false, rect, GroupKind::Frame), - Node::Dock { columns, .. } => { - // Interim rendering: columns side by side, groups stacked evenly. - let total: f32 = columns.iter().map(|c| c.width).sum(); - let mut left = rect.left(); - for column in columns { - let width = if total > 0.0 { rect.width() * column.width / total } else { 0.0 }; - let column_rect = Rect::from_min_max(pos2(left, rect.top()), pos2(left + width, rect.bottom())); - left += width; - self.stacked_groups(ui, &column.groups, column_rect, GroupKind::Dock); - } - } + Node::Dock { side, columns } => self.dock(ui, *side, columns, rect, rect.width()), Node::Stack { entries } => { let total_header = (entries.len() as f32 * self.style.tab_height).min(rect.height()); let remaining = (rect.height() - total_header).max(0.0); @@ -220,7 +214,10 @@ pub(in crate::docking) fn stripless

(panels: &[P], content: &dyn DockContent

(node: &Node

, style: &DockStyle, content: &dyn DockContent

) -> PanelLimits { match node { - Node::Dock { .. } => PanelLimits { min: Vec2::splat(style.min_pane), ..PanelLimits::default() }, + Node::Dock { columns, .. } => { + let width: f32 = columns.iter().map(dock::column_width).sum(); + PanelLimits { min: vec2(width.clamp(style.min_pane, 1_000_000.0), style.min_pane), ..PanelLimits::default() } + } Node::Tabs { panels, .. } => { let mut limits = PanelLimits::default(); for panel in panels { diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index de2aa4452b..010401de8c 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -2,7 +2,7 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Color32, Context, Key, Pos2, Rect, Stroke, StrokeKind, Vec2, vec2}; -use super::{Renderer, clamp_float}; +use super::{Renderer, clamp_float, dock::group_action}; use crate::docking::{ Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Placement, Target, Zone, cancel_drag, dock_model::Place, resolve_drop, }; @@ -32,7 +32,7 @@ impl Renderer<'_, P> { && (down || released) && let Some(pointer) = pointer && !self.blockers.iter().any(|r| r.contains(pointer)) - && self.host_drop(ctx, &drag.panel, pointer, true, released, ghost.filter(|_| drag.gesture == GroupGesture::Group)) + && self.host_drop(ctx, &drag.panel, pointer, true, released, ghost.filter(|_| drag.gesture != GroupGesture::Window)) { if released { ctx.data_mut(|d| d.remove::>(key)); @@ -59,11 +59,11 @@ impl Renderer<'_, P> { let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return }; match drag.gesture { GroupGesture::Window => self.output.group_drop = Some((drag.panel, pointer)), - GroupGesture::Group => self.drop_group(ctx, &drag, pointer, float_only), + GroupGesture::Group | GroupGesture::Column => self.drop_group(ctx, &drag, pointer, float_only), } } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { self.output.group_drag = Some(drag.panel.clone()); - if drag.gesture == GroupGesture::Group { + if drag.gesture != GroupGesture::Window { self.paint_group_drag(ctx, &drag, pointer, float_only); } } @@ -83,10 +83,7 @@ impl Renderer<'_, P> { }); } let proposal = resolve_drop(&drag.panel, pointer, std::slice::from_ref(target))?; - let action = Action::MoveGroup { - panel: drag.panel.clone(), - to: Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }, - }; + let action = group_action(drag, Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }); self.layout.clone().apply_with_permissions(action, |p| self.permissions(p)).is_ok().then_some(proposal) } @@ -97,11 +94,15 @@ impl Renderer<'_, P> { if pointer.distance(drag.origin) < 2.0 { return; } + if !float_only && let Some((action, _)) = self.dock_group_proposal(ctx, drag, pointer) { + self.output.actions.extend(action); + return; + } let floating = matches!(self.layout.place(&drag.panel), Some(Place::Floating { .. })); let proposal = if float_only { None } else { self.group_proposal(drag, pointer) }; if let Some(proposal) = proposal.as_ref().filter(|p| !p.noop) { let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; - self.output.actions.push(Action::MoveGroup { panel: drag.panel.clone(), to }); + self.output.actions.push(group_action(drag, to)); return; } if proposal.is_some() && !floating { @@ -110,8 +111,7 @@ impl Renderer<'_, P> { // No target: hosts that still apply their own policy for a whole-group release get it. self.output.group_drop = Some((drag.panel.clone(), pointer)); let rect = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); - let action = - Action::MoveGroup { panel: drag.panel.clone(), to: Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) } }; + let action = group_action(drag, Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) }); if self.layout.clone().apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() { self.output.actions.push(action); } @@ -125,6 +125,12 @@ impl Renderer<'_, P> { if float_only { return; } + if let Some((action, line)) = self.dock_group_proposal(ctx, drag, pointer) { + if action.is_some() { + self.paint_dock_line(ctx, line); + } + return; + } if let Some(proposal) = self.group_proposal(drag, pointer).filter(|p| !p.noop) { let split = matches!(proposal.placement, Placement::Split(zone) if zone != Zone::Center); let fill = if split { self.style.accent.gamma_multiply(0.15) } else { Color32::TRANSPARENT }; @@ -170,6 +176,19 @@ impl Renderer<'_, P> { } return; } + let dock = if float_only || gone { None } else { self.dock_tab_proposal(ctx, &drag.panel, pointer) }; + if let Some((action, line)) = dock { + if released { + cancel_drag::

(ctx, self.id); + if let Some(action) = action.filter(|_| pointer.distance(drag.origin) >= 2.0) { + self.output.actions.push(action); + self.output.focused = Some(drag.panel); + } + } else if action.is_some() { + self.paint_dock_line(ctx, line); + } + return; + } let proposal = if float_only { None } else { resolve_drop(&drag.panel, pointer, &self.targets) }; if released { cancel_drag::

(ctx, self.id); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 901fc27312..d721c44d65 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -45,6 +45,19 @@ pub struct DockStyle { /// Painted under every floating window, so it stays opaque when the panel colours are not. pub floating_background: Color32, pub floating_stroke: Stroke, + /// [D] Height of the bar above each dock column. It drags the column and holds its »/« button. + pub column_bar_height: f32, + /// [D] Height of the band around the seam between two stacked groups. + pub seam_band: f32, + /// [D] Width of the band along the window's left and right edges that makes a new dock. + pub edge_band: f32, + /// [D] Lay docks out right to left: `Side::Start` is the right edge. egui has no app-wide + /// layout direction, so the host sets this from its locale. Frame splits keep their sides. + pub right_to_left: bool, + /// [D] Accessibility label of a column bar. + pub move_column_label: String, + pub collapse_to_icons_label: String, + pub expand_panels_label: String, } impl DockStyle { @@ -77,12 +90,20 @@ impl DockStyle { drag_bar_width: 40.0, floating_background: visuals.window_fill, floating_stroke: visuals.window_stroke, + column_bar_height: 14.0, + seam_band: 8.0, + edge_band: 12.0, + right_to_left: false, + move_column_label: "Move panel column".into(), + collapse_to_icons_label: "Collapse to Icons".into(), + expand_panels_label: "Expand Panels".into(), } } pub(super) fn valid(&self) -> bool { [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size, self.drag_bar_width, self.floating_stroke.width] .iter() + .chain(&[self.column_bar_height, self.seam_band, self.edge_band]) .all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) && self.tab_height > 0.0 && self.font.size > 0.0 @@ -148,6 +169,8 @@ pub(super) enum GroupGesture { Window, /// A drag bar or top border: a ghost follows the pointer, the release picks the target. Group, + /// [D] A column bar: like `Group`, for the whole dock column. + Column, } #[derive(Clone)] @@ -378,7 +401,16 @@ impl DockArea

{ while let Some((node, path)) = nodes.pop() { match node { Node::Tabs { panels, .. } if group(panels) => return true, - Node::Dock { columns, .. } if columns.iter().flat_map(|c| c.groups.iter()).any(|g| group(&g.panels)) => return true, + Node::Dock { columns, .. } + if columns.iter().flat_map(|c| c.groups.iter()).any(|g| { + group(&g.panels) + || ["column-bar", "column-collapse", "column-resize", "group-resize"] + .iter() + .any(|name| matches(self.id.with((*name, g.panels.first())))) + }) => + { + return true; + } Node::Stack { entries } => { if entries.iter().any(|entry| { matches(self.id.with(("tab", &entry.panel))) @@ -485,6 +517,7 @@ impl DockArea

{ layout, workspace: rect, targets: Vec::new(), + dock_targets: Vec::new(), owned_interactions: Vec::new(), output: DockOutput::default(), }; diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index a4c8b63182..cd370e5abc 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -1,6 +1,6 @@ -use egui::{Pos2, Rect, pos2}; +use egui::{Pos2, Rangef, Rect, pos2}; -use super::{Placement, Zone}; +use super::{Placement, Side, Target, Zone}; /// One visible group, supplied in back-to-front order to [`resolve_drop`]. An empty tab strip /// or a group that rejects tabs may still accept side splits, e.g. a protected document canvas. @@ -149,3 +149,75 @@ pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarg noop: false, }) } + +/// [D] A dock drop target, built once per frame next to the [`DropTarget`]s. The pointer selects +/// it inside `band`; the preview is the line `line`. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct DockDrop

{ + pub(super) target: DockTarget

, + pub(super) band: Rect, + pub(super) line: Rect, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum DockTarget

{ + /// Column edge: a new column beside the column of `anchor`, further from the window edge + /// when `after` (P5). + ColumnEdge { anchor: P, after: bool }, + /// The seam between two stacked groups: a new group below the group of `anchor` (P4). + Seam { anchor: P }, + /// The top or bottom quarter of a group body, or the free room under a column's last group (P3). + GroupBand { anchor: P, below: bool }, + /// A window edge without a dock, or an empty dock (P5, P6). + NewDock { side: Side }, +} + +impl DockTarget

{ + pub(super) fn to(&self) -> Target

{ + match self { + Self::ColumnEdge { anchor, after } => Target::At { anchor: anchor.clone(), placement: Placement::Column { after: *after } }, + Self::Seam { anchor } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: true } }, + Self::GroupBand { anchor, below } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: *below } }, + Self::NewDock { side } => Target::NewDock { side: *side }, + } + } + + /// Rank in resolution order: column edges reach past their columns, so they come first. + fn rank(&self) -> u8 { + match self { + Self::ColumnEdge { .. } => 0, + Self::Seam { .. } => 1, + Self::GroupBand { .. } => 2, + Self::NewDock { .. } => 3, + } + } +} + +/// The dock target under the pointer: column edges, then seams, then group bands, then new docks. +pub(super) fn resolve_dock(pointer: Pos2, targets: &[DockDrop

]) -> Option<&DockDrop

> { + if !pointer.is_finite() { + return None; + } + targets.iter().filter(|t| usable(t.band) && t.band.contains(pointer)).min_by_key(|t| t.target.rank()) +} + +/// Width of the insertion lines dock targets preview with. +const LINE: f32 = 4.0; +/// How far a column edge band reaches into the column, and past the edge out of it. +const EDGE_IN: f32 = 6.0; +const EDGE_OUT: f32 = 10.0; + +/// Band and line of a column edge at `x`. `inward` is +1 when the column lies right of the edge, +/// -1 when it lies left of it. The band reaches further out of the column than into it. +pub(super) fn column_edge(x: f32, inward: f32, ys: Rangef) -> (Rect, Rect) { + let (a, b) = (x + inward * EDGE_IN, x - inward * EDGE_OUT); + (Rect::from_x_y_ranges(a.min(b)..=a.max(b), ys), vertical_line(x, ys)) +} + +pub(super) fn vertical_line(x: f32, ys: Rangef) -> Rect { + Rect::from_x_y_ranges((x - LINE * 0.5)..=(x + LINE * 0.5), ys) +} + +pub(super) fn horizontal_line(y: f32, xs: Rangef) -> Rect { + Rect::from_x_y_ranges(xs, (y - LINE * 0.5)..=(y + LINE * 0.5)) +} From c07a0debb409a24a672a79d473a738ef4c38770e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:15:14 +0000 Subject: [PATCH 15/94] docking: test dock columns, seams, column drags and RTL docks Behaviour tests with real egui input: seam, band, column edge and new dock drops with their line previews, tab drops, a column taking groups anywhere, scrolling, column bar drags and their cancellation, dividers, minimize, iconic toggles, occlusion by floating windows and the mirrored right-to-left layout. Behaviour follows vectorcraft crates/ui-egui/src/floating.rs tests. --- crates/ui/src/docking/dock_tests.rs | 471 ++++++++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 2 + 2 files changed, 473 insertions(+) create mode 100644 crates/ui/src/docking/dock_tests.rs diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs new file mode 100644 index 0000000000..b719d3a72a --- /dev/null +++ b/crates/ui/src/docking/dock_tests.rs @@ -0,0 +1,471 @@ +//! [D] Dock profile: columns, stacked groups, seams, column bars and their drops. + +use super::*; +use crate::layout::{SplitAxis, SplitSize}; +use egui::{Context, Event, Id, Modifiers, PointerButton, Pos2, RawInput, Rect, UiBuilder, pos2, vec2}; + +const AREA: &str = "dock-area"; + +fn group(panels: &[u32]) -> Group { + Group::new(panels.to_vec(), 0) +} + +/// A dock on `side` with `columns` (each a list of groups, 240 wide) beside canvas 0. +fn docked(side: Side, columns: &[&[&[u32]]]) -> Layout { + let dock = Node::Dock { side, columns: columns.iter().map(|groups| Column::new(groups.iter().map(|g| group(g)).collect(), 240.0)).collect() }; + let canvas = Node::Tabs { panels: vec![0], active: 0 }; + let (first, second, size) = match side { + Side::Start => (dock, canvas, SplitSize::FixedFirst(240.0)), + Side::End => (canvas, dock, SplitSize::FixedSecond(240.0)), + }; + Layout { root: Some(Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(first), second: Box::new(second) }), floating: Vec::new() } +} + +fn with_floating(mut layout: Layout, windows: &[(u32, [f32; 4])]) -> Layout { + layout.floating.extend(windows.iter().map(|(panel, rect)| Floating::single(vec![*panel], 0, *rect))); + layout +} + +fn columns(layout: &Layout, side: Side) -> Vec>> { + fn find(node: &Node, side: Side) -> Option>>> { + match node { + Node::Dock { side: s, columns } if *s == side => { + Some(columns.iter().map(|c| c.groups.iter().map(|g| g.panels.clone()).collect()).collect()) + } + Node::Split { first, second, .. } => find(first, side).or_else(|| find(second, side)), + _ => None, + } + } + layout.root.as_ref().and_then(|root| find(root, side)).unwrap_or_default() +} + +fn column(layout: &Layout, index: usize) -> Column { + fn find(node: &Node) -> Option<&Vec>> { + match node { + Node::Dock { columns, .. } => Some(columns), + Node::Split { first, second, .. } => find(first).or_else(|| find(second)), + _ => None, + } + } + layout.root.as_ref().and_then(find).and_then(|c| c.get(index)).cloned().unwrap() +} + +#[derive(Default)] +struct TestContent { + min_height: f32, +} + +impl DockContent for TestContent { + fn body(&mut self, ui: &mut egui::Ui, _: &u32) { + ui.label("Body"); + } + fn permissions(&self, panel: &u32) -> Permissions { + if *panel == 0 { Permissions::PROTECTED } else { Permissions::default() } + } + fn limits(&self, _: &u32) -> PanelLimits { + PanelLimits { min: vec2(0.0, self.min_height), ..PanelLimits::default() } + } +} + +/// Renders a layout in a 600x600 area of an 800x600 window and applies what it emits. +struct Driver { + ctx: Context, + layout: Layout, + content: TestContent, + focused: bool, + right_to_left: bool, + shapes: Vec, + time: f64, +} + +impl Driver { + fn new(layout: Layout) -> Self { + Self::with(layout, TestContent::default(), false) + } + + fn with(layout: Layout, content: TestContent, right_to_left: bool) -> Self { + let mut driver = Self { ctx: Context::default(), layout, content, focused: true, right_to_left, shapes: Vec::new(), time: 0.0 }; + // Floating areas settle after their sizing pass. + for _ in 0..3 { + driver.step(vec![]); + } + driver + } + + fn frame(&mut self, events: Vec) -> DockOutput { + let mut output = DockOutput::default(); + self.time += 1.0 / 60.0; + let input = RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), + events, + focused: self.focused, + time: Some(self.time), + ..Default::default() + }; + let (layout, content, rtl) = (&self.layout, &mut self.content, self.right_to_left); + let mut full = self.ctx.run_ui(input, |ui| { + let mut style = DockStyle::from_ui(ui); + style.right_to_left = rtl; + ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 600.0))), |ui| { + output = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content); + }); + }); + full.textures_delta.clear(); + self.shapes = full.shapes; + output + } + + fn step(&mut self, events: Vec) -> DockOutput { + let output = self.frame(events); + assert!(output.error.is_none(), "{output:?}"); + let permissions = |p: &u32| self.content.permissions(p); + for action in &output.actions { + self.layout.apply_with_permissions(action.clone(), permissions).unwrap(); + } + output + } + + fn rect(&self, name: &str, panel: u32) -> Rect { + self.ctx.read_response(Id::new(AREA).with((name, Some(&panel)))).unwrap().rect + } + + fn tab(&self, panel: u32) -> Rect { + self.ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect + } + + fn hold(&mut self, from: Pos2, to: Pos2) -> DockOutput { + self.step(vec![Event::PointerMoved(from)]); + self.step(vec![button(from, true)]); + self.step(vec![Event::PointerMoved(from + vec2(8.0, 6.0))]); + self.step(vec![Event::PointerMoved(to)]) + } + + fn drag(&mut self, from: Pos2, to: Pos2) -> DockOutput { + self.hold(from, to); + self.step(vec![button(to, false)]) + } + + fn click(&mut self, at: Pos2) -> DockOutput { + self.step(vec![Event::PointerMoved(at), button(at, true)]); + self.step(vec![button(at, false)]) + } + + /// Two frames: egui reports a moved widget's rect a frame late. + fn settle(&mut self) { + self.step(vec![]); + self.step(vec![]); + } + + fn wait(&mut self) { + for _ in 0..45 { + self.step(vec![]); + } + } + + /// Whether the last frame painted the filled insertion line `line`. + fn painted(&self, line: Rect) -> bool { + self.shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Rect(shape) => shape.rect == line && shape.fill != egui::Color32::TRANSPARENT, + _ => false, + }) + } +} + +fn button(pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } +} + +fn key(key: egui::Key) -> Event { + Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE } +} + +fn moved(actions: &[Action]) -> Option<(u32, &Target)> { + actions.iter().find_map(|a| match a { + Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } => Some((*panel, to)), + _ => None, + }) +} + +fn hline(y: f32, x: std::ops::RangeInclusive) -> Rect { + Rect::from_x_y_ranges(x, (y - 2.0)..=(y + 2.0)) +} + +fn vline(x: f32, y: std::ops::RangeInclusive) -> Rect { + Rect::from_x_y_ranges((x - 2.0)..=(x + 2.0), y) +} + +/// A floating group's drag bar. +fn bar(d: &Driver, panel: u32) -> Pos2 { + d.rect("drag-bar", panel).center() +} + +// Geometry of `docked(Start, ..)`: the dock is 0..240 wide, its column bar 14 high, and two open +// groups share 14..600, meeting at y = 307. + +#[test] +fn group_dropped_on_a_seam_inserts_between_and_shows_a_horizontal_line() { + let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [400.0, 300.0, 150.0, 150.0])]); + let mut d = Driver::new(layout); + assert_eq!(d.tab(3).top(), 307.0); + let seam = pos2(120.0, 309.0); + d.hold(bar(&d, 5), seam); + assert!(d.painted(hline(307.0, 0.0..=240.0)), "a horizontal line across the column at the seam"); + let out = d.step(vec![button(seam, false)]); + assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Group { below: true } }))); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![5], vec![3]]]); + assert!(d.layout.floating.is_empty()); +} + +#[test] +fn a_tab_dropped_on_a_seam_or_column_edge_moves_only_that_panel() { + let mut d = Driver::new(docked(Side::Start, &[&[&[2, 3], &[4]]])); + let out = d.drag(d.tab(3).center(), pos2(120.0, 309.0)); + assert_eq!(out.actions, vec![Action::Move { panel: 3, anchor: 2, placement: Placement::Group { below: true } }]); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3], vec![4]]]); + d.settle(); + d.drag(d.tab(4).center(), pos2(246.0, 200.0)); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3]], vec![vec![4]]]); +} + +#[test] +fn group_dropped_on_a_top_or_bottom_band_stacks_above_or_below() { + for (at, expected) in [ + // The top quarter of group 2's body, and the bottom quarter of group 3's. + (pos2(120.0, 14.0 + 26.0 + 20.0), vec![vec![5], vec![2], vec![3]]), + (pos2(120.0, 590.0), vec![vec![2], vec![3], vec![5]]), + // The middle of a body joins as tabs. + (pos2(120.0, 450.0), vec![vec![2], vec![3, 5]]), + ] { + let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [400.0, 300.0, 150.0, 150.0])]); + let mut d = Driver::new(layout); + d.drag(bar(&d, 5), at); + assert_eq!(columns(&d.layout, Side::Start), vec![expected], "{at:?}"); + } +} + +#[test] +fn group_dropped_on_a_column_edge_makes_a_new_column() { + // The dock's inner edge: a column after the existing one, previewed full height. + let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [400.0, 300.0, 150.0, 150.0])]); + let mut d = Driver::new(layout.clone()); + let edge = pos2(246.0, 200.0); + d.hold(bar(&d, 5), edge); + assert!(d.painted(vline(240.0, 0.0..=600.0)), "a vertical line the full height of the dock"); + let out = d.step(vec![button(edge, false)]); + assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Column { after: true } }))); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3]], vec![vec![5]]]); + assert_eq!(column(&d.layout, 1).width, 150.0, "the new column keeps the window's width"); + + // The window edge of the outermost column: a column before it. + let mut d = Driver::new(layout); + d.drag(bar(&d, 5), pos2(3.0, 200.0)); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]], vec![vec![2], vec![3]]]); +} + +#[test] +fn group_dropped_on_the_window_edge_without_a_dock_makes_a_new_dock() { + for (side, at, new) in [(Side::Start, pos2(595.0, 200.0), Side::End), (Side::End, pos2(4.0, 200.0), Side::Start)] { + let layout = with_floating(docked(side, &[&[&[2]]]), &[(5, [300.0, 300.0, 150.0, 150.0])]); + let mut d = Driver::new(layout); + d.hold(bar(&d, 5), at); + let x = if new == Side::End { 598.0 } else { 2.0 }; + assert!(d.painted(vline(x, 0.0..=600.0)), "{new:?}: a vertical line at the window edge"); + let out = d.step(vec![button(at, false)]); + assert_eq!(moved(&out.actions), Some((5, &Target::NewDock { side: new }))); + assert_eq!(columns(&d.layout, new), vec![vec![vec![5]]]); + assert_eq!(columns(&d.layout, side), vec![vec![vec![2]]]); + // The new dock is drawn on its edge, its »/« button at the window edge. + d.settle(); + let button = d.rect("column-collapse", 5); + assert!(if new == Side::End { button.right() == 600.0 } else { button.left() == 0.0 }, "{button:?}"); + } +} + +#[test] +fn a_column_takes_groups_anywhere_in_it_and_as_tabs() { + let windows = [(5, [400.0, 40.0, 150.0, 120.0]), (6, [400.0, 220.0, 150.0, 120.0]), (7, [400.0, 400.0, 150.0, 120.0])]; + let mut d = Driver::new(with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &windows)); + // Onto group 3's tab strip: joins as a tab. + d.drag(bar(&d, 5), pos2(d.tab(3).right() + 20.0, d.tab(3).center().y)); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3, 5]]]); + // Onto the middle of group 2's body: joins as the last tab. + d.drag(bar(&d, 6), pos2(120.0, 160.0)); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2, 6], vec![3, 5]]]); + // Into the room under the groups, every group minimized: below the last group. + d.step(vec![Event::PointerMoved(pos2(700.0, 10.0))]); + let mut minimized = d.layout.clone(); + for panel in [2, 3] { + minimized.apply(Action::SetMinimized { panel, minimized: true }).unwrap(); + } + d.layout = minimized; + d.step(vec![]); + d.drag(bar(&d, 7), pos2(120.0, 500.0)); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2, 6], vec![3, 5], vec![7]]]); +} + +#[test] +fn a_column_too_tall_for_the_window_scrolls() { + let groups: [&[u32]; 5] = [&[2], &[3], &[4], &[5], &[6]]; + let mut d = Driver::with(docked(Side::Start, &[&groups]), TestContent { min_height: 160.0 }, false); + let last = d.tab(6); + assert!(last.top() > 600.0, "the last group starts below the window: {last:?}"); + let over = d.tab(2).center(); + for _ in 0..6 { + d.step(vec![ + Event::PointerMoved(over), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -200.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }, + ]); + } + d.wait(); + let moved = d.tab(6); + assert!(moved.top() < last.top() - 100.0, "scrolled up: {moved:?} from {last:?}"); +} + +#[test] +fn column_bar_drag_moves_the_column_and_away_from_a_dock_floats_its_groups() { + let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[3]], &[&[5]]])); + // The second column to the window edge: it becomes the first. + let out = d.drag(d.rect("column-bar", 5).center(), pos2(3.0, 200.0)); + assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Column { after: false } }))); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]], vec![vec![2], vec![3]]]); + d.settle(); + // Away from the dock: a floating window holding the column's groups. + let source = Rect::from_min_max(pos2(240.0, 0.0), pos2(480.0, 600.0)); + assert_eq!(d.rect("column-bar", 2).left(), 240.0 + 18.0); + let grab = d.rect("column-bar", 2).center(); + d.hold(grab, pos2(560.0, 300.0)); + let ghost = source.translate(pos2(560.0, 300.0) - grab); + let ghost = egui::Rect::from_min_size(ghost.min.min(pos2(800.0, 600.0) - source.size()).max(Pos2::ZERO), source.size()); + assert!( + d.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == ghost && r.fill == egui::Color32::TRANSPARENT)), + "a ghost of the column follows the pointer" + ); + let out = d.step(vec![button(pos2(560.0, 300.0), false)]); + assert!(matches!(moved(&out.actions), Some((2, Target::Float { .. }))), "{:?}", out.actions); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]]]); + assert_eq!(d.layout.floating[0].groups, vec![group(&[2]), group(&[3])]); +} + +#[test] +fn column_drag_escape_focus_loss_pointer_exit_and_cancel_drag_leave_the_layout_unchanged() { + let layout = docked(Side::Start, &[&[&[2], &[3]], &[&[5]]]); + for case in ["escape", "focus", "exit", "cancel"] { + let mut d = Driver::new(layout.clone()); + let target = pos2(3.0, 200.0); + let held = d.hold(d.rect("column-bar", 5).center(), target); + assert_eq!(held.group_drag, Some(5), "{case}"); + let out = match case { + "escape" => d.step(vec![key(egui::Key::Escape)]), + "focus" => { + d.focused = false; + let out = d.step(vec![]); + d.focused = true; + out + } + "exit" => d.step(vec![Event::PointerGone]), + _ => { + cancel_drag::(&d.ctx, Id::new(AREA)); + d.step(vec![Event::PointerMoved(target + vec2(1.0, 0.0))]) + } + }; + assert!(out.actions.is_empty(), "{case}: {out:?}"); + let out = d.step(vec![Event::PointerMoved(target), button(target, false)]); + assert!(out.actions.is_empty() && out.group_drag.is_none(), "{case}: {out:?}"); + assert_eq!(d.layout, layout, "{case}"); + assert!(!is_dragging::(&d.ctx, Id::new(AREA)), "{case}"); + } +} + +#[test] +fn column_and_group_dividers_resize_and_minimized_groups_keep_their_height() { + let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[4]]])); + // The dock's inner edge widens its column; the canvas gives way. + d.drag(pos2(240.0, 300.0), pos2(280.0, 300.0)); + assert_eq!(column(&d.layout, 0).width, 280.0); + d.settle(); + assert_eq!(d.rect("column-bar", 2).right(), 280.0); + // The divider between the groups saves both heights. + d.wait(); + d.drag(pos2(120.0, 307.0), pos2(120.0, 357.0)); + let groups = column(&d.layout, 0).groups; + assert_eq!((groups[0].height, groups[1].height), (Some(343.0), Some(243.0))); + d.settle(); + assert_eq!(d.tab(4).top(), 357.0); + // Minimized, the lower group keeps its saved height and the upper one takes the room. + d.layout.apply(Action::SetMinimized { panel: 4, minimized: true }).unwrap(); + d.settle(); + assert_eq!(column(&d.layout, 0).groups[1].height, Some(243.0)); + assert_eq!(d.tab(4).top(), 600.0 - 26.0); +} + +#[test] +fn double_click_on_a_docked_tab_minimizes_and_clicking_another_tab_expands() { + let mut d = Driver::new(docked(Side::Start, &[&[&[2, 3], &[4]]])); + let minimized = |d: &Driver| column(&d.layout, 0).groups[0].minimized; + let tab = d.tab(2).center(); + d.click(tab); + d.click(tab); + assert!(minimized(&d)); + d.settle(); + assert_eq!(d.tab(4).top(), 14.0 + 26.0, "the minimized group takes its strip"); + d.wait(); + d.click(d.tab(3).center()); + assert!(!minimized(&d)); + assert_eq!(column(&d.layout, 0).groups[0].active_panel(), Some(&3)); +} + +#[test] +fn collapse_button_and_column_bar_double_click_emit_set_iconic() { + let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[3]]])); + let iconic = |d: &Driver| column(&d.layout, 0).iconic; + let button = d.rect("column-collapse", 2).center(); + let out = d.click(button); + assert_eq!(out.actions, vec![Action::SetIconic { panel: 2, iconic: true }]); + assert!(iconic(&d)); + d.wait(); + d.click(d.rect("column-collapse", 2).center()); + assert!(!iconic(&d)); + d.wait(); + let bar = d.rect("column-bar", 2).center(); + d.click(bar); + d.click(bar); + assert!(iconic(&d)); +} + +#[test] +fn dock_targets_respect_occlusion_by_floating_windows() { + // Window 5 covers the column's seam at x 150..240; window 6 is dragged. + let windows = [(5, [150.0, 250.0, 200.0, 150.0]), (6, [400.0, 450.0, 150.0, 120.0])]; + let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &windows); + let mut d = Driver::new(layout.clone()); + let out = d.drag(bar(&d, 6), pos2(200.0, 309.0)); + assert!(matches!(moved(&out.actions), Some((6, Target::At { anchor: 5, .. }))), "joins the window in front: {:?}", out.actions); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3]]]); + // Left of the window, the seam takes it. + let mut d = Driver::new(layout); + d.drag(bar(&d, 6), pos2(100.0, 309.0)); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![6], vec![3]]]); +} + +#[test] +fn right_to_left_mirrors_docks_their_edges_and_new_docks() { + let layout = with_floating(docked(Side::Start, &[&[&[2], &[3]]]), &[(5, [100.0, 300.0, 150.0, 150.0])]); + let mut d = Driver::with(layout.clone(), TestContent::default(), true); + // The start dock is on the right, its »/« button at the window edge. + let column_bar = d.rect("column-bar", 2); + assert_eq!((column_bar.left(), column_bar.right()), (360.0, 600.0 - 18.0)); + // Its inner edge is on the left: dragging it left widens the column. + d.drag(pos2(360.0, 300.0), pos2(320.0, 300.0)); + assert_eq!(column(&d.layout, 0).width, 280.0); + // The left window edge has no dock: a new end dock. + d.wait(); + let out = d.drag(bar(&d, 5), pos2(4.0, 200.0)); + assert_eq!(moved(&out.actions), Some((5, &Target::NewDock { side: Side::End }))); + d.settle(); + assert_eq!(d.rect("column-collapse", 5).left(), 0.0); +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 849a5e593b..842dbb8277 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -21,6 +21,8 @@ pub use workspace::Workspace; use surface::{Drag, GroupDrag, GroupGesture}; +#[cfg(test)] +mod dock_tests; #[cfg(test)] mod group_tests; #[cfg(test)] From 17cf8cd07bbf1726c1e4d92caeff26fdb9ccc02d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:19:33 +0000 Subject: [PATCH 16/94] docking: public floating window chrome docking::chrome holds the parts of a floating window that hosts other than DockArea need, such as office task panes: FloatingFrame (opaque frame on its own layer, anchored resize from both sides, the bottom and both bottom corners, arrow keys on a focused handle) and TitleBar (two grip lines or a title, an optional menu button, and a close button 10 pt in from the right). They return responses and requested rects; the caller turns them into its own commands. Behaviour follows vectorcraft floating.rs (show_set: TITLE 14, grip lines, close position). --- crates/ui/src/docking/chrome.rs | 334 ++++++++++++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 1 + 2 files changed, 335 insertions(+) create mode 100644 crates/ui/src/docking/chrome.rs diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs new file mode 100644 index 0000000000..2e2b14be68 --- /dev/null +++ b/crates/ui/src/docking/chrome.rs @@ -0,0 +1,334 @@ +//! Floating window chrome: an opaque frame with anchored resize handles, and a title bar with a +//! grip, an optional ▾ menu button and ×. [`super::DockArea`] draws its floating windows with +//! these; other hosts (task panes) use them with their own ids and actions. Nothing here changes +//! a layout: the caller turns the responses into its own commands. + +use egui::{Color32, Context, FontId, Id, Key, LayerId, Order, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetText, pos2, vec2}; + +use super::{DockStyle, PanelLimits, resize::AnchoredResize}; + +/// Height of a floating window's title bar. +pub const TITLE_HEIGHT: f32 = 14.0; + +/// Names of the resize handles, appended to the frame id: `id.with(name)`. +pub const RESIZE_HANDLES: [&str; 5] = ["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left"]; + +/// Colours and font of the frame and title bar. +#[derive(Clone, Debug)] +pub struct ChromeStyle { + /// Painted under the contents, so the window stays opaque when the contents are not. + pub background: Color32, + pub stroke: Stroke, + pub title_background: Color32, + pub text: Color32, + pub weak_text: Color32, + pub accent: Color32, + pub font: FontId, +} + +impl ChromeStyle { + pub fn from_ui(ui: &Ui) -> Self { + Self::from_dock(&DockStyle::from_ui(ui)) + } + + pub fn from_dock(style: &DockStyle) -> Self { + Self { + background: style.floating_background, + stroke: style.floating_stroke, + title_background: style.tab_background, + text: style.text, + weak_text: style.inactive_text, + accent: style.accent, + font: style.font.clone(), + } + } +} + +/// Resize handle hit rects and the edges they move: both sides, the bottom and both bottom +/// corners. The top edge belongs to the title bar. +fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 5] { + [ + ("resize", Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max), vec2(1.0, 1.0)), + ( + "resize-left", + Rect::from_min_max(pos2(rect.left(), rect.top() + 12.0), pos2((rect.left() + 4.0).min(rect.right()), rect.bottom() - 12.0)), + vec2(-1.0, 0.0), + ), + ( + "resize-right", + Rect::from_min_max(pos2((rect.right() - 4.0).max(rect.left()), rect.top() + 12.0), pos2(rect.right(), rect.bottom() - 12.0)), + vec2(1.0, 0.0), + ), + ( + "resize-bottom", + Rect::from_min_max(pos2(rect.left() + 12.0, (rect.bottom() - 4.0).max(rect.top())), pos2(rect.right() - 12.0, rect.bottom())), + vec2(0.0, 1.0), + ), + ( + "resize-bottom-left", + Rect::from_min_max(pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), pos2((rect.left() + 12.0).min(rect.right()), rect.bottom())), + vec2(-1.0, 1.0), + ), + ] +} + +/// An opaque in-window frame on its own `Order::Middle` layer, `id`, at `rect`. +pub struct FloatingFrame<'a> { + id: Id, + rect: Rect, + bounds: Option, + limits: PanelLimits, + resizable: bool, + resize_label: &'a str, +} + +/// What a [`FloatingFrame`] did this frame. +pub struct FrameResponse { + pub inner: R, + /// Where the frame was drawn, inside its bounds. + pub rect: Rect, + pub layer: LayerId, + /// The rect a resize handle asks for: pointer drags anchored at the opposite edges, or + /// arrow keys on a focused handle (8 pt per press). Escape and focus loss end a resize. + pub resized: Option, + /// The handle whose pointer resize started this frame. + pub resize_started: Option, + /// Every handle's response, for focus and gesture bookkeeping. + pub handles: Vec, +} + +impl<'a> FloatingFrame<'a> { + pub fn new(id: Id, rect: Rect) -> Self { + Self { id, rect, bounds: None, limits: PanelLimits::default(), resizable: true, resize_label: "Resize window" } + } + + /// The frame stays inside `bounds`; the default is the viewport's content rect. + pub fn bounds(mut self, bounds: Rect) -> Self { + self.bounds = Some(bounds); + self + } + + /// Size limits of a resize. The frame itself is drawn at the given rect. + pub fn limits(mut self, limits: PanelLimits) -> Self { + self.limits = limits; + self + } + + pub fn resizable(mut self, resizable: bool) -> Self { + self.resizable = resizable; + self + } + + /// Accessibility label of the resize handles. + pub fn resize_label(mut self, label: &'a str) -> Self { + self.resize_label = label; + self + } + + pub fn layer(id: Id) -> LayerId { + LayerId::new(Order::Middle, id) + } + + /// Draw the frame, then `add_contents` with the frame's rect, then the outline and handles. + pub fn show(self, ctx: &Context, style: &ChromeStyle, add_contents: impl FnOnce(&mut Ui, Rect) -> R) -> FrameResponse { + let bounds = self.bounds.unwrap_or_else(|| ctx.content_rect()); + let rect = clamp(self.rect, bounds); + let area = egui::Area::new(self.id).fade_in(false).order(Order::Middle).fixed_pos(rect.min) + .default_size(rect.size()) + .movable(false) + .constrain_to(bounds); + let shown = area.show(ctx, |ui| { + // Drawn at `rect` itself, also in egui's first (sizing) pass of a new area. + ui.set_min_size(rect.size()); + ui.allocate_rect(rect, Sense::hover()); + ui.painter().rect_filled(rect, 0.0, style.background); + let inner = add_contents(ui, rect); + ui.painter().rect_stroke(rect, 0.0, style.stroke, StrokeKind::Outside); + let (resized, resize_started, handles) = + if self.resizable { self.handles(ui, rect, bounds, style) } else { (None, None, Vec::new()) }; + FrameResponse { inner, rect, layer: Self::layer(self.id), resized, resize_started, handles } + }); + shown.inner + } + + fn handles(&self, ui: &mut Ui, rect: Rect, bounds: Rect, style: &ChromeStyle) -> (Option, Option, Vec) { + let mut resized = None; + let mut started = None; + let mut responses = Vec::new(); + let limits = PanelLimits { min: self.limits.min.max(vec2(40.0, TITLE_HEIGHT + 20.0)).min(self.limits.max), ..self.limits }; + let cancelled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused); + for (name, handle, direction) in handles(rect) { + if !super::targets::usable(handle) { + continue; + } + let cursor = if direction.x == 0.0 { + egui::CursorIcon::ResizeVertical + } else if direction.y == 0.0 { + egui::CursorIcon::ResizeHorizontal + } else if direction.x == direction.y { + egui::CursorIcon::ResizeNwSe + } else { + egui::CursorIcon::ResizeNeSw + }; + let response = ui.interact(handle, self.id.with(name), Sense::drag()).on_hover_cursor(cursor); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.resize_label)); + let anchor_id = response.id.with("pointer-anchor"); + if response.drag_started() { + response.request_focus(); + if let Some(origin) = ui.input(|i| i.pointer.press_origin()) + && let Some(anchor) = AnchoredResize::new(rect, origin, direction) + { + ui.ctx().data_mut(|data| data.insert_temp(anchor_id, anchor)); + started = Some(response.id); + } + } + let mut delta = Vec2::ZERO; + if response.has_focus() { + ui.memory_mut(|memory| { + memory.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + ui.input_mut(|input| { + for (key, step) in [(Key::ArrowLeft, vec2(-8.0, 0.0)), (Key::ArrowRight, vec2(8.0, 0.0)), (Key::ArrowUp, vec2(0.0, -8.0)), (Key::ArrowDown, vec2(0.0, 8.0))] { + if input.consume_key(egui::Modifiers::NONE, key) { + delta += step; + } + } + }); + } + let next = if response.dragged() || response.drag_stopped() { + ui.ctx() + .data(|data| data.get_temp::(anchor_id)) + .and_then(|anchor| ui.ctx().pointer_interact_pos().and_then(|pointer| anchor.rect(pointer, bounds, limits))) + } else if delta != Vec2::ZERO { + AnchoredResize::new(rect, rect.max, direction).and_then(|anchor| anchor.rect(rect.max + delta, bounds, limits)) + } else { + None + }; + if response.enabled() + && !cancelled + && let Some(next) = next.filter(|next| *next != rect) + { + resized = Some(next); + } + if response.drag_stopped() { + response.surrender_focus(); + } + if cancelled || !ui.input(|input| input.pointer.primary_down()) { + ui.ctx().data_mut(|data| data.remove::(anchor_id)); + } + if name == "resize" && (response.hovered() || response.dragged() || response.has_focus()) { + ui.painter().line_segment([handle.left_bottom(), handle.right_top()], Stroke::new(2.0, style.accent)); + } + responses.push(response); + } + (resized, started, responses) + } +} + +/// Keep `rect` inside `bounds`, shrinking it when it is larger. +pub fn clamp(rect: Rect, bounds: Rect) -> Rect { + if !super::targets::usable(bounds) { + return rect; + } + let size = rect.size().max(vec2(1.0, 1.0)).min(bounds.size()); + let min = rect.min.max(bounds.min).min(bounds.max - size); + Rect::from_min_size(min, size) +} + +/// A title bar: two grip lines (or a title), an optional ▾ menu button and an optional ×, 10 pt +/// in from the right edge. The bar senses clicks and drags; double-clicks are the caller's. +pub struct TitleBar<'a> { + id: Id, + move_label: &'a str, + title: Option, + menu: Option<&'a str>, + close: Option<&'a str>, + movable: bool, +} + +/// The parts of a [`TitleBar`] that were shown. +pub struct TitleResponse { + /// Drag to move; double-click is the caller's (docking minimizes every group). + pub bar: Response, + pub menu: Option, + pub close: Option, +} + +impl<'a> TitleBar<'a> { + /// `id` is the bar's own; the buttons use `id.with("menu")` and `id.with("close")`. + /// `move_label` names the bar for accessibility. + pub fn new(id: Id, move_label: &'a str) -> Self { + Self { id, move_label, title: None, menu: None, close: None, movable: true } + } + + /// Text at the left instead of the grip lines. + pub fn title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + /// Show a ▾ button with this accessibility label. + pub fn menu(mut self, label: &'a str) -> Self { + self.menu = Some(label); + self + } + + /// Show a × button with this accessibility label. + pub fn close(mut self, label: &'a str) -> Self { + self.close = Some(label); + self + } + + /// Whether the bar shows the grab cursor. It senses drags either way. + pub fn movable(mut self, movable: bool) -> Self { + self.movable = movable; + self + } + + pub fn show(self, ui: &mut Ui, rect: Rect, style: &ChromeStyle) -> TitleResponse { + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + painter.rect_filled(rect, 0.0, style.title_background); + let side = rect.height(); + let close_rect = self.close.map(|_| Rect::from_center_size(pos2(rect.right() - 10.0, rect.center().y), vec2(side, side))); + let menu_right = close_rect.map_or(rect.right() - 3.0, |close| close.left() - 2.0); + let menu_rect = self.menu.map(|_| Rect::from_min_max(pos2(menu_right - side, rect.top()), pos2(menu_right, rect.bottom()))); + let buttons = menu_rect.or(close_rect).map_or(rect.right(), |r| r.left()); + let bar_rect = Rect::from_min_max(rect.min, pos2(buttons.max(rect.left()), rect.bottom())); + let bar = ui.interact(bar_rect, self.id, Sense::click_and_drag()); + let bar = if self.movable { bar.on_hover_cursor(egui::CursorIcon::Grab) } else { bar }; + bar.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.move_label)); + if let Some(title) = self.title { + let galley = title.into_galley(ui, Some(egui::TextWrapMode::Truncate), (bar_rect.width() - 12.0).max(0.0), style.font.clone()); + painter.galley(pos2(rect.left() + 6.0, rect.center().y - galley.size().y * 0.5), galley, style.text); + } else { + let grip = Stroke::new(0.6, style.weak_text); + for k in 0..2 { + let y = rect.center().y - 1.5 + k as f32 * 3.0; + painter.line_segment([pos2(rect.center().x - 9.0, y), pos2(rect.center().x + 9.0, y)], grip); + } + } + if bar.has_focus() { + painter.rect_stroke(bar_rect.shrink(1.0), 0.0, Stroke::new(1.0, style.accent), StrokeKind::Inside); + } + let button = |ui: &mut Ui, rect: Rect, name: &str, label: &str| { + let response = ui.interact(rect, self.id.with(name), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label)); + let color = if response.hovered() || response.has_focus() { style.text } else { style.weak_text }; + (response, Stroke::new(1.2, color)) + }; + let menu = menu_rect.zip(self.menu).map(|(menu_rect, label)| { + let (response, stroke) = button(ui, menu_rect, "menu", label); + let c = menu_rect.center(); + painter.add(egui::Shape::convex_polygon(vec![c + vec2(-3.5, -1.5), c + vec2(3.5, -1.5), c + vec2(0.0, 2.5)], stroke.color, Stroke::NONE)); + response + }); + let close = close_rect.zip(self.close).map(|(close_rect, label)| { + let (response, stroke) = button(ui, close_rect, "close", label); + let r = Rect::from_center_size(close_rect.center(), Vec2::splat((side * 0.5).max(4.0))); + painter.line_segment([r.left_top(), r.right_bottom()], stroke); + painter.line_segment([r.right_top(), r.left_bottom()], stroke); + response + }); + TitleResponse { bar, menu, close } + } +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 849a5e593b..2c58dbff41 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -5,6 +5,7 @@ //! Validate deserialized layouts before rendering them. Every transaction checks its complete //! input and commits only a valid result; a rejected move cannot lose the source panel. +pub mod chrome; mod dock_model; mod model; mod render; From 40fefd9c7bd1fd1c06893210b07ca3a06923a3bd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:19:44 +0000 Subject: [PATCH 17/94] docking: floating title bars and stacks, frame profile, native windows Floating windows: - A title bar (TITLE 14) drags the whole window live; Escape and focus loss put it back. A release over a tab strip, a floating stack's band or seam, or the outer edge emits MoveWindow; elsewhere the window stays and hosts get group_drop. Double-click minimizes or expands every group; the close button closes every panel (CloseWindow). - Stacked groups with a 3 pt bar between them and dividers that resize both neighbours (ResizeGroup). The top and bottom quarter of a group and the seam between two groups insert a new group there, with a line preview (P3, P4). The title bar occludes what lies behind it. - The only group of a window carries the window rect when dragged by its bar, so floating it again keeps the window's size. Frame profile (DockStyle::profile): - Ctrl/Cmd held at the start of a tab drag undocks the panel (S9). - The outer edge band splits at the root: top and bottom in both profiles, left and right in the frame profile (P8). - Menu tail: Undock Panel, Close Panel Group, Undock Panel Group, Close Other Panels in Group and Maximize Frame (DockEvent::ToggleMaximize). DockArea::maximized draws only the docked frame holding the panel; other frames and floating windows do not render or take input. DockArea::hide_panels leaves out every panel, or every panel except a host-chosen set; protected panels stay and the layout is unchanged. Feature native-windows: a floating window with a native rect gets its own OS window through show_viewport_immediate when the backend does not embed viewports, and stays in-window otherwise. Closing it emits SetNative None, so the group returns to its in-window rect; moves and resizes are read back as SetNative with bounded sizes and positions. Tabs and groups do not drag between OS windows. Move Panel to New Window is in the menu tail where native windows are available. A floating panel whose window closed as a whole restores at its last rect. Behaviour follows vectorcraft floating.rs (show_set, draw_groups, track), effectcraft dock_ui.rs (panel_window, set_panel_window, toggle_maximize) and dock.rs (PanelWindow::sanitized), filmcraft dock_ui.rs (workspace_edge, EDGE_BAND, maximized) and storytold/filmcraft#2118 (saved_native_rect, bounded_inner_size). --- crates/ui/Cargo.toml | 2 + crates/ui/src/docking/floating_tests.rs | 534 +++++++++++++++++++++++ crates/ui/src/docking/group_tests.rs | 2 +- crates/ui/src/docking/mod.rs | 7 +- crates/ui/src/docking/model.rs | 9 +- crates/ui/src/docking/render/floating.rs | 426 +++++++++++------- crates/ui/src/docking/render/frame.rs | 231 ++++++++++ crates/ui/src/docking/render/group.rs | 59 +-- crates/ui/src/docking/render/mod.rs | 16 +- crates/ui/src/docking/render/native.rs | 154 +++++++ crates/ui/src/docking/render/preview.rs | 60 ++- crates/ui/src/docking/surface.rs | 110 ++++- crates/ui/src/docking/tests.rs | 8 +- 13 files changed, 1374 insertions(+), 244 deletions(-) create mode 100644 crates/ui/src/docking/floating_tests.rs create mode 100644 crates/ui/src/docking/render/frame.rs create mode 100644 crates/ui/src/docking/render/native.rs diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index 0b8edc2f00..dd85edd4a6 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -16,6 +16,8 @@ serde = { version = "1", features = ["derive"], optional = true } [features] serde = ["dep:serde"] +# Floating windows may move to their own OS windows (desktop egui backends with viewports). +native-windows = [] [dev-dependencies] egui = { workspace = true, features = ["default_fonts"] } diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs new file mode 100644 index 0000000000..8d8dc7581d --- /dev/null +++ b/crates/ui/src/docking/floating_tests.rs @@ -0,0 +1,534 @@ +//! Floating windows (title bar, stacks, close), the frame profile (outer edge, Maximize, +//! Ctrl/Cmd undock, frame menu items), hidden panels, native windows and the public chrome. + +use super::*; +use crate::layout::{SplitAxis, SplitSize}; +use egui::{Context, Event, Id, Modifiers, PointerButton, RawInput, Rect, Vec2, pos2, vec2}; + +const AREA: &str = "floating-area"; + +fn tabs(panels: &[u32], active: usize) -> Node { + Node::Tabs { panels: panels.to_vec(), active } +} + +/// `[1] | [2, 3]` with panel 3 selected. +fn frames() -> Layout { + Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(300.0), + first: Box::new(tabs(&[1], 0)), + second: Box::new(tabs(&[2, 3], 1)), + }), + floating: Vec::new(), + } +} + +/// A start dock (`[2, 3]` above `[4]`) beside protected canvas 0; window W1 stacks `[5]` above +/// `[6, 7]`; window W2 holds `[8]`. +fn workspace() -> Layout { + Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(240.0), + first: Box::new(Node::Dock { + side: Side::Start, + columns: vec![Column::new(vec![Group::new(vec![2, 3], 1), Group::new(vec![4], 0)], 240.0)], + }), + second: Box::new(tabs(&[0], 0)), + }), + floating: vec![ + Floating { groups: vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], rect: [300.0, 80.0, 240.0, 300.0], native: None }, + Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0]), + ], + } +} + +#[derive(Default)] +struct Content { + native: bool, + keep: Vec, +} + +impl DockContent for Content { + fn body(&mut self, ui: &mut egui::Ui, _: &u32) { + ui.label("Body"); + } + fn logical_label(&self, panel: &u32) -> String { + format!("Panel {panel}") + } + fn permissions(&self, panel: &u32) -> Permissions { + if *panel == 0 { Permissions::PROTECTED } else { Permissions::default() } + } + fn allow_native(&self, _: &u32) -> bool { + self.native + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Hide { + None, + All, + Keep, +} + +struct Driver { + ctx: Context, + layout: Layout, + content: Content, + profile: Profile, + maximized: Option, + hide: Hide, + modifiers: Modifiers, + time: f64, +} + +impl Driver { + fn new(layout: Layout, profile: Profile) -> Self { + let mut driver = Self { + ctx: Context::default(), + layout, + content: Content::default(), + profile, + maximized: None, + hide: Hide::None, + modifiers: Modifiers::NONE, + time: 0.0, + }; + driver.step(vec![]); + driver.step(vec![]); + driver + } + + fn frame(&mut self, mut events: Vec) -> DockOutput { + let mut output = DockOutput::default(); + events.insert(0, Event::ModifiersChanged(self.modifiers)); + self.time += 1.0 / 60.0; + let input = RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), + events, + focused: true, + time: Some(self.time), + ..Default::default() + }; + let (layout, content, profile, maximized, hide) = (&self.layout, &mut self.content, self.profile, self.maximized, self.hide); + let keep: Vec = content.keep.clone(); + let keep = move |p: &u32| keep.contains(p); + let full = self.ctx.run_ui(input, |ui| { + let mut style = DockStyle::from_ui(ui); + style.profile = profile; + let hide = match hide { + Hide::None => HidePanels::None, + Hide::All => HidePanels::All, + Hide::Keep => HidePanels::Except(&keep), + }; + output = DockArea::new(Id::new(AREA)).maximized(maximized).hide_panels(hide).show_content(ui, layout, &style, content); + }); + let mut full = full; + full.textures_delta.clear(); + output + } + + fn step(&mut self, events: Vec) -> DockOutput { + let output = self.frame(events); + assert!(output.error.is_none(), "{output:?}"); + for action in &output.actions { + self.layout.apply_with_permissions(action.clone(), |p| self.content.permissions(p)).unwrap(); + } + output + } + + fn response(&self, id: Id) -> Option { + self.ctx.read_response(id).map(|r| r.rect) + } + + fn title(&self, first: u32) -> Rect { + self.response(Id::new(AREA).with(("move-group", Some(&first)))).unwrap() + } + + fn tab(&self, panel: u32) -> Option { + self.response(Id::new(AREA).with(("tab", &panel))) + } + + fn hold(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput { + self.step(vec![Event::PointerMoved(from), button(from, true)]); + self.step(vec![Event::PointerMoved(from + vec2(8.0, 6.0))]); + self.step(vec![Event::PointerMoved(to)]) + } + + fn drag(&mut self, from: egui::Pos2, to: egui::Pos2) -> DockOutput { + self.hold(from, to); + self.step(vec![button(to, false)]) + } + + fn click(&mut self, at: egui::Pos2) -> DockOutput { + self.step(vec![Event::PointerMoved(at), button(at, true)]); + self.step(vec![button(at, false)]) + } + + fn wait(&mut self) { + for _ in 0..45 { + self.step(vec![]); + } + } +} + +fn done(mut full: egui::FullOutput) { + full.textures_delta.clear(); +} + +fn button(pos: egui::Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } +} + +fn window_of(layout: &Layout, panel: u32) -> Option<&Floating> { + layout.floating.iter().find(|w| w.contains(&panel)) +} + +fn groups_of(window: &Floating) -> Vec> { + window.groups.iter().map(|g| g.panels.clone()).collect() +} + +#[test] +fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_groups() { + // The window follows the pointer with every group; Escape puts it back. + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(5).center(); + d.hold(title, title + vec2(40.0, 30.0)); + assert_eq!(d.layout.floating[0].rect, [340.0, 110.0, 240.0, 300.0]); + assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![5], vec![6, 7]]); + d.step(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + d.step(vec![button(title + vec2(40.0, 30.0), false)]); + assert_eq!(d.layout, workspace()); + + // Released over another window's lower band: its groups stack below that window's. + let out = d.drag(title, pos2(660.0, 480.0)); + assert!( + out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::At { anchor: 8, placement: Placement::Group { below: true } } }), + "{:?}", + out.actions + ); + assert_eq!(d.layout.floating.len(), 1); + assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![8], vec![5], vec![6, 7]]); + + // Released over a docked group's strip: every panel joins it as tabs. + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(5).center(); + let strip = d.tab(4).unwrap().center(); + let out = d.drag(title, strip); + assert!(out.actions.iter().any(|a| matches!(a, Action::MoveWindow { panel: 5, to: Target::At { anchor: 4, .. } })), "{:?}", out.actions); + assert!(window_of(&d.layout, 5).is_none() && window_of(&d.layout, 7).is_none()); + assert_eq!(d.layout.place(&4), d.layout.place(&6)); + + // Released over the canvas: the window stays where it was moved and hosts get the release. + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(5).center(); + let out = d.drag(title, pos2(500.0, 300.0)); + assert!(!out.actions.iter().any(|a| matches!(a, Action::MoveWindow { .. })), "{:?}", out.actions); + assert_eq!(out.group_drop, Some((5, pos2(500.0, 300.0)))); + assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![6, 7]]); +} + +#[test] +fn floating_stack_seams_and_bands_insert_groups() { + // A group dragged by its bar to another window's top band stacks above that group. + let mut d = Driver::new(workspace(), Profile::Dock); + let bar = d.response(Id::new(AREA).with(("drag-bar", Some(&6u32)))).unwrap().center(); + let out = d.drag(bar, pos2(660.0, 360.0)); + assert!( + out.actions.contains(&Action::MoveGroup { panel: 6, to: Target::At { anchor: 8, placement: Placement::Group { below: false } } }), + "{:?}", + out.actions + ); + assert_eq!(groups_of(window_of(&d.layout, 8).unwrap()), vec![vec![6, 7], vec![8]]); + assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5]]); + + // A tab dropped on the seam between two stacked groups becomes a group between them. + let mut d = Driver::new(workspace(), Profile::Dock); + let tab = d.tab(8).unwrap().center(); + let seam = pos2(420.0, 237.0); + let out = d.drag(tab, seam); + assert!( + out.actions.contains(&Action::Move { panel: 8, anchor: 5, placement: Placement::Group { below: true } }), + "{:?}", + out.actions + ); + assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![8], vec![6, 7]]); + + // The divider between two open groups resizes both. + let mut d = Driver::new(workspace(), Profile::Dock); + let divider = d.response(Id::new(AREA).with(("floating-divider", Some(&5u32)))).unwrap().center(); + d.drag(divider, divider + vec2(0.0, 40.0)); + let heights: Vec<_> = window_of(&d.layout, 5).unwrap().groups.iter().map(|g| g.height.unwrap()).collect(); + assert!((heights[0] - 181.5).abs() < 2.0 && (heights[1] - 101.5).abs() < 2.0, "{heights:?}"); +} + +#[test] +fn title_bar_double_click_minimizes_every_group_and_close_box_closes_the_window() { + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(5).center(); + d.click(title); + d.click(title); + assert!(window_of(&d.layout, 5).unwrap().groups.iter().all(|g| g.minimized)); + d.wait(); + d.click(title); + d.click(title); + assert!(window_of(&d.layout, 5).unwrap().groups.iter().all(|g| !g.minimized)); + + let close = d.response(Id::new(AREA).with(("move-group", Some(&5u32))).with("close")).unwrap(); + assert_eq!(close.center().x, 530.0, "× sits 10 pt in from the right edge"); + let before = d.layout.clone(); + let out = d.click(close.center()); + assert_eq!(out.actions, vec![Action::CloseWindow { panel: 5 }]); + assert_eq!(before.closed_by(&Action::CloseWindow { panel: 5 }), Ok(vec![5, 6, 7])); + assert!(window_of(&d.layout, 6).is_none() && d.layout.contains(&8)); +} + +#[test] +fn closed_floating_window_reopens_each_panel_at_its_last_rect() { + let mut layout = workspace(); + let locations: Vec<_> = [5, 6, 7].map(|p| (p, layout.location(&p).unwrap())).into(); + layout.apply(Action::CloseWindow { panel: 6 }).unwrap(); + for (panel, location) in locations { + layout.restore(panel, &location).unwrap(); + assert_eq!(window_of(&layout, panel).unwrap().rect, [300.0, 80.0, 240.0, 300.0], "{panel}"); + } +} + +#[test] +fn ctrl_drag_from_a_frame_strip_undocks_to_a_floating_window() { + let mut d = Driver::new(frames(), Profile::Frame); + let tab = d.tab(3).unwrap().center(); + let other = d.tab(1).unwrap().center(); + d.modifiers = Modifiers::COMMAND; + d.hold(tab, other); + d.modifiers = Modifiers::NONE; + let out = d.step(vec![button(other, false)]); + assert!(matches!(out.actions.as_slice(), [Action::Float { panel: 3, .. }]), "{:?}", out.actions); + assert!(window_of(&d.layout, 3).is_some()); + + // Without the modifier the same drag joins the other frame. + let mut d = Driver::new(frames(), Profile::Frame); + let out = d.drag(tab, other); + assert!(matches!(out.actions.as_slice(), [Action::Move { panel: 3, anchor: 1, .. }]), "{:?}", out.actions); +} + +#[test] +fn outer_edge_band_splits_at_the_root() { + // Frame profile: all four edges. + let mut d = Driver::new(frames(), Profile::Frame); + let tab = d.tab(3).unwrap().center(); + let out = d.drag(tab, pos2(3.0, 300.0)); + assert!(out.actions.contains(&Action::Move { panel: 3, anchor: 1, placement: Placement::Edge(Zone::Left) }), "{:?}", out.actions); + let Some(Node::Split { axis: SplitAxis::Horizontal, first, .. }) = &d.layout.root else { panic!("{:?}", d.layout) }; + assert_eq!(**first, tabs(&[3], 0)); + + // Dock profile: the bottom edge of the part between the docks, for a Timeline. + let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, Profile::Dock); + let tab = d.tab(2).unwrap().center(); + let out = d.drag(tab, pos2(500.0, 597.0)); + assert!(out.actions.iter().any(|a| matches!(a, Action::Move { panel: 2, placement: Placement::Edge(Zone::Bottom), .. })), "{:?}", out.actions); + let Some(Node::Split { first, second, .. }) = &d.layout.root else { panic!() }; + assert!(matches!(**first, Node::Dock { .. })); + assert!(matches!(&**second, Node::Split { axis: SplitAxis::Vertical, second, .. } if **second == tabs(&[2], 0))); + + // Its left and right edges are the docks' (new columns and docks), not root splits. + let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, Profile::Dock); + let tab = d.tab(4).unwrap().center(); + let out = d.drag(tab, pos2(246.0, 300.0)); + assert!(!out.actions.iter().any(|a| matches!(a, Action::Move { placement: Placement::Edge(_), .. })), "{:?}", out.actions); +} + +#[test] +fn maximized_frame_fills_the_area_and_other_frames_do_not_render_or_take_input() { + let mut layout = frames(); + layout.floating.push(Floating::single(vec![5], 0, [400.0, 300.0, 200.0, 150.0])); + let mut d = Driver::new(layout.clone(), Profile::Frame); + let window_title = d.title(5).center(); + d.maximized = Some(2); + d.step(vec![]); + d.step(vec![]); + assert_eq!(d.tab(2).unwrap().left(), 0.0, "the maximized frame starts at the area's edge"); + assert!(d.tab(1).is_none()); + assert!(d.response(Id::new(AREA).with(("move-group", Some(&5u32)))).is_none()); + let out = d.drag(window_title, window_title + vec2(30.0, 30.0)); + assert!(out.actions.iter().all(|a| !matches!(a, Action::MoveFloating { .. } | Action::MoveWindow { .. })), "{:?}", out.actions); + + // A floating panel does not maximize. + let mut d = Driver::new(layout, Profile::Frame); + d.maximized = Some(5); + d.step(vec![]); + d.step(vec![]); + assert!(d.tab(1).is_some()); +} + +#[test] +fn close_other_panels_keeps_only_the_chosen_tab() { + use egui_kittest::{Harness, kittest::Queryable}; + type State = (Content, Vec>, Vec>); + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, (content, actions, events): &mut State| { + let mut style = DockStyle::from_ui(ui); + style.profile = Profile::Frame; + let out = DockArea::new(Id::new(AREA)).show_content(ui, &frames(), &style, content); + actions.extend(out.actions); + events.extend(out.events); + }, + (Content::default(), Vec::new(), Vec::new()), + ); + h.run_steps(2); + let at = h.ctx.read_response(Id::new(AREA).with(("tab", &3u32))).unwrap().rect.center(); + let open_menu = |h: &mut Harness<'_, State>| { + 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); + }; + open_menu(&mut h); + for label in ["Undock Panel", "Close Panel Group", "Undock Panel Group", "Close Other Panels in Group", "Maximize Frame"] { + assert_eq!(h.query_all_by_label(label).count(), 1, "{label}"); + } + assert_eq!(h.query_all_by_label("Minimize").count(), 0); + h.get_by_label("Close Other Panels in Group").click(); + h.run_steps(2); + assert_eq!(h.state().1, vec![Action::CloseOthers { panel: 3 }]); + let mut layout = frames(); + layout.apply(Action::CloseOthers { panel: 3 }).unwrap(); + assert!(layout.contains(&3) && !layout.contains(&2)); + + open_menu(&mut h); + h.get_by_label("Maximize Frame").click(); + h.run_steps(2); + assert_eq!(h.state().2, vec![DockEvent::ToggleMaximize { panel: 3 }]); +} + +#[test] +fn hide_panels_keeps_protected_panels_and_the_except_set() { + let mut d = Driver::new(workspace(), Profile::Dock); + d.hide = Hide::All; + d.step(vec![]); + d.step(vec![]); + for panel in [2, 3, 4, 5, 6, 8] { + assert!(d.tab(panel).is_none(), "{panel}"); + } + assert!(d.layout == workspace(), "hiding leaves the layout unchanged"); + + d.hide = Hide::Keep; + d.content.keep = vec![4, 6]; + d.step(vec![]); + d.step(vec![]); + assert_eq!(d.tab(4).map(|r| r.left()), Some(0.0)); + assert!(d.tab(6).is_some()); + for panel in [2, 3, 5, 7, 8] { + assert!(d.tab(panel).is_none(), "{panel}"); + } + // A window keeps its rect with its hidden groups left out. + d.step(vec![]); + assert_eq!(d.title(6).min, pos2(300.0, 80.0)); +} + +#[test] +fn native_window_falls_back_in_window_when_viewports_are_embedded() { + let mut layout = workspace(); + layout.floating[0].native = Some([1200.0, 900.0, 240.0, 300.0]); + let mut d = Driver::new(layout.clone(), Profile::Dock); + d.content.native = true; + assert!(d.ctx.embed_viewports()); + let out = d.step(vec![]); + assert!(out.actions.is_empty(), "{out:?}"); + assert_eq!(d.title(5).min, pos2(300.0, 80.0)); + assert_eq!(d.layout, layout); +} + +#[cfg(feature = "native-windows")] +#[test] +fn native_window_close_returns_the_group_to_its_in_window_rect() { + use std::{cell::Cell, rc::Rc}; + let close = Rc::new(Cell::new(false)); + let requested = close.clone(); + // A backend with real viewports: the child reports its place and, when asked, a close. + Context::set_immediate_viewport_renderer(move |ctx, mut viewport| { + let mut info = egui::ViewportInfo { + outer_rect: Some(Rect::from_min_size(pos2(1210.0, 905.0), vec2(250.0, 330.0))), + inner_rect: Some(Rect::from_min_size(pos2(1210.0, 935.0), vec2(250.0, 300.0))), + ..Default::default() + }; + if requested.get() { + info.events.push(egui::ViewportEvent::Close); + } + let input = RawInput { + viewport_id: viewport.ids.this, + viewports: std::iter::once((viewport.ids.this, info)).collect(), + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(250.0, 300.0))), + ..Default::default() + }; + done(ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui))); + }); + let mut layout = workspace(); + layout.floating[0].native = Some([1200.0, 900.0, 240.0, 300.0]); + let mut d = Driver::new(Layout::default(), Profile::Dock); + d.ctx.set_embed_viewports(false); + d.content.native = true; + d.layout = layout; + let out = d.step(vec![]); + assert!(d.response(Id::new(AREA).with(("move-group", Some(&5u32)))).is_none(), "drawn in its own OS window"); + assert!(out.actions.contains(&Action::SetNative { panel: 5, rect: Some([1210.0, 905.0, 250.0, 300.0]) }), "{:?}", out.actions); + + close.set(true); + let out = d.step(vec![]); + assert!(out.actions.contains(&Action::SetNative { panel: 5, rect: None }), "{:?}", out.actions); + assert_eq!(d.layout.floating[0].native, None); + assert_eq!(d.layout.floating[0].rect, [300.0, 80.0, 240.0, 300.0]); + d.step(vec![]); + d.step(vec![]); + assert_eq!(d.title(5).min, pos2(300.0, 80.0)); +} + +#[test] +fn chrome_frame_and_title_bar_work_without_a_dock_area() { + use chrome::{ChromeStyle, FloatingFrame, TitleBar}; + let ctx = Context::default(); + let id = Id::new("task-pane"); + let rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(300.0, 200.0)); + let mut time = 0.0; + let mut frame = |events: Vec| { + time += 1.0 / 60.0; + let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), events, time: Some(time), ..Default::default() }; + let mut result = None; + done(ctx.run_ui(input, |ui| { + let style = ChromeStyle::from_ui(ui); + let shown = FloatingFrame::new(id, rect).show(ui.ctx(), &style, |ui, inner| { + let title = Rect::from_min_size(inner.min, vec2(inner.width(), 22.0)); + let bar = TitleBar::new(id.with("title"), "Move pane").title("Styles").menu("Pane menu").close("Close pane").show(ui, title, &style); + (bar.bar.dragged(), bar.bar.drag_delta(), bar.menu.is_some_and(|r| r.clicked()), bar.close.is_some_and(|r| r.clicked())) + }); + result = Some((shown.inner, shown.resized)); + })); + result.unwrap() + }; + frame(vec![]); + frame(vec![]); + let click = |frame: &mut dyn FnMut(Vec) -> ((bool, Vec2, bool, bool), Option), at| { + frame(vec![Event::PointerMoved(at), button(at, true)]); + frame(vec![button(at, false)]) + }; + let ((_, _, _, closed), _) = click(&mut frame, pos2(390.0, 111.0)); + assert!(closed, "× 10 pt in from the right"); + let ((_, _, menu, _), _) = click(&mut frame, pos2(374.0, 111.0)); + assert!(menu, "▾ left of ×"); + + frame(vec![Event::PointerMoved(pos2(200.0, 110.0)), button(pos2(200.0, 110.0), true)]); + frame(vec![Event::PointerMoved(pos2(210.0, 115.0))]); + let ((dragged, delta, ..), _) = frame(vec![Event::PointerMoved(pos2(230.0, 125.0))]); + assert!(dragged && delta == vec2(20.0, 10.0), "{delta:?}"); + frame(vec![button(pos2(230.0, 125.0), false)]); + + let edge = pos2(398.0, 200.0); + frame(vec![Event::PointerMoved(edge), button(edge, true)]); + frame(vec![Event::PointerMoved(edge + vec2(10.0, 0.0))]); + let (_, resized) = frame(vec![Event::PointerMoved(edge + vec2(50.0, 0.0))]); + assert_eq!(resized, Some(Rect::from_min_size(rect.min, vec2(350.0, 200.0)))); +} diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 7edcf28fa4..673b21334c 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -527,7 +527,7 @@ fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() { let mut d = Driver::new(layout); let from = d.rect("drag-bar", 6).center(); let out = d.drag(from, pos2(700.0, 300.0)); - assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 200.0]) })), "{:?}", out.actions); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 191.5]) })), "{:?}", out.actions); assert_eq!(d.layout.floating.len(), 2); assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![5], 0)]); assert_eq!(d.layout.floating[1].groups, vec![Group::new(vec![6, 7], 1)]); diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 2c58dbff41..eae01b8660 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -16,12 +16,17 @@ mod workspace; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; -pub use surface::{DockArea, DockContent, DockOutput, DockStyle, DropFeedback, DropRequest, PanelLimits, begin_drag, cancel_drag, is_dragging}; +pub use surface::{ + DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, HidePanels, PanelLimits, Profile, begin_drag, cancel_drag, + is_dragging, +}; pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect}; pub use workspace::Workspace; use surface::{Drag, GroupDrag, GroupGesture}; +#[cfg(test)] +mod floating_tests; #[cfg(test)] mod group_tests; #[cfg(test)] diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 952092ea93..6800e56569 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -576,7 +576,8 @@ impl Layout

{ } /// Restore an absent panel at a captured location. Missing anchors are reported without - /// changes, allowing the app to choose an explicit default. Unrelated tabs retain selection. + /// changes, allowing the app to choose an explicit default; a floating panel whose + /// window is gone floats at its last rect instead. Unrelated tabs retain selection. pub fn restore(&mut self, panel: P, location: &Location

) -> Result<(), DockError> { self.validate()?; if self.contains(&panel) { @@ -608,10 +609,8 @@ impl Layout

{ if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } - if let Some(anchor) = &location.anchor { - if !proposed.floating.iter().any(|g| g.contains(anchor)) { - return Err(DockError::MissingTarget); - } + // A window that closed as a whole reopens at its last rect. + if let Some(anchor) = location.anchor.as_ref().filter(|anchor| proposed.floating.iter().any(|g| g.contains(anchor))) { if let Placement::Group { .. } = location.placement { proposed.insert_moving(moving(), Target::At { anchor: anchor.clone(), placement: location.placement.clone() })?; } else { diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 43d18e2589..383a68b4b9 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -1,176 +1,308 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Context, Id, Key, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; +use egui::{Context, Id, Key, Pos2, Rect, Ui, pos2, vec2}; -use super::{GroupKind, Renderer, clamp_float}; -use crate::docking::{Action, Floating, Node, PanelLimits, resize::AnchoredResize}; +use super::{GroupKind, Renderer, clamp_float, node_limits}; +use crate::docking::chrome::{ChromeStyle, FloatingFrame, TitleBar}; +use crate::docking::{Action, DropProposal, Floating, Group, GroupDrag, GroupGesture, Node, PanelLimits, Placement, Target}; +use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; -/// Floating window resize handles: id suffix, hit rect and the edges they move. -fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 5] { - [ - ("resize", Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max), vec2(1.0, 1.0)), - ( - "resize-left", - Rect::from_min_max(pos2(rect.left(), rect.top() + 12.0), pos2((rect.left() + 4.0).min(rect.right()), rect.bottom() - 12.0)), - vec2(-1.0, 0.0), - ), - ( - "resize-right", - Rect::from_min_max(pos2((rect.right() - 4.0).max(rect.left()), rect.top() + 12.0), pos2(rect.right(), rect.bottom() - 12.0)), - vec2(1.0, 0.0), - ), - ( - "resize-bottom", - Rect::from_min_max(pos2(rect.left() + 12.0, (rect.bottom() - 4.0).max(rect.top())), pos2(rect.right() - 12.0, rect.bottom())), - vec2(0.0, 1.0), - ), - ( - "resize-bottom-left", - Rect::from_min_max( - pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), - pos2((rect.left() + 12.0).min(rect.right()), rect.bottom()), - ), - vec2(-1.0, 1.0), - ), - ] +pub(in crate::docking) use crate::docking::chrome::RESIZE_HANDLES; + +/// Height of the bar between two stacked groups of a floating window. +const GAP: f32 = 3.0; +/// Height of the band around a seam between stacked groups that inserts a new group there. +const SEAM_BAND: f32 = 8.0; + +/// A floating stack as drawn, for its band and seam targets. +pub(in crate::docking) struct StackHit

{ + pub(super) window: Rect, + /// Each group's members, rect and tab strip, top to bottom. + pub(super) groups: Vec<(Vec

, Rect, Rect)>, + /// The upper group's index and the band of each seam. + pub(super) seams: Vec<(usize, Rect)>, } -/// Names of every floating window resize handle, for focus classification. -pub(in crate::docking) const RESIZE_HANDLES: [&str; 5] = ["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left"]; - impl Renderer<'_, P> { - pub(in crate::docking) fn floating(&mut self, ctx: &Context) { + pub(in crate::docking) fn floating(&mut self, ctx: &Context, windows: &[Floating

]) { let screen = ctx.content_rect(); if !crate::docking::targets::usable(screen) { return; } let layers = ctx.memory(|memory| memory.layer_ids().collect::>()); - let mut windows: Vec<_> = self.layout.floating.iter().collect(); + let mut windows: Vec<_> = windows.iter().collect(); windows.sort_by_key(|window| { let id = window.panels().next().map(|panel| self.id.with(("floating", panel))); layers.iter().position(|layer| Some(layer.id) == id).unwrap_or(usize::MAX) }); + #[cfg(feature = "native-windows")] + let windows = self.native_windows(ctx, windows); for window in windows { - let Some(first) = window.panels().next() else { continue }; - let [x, y, width, height] = window.rect; - let limits = self.node_limits(&Node::Tabs { panels: window.panels().cloned().collect(), active: 0 }); - let mut size = vec2(width, height).max(limits.min).min(limits.max); - if window.groups.iter().all(|group| group.minimized) { - size.y = size.y.min(window.groups.len() as f32 * self.style.tab_height); - } - let rect = clamp_float(Rect::from_min_size(pos2(x, y), size), screen); - let id = self.id.with(("floating", first)); - if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { - ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id)); - ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); - self.output.focused = self.activation.clone(); - } - egui::Area::new(id).fade_in(false).order(egui::Order::Middle).fixed_pos(rect.min).movable(false).constrain_to(screen).show(ctx, |ui| { - ui.set_min_size(rect.size()); - let rect = Rect::from_min_size(ui.min_rect().min, rect.size()); - ui.allocate_rect(rect, Sense::hover()); - // Opaque even when the host's panel colours are transparent. - ui.painter().rect_filled(rect, 0.0, self.style.floating_background); - self.stacked_groups(ui, &window.groups, rect, GroupKind::Floating { window: rect }); - ui.painter().rect_stroke(rect, 0.0, self.style.floating_stroke, egui::StrokeKind::Outside); - self.resize_handles(ui, window, id, rect, limits, screen); - }); + self.floating_window(ctx, window, screen); } } - /// Anchored resize from the side edges, the bottom edge and both bottom corners: the - /// opposite edges stay where they are. - fn resize_handles(&mut self, ui: &mut Ui, window: &Floating

, id: Id, rect: Rect, limits: PanelLimits, screen: Rect) { + /// Size limits of a floating window: its title bar, each group's strip and the bodies of + /// the groups that are not minimized. + pub(super) fn window_limits(&self, window: &Floating

) -> PanelLimits { + let mut limits = PanelLimits { min: vec2(0.0, self.style.title_height), max: vec2(1_000_000.0, self.style.title_height) }; + for (index, group) in window.groups.iter().enumerate() { + let policy = node_limits(&Node::Tabs { panels: group.panels.clone(), active: 0 }, self.style, &*self.content); + let gap = if index > 0 { GAP } else { 0.0 }; + limits.min.x = limits.min.x.max(policy.min.x); + limits.max.x = limits.max.x.min(policy.max.x); + let (min, max) = if group.minimized { (self.style.tab_height, self.style.tab_height) } else { (policy.min.y, policy.max.y) }; + limits.min.y += min + gap; + limits.max.y += max + gap; + } + let min = limits.min.min(vec2(1_000_000.0, 1_000_000.0)); + PanelLimits { min, max: limits.max.max(min).min(vec2(1_000_000.0, 1_000_000.0)) } + } + + fn floating_window(&mut self, ctx: &Context, window: &Floating

, screen: Rect) { let Some(first) = window.panels().next() else { return }; - for (name, handle, direction) in handles(rect) { - if !crate::docking::targets::usable(handle) { - continue; + let [x, y, width, height] = window.rect; + let limits = self.window_limits(window); + let size = vec2(width, height).max(limits.min).min(limits.max); + let rect = Rect::from_min_size(pos2(x, y), size); + let id = self.id.with(("floating", first)); + if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { + ctx.move_to_top(FloatingFrame::layer(id)); + ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); + self.output.focused = self.activation.clone(); + } + let movable = window.panels().all(|panel| self.permissions(panel).movable); + let style = ChromeStyle::from_dock(self.style); + let resize_label = self.style.resize_window_label.clone(); + let response = FloatingFrame::new(id, rect) + .bounds(screen) + .limits(limits) + .resizable(movable) + .resize_label(&resize_label) + .show(ctx, &style, |ui, rect| self.window_contents(ui, window, rect, &style)); + for handle in &response.handles { + self.register_interaction(ctx, handle.id); + } + let down = ctx.input(|i| i.pointer.primary_down()); + ctx.data_mut(|data| { + let key = self.id.with("pointer-resize"); + if let Some(started) = response.resize_started { + data.insert_temp(key, started); + } else if !down && data.get_temp::(key).is_some_and(|id| response.handles.iter().any(|h| h.id == id)) { + data.remove::(key); } - let cursor = if direction.x == 0.0 { - egui::CursorIcon::ResizeVertical - } else if direction.y == 0.0 { - egui::CursorIcon::ResizeHorizontal - } else if direction.x == direction.y { - egui::CursorIcon::ResizeNwSe - } else { - egui::CursorIcon::ResizeNeSw + }); + if let Some(resized) = response.resized { + self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [resized.left(), resized.top(), resized.width(), resized.height()] }); + } + } + + /// The title bar, then the stacked groups below it. + pub(super) fn window_contents(&mut self, ui: &mut Ui, window: &Floating

, rect: Rect, style: &ChromeStyle) { + let title = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.title_height).min(rect.bottom()))); + self.title_bar(ui, window, title, rect, style); + let body = Rect::from_min_max(pos2(rect.left(), title.bottom()), rect.max); + self.floating_stack(ui, &window.groups, body, rect); + } + + /// Drag moves the whole window live, double-click minimizes or expands every group, × + /// closes every panel in it. + fn title_bar(&mut self, ui: &mut Ui, window: &Floating

, title: Rect, rect: Rect, style: &ChromeStyle) { + let Some(first) = window.panels().next() else { return }; + let movable = window.panels().all(|p| self.permissions(p).movable); + let closable = window.panels().all(|p| self.permissions(p).closable); + let (move_label, close_label) = (self.style.move_window_label.clone(), self.style.close_window_label.clone()); + let mut bar = TitleBar::new(self.id.with(("move-group", Some(first))), &move_label).movable(movable); + if closable { + bar = bar.close(&close_label); + } + let response = bar.show(ui, title, style); + self.register_interaction(ui.ctx(), response.bar.id); + if movable && response.bar.drag_started() { + let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(title.center()); + let drag = GroupDrag { + panel: first.clone(), + original: [rect.left(), rect.top(), rect.width(), rect.height()], + gesture: GroupGesture::Window, + members: window.panels().cloned().collect(), + origin, + source: rect, }; - let response = ui.interact(handle, id.with(name), Sense::drag()).on_hover_cursor(cursor); - self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.resize_window_label)); - let anchor_id = response.id.with("pointer-anchor"); - if response.drag_started() { - response.request_focus(); - if let Some(origin) = ui.input(|i| i.pointer.press_origin()) - && let Some(anchor) = AnchoredResize::new(rect, origin, direction) - { - ui.ctx().data_mut(|data| { - if let Some(previous) = data.get_temp::(self.id.with("pointer-resize")) { - data.remove::(previous.with("pointer-anchor")); - } - data.insert_temp(self.id.with("pointer-resize"), response.id); - data.insert_temp(anchor_id, anchor); - }); + ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag)); + } + if movable + && response.bar.dragged() + && let Some(drag) = ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))) + && drag.gesture == GroupGesture::Window + && let Some(pointer) = ui.ctx().pointer_interact_pos() + && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) + { + // From the press origin, so fractional pointer steps do not accumulate rounding. + let moved = clamp_float(drag.source.translate(pointer - drag.origin), ui.ctx().content_rect()); + self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); + } + if response.bar.double_clicked() { + let minimized = !window.groups.iter().all(|g| g.minimized); + for group in window.groups.iter().filter(|g| g.minimized != minimized) { + if let Some(panel) = group.active_panel() { + self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized }); } } - let cancelled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused); - let mut delta = Vec2::ZERO; - if response.has_focus() { - ui.memory_mut(|memory| { - memory.set_focus_lock_filter( - response.id, - egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }, - ) - }); - ui.input_mut(|input| { - if input.consume_key(egui::Modifiers::NONE, Key::ArrowLeft) { - delta.x -= 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowRight) { - delta.x += 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowUp) { - delta.y -= 8.0; - } - if input.consume_key(egui::Modifiers::NONE, Key::ArrowDown) { - delta.y += 8.0; - } - }); - } - let pointer_resize = response.dragged() || response.drag_stopped(); - let limits = PanelLimits { min: limits.min.max(vec2(40.0, self.style.tab_height + 20.0)).min(limits.max), ..limits }; - let next = if pointer_resize { - ui.ctx() - .data(|data| data.get_temp::(anchor_id)) - .and_then(|anchor| ui.ctx().pointer_interact_pos().and_then(|pointer| anchor.rect(pointer, screen, limits))) - } else if delta != Vec2::ZERO { - AnchoredResize::new(rect, rect.max, direction).and_then(|anchor| anchor.rect(rect.max + delta, screen, limits)) - } else { - None - }; - let permitted = response.enabled() && window.panels().all(|panel| self.permissions(panel).movable); - if permitted - && !cancelled - && let Some(resized) = next.filter(|next| *next != rect) - { - self.output - .actions - .push(Action::MoveFloating { panel: first.clone(), rect: [resized.left(), resized.top(), resized.width(), resized.height()] }); - } - if response.drag_stopped() { - response.surrender_focus(); - } - if cancelled || !permitted || !ui.input(|input| input.pointer.primary_down()) { - ui.ctx().data_mut(|data| { - data.remove::(anchor_id); - if data.get_temp::(self.id.with("pointer-resize")) == Some(response.id) { - data.remove::(self.id.with("pointer-resize")); - } - }); - } - if name == "resize" && (response.hovered() || response.dragged() || response.has_focus()) { - ui.painter().line_segment([handle.left_bottom(), handle.right_top()], Stroke::new(2.0, self.style.accent)); + } + if let Some(close) = response.close { + self.register_interaction(ui.ctx(), close.id); + if close.clicked() { + self.output.actions.push(Action::CloseWindow { panel: first.clone() }); } } } + + /// Groups top to bottom with a bar between them. Minimized groups take their strip; the + /// others share the rest by their preferred heights, equally when none is set. + pub(super) fn floating_stack(&mut self, ui: &mut Ui, groups: &[Group

], body: Rect, window: Rect) { + let strip = self.style.tab_height; + let open = groups.iter().filter(|g| !g.minimized).count(); + let fixed = groups.len().saturating_sub(open) as f32 * strip + groups.len().saturating_sub(1) as f32 * GAP; + let available = (body.height() - fixed).max(0.0); + let equal = if open > 0 { available / open as f32 } else { 0.0 }; + let wanted = |g: &Group

| g.height.filter(|h| h.is_finite() && *h > 0.0).unwrap_or(equal).max(1.0); + let total: f32 = groups.iter().filter(|g| !g.minimized).map(wanted).sum(); + let scale = if total > 0.0 { available / total } else { 0.0 }; + let mut hit = StackHit { window, groups: Vec::new(), seams: Vec::new() }; + let mut top = body.top(); + let mut rects = Vec::new(); + for (index, group) in groups.iter().enumerate() { + if index > 0 { + let gap = Rect::from_min_max(pos2(body.left(), top), pos2(body.right(), (top + GAP).min(body.bottom()))); + ui.painter().rect_filled(gap, 0.0, self.style.tab_background); + hit.seams.push((index - 1, Rect::from_center_size(gap.center(), vec2(gap.width(), SEAM_BAND)))); + top = gap.bottom(); + } + let height = if group.minimized { strip } else { wanted(group) * scale }; + let rect = Rect::from_min_max(pos2(body.left(), top), pos2(body.right(), (top + height).min(body.bottom()))); + self.group(ui, &group.panels, group.active, group.minimized, rect, GroupKind::Floating { window }); + let strip_rect = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + strip).min(rect.bottom()))); + hit.groups.push((group.panels.clone(), rect, strip_rect)); + rects.push(rect); + top = rect.bottom(); + } + // Dividers between two open groups resize both; registered after the strips, so their + // hit region wins at the shared edge. + for (index, pair) in groups.windows(2).enumerate() { + let ([upper, lower], Some(a), Some(b)) = (pair, rects.get(index), rects.get(index + 1)) else { continue }; + if upper.minimized || lower.minimized || scale <= 0.0 { + continue; + } + let (Some(upper_panel), Some(lower_panel)) = (upper.active_panel(), lower.active_panel()) else { continue }; + let divider = Rect::from_min_max(pos2(body.left(), a.bottom()), pos2(body.right(), b.top())); + let least = strip + self.style.min_pane; + let pair_size = a.height() + b.height(); + let (lo, hi) = if pair_size >= 2.0 * least { (least, pair_size - least) } else { (a.height(), a.height()) }; + let response = ResizeHandle::new( + self.id.with(("floating-divider", upper.panels.first())), + SplitAxis::Vertical, + divider, + &self.style.resize_label, + ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, + ) + .value(a.height(), lo..=hi) + .show(ui); + self.register_interaction(ui.ctx(), response.response.id); + if response.delta != 0.0 { + let next = (a.height() + response.delta).clamp(lo, hi); + self.output.actions.push(Action::ResizeGroup { panel: upper_panel.clone(), height: Some(next / scale) }); + self.output.actions.push(Action::ResizeGroup { panel: lower_panel.clone(), height: Some((pair_size - next) / scale) }); + } + } + self.frame.stacks.push(hit); + } + + /// Targets the group targets do not cover: the bands and seams of a floating stack (P3, + /// P4), then the layout's outer edge (P8). None leaves the pointer to the group targets. + /// `skip_own` looks through the window holding `members` (a window moving live). + pub(super) fn extra_proposal(&self, members: &[P], pointer: Pos2, skip_own: bool) -> Option> { + let own = |panels: &[P]| panels.iter().any(|p| members.contains(p)); + let window = self.frame.stacks.iter().rev().find(|w| w.window.contains(pointer) && !(skip_own && w.groups.iter().any(|(g, ..)| own(g)))); + if let Some(window) = window { + let in_group = window.groups.iter().any(|(_, rect, _)| rect.contains(pointer)) || window.seams.iter().any(|(_, b)| b.contains(pointer)); + if !in_group { + // The title bar occludes what lies behind the window. + let anchor = members.first()?.clone(); + return Some(DropProposal { anchor, placement: Placement::Tab { before: None }, preview: Rect::NOTHING, insertion: None, noop: true }); + } + return self.stack_proposal(window, members, pointer); + } + let (anchor, zone, preview) = self.edge_proposal(members, pointer)?; + Some(DropProposal { anchor, placement: Placement::Edge(zone), preview, insertion: None, noop: false }) + } + + fn stack_proposal(&self, hit: &StackHit

, members: &[P], pointer: Pos2) -> Option> { + let line = |y: f32| Rect::from_min_max(pos2(hit.window.left(), y - 1.0), pos2(hit.window.right(), y + 1.0)); + let same = |panels: &[P]| panels == members; + // An anchor in the group that is not itself moving. + let anchor = |panels: &[P]| panels.iter().find(|p| !members.contains(p)).cloned(); + for (upper, band) in &hit.seams { + if !band.contains(pointer) { + continue; + } + let (Some((a, rect, _)), Some((b, ..))) = (hit.groups.get(*upper), hit.groups.get(upper + 1)) else { return None }; + let line = line(rect.bottom() + GAP * 0.5); + if same(a) || same(b) { + let anchor = members.first()?.clone(); + return Some(DropProposal { anchor, placement: Placement::Group { below: true }, preview: Rect::NOTHING, insertion: None, noop: true }); + } + let (anchor, below) = match anchor(a) { + Some(panel) => (panel, true), + None => (anchor(b)?, false), + }; + return Some(DropProposal { anchor, placement: Placement::Group { below }, preview: Rect::NOTHING, insertion: Some(line), noop: false }); + } + let (panels, rect, strip) = hit.groups.iter().find(|(_, rect, _)| rect.contains(pointer))?; + if strip.contains(pointer) || same(panels) { + return None; + } + let band = rect.height() * 0.25; + let below = if pointer.y < rect.top() + band { + false + } else if pointer.y > rect.bottom() - band { + true + } else { + return None; + }; + let insertion = Some(line(if below { rect.bottom() } else { rect.top() })); + Some(DropProposal { anchor: anchor(panels)?, placement: Placement::Group { below }, preview: Rect::NOTHING, insertion, noop: false }) + } + + /// What a group drag carries: the whole window rect for the only group of a floating + /// window, so floating it again keeps the window's size; else the group's rect. + pub(super) fn drag_source(&self, owner: &super::group::TabGroup<'_, P>) -> Rect { + match owner.kind { + GroupKind::Floating { window } + if owner.panels.first().is_some_and(|p| self.layout.floating.iter().any(|w| w.groups.len() == 1 && w.contains(p))) => + { + window + } + _ => owner.rect, + } + } + + /// The action a whole-group or whole-window gesture emits for `to`. + pub(super) fn group_action(&self, drag: &GroupDrag

, to: Target

) -> Action

{ + match drag.gesture { + GroupGesture::Window => Action::MoveWindow { panel: drag.panel.clone(), to }, + GroupGesture::Group => Action::MoveGroup { panel: drag.panel.clone(), to }, + } + } + + /// Release of a title bar drag. The window already sits where it was dragged; a target + /// docks or merges every group in it, else hosts get the release in `group_drop`. + pub(super) fn drop_window(&mut self, drag: &GroupDrag

, pointer: Pos2, proposal: Option>) { + match proposal.filter(|p| !p.noop) { + Some(proposal) => { + let to = Target::At { anchor: proposal.anchor, placement: proposal.placement }; + self.output.actions.push(self.group_action(drag, to)); + } + None => self.output.group_drop = Some((drag.panel.clone(), pointer)), + } + } } diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs new file mode 100644 index 0000000000..8ad5058999 --- /dev/null +++ b/crates/ui/src/docking/render/frame.rs @@ -0,0 +1,231 @@ +//! Frame profile: Maximize Frame, the outer edge band, hidden panels and the frame menu items. + +use std::{borrow::Cow, collections::HashMap, fmt::Debug, hash::Hash}; + +use egui::{Context, Pos2, Rect, pos2, vec2}; + +use super::{GroupKind, Renderer, floating::StackHit, group::TabGroup}; +use crate::docking::{ + Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Permissions, Profile, Zone, + dock_model::{Place, node_at}, +}; + +/// What the renderer draws when it is not the layout itself, and the targets that depend on it. +pub(in crate::docking) struct FrameState

{ + /// View path to layout path of each split, when the view is not the layout. + paths: Option, Vec>>, + /// The view node whose rect is the outer edge area; none while a frame is maximized. + edge_path: Option>, + pub(super) edge: Option, + pub(super) maximized: Option

, + /// Floating stacks as drawn, back to front. + pub(super) stacks: Vec>, +} + +/// The layout as shown: a maximized frame alone, and hidden panels left out. +pub(in crate::docking) fn view<'a, P: Clone + Eq + Hash>( + layout: &'a Layout

, + maximized: Option<&P>, + hide: HidePanels<'_, P>, + content: &dyn DockContent

, +) -> (Cow<'a, Layout

>, FrameState

) { + let protected = |p: &P| content.permissions(p) == Permissions::PROTECTED; + let hidden = |p: &P| match hide { + HidePanels::None => false, + HidePanels::All => !protected(p), + HidePanels::Except(keep) => !protected(p) && !keep(p), + }; + // Only a docked panel maximizes its frame. + let maximized = maximized.and_then(|panel| match layout.place(panel)? { + Place::Node(path) => Some((panel.clone(), path.clone(), layout.root.as_ref().and_then(|root| node_at(root, &path))?.clone())), + place @ Place::Dock { .. } => { + let group = layout.group(&place)?; + Some((panel.clone(), path_of(&place), Node::Tabs { panels: group.panels.clone(), active: group.active })) + } + Place::Floating { .. } => None, + }); + let mut state = FrameState { paths: None, edge_path: None, edge: None, maximized: None, stacks: Vec::new() }; + if maximized.is_none() && matches!(hide, HidePanels::None) { + state.edge_path = Some(layout.edge_path()); + return (Cow::Borrowed(layout), state); + } + let mut paths = HashMap::new(); + let view = match maximized { + Some((panel, path, node)) => { + state.maximized = Some(panel); + Layout { root: prune(&node, path, Vec::new(), &hidden, &mut paths), floating: Vec::new() } + } + None => { + let root = layout.root.as_ref().and_then(|root| prune(root, Vec::new(), Vec::new(), &hidden, &mut paths)); + let floating = layout + .floating + .iter() + .filter_map(|window| { + let groups: Vec<_> = window.groups.iter().filter_map(|g| prune_group(g, &hidden)).collect(); + (!groups.is_empty()).then(|| Floating { groups, rect: window.rect, native: window.native }) + }) + .collect(); + Layout { root, floating } + } + }; + if state.maximized.is_none() { + state.edge_path = Some(view.edge_path()); + } + state.paths = Some(paths); + (Cow::Owned(view), state) +} + +fn path_of(place: &Place) -> Vec { + match place { + Place::Node(path) | Place::Dock { path, .. } => path.clone(), + Place::Floating { .. } => Vec::new(), + } +} + +fn visible

(node: &Node

, hidden: &dyn Fn(&P) -> bool) -> bool { + match node { + Node::Split { first, second, .. } => visible(first, hidden) || visible(second, hidden), + Node::Tabs { panels, .. } => panels.iter().any(|p| !hidden(p)), + Node::Stack { entries } => entries.iter().any(|e| !hidden(&e.panel)), + Node::Dock { columns, .. } => columns.iter().flat_map(|c| &c.groups).flat_map(|g| &g.panels).any(|p| !hidden(p)), + } +} + +/// `node` without hidden panels; a split with one visible side becomes that side. Records the +/// layout path of every split kept. +fn prune( + node: &Node

, + path: Vec, + at: Vec, + hidden: &dyn Fn(&P) -> bool, + paths: &mut HashMap, Vec>, +) -> Option> { + let child = |path: &[bool], side: bool| [path, &[side]].concat(); + match node { + Node::Split { axis, size, first, second } => match (visible(first, hidden), visible(second, hidden)) { + (true, true) => { + let first = prune(first, child(&path, false), child(&at, false), hidden, paths)?; + let second = prune(second, child(&path, true), child(&at, true), hidden, paths)?; + paths.insert(at, path); + Some(Node::Split { axis: *axis, size: *size, first: Box::new(first), second: Box::new(second) }) + } + (true, false) => prune(first, child(&path, false), at, hidden, paths), + (false, true) => prune(second, child(&path, true), at, hidden, paths), + (false, false) => None, + }, + Node::Tabs { panels, active } => { + let group = prune_group(&Group::new(panels.clone(), *active), hidden)?; + Some(Node::Tabs { panels: group.panels, active: group.active }) + } + Node::Stack { entries } => { + let entries: Vec<_> = entries.iter().filter(|e| !hidden(&e.panel)).cloned().collect(); + (!entries.is_empty()).then_some(Node::Stack { entries }) + } + Node::Dock { side, columns } => { + let columns: Vec<_> = columns + .iter() + .filter_map(|c| { + let groups: Vec<_> = c.groups.iter().filter_map(|g| prune_group(g, hidden)).collect(); + (!groups.is_empty()).then(|| Column { groups, ..c.clone() }) + }) + .collect(); + (!columns.is_empty()).then_some(Node::Dock { side: *side, columns }) + } + } +} + +/// A group without hidden panels; the selected panel stays selected when it is shown. +fn prune_group(group: &Group

, hidden: &dyn Fn(&P) -> bool) -> Option> { + let selected = group.active_panel(); + let panels: Vec

= group.panels.iter().filter(|p| !hidden(p)).cloned().collect(); + let active = selected.and_then(|s| panels.iter().position(|p| p == s)).unwrap_or(0); + (!panels.is_empty()).then(|| Group { panels, active, ..group.clone() }) +} + +impl Renderer<'_, P> { + pub(super) fn note_edge(&mut self, path: &[bool], rect: Rect) { + if self.frame.edge_path.as_deref() == Some(path) { + self.frame.edge = Some(rect); + } + } + + /// The layout path of a split drawn at view path `path`. + pub(super) fn original_path(&self, path: &[bool]) -> Vec { + self.frame.paths.as_ref().and_then(|paths| paths.get(path).cloned()).unwrap_or_else(|| path.to_vec()) + } + + /// The outer edge band under the pointer (P8): top and bottom in both profiles, left and + /// right in the frame profile. Returns a docked anchor that is not moving, the zone and + /// the preview of the new frame. + pub(super) fn edge_proposal(&self, members: &[P], pointer: Pos2) -> Option<(P, Zone, Rect)> { + let area = self.frame.edge.filter(|area| area.contains(pointer))?; + let band = self.style.edge_band.min(area.width() / 4.0).min(area.height() / 4.0); + let mut edges = vec![(pointer.y - area.top(), Zone::Top), (area.bottom() - pointer.y, Zone::Bottom)]; + if self.style.profile == Profile::Frame { + edges.extend([(pointer.x - area.left(), Zone::Left), (area.right() - pointer.x, Zone::Right)]); + } + let (distance, zone) = edges.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?; + if distance > band { + return None; + } + let anchor = self + .layout + .panels() + .into_iter() + .find(|p| !members.contains(p) && !matches!(self.layout.place(p), Some(Place::Floating { .. }) | None))? + .clone(); + let size = area.size() * 0.25; + let preview = match zone { + Zone::Left => Rect::from_min_size(area.min, vec2(size.x, area.height())), + Zone::Right => Rect::from_min_max(pos2(area.right() - size.x, area.top()), area.max), + Zone::Top => Rect::from_min_size(area.min, vec2(area.width(), size.y)), + Zone::Bottom | Zone::Center => Rect::from_min_max(pos2(area.left(), area.bottom() - size.y), area.max), + }; + Some((anchor, zone, preview)) + } + + pub(super) fn float_label(&self) -> &str { + if self.style.profile == Profile::Frame { &self.style.undock_label } else { &self.style.float_label } + } + + pub(super) fn float_group_label(&self) -> &str { + if self.style.profile == Profile::Frame { &self.style.undock_group_label } else { &self.style.float_group_label } + } + + pub(super) fn close_group_label(&self) -> &str { + if self.style.profile == Profile::Frame { &self.style.close_panel_group_label } else { &self.style.close_group_label } + } + + /// Ctrl/Cmd held when a frame-profile tab drag starts: the drop floats (S9). + pub(super) fn latch_undock(&self, ctx: &Context, kind: Option) { + let command = ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.mac_cmd); + if self.style.profile == Profile::Frame && kind == Some(GroupKind::Frame) && command { + ctx.data_mut(|d| { + if let Some(drag) = d.get_temp::>(self.id.with("drag")) { + d.insert_temp(self.id.with("drag"), crate::docking::Drag { undock: true, ..drag }); + } + }); + } + } + + /// Frame items of the menu tail: Close Other Panels in Group and Maximize Frame (frame + /// profile), and Move Panel to New Window where native windows are available. + pub(super) fn frame_items(&mut self, ui: &mut egui::Ui, owner: &TabGroup<'_, P>, panel: &P) { + if self.style.profile == Profile::Frame { + let others = owner.panels.iter().filter(|p| *p != panel).all(|p| self.permissions(p).closable); + if owner.panels.len() > 1 && others && self.menu_action(ui, &self.style.close_others_label.clone()) { + self.output.actions.push(Action::CloseOthers { panel: panel.clone() }); + } + if owner.kind == GroupKind::Frame { + let restore = self.frame.maximized.as_ref().is_some_and(|m| owner.panels.contains(m)); + let label = if restore { self.style.restore_frame_label.clone() } else { self.style.maximize_label.clone() }; + if self.menu_action(ui, &label) { + let panel = if restore { self.frame.maximized.clone().unwrap_or_else(|| panel.clone()) } else { panel.clone() }; + self.output.events.push(DockEvent::ToggleMaximize { panel }); + } + } + } + #[cfg(feature = "native-windows")] + self.new_window_item(ui, owner, panel); + } +} diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 3b80dfb3e9..b8f4ed8acb 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -26,8 +26,6 @@ pub(super) struct TabGroup<'a, P> { pub(super) rect: Rect, } -/// Width of a floating window's move grip at the left of each strip. -const GRIP_WIDTH: f32 = 12.0; /// The top band of a strip that drags the whole group. const BORDER_BAND: f32 = 4.0; @@ -65,13 +63,8 @@ impl Renderer<'_, P> { return; } let movable = panels.iter().all(|p| self.permissions(p).movable); - let mut strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom()))); + let strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom()))); ui.painter().rect_filled(strip, 0.0, self.style.tab_background); - if let GroupKind::Floating { window } = kind { - let grip = Rect::from_min_max(strip.min, pos2((strip.left() + GRIP_WIDTH).min(strip.right()), strip.bottom())); - self.window_grip(ui, panels, grip, window, movable); - strip.min.x = grip.right(); - } let floating = matches!(kind, GroupKind::Floating { .. }); let requested = self.content.group_header_width(panels, selected, floating); let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 }; @@ -149,38 +142,6 @@ impl Renderer<'_, P> { ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); } - /// The floating window's own move: the window follows the pointer, every group included. - fn window_grip(&mut self, ui: &mut Ui, panels: &[P], grip: Rect, window: Rect, movable: bool) { - let Some(first) = panels.first() else { return }; - let response = ui.interact(grip, self.id.with(("move-group", Some(first))), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); - if movable && response.drag_started() { - let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center()); - let drag = GroupDrag { - panel: first.clone(), - original: [window.left(), window.top(), window.width(), window.height()], - gesture: GroupGesture::Window, - members: panels.to_vec(), - origin, - source: window, - }; - ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag)); - } - if movable - && response.dragged() - && let Some(drag) = ui.ctx().data(|d| d.get_temp::>(self.id.with("group-drag"))) - && drag.gesture == GroupGesture::Window - && let Some(pointer) = ui.ctx().pointer_interact_pos() - && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) - { - // From the press origin, so fractional pointer steps do not accumulate rounding. - let moved = clamp_float(drag.source.translate(pointer - drag.origin), ui.ctx().content_rect()); - self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); - } - ui.painter().line_segment([grip.center() - vec2(0.0, 5.0), grip.center() + vec2(0.0, 5.0)], self.style.border); - } - /// The drag bar (`drag-bar`: click, double-click, menu and drag) or the top border band /// (`drag-border`: drag only). Both move the whole group. fn group_handle(&mut self, ui: &mut Ui, name: &'static str, hit: Rect, owner: &TabGroup<'_, P>, movable: bool) { @@ -194,7 +155,7 @@ impl Renderer<'_, P> { self.register_interaction(ui.ctx(), response.id); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label)); if movable && response.drag_started() { - self.start_group_drag(ui, owner.panels, owner.rect); + self.start_group_drag(ui, owner.panels, self.drag_source(owner)); } if !bar { return; @@ -242,7 +203,7 @@ impl Renderer<'_, P> { let closable = all(&|p| p.closable); let movable = all(&|p| p.movable); let floatable = movable && all(&|p| p.floatable); - if closable && self.menu_action(ui, &self.style.close_group_label.clone()) { + if closable && self.menu_action(ui, &self.close_group_label().to_owned()) { self.output.actions.push(Action::CloseGroup { panel: panel.clone() }); } if owner.kind != GroupKind::Frame { @@ -251,7 +212,7 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !owner.minimized }); } } - if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.style.float_group_label.clone()) { + if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.float_group_label().to_owned()) { let rect = clamp_float(owner.rect.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); self.output.actions.push(Action::MoveGroup { panel: panel.clone(), @@ -277,11 +238,12 @@ impl Renderer<'_, P> { }); response.response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); } + self.frame_items(ui, owner, panel); } /// A stock menu button with shaped text and its logical accessibility label; true when /// clicked, after closing the menu. - fn menu_action(&mut self, ui: &mut Ui, logical: &str) -> bool { + pub(super) fn menu_action(&mut self, ui: &mut Ui, logical: &str) -> bool { let text = self.content.action_label(ui, logical, &self.style.font, self.style.text); let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), logical)); @@ -353,15 +315,16 @@ impl Renderer<'_, P> { { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized }); } - if policy.movable && response.drag_started() { - begin_drag(ui.ctx(), self.id, panel.clone(), group); + if policy.movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), group) { + self.latch_undock(ui.ctx(), owner.map(|owner| owner.kind)); } response.context_menu(|ui| { self.content.panel_menu(ui, panel); if policy.movable && policy.floatable { - let text = self.content.action_label(ui, &self.style.float_label, &self.style.font, self.style.text); + let logical = self.float_label().to_owned(); + let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text); let response = ui.button(text); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.float_label)); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); if response.clicked() { let size = self.float_size(panel, group.size()); let rect = clamp_float(Rect::from_min_size(group.min + vec2(24.0, 24.0), size), ui.ctx().content_rect()); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 7539a1c0c5..fb299a0702 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -7,6 +7,11 @@ use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions}; mod floating; +mod frame; +#[cfg(feature = "native-windows")] +mod native; + +pub(in crate::docking) use frame::{FrameState, view}; pub(in crate::docking) use group::GroupKind; @@ -26,6 +31,7 @@ pub(super) struct Renderer<'a, P> { pub(super) targets: Vec>, pub(super) owned_interactions: Vec, pub(super) output: DockOutput

, + pub(super) frame: FrameState

, } impl Renderer<'_, P> { @@ -62,6 +68,7 @@ impl Renderer<'_, P> { if !crate::docking::targets::usable(rect) { return; } + self.note_edge(path, rect); match node { Node::Split { axis, size, first, second } => { let Some(wanted) = split_rect(rect, *axis, *size, self.style.gap, 0.0) else { return }; @@ -89,7 +96,7 @@ impl Renderer<'_, P> { if response.delta != 0.0 && let Some(size) = split.resized(*size, (split.first_size() + response.delta).clamp(lo, hi) - split.first_size(), 0.0) { - self.output.actions.push(Action::ResizeSplit { path: path.clone(), size }); + self.output.actions.push(Action::ResizeSplit { path: self.original_path(path), size }); } } Node::Tabs { panels, active } => self.group(ui, panels, *active, false, rect, GroupKind::Frame), @@ -266,12 +273,7 @@ pub(in crate::docking) fn node_limits

(node: &Node

, style: &DockStyle, cont } pub(super) fn clamp_float(rect: Rect, screen: Rect) -> Rect { - if !crate::docking::targets::usable(screen) { - return rect; - } - let size = rect.size().max(vec2(1.0, 1.0)).min(screen.size()); - let min = rect.min.max(screen.min).min(screen.max - size); - Rect::from_min_size(min, size) + crate::docking::chrome::clamp(rect, screen) } pub(super) fn split_bounds(available: f32, axis: SplitAxis, first: PanelLimits, second: PanelLimits) -> (f32, f32) { diff --git a/crates/ui/src/docking/render/native.rs b/crates/ui/src/docking/render/native.rs new file mode 100644 index 0000000000..05fe819667 --- /dev/null +++ b/crates/ui/src/docking/render/native.rs @@ -0,0 +1,154 @@ +//! Floating windows in their own OS windows (feature `native-windows`). A window with a native +//! rect is drawn with `show_viewport_immediate` where the backend has viewports; where egui +//! embeds viewports (wasm, tests) it stays in-window at its in-window rect. Tabs and groups do +//! not drag between OS windows. + +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Pos2, Rect, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId, vec2}; + +use super::{Renderer, clamp_float, group::TabGroup}; +use crate::docking::{Action, Drag, Floating, GroupDrag}; + +/// Smallest and largest native window, and the farthest it may sit from the desktop origin. +const MIN_SIZE: [f32; 2] = [160.0, 100.0]; +const MAX_SIZE: f32 = 16_384.0; +const MAX_POSITION: f32 = 100_000.0; + +/// A rect safe to hand to the windowing system: finite, its size and position bounded. +/// Hostile workspace files and bad monitor reports included. +pub(super) fn sanitized(rect: [f32; 4]) -> [f32; 4] { + let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback }; + let [x, y, w, h] = rect; + [ + finite(x, 0.0).clamp(-MAX_POSITION, MAX_POSITION), + finite(y, 0.0).clamp(-MAX_POSITION, MAX_POSITION), + finite(w, 420.0).clamp(MIN_SIZE[0], MAX_SIZE), + finite(h, 320.0).clamp(MIN_SIZE[1], MAX_SIZE), + ] +} + +/// The desktop rect a native viewport reports: outer position, inner size. None when the +/// backend reports nothing usable. +fn placed(outer: Option, inner: Option) -> Option<[f32; 4]> { + let (outer, inner) = (outer?, inner?); + (outer.min.is_finite() && inner.size().is_finite()).then(|| sanitized([outer.min.x, outer.min.y, inner.width(), inner.height()])) +} + +impl Renderer<'_, P> { + /// Show the native windows and return the windows to draw in-window. + pub(super) fn native_windows<'w>(&mut self, ctx: &Context, windows: Vec<&'w Floating

>) -> Vec<&'w Floating

> { + let native = !ctx.embed_viewports(); + let mut shown = Vec::new(); + let mut in_window = Vec::new(); + for window in windows { + match window.native { + Some(rect) if native && window.panels().all(|p| self.content.allow_native(p)) => { + if let Some(id) = self.native_window(ctx, window, rect) { + shown.push(id); + } + } + _ => in_window.push(window), + } + } + // Forget where windows that are no longer native were told to open. + let key = self.id.with("native-shown"); + let previous = ctx.data_mut(|d| d.remove_temp::>(key)).unwrap_or_default(); + ctx.data_mut(|d| { + for id in previous.iter().filter(|id| !shown.contains(id)) { + d.remove::<[f32; 4]>(*id); + } + d.insert_temp(key, shown); + }); + in_window + } + + /// One floating window in its own viewport. Returns the key of its spawn rect. + fn native_window(&mut self, ctx: &Context, window: &Floating

, rect: [f32; 4]) -> Option { + let first = window.panels().next()?.clone(); + let viewport = ViewportId::from_hash_of((self.id, "native", &first)); + // The window opens at its saved rect; after that the window system owns its position + // and size, which are read back below. + let spawn_key = self.id.with(("native-spawn", &first)); + let spawn = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(spawn_key, || sanitized(rect))); + let title = window.groups.first().and_then(|g| g.active_panel()).map(|p| self.label_of(p)).unwrap_or_default(); + let builder = ViewportBuilder::default() + .with_title(title) + .with_position([spawn[0], spawn[1]]) + .with_inner_size([spawn[2], spawn[3]]) + .with_min_inner_size(MIN_SIZE); + if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { + ctx.send_viewport_cmd_to(viewport, ViewportCommand::Focus); + self.output.focused = self.activation.clone(); + } + let (targets, stacks) = (self.targets.len(), self.frame.stacks.len()); + let (closed, placed) = ctx.show_viewport_immediate(viewport, builder, |ui, class| { + let rect = ui.max_rect(); + ui.painter().rect_filled(rect, 0.0, self.style.floating_background); + self.floating_stack(ui, &window.groups, rect, rect); + // An embedded fallback reads the main window's input: its close request and place + // are not this window's. + if matches!(class, ViewportClass::Immediate | ViewportClass::Deferred) { + ui.input(|i| (i.viewport().close_requested(), placed(i.viewport().outer_rect, i.viewport().inner_rect))) + } else { + (false, None) + } + }); + // Targets in another OS window are in its coordinates, and no drag crosses windows. + self.targets.truncate(targets); + self.frame.stacks.truncate(stacks); + ctx.data_mut(|d| { + if d.get_temp::>(self.id.with("drag")).is_some_and(|drag| window.contains(&drag.panel)) { + d.remove::>(self.id.with("drag")); + } + if d.get_temp::>(self.id.with("group-drag")).is_some_and(|drag| window.contains(&drag.panel)) { + d.remove::>(self.id.with("group-drag")); + } + }); + if closed { + ctx.data_mut(|d| d.remove::<[f32; 4]>(spawn_key)); + self.output.actions.push(Action::SetNative { panel: first, rect: None }); + return None; + } + if let Some(placed) = placed.filter(|placed| placed.iter().zip(rect).any(|(a, b)| (a - b).abs() > 0.5)) { + self.output.actions.push(Action::SetNative { panel: first, rect: Some(placed) }); + } + Some(spawn_key) + } + + /// Move Panel to New Window: a floating panel's window, or the panel floated on its own. + pub(super) fn new_window_item(&mut self, ui: &mut egui::Ui, owner: &TabGroup<'_, P>, panel: &P) { + let ctx = ui.ctx().clone(); + if ctx.embed_viewports() { + return; + } + let window = self.layout.floating.iter().find(|w| w.contains(panel)); + if window.is_some_and(|w| w.native.is_some()) { + return; + } + let movers: Vec

= window.map_or_else(|| vec![panel.clone()], |w| w.panels().cloned().collect()); + let allowed = |p: &P| self.content.allow_native(p) && self.permissions(p).floatable && self.permissions(p).movable; + if !movers.iter().all(allowed) { + return; + } + let in_window = match window { + Some(window) => window.rect, + None => { + let size = self.float_size(panel, owner.rect.size()); + let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), ctx.content_rect()); + [rect.left(), rect.top(), rect.width(), rect.height()] + } + }; + if !self.menu_action(ui, &self.style.new_window_label.clone()) { + return; + } + // Over the panel's place in the app window: its content's position on the desktop. + let origin = ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(Pos2::ZERO); + let [x, y, w, h] = in_window; + if window.is_none() { + self.output.actions.push(Action::Float { panel: panel.clone(), rect: in_window }); + } + let native = sanitized([origin.x + x, origin.y + y, w, h]); + self.output.actions.push(Action::SetNative { panel: panel.clone(), rect: Some(native) }); + } +} diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index de2aa4452b..45afb5dea3 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -58,22 +58,34 @@ impl Renderer<'_, P> { } let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return }; match drag.gesture { - GroupGesture::Window => self.output.group_drop = Some((drag.panel, pointer)), + GroupGesture::Window => { + let proposal = if float_only { None } else { self.group_proposal(&drag, pointer) }; + self.drop_window(&drag, pointer, proposal); + } GroupGesture::Group => self.drop_group(ctx, &drag, pointer, float_only), } } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { self.output.group_drag = Some(drag.panel.clone()); - if drag.gesture == GroupGesture::Group { - self.paint_group_drag(ctx, &drag, pointer, float_only); - } + self.paint_group_drag(ctx, &drag, pointer, float_only); } } /// The valid target under the pointer for a whole group. A target holding the group - /// itself is a no-op proposal; a target the model would reject is no target. + /// itself is a no-op proposal; a target the model would reject is no target. A window + /// moving live looks through itself and does not split frames or join a body's centre. fn group_proposal(&self, drag: &GroupDrag

, pointer: Pos2) -> Option> { - let target = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer))?; - if target.tabs.iter().any(|(p, _)| drag.members.contains(p)) { + let window = drag.gesture == GroupGesture::Window; + let valid = |proposal: DropProposal

| { + let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; + (proposal.noop || self.layout.clone().apply_with_permissions(self.group_action(drag, to), |p| self.permissions(p)).is_ok()).then_some(proposal) + }; + if let Some(proposal) = self.extra_proposal(&drag.members, pointer, window) { + return valid(proposal); + } + let own = |t: &crate::docking::DropTarget

| t.tabs.iter().any(|(p, _)| drag.members.contains(p)); + let target = + self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer) && !(window && own(t)))?; + if own(target) { return Some(DropProposal { anchor: drag.panel.clone(), placement: Placement::Tab { before: None }, @@ -83,11 +95,10 @@ impl Renderer<'_, P> { }); } let proposal = resolve_drop(&drag.panel, pointer, std::slice::from_ref(target))?; - let action = Action::MoveGroup { - panel: drag.panel.clone(), - to: Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }, - }; - self.layout.clone().apply_with_permissions(action, |p| self.permissions(p)).is_ok().then_some(proposal) + if window && matches!(proposal.placement, Placement::Split(_)) { + return None; + } + valid(proposal) } /// Release of a group drag: join or split at the target, or float at the ghost with the @@ -117,18 +128,23 @@ impl Renderer<'_, P> { } } - /// Ghost outline at the pointer and one destination preview. + /// Ghost outline at the pointer (a window moving live is its own ghost) and one + /// destination preview. fn paint_group_drag(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { let painter = self.preview_painter(ctx); - let ghost = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); - painter.rect_stroke(ghost, 0.0, Stroke::new(1.0, self.style.accent.gamma_multiply(0.6)), StrokeKind::Inside); + if drag.gesture == GroupGesture::Group { + let ghost = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); + painter.rect_stroke(ghost, 0.0, Stroke::new(1.0, self.style.accent.gamma_multiply(0.6)), StrokeKind::Inside); + } if float_only { return; } if let Some(proposal) = self.group_proposal(drag, pointer).filter(|p| !p.noop) { - let split = matches!(proposal.placement, Placement::Split(zone) if zone != Zone::Center); + let split = matches!(proposal.placement, Placement::Split(zone) | Placement::Edge(zone) if zone != Zone::Center); let fill = if split { self.style.accent.gamma_multiply(0.15) } else { Color32::TRANSPARENT }; - painter.rect(proposal.preview.shrink(1.0), 0.0, fill, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + if crate::docking::targets::usable(proposal.preview) { + painter.rect(proposal.preview.shrink(1.0), 0.0, fill, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + } if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); } @@ -160,7 +176,7 @@ impl Renderer<'_, P> { } return; } - let float_only = float_only(ctx); + let float_only = float_only(ctx) || drag.undock; let floatable = self.permissions(&drag.panel).floatable && (float_only || gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); let floating_rect = floatable.then(|| self.tab_float_rect(ctx, &drag, pointer)); @@ -170,7 +186,11 @@ impl Renderer<'_, P> { } return; } - let proposal = if float_only { None } else { resolve_drop(&drag.panel, pointer, &self.targets) }; + let proposal = if float_only { + None + } else { + self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false).or_else(|| resolve_drop(&drag.panel, pointer, &self.targets)) + }; if released { cancel_drag::

(ctx, self.id); if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !gone) { @@ -199,7 +219,7 @@ impl Renderer<'_, P> { // Reordering inside the source strip shows only the insertion line. let same_group = proposal.insertion.is_some() && self.targets.iter().any(|target| target.rect == proposal.preview && target.tabs.iter().any(|(panel, _)| panel == &drag.panel)); - if !same_group && !proposal.noop { + if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) { painter.rect( proposal.preview.shrink(1.0), 0.0, diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 901fc27312..2c11c4cd2b 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -45,6 +45,32 @@ pub struct DockStyle { /// Painted under every floating window, so it stays opaque when the panel colours are not. pub floating_background: Color32, pub floating_stroke: Stroke, + /// Dock: docks, columns and stacked groups. Frame: a split tree of tab frames, with + /// Maximize, Ctrl/Cmd-drag undock, splits on all four outer edges and frame menu labels. + pub profile: Profile, + /// Height of a floating window's title bar. + pub title_height: f32, + /// Width of the band along the layout's outer edge that splits at the root. + pub edge_band: f32, + pub move_window_label: String, + pub close_window_label: String, + /// Frame profile menu labels. + pub undock_label: String, + pub undock_group_label: String, + pub close_panel_group_label: String, + pub close_others_label: String, + pub maximize_label: String, + pub restore_frame_label: String, + /// Shown where native windows are available (feature `native-windows`). + pub new_window_label: String, +} + +/// Which arrangement a [`DockStyle`] renders and labels. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Profile { + #[default] + Dock, + Frame, } impl DockStyle { @@ -77,11 +103,23 @@ impl DockStyle { drag_bar_width: 40.0, floating_background: visuals.window_fill, floating_stroke: visuals.window_stroke, + profile: Profile::Dock, + title_height: super::chrome::TITLE_HEIGHT, + edge_band: 8.0, + move_window_label: "Move panel window".into(), + close_window_label: "Close panel window".into(), + undock_label: "Undock Panel".into(), + undock_group_label: "Undock Panel Group".into(), + close_panel_group_label: "Close Panel Group".into(), + close_others_label: "Close Other Panels in Group".into(), + maximize_label: "Maximize Frame".into(), + restore_frame_label: "Restore Frame Size".into(), + new_window_label: "Move Panel to New Window".into(), } } pub(super) fn valid(&self) -> bool { - [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size, self.drag_bar_width, self.floating_stroke.width] + [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size, self.drag_bar_width, self.floating_stroke.width, self.title_height, self.edge_band] .iter() .all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) && self.tab_height > 0.0 @@ -98,14 +136,41 @@ pub struct DockOutput

{ pub group_drag: Option

, /// Whole-group release for host-owned atomic docking policy. pub group_drop: Option<(P, Pos2)>, + /// Requests that are not layout actions. + pub events: Vec>, } impl

Default for DockOutput

{ fn default() -> Self { - Self { actions: Vec::new(), error: None, focused: None, group_drag: None, group_drop: None } + Self { actions: Vec::new(), error: None, focused: None, group_drag: None, group_drop: None, events: Vec::new() } } } +/// A request for host state outside the layout. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DockEvent

{ + /// Maximize Frame: maximize the frame holding `panel`, or restore it when it is the one + /// passed to [`DockArea::maximized`]. + ToggleMaximize { panel: P }, +} + +/// Which panels [`DockArea::hide_panels`] hides. Protected panels always stay. +pub enum HidePanels<'a, P> { + None, + All, + /// Every panel except those for which the function returns true. + Except(&'a dyn Fn(&P) -> bool), +} + +impl

Clone for HidePanels<'_, P> { + fn clone(&self) -> Self { + *self + } +} + +impl

Copy for HidePanels<'_, P> {} + /// Preferred body bounds. Tiny viewports relax minima proportionally rather than producing /// inverted rectangles. Maximums constrain a pane when its sibling can occupy the remainder. #[derive(Clone, Copy, Debug, PartialEq)] @@ -139,6 +204,8 @@ pub(super) struct Drag

{ pub(super) origin: Pos2, pub(super) source: Rect, pub(super) grab: Vec2, + /// Ctrl/Cmd held at the press of a frame-profile tab drag: the drop always floats. + pub(super) undock: bool, } /// What a group gesture moves. @@ -171,7 +238,7 @@ pub fn begin_drag(ctx: &Context, area_id: Id, return false; } let grab = (origin - source_rect.min).clamp(Vec2::ZERO, source_rect.size()); - ctx.data_mut(|d| d.insert_temp(area_id.with("drag"), Drag { panel, origin, source: source_rect, grab })); + ctx.data_mut(|d| d.insert_temp(area_id.with("drag"), Drag { panel, origin, source: source_rect, grab, undock: false })); true } @@ -339,15 +406,31 @@ impl + ?Sized> DockContent

for Overrides<'_, P, C> { /// Optional renderer for applications without an existing docking surface. Apps with custom /// chrome can instead use the model, target resolver and resize/tab primitives independently. -pub struct DockArea

{ +pub struct DockArea<'a, P = ()> { id: Id, activation: Option

, blockers: Vec, + maximized: Option

, + hide: HidePanels<'a, P>, } -impl DockArea

{ +impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { pub fn new(id: Id) -> Self { - Self { id, activation: None, blockers: Vec::new() } + Self { id, activation: None, blockers: Vec::new(), maximized: None, hide: HidePanels::None } + } + + /// Maximize Frame: the docked frame holding `panel` fills the area; other frames and + /// floating windows do not render or take input. A floating or absent panel is ignored. + pub fn maximized(mut self, panel: Option

) -> Self { + self.maximized = panel; + self + } + + /// Hide panels (Tab, Shift+Tab); their space goes to the panels that stay. Protected + /// panels always stay. The layout is unchanged. + pub fn hide_panels(mut self, hide: HidePanels<'a, P>) -> Self { + self.hide = hide; + self } /// Whether keyboard focus belongs to a rendered docking control in this layout. @@ -369,7 +452,11 @@ impl DockArea

{ || floating .panels() .next() - .is_some_and(|first| RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name)))) + .is_some_and(|first| { + RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name))) + || matches(self.id.with(("move-group", Some(first))).with("close")) + }) + || floating.groups.iter().any(|g| matches(self.id.with(("floating-divider", g.panels.first())))) { return true; } @@ -420,7 +507,8 @@ impl DockArea

{ /// Render a validated snapshot and return requested actions for the app's command handler. /// No action is applied here. Panel contents get a global stable egui ID across moves. - /// Floating groups are egui areas inside this viewport; this does not create native windows. + /// Floating windows are egui areas inside this viewport; with feature `native-windows`, a + /// window with a native rect gets its own OS window where the backend has viewports. pub fn show( self, ui: &mut Ui, @@ -476,6 +564,7 @@ impl DockArea

{ cancel_drag::

(ui.ctx(), self.id); return DockOutput { error: Some(DockError::InvalidGeometry), ..Default::default() }; } + let (view, frame) = super::render::view(layout, self.maximized.as_ref(), self.hide, &*content); let mut renderer = Renderer { id: self.id, style, @@ -487,12 +576,13 @@ impl DockArea

{ targets: Vec::new(), owned_interactions: Vec::new(), output: DockOutput::default(), + frame, }; - if let Some(root) = &layout.root { + if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); ui.allocate_rect(rect, Sense::hover()); } - renderer.floating(ui.ctx()); + renderer.floating(ui.ctx(), &view.floating); renderer.finish_group_drag(ui.ctx()); renderer.finish_drag(ui.ctx()); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index cd5adafc8d..618ca2680d 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -904,7 +904,7 @@ fn custom_chrome_shaped_labels_and_programmatic_raise_are_available() { assert!(out.actions.is_empty()); assert!(content.headers >= 3 && content.bodies >= 3); assert!(content.labels.iter().any(|s| s == "Logical 5")); - let at = pos2(130.0, 82.0); + let at = pos2(130.0, 96.0); custom_frame( &ctx, &layout, @@ -1249,9 +1249,7 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() { h.output().shapes.iter().any(|shape| paints(&shape.shape, &format!("Action visual: {logical}"))), "custom action must paint: {logical}" ); - // This sample also has a floating-group grip labeled Move to group. - let expected = if logical == "Move to group" { 2 } else { 1 }; - assert_eq!(h.query_all_by_label(logical).count(), expected, "popup action must retain its own logical accessibility: {logical}"); + assert_eq!(h.query_all_by_label(logical).count(), 1, "popup action must retain its own logical accessibility: {logical}"); assert_eq!( h.query_all_by_label(&format!("Action visual: {logical}")).count(), 0, @@ -1368,7 +1366,7 @@ fn collapsed_floating_height_cap_does_not_disable_keyboard_width_resizing() { } ctx.memory_mut(|memory| memory.request_focus(id)); frame(vec![Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); - assert_eq!(layout.floating[0].rect, [80.0, 70.0, 308.0, 26.0]); + assert_eq!(layout.floating[0].rect, [80.0, 70.0, 308.0, 40.0]); } #[test] From e235c4c1832d53d87e9ce0ec50664a355c955405 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:21:35 +0000 Subject: [PATCH 18/94] docking: rustfmt and clippy for the floating and frame changes --- crates/ui/src/docking/chrome.rs | 25 ++++++++++++++----- crates/ui/src/docking/dock_model.rs | 3 +-- crates/ui/src/docking/floating_tests.rs | 12 ++++----- crates/ui/src/docking/render/floating.rs | 31 +++++++++++++++++------- crates/ui/src/docking/render/frame.rs | 12 ++++----- crates/ui/src/docking/render/group.rs | 6 ++--- crates/ui/src/docking/render/preview.rs | 3 ++- crates/ui/src/docking/surface.rs | 27 +++++++++++++-------- 8 files changed, 75 insertions(+), 44 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index 2e2b14be68..c8fe2ddd37 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -66,7 +66,10 @@ fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 5] { ), ( "resize-bottom-left", - Rect::from_min_max(pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), pos2((rect.left() + 12.0).min(rect.right()), rect.bottom())), + Rect::from_min_max( + pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), + pos2((rect.left() + 12.0).min(rect.right()), rect.bottom()), + ), vec2(-1.0, 1.0), ), ] @@ -133,7 +136,10 @@ impl<'a> FloatingFrame<'a> { pub fn show(self, ctx: &Context, style: &ChromeStyle, add_contents: impl FnOnce(&mut Ui, Rect) -> R) -> FrameResponse { let bounds = self.bounds.unwrap_or_else(|| ctx.content_rect()); let rect = clamp(self.rect, bounds); - let area = egui::Area::new(self.id).fade_in(false).order(Order::Middle).fixed_pos(rect.min) + let area = egui::Area::new(self.id) + .fade_in(false) + .order(Order::Middle) + .fixed_pos(rect.min) .default_size(rect.size()) .movable(false) .constrain_to(bounds); @@ -144,8 +150,7 @@ impl<'a> FloatingFrame<'a> { ui.painter().rect_filled(rect, 0.0, style.background); let inner = add_contents(ui, rect); ui.painter().rect_stroke(rect, 0.0, style.stroke, StrokeKind::Outside); - let (resized, resize_started, handles) = - if self.resizable { self.handles(ui, rect, bounds, style) } else { (None, None, Vec::new()) }; + let (resized, resize_started, handles) = if self.resizable { self.handles(ui, rect, bounds, style) } else { (None, None, Vec::new()) }; FrameResponse { inner, rect, layer: Self::layer(self.id), resized, resize_started, handles } }); shown.inner @@ -185,10 +190,18 @@ impl<'a> FloatingFrame<'a> { let mut delta = Vec2::ZERO; if response.has_focus() { ui.memory_mut(|memory| { - memory.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + memory.set_focus_lock_filter( + response.id, + egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }, + ) }); ui.input_mut(|input| { - for (key, step) in [(Key::ArrowLeft, vec2(-8.0, 0.0)), (Key::ArrowRight, vec2(8.0, 0.0)), (Key::ArrowUp, vec2(0.0, -8.0)), (Key::ArrowDown, vec2(0.0, 8.0))] { + for (key, step) in [ + (Key::ArrowLeft, vec2(-8.0, 0.0)), + (Key::ArrowRight, vec2(8.0, 0.0)), + (Key::ArrowUp, vec2(0.0, -8.0)), + (Key::ArrowDown, vec2(0.0, 8.0)), + ] { if input.consume_key(egui::Modifiers::NONE, key) { delta += step; } diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index 05b3409fce..7049543f81 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -526,8 +526,7 @@ impl Layout

{ let new = Node::Tabs { panels, active }; let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; - let (first, second, size) = - if matches!(zone, Zone::Top | Zone::Left) { (new, old, 0.25) } else { (old, new, 0.75) }; + let (first, second, size) = if matches!(zone, Zone::Top | Zone::Left) { (new, old, 0.25) } else { (old, new, 0.75) }; *node = Node::Split { axis, size: SplitSize::Ratio(size), first: Box::new(first), second: Box::new(second) }; Ok(()) } diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 8d8dc7581d..b278223375 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -248,11 +248,7 @@ fn floating_stack_seams_and_bands_insert_groups() { let tab = d.tab(8).unwrap().center(); let seam = pos2(420.0, 237.0); let out = d.drag(tab, seam); - assert!( - out.actions.contains(&Action::Move { panel: 8, anchor: 5, placement: Placement::Group { below: true } }), - "{:?}", - out.actions - ); + assert!(out.actions.contains(&Action::Move { panel: 8, anchor: 5, placement: Placement::Group { below: true } }), "{:?}", out.actions); assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![8], vec![6, 7]]); // The divider between two open groups resizes both. @@ -496,7 +492,8 @@ fn chrome_frame_and_title_bar_work_without_a_dock_area() { let mut time = 0.0; let mut frame = |events: Vec| { time += 1.0 / 60.0; - let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), events, time: Some(time), ..Default::default() }; + let input = + RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), events, time: Some(time), ..Default::default() }; let mut result = None; done(ctx.run_ui(input, |ui| { let style = ChromeStyle::from_ui(ui); @@ -511,7 +508,8 @@ fn chrome_frame_and_title_bar_work_without_a_dock_area() { }; frame(vec![]); frame(vec![]); - let click = |frame: &mut dyn FnMut(Vec) -> ((bool, Vec2, bool, bool), Option), at| { + type Shown = ((bool, Vec2, bool, bool), Option); + let click = |frame: &mut dyn FnMut(Vec) -> Shown, at| { frame(vec![Event::PointerMoved(at), button(at, true)]); frame(vec![button(at, false)]) }; diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 383a68b4b9..f40da2c8ca 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -74,12 +74,11 @@ impl Renderer<'_, P> { let movable = window.panels().all(|panel| self.permissions(panel).movable); let style = ChromeStyle::from_dock(self.style); let resize_label = self.style.resize_window_label.clone(); - let response = FloatingFrame::new(id, rect) - .bounds(screen) - .limits(limits) - .resizable(movable) - .resize_label(&resize_label) - .show(ctx, &style, |ui, rect| self.window_contents(ui, window, rect, &style)); + let response = FloatingFrame::new(id, rect).bounds(screen).limits(limits).resizable(movable).resize_label(&resize_label).show( + ctx, + &style, + |ui, rect| self.window_contents(ui, window, rect, &style), + ); for handle in &response.handles { self.register_interaction(ctx, handle.id); } @@ -93,7 +92,9 @@ impl Renderer<'_, P> { } }); if let Some(resized) = response.resized { - self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [resized.left(), resized.top(), resized.width(), resized.height()] }); + self.output + .actions + .push(Action::MoveFloating { panel: first.clone(), rect: [resized.left(), resized.top(), resized.width(), resized.height()] }); } } @@ -228,7 +229,13 @@ impl Renderer<'_, P> { if !in_group { // The title bar occludes what lies behind the window. let anchor = members.first()?.clone(); - return Some(DropProposal { anchor, placement: Placement::Tab { before: None }, preview: Rect::NOTHING, insertion: None, noop: true }); + return Some(DropProposal { + anchor, + placement: Placement::Tab { before: None }, + preview: Rect::NOTHING, + insertion: None, + noop: true, + }); } return self.stack_proposal(window, members, pointer); } @@ -249,7 +256,13 @@ impl Renderer<'_, P> { let line = line(rect.bottom() + GAP * 0.5); if same(a) || same(b) { let anchor = members.first()?.clone(); - return Some(DropProposal { anchor, placement: Placement::Group { below: true }, preview: Rect::NOTHING, insertion: None, noop: true }); + return Some(DropProposal { + anchor, + placement: Placement::Group { below: true }, + preview: Rect::NOTHING, + insertion: None, + noop: true, + }); } let (anchor, below) = match anchor(a) { Some(panel) => (panel, true), diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index 8ad5058999..d39235bcc2 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -184,16 +184,16 @@ impl Renderer<'_, P> { Some((anchor, zone, preview)) } - pub(super) fn float_label(&self) -> &str { - if self.style.profile == Profile::Frame { &self.style.undock_label } else { &self.style.float_label } + pub(super) fn float_label(&self) -> String { + if self.style.profile == Profile::Frame { self.style.undock_label.clone() } else { self.style.float_label.clone() } } - pub(super) fn float_group_label(&self) -> &str { - if self.style.profile == Profile::Frame { &self.style.undock_group_label } else { &self.style.float_group_label } + pub(super) fn float_group_label(&self) -> String { + if self.style.profile == Profile::Frame { self.style.undock_group_label.clone() } else { self.style.float_group_label.clone() } } - pub(super) fn close_group_label(&self) -> &str { - if self.style.profile == Profile::Frame { &self.style.close_panel_group_label } else { &self.style.close_group_label } + pub(super) fn close_group_label(&self) -> String { + if self.style.profile == Profile::Frame { self.style.close_panel_group_label.clone() } else { self.style.close_group_label.clone() } } /// Ctrl/Cmd held when a frame-profile tab drag starts: the drop floats (S9). diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index b8f4ed8acb..fbdf35aea0 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -203,7 +203,7 @@ impl Renderer<'_, P> { let closable = all(&|p| p.closable); let movable = all(&|p| p.movable); let floatable = movable && all(&|p| p.floatable); - if closable && self.menu_action(ui, &self.close_group_label().to_owned()) { + if closable && self.menu_action(ui, &self.close_group_label()) { self.output.actions.push(Action::CloseGroup { panel: panel.clone() }); } if owner.kind != GroupKind::Frame { @@ -212,7 +212,7 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !owner.minimized }); } } - if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.float_group_label().to_owned()) { + if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.float_group_label()) { let rect = clamp_float(owner.rect.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); self.output.actions.push(Action::MoveGroup { panel: panel.clone(), @@ -321,7 +321,7 @@ impl Renderer<'_, P> { response.context_menu(|ui| { self.content.panel_menu(ui, panel); if policy.movable && policy.floatable { - let logical = self.float_label().to_owned(); + let logical = self.float_label(); let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text); let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 45afb5dea3..a253a8bf0e 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -77,7 +77,8 @@ impl Renderer<'_, P> { let window = drag.gesture == GroupGesture::Window; let valid = |proposal: DropProposal

| { let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; - (proposal.noop || self.layout.clone().apply_with_permissions(self.group_action(drag, to), |p| self.permissions(p)).is_ok()).then_some(proposal) + (proposal.noop || self.layout.clone().apply_with_permissions(self.group_action(drag, to), |p| self.permissions(p)).is_ok()) + .then_some(proposal) }; if let Some(proposal) = self.extra_proposal(&drag.members, pointer, window) { return valid(proposal); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 2c11c4cd2b..b51bf258ae 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -119,9 +119,19 @@ impl DockStyle { } pub(super) fn valid(&self) -> bool { - [self.tab_height, self.gap, self.min_pane, self.border.width, self.font.size, self.drag_bar_width, self.floating_stroke.width, self.title_height, self.edge_band] - .iter() - .all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) + [ + self.tab_height, + self.gap, + self.min_pane, + self.border.width, + self.font.size, + self.drag_bar_width, + self.floating_stroke.width, + self.title_height, + self.edge_band, + ] + .iter() + .all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) && self.tab_height > 0.0 && self.font.size > 0.0 } @@ -449,13 +459,10 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { }; for floating in &layout.floating { if floating.groups.iter().any(|g| group(&g.panels)) - || floating - .panels() - .next() - .is_some_and(|first| { - RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name))) - || matches(self.id.with(("move-group", Some(first))).with("close")) - }) + || floating.panels().next().is_some_and(|first| { + RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name))) + || matches(self.id.with(("move-group", Some(first))).with("close")) + }) || floating.groups.iter().any(|g| matches(self.id.with(("floating-divider", g.panels.first())))) { return true; From a842d330e0d9ef14bf860a7c0f1328f0d64e7dd8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:22:03 +0000 Subject: [PATCH 19/94] docking: test that hidden panels map split resizes to layout paths --- crates/ui/src/docking/floating_tests.rs | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index b278223375..fa48632458 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -530,3 +530,32 @@ fn chrome_frame_and_title_bar_work_without_a_dock_area() { let (_, resized) = frame(vec![Event::PointerMoved(edge + vec2(50.0, 0.0))]); assert_eq!(resized, Some(Rect::from_min_size(rect.min, vec2(350.0, 200.0)))); } + +#[test] +fn hidden_panels_leave_their_split_and_resizing_names_the_layout_path() { + let layout = Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(200.0), + first: Box::new(tabs(&[9], 0)), + second: Box::new(Node::Split { + axis: SplitAxis::Vertical, + size: SplitSize::Ratio(0.5), + first: Box::new(tabs(&[1], 0)), + second: Box::new(tabs(&[2], 0)), + }), + }), + floating: Vec::new(), + }; + let mut d = Driver::new(layout, Profile::Frame); + d.hide = Hide::Keep; + d.content.keep = vec![1, 2]; + d.step(vec![]); + d.step(vec![]); + assert_eq!(d.tab(1).map(|r| r.left()), Some(0.0), "the hidden frame's space goes to the others"); + let divider = d.response(Id::new(AREA).with(("split", &Vec::::new()))).unwrap().center(); + let out = d.hold(divider, divider + vec2(0.0, 60.0)); + assert!(out.actions.iter().any(|a| matches!(a, Action::ResizeSplit { path, .. } if path == &vec![true])), "{:?}", out.actions); + let Some(Node::Split { size: SplitSize::FixedFirst(200.0), second, .. }) = &d.layout.root else { panic!("{:?}", d.layout) }; + assert!(matches!(**second, Node::Split { size, .. } if size != SplitSize::Ratio(0.5))); +} From 315fde3ed8d45fecb8a088895415835b13fe707d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:27:17 +0000 Subject: [PATCH 20/94] docking: test window title drags onto dock seams and new-dock bands --- crates/ui/src/docking/floating_tests.rs | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index fa48632458..2f7cfb58a8 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -229,6 +229,32 @@ fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_gro assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![6, 7]]); } +#[test] +fn title_bar_drag_onto_dock_targets_docks_the_window() { + // Released on the seam between two docked groups: the window's group stacks between them. + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(8).center(); + let seam = pos2(120.0, d.tab(4).unwrap().top()); + let out = d.drag(title, seam); + assert!( + out.actions.contains(&Action::MoveWindow { panel: 8, to: Target::At { anchor: 2, placement: Placement::Group { below: true } } }), + "{:?}", + out.actions + ); + assert!(window_of(&d.layout, 8).is_none()); + let Some(Node::Split { first, .. }) = &d.layout.root else { panic!("{:?}", d.layout.root) }; + let Node::Dock { columns, .. } = first.as_ref() else { panic!("{first:?}") }; + let stacked: Vec<_> = columns[0].groups.iter().map(|g| g.panels.clone()).collect(); + assert_eq!(stacked, vec![vec![2, 3], vec![8], vec![4]]); + + // Released on the new-dock band along the right edge: the window becomes an end dock. + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(5).center(); + let out = d.drag(title, pos2(796.0, 300.0)); + assert!(out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::NewDock { side: Side::End } }), "{:?}", out.actions); + assert!(window_of(&d.layout, 5).is_none() && window_of(&d.layout, 6).is_none()); +} + #[test] fn floating_stack_seams_and_bands_insert_groups() { // A group dragged by its bar to another window's top band stacks above that group. From 87e6562a5e8967abd1781f3c5ae653ef1833bf6f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:36:18 +0000 Subject: [PATCH 21/94] ui: chrome live_move for title-bar moves Moves a rect with a title-bar drag from the rect and press position kept at drag start, so the window follows the pointer without drift. Escape or window focus loss ends the move and returns the start rect. --- crates/ui/src/docking/chrome.rs | 44 ++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index c8fe2ddd37..4c8985a928 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -3,7 +3,7 @@ //! these; other hosts (task panes) use them with their own ids and actions. Nothing here changes //! a layout: the caller turns the responses into its own commands. -use egui::{Color32, Context, FontId, Id, Key, LayerId, Order, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetText, pos2, vec2}; +use egui::{Color32, Context, FontId, Id, Key, LayerId, Order, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetText, pos2, vec2}; use super::{DockStyle, PanelLimits, resize::AnchoredResize}; @@ -345,3 +345,45 @@ impl<'a> TitleBar<'a> { TitleResponse { bar, menu, close } } } + +/// One step of a title-bar move, from [`live_move`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum MoveStep { + /// The rect follows the pointer, inside the bounds. + Moving(Rect), + /// Escape or window focus loss ended the move: the rect it started from. + Cancelled(Rect), + /// Released over `pointer`, with the rect where it was dropped. + Dropped { rect: Rect, pointer: Pos2 }, +} + +/// Move `rect` with a drag on `bar` (usually [`TitleResponse::bar`]). The rect and the press +/// position at drag start are kept in egui memory under the bar's id, so the window follows the +/// pointer without drift. Escape or window focus loss ends the move and returns the start rect; +/// the rest of that drag is ignored. `None` when the bar is not being moved. +pub fn live_move(ctx: &Context, bar: &Response, rect: Rect, bounds: Rect) -> Option { + let key = bar.id.with("live-move"); + if bar.drag_started() + && let Some(origin) = ctx.input(|input| input.pointer.press_origin()) + { + ctx.data_mut(|data| data.insert_temp(key, (rect, origin))); + } + let (start, origin) = ctx.data(|data| data.get_temp::<(Rect, Pos2)>(key))?; + let forget = || ctx.data_mut(|data| data.remove::<(Rect, Pos2)>(key)); + if ctx.input(|input| input.key_pressed(Key::Escape) || !input.focused) { + forget(); + return Some(MoveStep::Cancelled(start)); + } + let pointer = ctx.pointer_latest_pos().unwrap_or(origin); + let moved = clamp(start.translate(pointer - origin), bounds); + if bar.drag_stopped() { + forget(); + return Some(MoveStep::Dropped { rect: moved, pointer }); + } + if bar.dragged() { + return Some(MoveStep::Moving(moved)); + } + // The drag ended without a release on this bar (the bar was not shown). + forget(); + None +} From 484717644c4271b291f2ad60fea32c2a6b20ff60 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:36:18 +0000 Subject: [PATCH 22/94] panes: task-pane host for document apps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PaneHost draws the open panes as egui side and bottom panels before the app's CentralPanel, or as floating frames, each with a title, a ▾ menu (app items, Move to Start/End, Float, Close), × and a resize edge. Edges are logical (Start/End) with an RTL flag. Columns shows every pane side by side; OneSlot shows one closable pane per edge. The app owns open state and pane state: the host returns Close, Place, Resize, FloatRect and Focus requests, the focused pane, and cycles focus with F6. Drag-out-to-float and edge snap follow wordcraft#2584. --- crates/ui/src/lib.rs | 1 + crates/ui/src/panes/mod.rs | 732 +++++++++++++++++++++++++++++++++++ crates/ui/src/panes/tests.rs | 308 +++++++++++++++ 3 files changed, 1041 insertions(+) create mode 100644 crates/ui/src/panes/mod.rs create mode 100644 crates/ui/src/panes/tests.rs diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index fcb608299b..f54d1bbc1b 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -9,6 +9,7 @@ pub mod buttons; pub mod docking; pub mod icons; pub mod layout; +pub mod panes; pub mod printing; pub mod tabs; pub mod theme; diff --git a/crates/ui/src/panes/mod.rs b/crates/ui/src/panes/mod.rs new file mode 100644 index 0000000000..c90fb9f431 --- /dev/null +++ b/crates/ui/src/panes/mod.rs @@ -0,0 +1,732 @@ +//! Task panes for document apps: side and bottom panes around the app's own central document. +//! +//! [`PaneHost`] draws each open pane as an egui side or bottom panel, or as a floating frame, with +//! a title bar (title, ▾ menu, ×) and a resizable inner edge. Call it before the app's +//! `CentralPanel`; the document never becomes a panel. The app owns which panes are open and +//! where they are: the host takes the open list and each pane's [`PaneState`] every frame and +//! returns [`PaneRequest`]s for the app to run through its own commands. Docking chrome +//! ([`crate::docking::chrome`]) draws the floating frames and title bars. + +use std::fmt::Debug; +use std::hash::Hash; +use std::ops::RangeInclusive; + +use egui::{ + Color32, Context, Frame, Id, Key, LayerId, Margin, Modifiers, Order, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, pos2, + vec2, +}; + +use crate::docking::PanelLimits; +use crate::docking::chrome::{self, ChromeStyle, FloatingFrame, MoveStep, TitleBar}; +use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +/// A title dragged this far out of a docked pane floats it; a pane dropped this close to the +/// host's left or right edge docks there. +pub const DOCK_SNAP: f32 = 32.0; +/// Height of a pane's title bar. +pub const TITLE_BAR_HEIGHT: f32 = 24.0; +/// Size of a pane floated for the first time. +pub const FLOAT_DEFAULT: Vec2 = vec2(270.0, 480.0); +const FLOAT_MIN_HEIGHT: f32 = 160.0; +/// Where the title bar is held when a dragged-out pane floats at the pointer. +const FLOAT_GRAB: Vec2 = vec2(40.0, 12.0); + +/// A logical edge of the host area. `Start` is left in left-to-right interfaces and right in +/// right-to-left ones. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Edge { + Start, + End, + Bottom, +} + +/// Where a pane is shown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Place { + Docked(Edge), + Floating, +} + +/// The persisted layout of one pane. The app stores it where it keeps its preferences. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct PaneState { + pub place: Place, + /// Width of a side pane or height of a bottom pane, in points. `None`: the pane's default. + pub size: Option, + /// `[x, y, width, height]` of the floating pane, also kept while it is docked. + pub float_rect: Option<[f32; 4]>, +} + +impl PaneState { + pub fn docked(edge: Edge, size: f32) -> Self { + Self { place: Place::Docked(edge), size: Some(size), float_rect: None } + } + + fn apply

(&mut self, request: &PaneRequest

) { + match request { + PaneRequest::Place(_, place) => self.place = *place, + PaneRequest::Resize(_, size) => self.size = Some(*size), + PaneRequest::FloatRect(_, rect) => self.float_rect = Some(*rect), + PaneRequest::Close(_) | PaneRequest::Focus(_) => {} + } + } +} + +/// How docked panes share an edge. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SidePolicy { + /// Every pane on an edge is shown, side by side in `open` order, the first outermost. + #[default] + Columns, + /// One pane per edge: the last of the edge's closable panes in `open`. Panes that are not + /// closable (context panes the app shows from its own state) are shown beside the slot. + OneSlot, +} + +/// A change the user asked for. The host applies none of them to the app's state. +#[derive(Clone, Debug, PartialEq)] +pub enum PaneRequest

{ + Close(P), + Place(P, Place), + Resize(P, f32), + FloatRect(P, [f32; 4]), + /// The pane took focus from a click, keyboard focus or F6. + Focus(P), +} + +impl

PaneRequest

{ + pub fn pane(&self) -> &P { + match self { + Self::Close(p) | Self::Place(p, _) | Self::Resize(p, _) | Self::FloatRect(p, _) | Self::Focus(p) => p, + } + } +} + +/// What [`PaneHost::show`] returns. +#[derive(Clone, Debug, PartialEq)] +pub struct PaneOutput

{ + /// In the order they happened; apply them in order. Resize and FloatRect arrive every + /// frame a gesture changes the size or rect. + pub requests: Vec>, + /// The pane holding keyboard focus or last clicked, if it is still shown. + pub focused: Option

, + /// F6 moved focus past the last pane (or Shift+F6 past the first): focus the document. + pub to_document: bool, +} + +/// The app's side of a pane: its contents and defaults. +pub trait PaneContent

{ + /// May follow the selection (Format Shape, Format Picture). + fn title(&self, pane: &P) -> String; + fn body(&mut self, ui: &mut Ui, pane: &P); + /// Used when the state callback returns `None` and the host has none in memory. + fn default_state(&self, pane: &P) -> PaneState; + /// Width (or bottom height) limits of the docked pane. + fn size_range(&self, _pane: &P) -> RangeInclusive { + 200.0..=520.0 + } + /// `false`: no Move or Float items and no title drag. + fn movable(&self, _pane: &P) -> bool { + true + } + /// `false`: no × and no Close item (context panes such as PivotTable Fields). + fn closable(&self, _pane: &P) -> bool { + true + } + /// App items, shown above the Move, Float and Close items of the ▾ menu. + fn menu(&mut self, _ui: &mut Ui, _pane: &P) {} +} + +/// Labels of the chrome; translate them in the app. +#[derive(Clone, Debug)] +pub struct PaneLabels { + pub menu: String, + pub move_start: String, + pub move_end: String, + pub move_bottom: String, + pub float: String, + pub close: String, + /// Accessibility label of the title bar. + pub move_pane: String, + /// Accessibility label of the resize edges. + pub resize: String, +} + +impl Default for PaneLabels { + fn default() -> Self { + Self { + menu: "Pane options".into(), + move_start: "Move to Start".into(), + move_end: "Move to End".into(), + move_bottom: "Move to Bottom".into(), + float: "Float".into(), + close: "Close".into(), + move_pane: "Move pane".into(), + resize: "Resize pane".into(), + } + } +} + +/// Draws the open panes. Build it every frame. +pub struct PaneHost { + id: Id, + rtl: bool, + policy: SidePolicy, + max_fraction: f32, + f6: bool, + labels: PaneLabels, + frame: Option, + margin: Margin, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Side { + Left, + Right, + Bottom, +} + +#[derive(Clone, Copy, Debug, Default)] +struct Memory { + active: Option, + last_focus: Option, + /// F6 pressed or [`focus_next`] called: `true` cycles backwards. + cycle: Option, + drag_out: Option, +} + +#[derive(Clone, Copy, Debug)] +struct DragOut { + pane: Id, + cancelled: bool, +} + +struct Shown

{ + pane: P, + id: Id, + state: PaneState, +} + +/// Where a pane was drawn, for focus tracking. +struct Region { + pane: Id, + rect: Rect, + floating: Option, +} + +fn memory_id(id: Id) -> Id { + id.with("panes-memory") +} + +/// Move focus to the next pane (the previous one with `reverse`) at the host's next frame. For +/// apps that route F6 through their own commands; see [`PaneHost::f6`]. +pub fn focus_next(ctx: &Context, id: impl Into, reverse: bool) { + let key = memory_id(id.into()); + ctx.data_mut(|data| data.get_temp_mut_or_default::(key).cycle = Some(reverse)); + ctx.request_repaint(); +} + +impl PaneHost { + pub fn new(id: impl Into) -> Self { + Self { + id: id.into(), + rtl: false, + policy: SidePolicy::Columns, + max_fraction: 1.0, + f6: true, + labels: PaneLabels::default(), + frame: None, + margin: Margin::same(8), + } + } + + /// Right-to-left interface: `Start` is the right edge. + pub fn rtl(mut self, rtl: bool) -> Self { + self.rtl = rtl; + self + } + + pub fn policy(mut self, policy: SidePolicy) -> Self { + self.policy = policy; + self + } + + /// Largest share of the host's width (height for bottom panes) one docked pane may take. + pub fn max_fraction(mut self, fraction: f32) -> Self { + self.max_fraction = if fraction.is_finite() { fraction.clamp(0.0, 1.0) } else { 1.0 }; + self + } + + /// Whether the host takes F6 and Shift+F6 to cycle focus through the panes and back to the + /// document. Default on. Apps that bind F6 themselves call [`focus_next`]. + pub fn f6(mut self, f6: bool) -> Self { + self.f6 = f6; + self + } + + pub fn labels(mut self, labels: PaneLabels) -> Self { + self.labels = labels; + self + } + + /// Frame of the docked panels. Default: the panel fill and a hairline border, no margin. + pub fn frame(mut self, frame: Frame) -> Self { + self.frame = Some(frame); + self + } + + /// Margin around each pane's body. Default 8. + pub fn body_margin(mut self, margin: Margin) -> Self { + self.margin = margin; + self + } + + fn pane_id(&self, pane: &P) -> Id { + self.id.with(("pane", pane)) + } + + fn side(&self, edge: Edge) -> Side { + match (edge, self.rtl) { + (Edge::Bottom, _) => Side::Bottom, + (Edge::Start, false) | (Edge::End, true) => Side::Left, + (Edge::Start, true) | (Edge::End, false) => Side::Right, + } + } + + /// The edge a pane dropped at `pointer` docks against, if it is within [`DOCK_SNAP`] of the + /// host's left or right edge. + fn snap(&self, pointer: Pos2, bounds: Rect) -> Option { + let left = if self.rtl { Edge::End } else { Edge::Start }; + let right = if self.rtl { Edge::Start } else { Edge::End }; + if pointer.x <= bounds.left() + DOCK_SNAP { + Some(left) + } else if pointer.x >= bounds.right() - DOCK_SNAP { + Some(right) + } else { + None + } + } + + /// Draw the panes in `open` with the state `states` returns for each (`None`: the state the + /// host kept from earlier requests, else the pane's default). Call between the app's top + /// and bottom bars and its `CentralPanel`. + pub fn show>( + self, + ui: &mut Ui, + open: &[P], + states: impl Fn(&P) -> Option, + content: &mut C, + ) -> PaneOutput

{ + let ctx = ui.ctx().clone(); + let bounds = ui.available_rect_before_wrap(); + let style = ChromeStyle::from_ui(ui); + let key = memory_id(self.id); + let mut memory = ctx.data(|data| data.get_temp::(key)).unwrap_or_default(); + let mut requests = Vec::new(); + let mut to_document = false; + + if self.f6 { + ui.input_mut(|input| { + if input.consume_key(Modifiers::SHIFT, Key::F6) { + memory.cycle = Some(true); + } else if input.consume_key(Modifiers::NONE, Key::F6) { + memory.cycle = Some(false); + } + }); + } + + let mut shown: Vec> = Vec::new(); + for pane in open { + let id = self.pane_id(pane); + if shown.iter().any(|s| s.id == id) { + continue; + } + let state = + states(pane).or_else(|| ctx.data(|data| data.get_temp::(id.with("state")))).unwrap_or_else(|| content.default_state(pane)); + shown.push(Shown { pane: pane.clone(), id, state }); + } + if self.policy == SidePolicy::OneSlot { + let mut taken = Vec::new(); + for index in (0..shown.len()).rev() { + if let Place::Docked(edge) = shown[index].state.place + && content.closable(&shown[index].pane) + { + if taken.contains(&edge) { + shown.remove(index); + } else { + taken.push(edge); + } + } + } + } + + let previous = memory.active.filter(|active| shown.iter().any(|s| s.id == *active)); + memory.active = previous; + let mut focus_target = None; + if let Some(reverse) = memory.cycle.take() { + let current = memory.active.and_then(|active| shown.iter().position(|s| s.id == active)); + let next = match (current, reverse) { + (None, false) => shown.first(), + (None, true) => shown.last(), + (Some(i), false) => shown.get(i + 1), + (Some(i), true) => i.checked_sub(1).and_then(|i| shown.get(i)), + }; + focus_target = next.map(|s| s.id); + memory.active = focus_target; + if focus_target.is_none() { + to_document = true; + ctx.memory_mut(|m| { + if let Some(focused) = m.focused() { + m.surrender_focus(focused); + } + }); + } + } + + let preview = ctx.layer_painter(LayerId::new(Order::Tooltip, self.id.with("drop-preview"))); + let mut regions = Vec::new(); + for edge in [Edge::Start, Edge::End, Edge::Bottom] { + for s in shown.iter().filter(|s| s.state.place == Place::Docked(edge)) { + let rect = self.docked(ui, s, edge, content, &style, focus_target == Some(s.id), bounds, &mut memory, &preview, &mut requests); + regions.push(Region { pane: s.id, rect, floating: None }); + } + } + for s in shown.iter().filter(|s| s.state.place == Place::Floating) { + let (rect, layer) = self.floating(&ctx, s, content, &style, focus_target == Some(s.id), bounds, &mut requests); + regions.push(Region { pane: s.id, rect, floating: Some(layer) }); + } + + if focus_target.is_none() && !to_document { + self.track_focus(&ctx, ui.layer_id(), ®ions, &mut memory); + } + memory.last_focus = ctx.memory(|m| m.focused()); + if memory.active != previous + && let Some(s) = memory.active.and_then(|active| shown.iter().find(|s| s.id == active)) + { + requests.push(PaneRequest::Focus(s.pane.clone())); + } + + for s in &shown { + let mut state = s.state; + let mut changed = false; + for request in requests.iter().filter(|r| self.pane_id(r.pane()) == s.id) { + state.apply(request); + changed = true; + } + if changed { + ctx.data_mut(|data| data.insert_temp(s.id.with("state"), state)); + } + } + let focused = memory.active.and_then(|active| shown.iter().find(|s| s.id == active)).map(|s| s.pane.clone()); + ctx.data_mut(|data| data.insert_temp(key, memory)); + PaneOutput { requests, focused, to_document } + } + + /// The pane under a primary press, or the pane holding a newly focused widget, becomes active. + /// Presses and focus outside every pane (the document) clear it; presses on other layers + /// (menus, the app's own windows) leave it. + fn track_focus(&self, ctx: &Context, layer: LayerId, regions: &[Region], memory: &mut Memory) { + let find = |at_layer: Option, pos: Pos2| -> Option> { + if let Some(region) = regions.iter().find(|r| r.floating.is_some() && r.floating == at_layer) { + return Some(Some(region.pane)); + } + if at_layer.is_none() || at_layer == Some(layer) { + return Some(regions.iter().find(|r| r.floating.is_none() && r.rect.contains(pos)).map(|r| r.pane)); + } + None + }; + if ctx.input(|input| input.pointer.primary_pressed()) + && let Some(pos) = ctx.input(|input| input.pointer.press_origin()) + && let Some(active) = find(ctx.layer_id_at(pos), pos) + { + memory.active = active; + } + let focused = ctx.memory(|m| m.focused()); + if focused != memory.last_focus + && let Some(response) = focused.and_then(|id| ctx.read_response(id)) + && let Some(active) = find(Some(response.layer_id), response.rect.center()) + { + memory.active = active; + } + } + + fn limits>(&self, content: &C, pane: &P, extent: f32) -> (f32, f32) { + let range = content.size_range(pane); + let min = if range.start().is_finite() { range.start().max(0.0) } else { 0.0 }; + let max = if range.end().is_finite() { range.end().max(min) } else { min.max(extent) }; + (min, max.min(self.max_fraction * extent).max(min)) + } + + #[allow(clippy::too_many_arguments)] + fn docked>( + &self, + ui: &mut Ui, + s: &Shown

, + edge: Edge, + content: &mut C, + style: &ChromeStyle, + focus: bool, + bounds: Rect, + memory: &mut Memory, + preview: &egui::Painter, + requests: &mut Vec>, + ) -> Rect { + let side = self.side(edge); + let extent = if side == Side::Bottom { bounds.height() } else { bounds.width() }; + let (min, max) = self.limits(content, &s.pane, extent); + let default = content.default_state(&s.pane).size; + let size = s.state.size.filter(|v| v.is_finite()).or(default.filter(|v| v.is_finite())).unwrap_or(min).clamp(min, max); + let panel_id = s.id.with("panel"); + let panel = match side { + Side::Left => egui::Panel::left(panel_id), + Side::Right => egui::Panel::right(panel_id), + Side::Bottom => egui::Panel::bottom(panel_id), + }; + let frame = self.frame.unwrap_or_else(|| Frame::NONE.fill(ui.visuals().panel_fill).stroke(ui.visuals().widgets.noninteractive.bg_stroke)); + let shown = panel.exact_size(size).resizable(false).frame(frame).show(ui, |ui| { + let top = ui.max_rect(); + let title = Rect::from_min_size(top.min, vec2(top.width(), TITLE_BAR_HEIGHT)); + ui.allocate_rect(title, Sense::hover()); + let bar = self.chrome(ui, title, s, content, style, focus, bounds, requests); + Frame::NONE.inner_margin(self.margin).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + content.body(ui, &s.pane); + }); + bar + }); + let rect = shown.response.rect; + let bar = shown.inner; + + let (axis, strip) = match side { + Side::Left => (SplitAxis::Horizontal, Rect::from_x_y_ranges(rect.right() - 2.0..=rect.right() + 2.0, rect.y_range())), + Side::Right => (SplitAxis::Horizontal, Rect::from_x_y_ranges(rect.left() - 2.0..=rect.left() + 2.0, rect.y_range())), + Side::Bottom => (SplitAxis::Vertical, Rect::from_x_y_ranges(rect.x_range(), rect.top() - 2.0..=rect.top() + 2.0)), + }; + let handle_style = ResizeHandleStyle { hovered: style.accent.gamma_multiply(0.5), dragged: style.accent, focused: style.accent }; + let resize = ResizeHandle::new(s.id.with("resize"), axis, strip, &self.labels.resize, handle_style).show(ui); + let next = if resize.response.dragged() { + resize.response.interact_pointer_pos().map(|p| match side { + Side::Left => p.x - rect.left(), + Side::Right => rect.right() - p.x, + Side::Bottom => rect.bottom() - p.y, + }) + } else if resize.delta != 0.0 { + // Arrow keys move the edge: right grows a left pane, left grows a right pane. + Some(if side == Side::Left { size + resize.delta } else { size - resize.delta }) + } else { + None + }; + if let Some(next) = next.filter(|v| v.is_finite()).map(|v| v.clamp(min, max).round()) + && next != size + { + requests.push(PaneRequest::Resize(s.pane.clone(), next)); + } + + if content.movable(&s.pane) { + self.drag_out(ui.ctx(), &bar, s, edge, rect, bounds, memory, preview, style, requests); + } + rect + } + + /// A docked pane's title dragged beyond [`DOCK_SNAP`] of the pane: dropped near the host's + /// left or right edge it docks there, elsewhere it floats under the pointer. + #[allow(clippy::too_many_arguments)] + fn drag_out( + &self, + ctx: &Context, + bar: &Response, + s: &Shown

, + edge: Edge, + rect: Rect, + bounds: Rect, + memory: &mut Memory, + preview: &egui::Painter, + style: &ChromeStyle, + requests: &mut Vec>, + ) { + if bar.drag_started() { + memory.drag_out = Some(DragOut { pane: s.id, cancelled: false }); + } + let Some(mut drag) = memory.drag_out.filter(|d| d.pane == s.id) else { return }; + if ctx.input(|input| input.key_pressed(Key::Escape) || !input.focused) { + drag.cancelled = true; + } + let near = rect.expand(DOCK_SNAP); + let Some(pointer) = ctx.pointer_latest_pos() else { return }; + let outside = if edge == Edge::Bottom { !near.y_range().contains(pointer.y) } else { !near.x_range().contains(pointer.x) }; + let size = s.state.float_rect.map_or(FLOAT_DEFAULT, |r| vec2(r[2], r[3])); + let float = float_rect(Some(rect_array(Rect::from_min_size(pointer - FLOAT_GRAB, size))), bounds, vec2(0.0, FLOAT_MIN_HEIGHT)); + let target = self.snap(pointer, bounds); + if bar.drag_stopped() { + memory.drag_out = None; + if drag.cancelled || !outside { + return; + } + match target { + Some(target) if target != edge => requests.push(PaneRequest::Place(s.pane.clone(), Place::Docked(target))), + Some(_) => {} + None => { + requests.push(PaneRequest::Place(s.pane.clone(), Place::Floating)); + requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(float))); + } + } + return; + } + if !bar.dragged() { + memory.drag_out = None; + return; + } + memory.drag_out = Some(drag); + if drag.cancelled || !outside { + return; + } + let shape = match target.map(|t| self.side(t)) { + Some(Side::Left) => Rect::from_x_y_ranges(bounds.left()..=bounds.left() + rect.width(), bounds.y_range()), + Some(_) => Rect::from_x_y_ranges(bounds.right() - rect.width()..=bounds.right(), bounds.y_range()), + None => float, + }; + paint_preview(preview, shape, style.accent); + } + + #[allow(clippy::too_many_arguments)] + fn floating>( + &self, + ctx: &Context, + s: &Shown

, + content: &mut C, + style: &ChromeStyle, + focus: bool, + bounds: Rect, + requests: &mut Vec>, + ) -> (Rect, LayerId) { + let (min_width, _) = self.limits(content, &s.pane, bounds.width()); + let min = vec2(min_width, FLOAT_MIN_HEIGHT); + let rect = float_rect(s.state.float_rect, bounds, min); + let limits = PanelLimits { min, max: bounds.size().max(min) }; + let shown = FloatingFrame::new(s.id.with("float"), rect).bounds(bounds).limits(limits).resize_label(&self.labels.resize).show( + ctx, + style, + |ui, rect| { + let title = Rect::from_min_size(rect.min, vec2(rect.width(), TITLE_BAR_HEIGHT)); + let bar = self.chrome(ui, title, s, content, style, focus, bounds, requests); + let body = Rect::from_min_max(pos2(rect.left(), title.bottom()), rect.max) - self.margin; + if body.is_positive() { + ui.scope_builder(UiBuilder::new().max_rect(body), |ui| { + ui.set_clip_rect(body.intersect(ui.clip_rect())); + content.body(ui, &s.pane); + }); + } + bar + }, + ); + if let Some(resized) = shown.resized { + requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(resized))); + } + if content.movable(&s.pane) { + match chrome::live_move(ctx, &shown.inner, shown.rect, bounds) { + Some(MoveStep::Moving(next) | MoveStep::Cancelled(next)) if next != shown.rect => { + requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(next))); + } + Some(MoveStep::Dropped { rect, pointer }) => { + if let Some(edge) = self.snap(pointer, bounds) { + requests.push(PaneRequest::Place(s.pane.clone(), Place::Docked(edge))); + } else if rect != shown.rect { + requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(rect))); + } + } + _ => {} + } + } + (shown.rect, shown.layer) + } + + /// Title, ▾ menu and ×. Returns the bar, which senses the title drag. + #[allow(clippy::too_many_arguments)] + fn chrome>( + &self, + ui: &mut Ui, + rect: Rect, + s: &Shown

, + content: &mut C, + style: &ChromeStyle, + focus: bool, + bounds: Rect, + requests: &mut Vec>, + ) -> Response { + let movable = content.movable(&s.pane); + let closable = content.closable(&s.pane); + let mut bar = + TitleBar::new(s.id.with("title"), &self.labels.move_pane).title(content.title(&s.pane)).menu(&self.labels.menu).movable(movable); + if closable { + bar = bar.close(&self.labels.close); + } + let title = bar.show(ui, rect, style); + if focus { + title.bar.request_focus(); + } + if title.close.as_ref().is_some_and(Response::clicked) { + requests.push(PaneRequest::Close(s.pane.clone())); + } + if let Some(menu) = &title.menu { + egui::Popup::menu(menu).show(|ui| { + let top = ui.cursor().top(); + content.menu(ui, &s.pane); + if ui.cursor().top() > top && (movable || closable) { + ui.separator(); + } + if movable { + let mut places = vec![(Place::Docked(Edge::Start), &self.labels.move_start), (Place::Docked(Edge::End), &self.labels.move_end)]; + if content.default_state(&s.pane).place == Place::Docked(Edge::Bottom) { + places.push((Place::Docked(Edge::Bottom), &self.labels.move_bottom)); + } + places.push((Place::Floating, &self.labels.float)); + for (place, label) in places { + if ui.selectable_label(s.state.place == place, label.as_str()).clicked() && s.state.place != place { + requests.push(PaneRequest::Place(s.pane.clone(), place)); + if place == Place::Floating { + let rect = float_rect(s.state.float_rect, bounds, vec2(0.0, FLOAT_MIN_HEIGHT)); + requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(rect))); + } + } + } + } + if closable && ui.button(self.labels.close.as_str()).clicked() { + requests.push(PaneRequest::Close(s.pane.clone())); + } + }); + } + title.bar + } +} + +fn paint_preview(painter: &egui::Painter, rect: Rect, accent: Color32) { + painter.rect(rect.shrink(1.0), 0.0, accent.gamma_multiply(0.15), Stroke::new(2.0, accent), StrokeKind::Inside); +} + +fn rect_array(rect: Rect) -> [f32; 4] { + [rect.min.x, rect.min.y, rect.width(), rect.height()] +} + +/// The floating rect for `saved` (`[x, y, width, height]`), at least `min` and at most the +/// bounds in size, inside `bounds`. Without a saved rect: [`FLOAT_DEFAULT`] right of the middle. +/// Non-finite or negative values fall back to the defaults, so the result is always finite. +pub fn float_rect(saved: Option<[f32; 4]>, bounds: Rect, min: Vec2) -> Rect { + let bounds = if bounds.is_finite() && bounds.is_positive() { bounds } else { Rect::from_min_size(Pos2::ZERO, FLOAT_DEFAULT) }; + let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback }; + let size = saved.map_or(FLOAT_DEFAULT, |r| vec2(finite(r[2], FLOAT_DEFAULT.x), finite(r[3], FLOAT_DEFAULT.y))); + let size = size.max(min.max(Vec2::splat(1.0))).min(bounds.size()); + let free = (bounds.size() - size).max(Vec2::ZERO); + let default = (bounds.min + vec2(free.x * 0.75, free.y * 0.3)).round(); + let pos = saved.map_or(default, |r| pos2(finite(r[0], default.x), finite(r[1], default.y))); + let pos = pos.max(bounds.min).min((bounds.max - size).max(bounds.min)); + Rect::from_min_size(pos, size) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/panes/tests.rs b/crates/ui/src/panes/tests.rs new file mode 100644 index 0000000000..837760be03 --- /dev/null +++ b/crates/ui/src/panes/tests.rs @@ -0,0 +1,308 @@ +//! Behaviour tests for the pane host, driven by egui pointer and key events in an 800 × 600 +//! window. The harness's root ui has an 8 pt margin, so the host spans x 8..792, y 8..592. + +use std::collections::HashMap; + +use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2, Rect, Ui, pos2, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; + +use super::*; + +const L: f32 = 8.0; +const R: f32 = 792.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Pane { + Nav, + Styles, + Comments, + /// A context pane, like PivotTable Fields: not closable, not movable. + Pivot, +} + +struct Content; + +impl PaneContent for Content { + fn title(&self, pane: &Pane) -> String { + format!("{pane:?}") + } + fn body(&mut self, ui: &mut Ui, pane: &Pane) { + ui.label(format!("{pane:?} body")); + } + fn default_state(&self, pane: &Pane) -> PaneState { + let edge = if matches!(pane, Pane::Comments | Pane::Pivot) { Edge::End } else { Edge::Start }; + PaneState::docked(edge, 250.0) + } + fn movable(&self, pane: &Pane) -> bool { + *pane != Pane::Pivot + } + fn closable(&self, pane: &Pane) -> bool { + *pane != Pane::Pivot + } +} + +/// The app side: open list, persisted states and every request it received. +struct App { + open: Vec, + states: HashMap, + log: Vec>, + focused: Option, + to_document: usize, + rtl: bool, + policy: SidePolicy, +} + +impl App { + fn new(open: &[Pane]) -> Self { + Self { open: open.to_vec(), states: HashMap::new(), log: Vec::new(), focused: None, to_document: 0, rtl: false, policy: SidePolicy::Columns } + } + + fn frame(&mut self, ui: &mut Ui) { + let states = self.states.clone(); + let out = PaneHost::new("panes").rtl(self.rtl).policy(self.policy).show(ui, &self.open, |p| states.get(p).copied(), &mut Content); + egui::CentralPanel::default().show(ui, |ui| ui.label("Document")); + for request in &out.requests { + match request { + PaneRequest::Close(p) => self.open.retain(|o| o != p), + PaneRequest::Focus(_) => {} + other => { + let pane = *other.pane(); + let state = self.states.entry(pane).or_insert_with(|| Content.default_state(&pane)); + state.apply(other); + } + } + } + self.log.extend(out.requests); + self.focused = out.focused; + self.to_document += usize::from(out.to_document); + } + + fn place(&self, pane: Pane) -> Place { + self.states.get(&pane).map_or_else(|| Content.default_state(&pane).place, |s| s.place) + } +} + +fn harness(app: App) -> Harness<'static, App> { + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(|ui, app: &mut App| app.frame(ui), app); + h.input_mut().focused = true; + h.run_steps(2); + h +} + +fn pane_id(pane: Pane) -> Id { + Id::new("panes").with(("pane", &pane)) +} + +fn rect(h: &Harness<'_, App>, id: Id) -> Option { + h.ctx.read_response(id).map(|r| r.rect) +} + +fn title(h: &Harness<'_, App>, pane: Pane) -> Rect { + rect(h, pane_id(pane).with("title")).unwrap() +} + +/// The x of a side pane's inner edge. +fn edge(h: &Harness<'_, App>, pane: Pane) -> f32 { + rect(h, pane_id(pane).with("resize")).unwrap().center().x +} + +fn button(pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } +} + +fn send(h: &mut Harness<'_, App>, events: Vec) { + h.input_mut().events.extend(events); + h.run_steps(1); +} + +fn click(h: &mut Harness<'_, App>, at: Pos2) { + send(h, vec![Event::PointerMoved(at), button(at, true)]); + send(h, vec![button(at, false)]); + h.run_steps(1); +} + +fn hold(h: &mut Harness<'_, App>, from: Pos2, to: Pos2) { + send(h, vec![Event::PointerMoved(from), button(from, true)]); + send(h, vec![Event::PointerMoved(from + vec2(8.0, 6.0))]); + send(h, vec![Event::PointerMoved(to)]); +} + +fn drag(h: &mut Harness<'_, App>, from: Pos2, to: Pos2) { + hold(h, from, to); + send(h, vec![button(to, false)]); + h.run_steps(2); +} + +fn key(h: &mut Harness<'_, App>, key: Key, modifiers: Modifiers) { + send(h, vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + h.run_steps(1); +} + +/// The requests that change a pane's state or open list. +fn changes(app: &App) -> Vec> { + app.log.iter().filter(|r| !matches!(r, PaneRequest::Focus(_))).cloned().collect() +} + +fn last_resize(app: &App, pane: Pane) -> Option { + app.log.iter().rev().find_map(|r| match r { + PaneRequest::Resize(p, size) if *p == pane => Some(*size), + _ => None, + }) +} + +#[test] +fn columns_sit_side_by_side_resize_and_move_to_end() { + let mut h = harness(App::new(&[Pane::Nav, Pane::Styles])); + assert_eq!(edge(&h, Pane::Nav), L + 250.0); + assert_eq!(edge(&h, Pane::Styles), L + 500.0); + assert!(title(&h, Pane::Nav).left() < L + 2.0); + + drag(&mut h, pos2(L + 250.0, 300.0), pos2(L + 300.0, 300.0)); + assert_eq!(last_resize(h.state(), Pane::Nav), Some(300.0)); + assert_eq!(edge(&h, Pane::Nav), L + 300.0); + assert_eq!(edge(&h, Pane::Styles), L + 550.0, "the second column follows"); + + let at = rect(&h, pane_id(Pane::Nav).with("title").with("menu")).unwrap().center(); + click(&mut h, at); + for label in ["Move to Start", "Move to End", "Float", "Close"] { + assert!(h.query_all_by_label(label).count() >= 1, "{label}"); + } + h.get_by_label("Move to End").click(); + h.run_steps(3); + assert!(h.state().log.contains(&PaneRequest::Place(Pane::Nav, Place::Docked(Edge::End)))); + assert_eq!(edge(&h, Pane::Nav), R - 300.0, "a 300 pt pane at the right edge"); + assert_eq!(edge(&h, Pane::Styles), L + 250.0); +} + +#[test] +fn title_dragged_out_floats_and_a_drop_near_an_edge_docks() { + // Drag-out-to-float and the 32 pt edge snap follow wordcraft#2584. + let mut h = harness(App::new(&[Pane::Styles])); + let from = title(&h, Pane::Styles).center(); + // Within DOCK_SNAP of the pane: nothing happens. + drag(&mut h, from, pos2(L + 270.0, 300.0)); + assert!(changes(h.state()).is_empty(), "{:?}", h.state().log); + + drag(&mut h, from, pos2(400.0, 300.0)); + assert_eq!( + changes(h.state()), + vec![PaneRequest::Place(Pane::Styles, Place::Floating), PaneRequest::FloatRect(Pane::Styles, [360.0, 112.0, 270.0, 480.0])], + "floats under the pointer, clamped to the window" + ); + assert_eq!(title(&h, Pane::Styles).min, pos2(360.0, 112.0)); + + // Dropped within 32 pt of the right edge: docked at End. + h.state_mut().log.clear(); + let from = title(&h, Pane::Styles).center(); + drag(&mut h, from, pos2(780.0, 300.0)); + assert_eq!(h.state().log.last(), Some(&PaneRequest::Place(Pane::Styles, Place::Docked(Edge::End)))); + assert_eq!(edge(&h, Pane::Styles), R - 250.0); + // The floating rect's size is kept for the next float. + assert_eq!(h.state().states[&Pane::Styles].float_rect.map(|r| [r[2], r[3]]), Some([270.0, 480.0])); +} + +#[test] +fn escape_and_focus_loss_restore_a_floating_pane_during_a_move() { + let mut app = App::new(&[Pane::Styles]); + let start = [300.0, 100.0, 270.0, 400.0]; + app.states.insert(Pane::Styles, PaneState { place: Place::Floating, size: None, float_rect: Some(start) }); + let mut h = harness(app); + let from = title(&h, Pane::Styles).center(); + let float_rect = |h: &Harness<'_, App>| h.state().states[&Pane::Styles].float_rect; + + hold(&mut h, from, from + vec2(40.0, 30.0)); + assert_eq!(float_rect(&h), Some([340.0, 130.0, 270.0, 400.0]), "follows the pointer"); + key(&mut h, Key::Escape, Modifiers::NONE); + assert_eq!(float_rect(&h), Some(start)); + send(&mut h, vec![Event::PointerMoved(pos2(790.0, 300.0))]); + send(&mut h, vec![button(pos2(790.0, 300.0), false)]); + h.run_steps(1); + assert_eq!(h.state().place(Pane::Styles), Place::Floating, "the rest of the drag is ignored"); + assert_eq!(float_rect(&h), Some(start)); + + hold(&mut h, from, from + vec2(-60.0, 20.0)); + assert_eq!(float_rect(&h), Some([240.0, 120.0, 270.0, 400.0])); + h.input_mut().focused = false; + h.run_steps(1); + h.input_mut().focused = true; + send(&mut h, vec![button(from + vec2(-60.0, 20.0), false)]); + assert_eq!(float_rect(&h), Some(start)); +} + +#[test] +fn f6_cycles_through_the_panes_and_back_to_the_document() { + let mut h = harness(App::new(&[Pane::Nav, Pane::Comments])); + let focused_widget = |h: &Harness<'_, App>| h.ctx.memory(|m| m.focused()); + key(&mut h, Key::F6, Modifiers::NONE); + assert_eq!(h.state().focused, Some(Pane::Nav)); + assert_eq!(focused_widget(&h), Some(pane_id(Pane::Nav).with("title"))); + key(&mut h, Key::F6, Modifiers::NONE); + assert_eq!(h.state().focused, Some(Pane::Comments)); + key(&mut h, Key::F6, Modifiers::NONE); + assert_eq!((h.state().focused, h.state().to_document), (None, 1)); + assert_eq!(focused_widget(&h), None); + key(&mut h, Key::F6, Modifiers::SHIFT); + assert_eq!(h.state().focused, Some(Pane::Comments), "Shift+F6 from the document goes to the last pane"); + let focus: Vec<_> = h.state().log.iter().filter(|r| matches!(r, PaneRequest::Focus(_))).cloned().collect(); + assert_eq!(focus, vec![PaneRequest::Focus(Pane::Nav), PaneRequest::Focus(Pane::Comments), PaneRequest::Focus(Pane::Comments)]); + + // A click in the document clears it; a click in a pane sets it. + click(&mut h, pos2(400.0, 300.0)); + assert_eq!(h.state().focused, None); + click(&mut h, pos2(100.0, 300.0)); + assert_eq!(h.state().focused, Some(Pane::Nav)); +} + +#[test] +fn one_slot_shows_the_last_pane_per_edge_beside_context_panes() { + let mut app = App::new(&[Pane::Pivot, Pane::Comments, Pane::Styles]); + app.policy = SidePolicy::OneSlot; + app.states.insert(Pane::Styles, PaneState::docked(Edge::End, 300.0)); + let mut h = harness(app); + assert!(rect(&h, pane_id(Pane::Comments).with("title")).is_none()); + assert_eq!(edge(&h, Pane::Pivot), R - 250.0, "the context pane stays, outermost"); + assert_eq!(edge(&h, Pane::Styles), R - 550.0); + assert!(rect(&h, pane_id(Pane::Pivot).with("title").with("close")).is_none()); + + let at = rect(&h, pane_id(Pane::Styles).with("title").with("close")).unwrap().center(); + click(&mut h, at); + h.run_steps(1); + assert_eq!(h.state().open, vec![Pane::Pivot, Pane::Comments]); + assert_eq!(edge(&h, Pane::Comments), R - 500.0, "the slot shows the remaining pane"); +} + +#[test] +fn rtl_mirrors_sides_and_edge_snaps() { + let mut app = App::new(&[Pane::Nav, Pane::Comments]); + app.rtl = true; + let mut h = harness(app); + assert_eq!(edge(&h, Pane::Nav), R - 250.0, "Start is the right edge"); + assert_eq!(edge(&h, Pane::Comments), L + 250.0); + + let from = title(&h, Pane::Nav).center(); + drag(&mut h, from, pos2(10.0, 300.0)); + assert_eq!(changes(h.state()), vec![PaneRequest::Place(Pane::Nav, Place::Docked(Edge::End))], "the left edge is End"); + // Both on End, outermost first in open order. + assert_eq!(edge(&h, Pane::Nav), L + 250.0); + assert_eq!(edge(&h, Pane::Comments), L + 500.0); +} + +#[test] +fn float_rect_is_finite_and_inside_the_bounds() { + let bounds = Rect::from_min_size(pos2(0.0, 100.0), vec2(800.0, 500.0)); + let min = vec2(200.0, 160.0); + assert_eq!(float_rect(Some([300.0, 150.0, 280.0, 300.0]), bounds, min), Rect::from_min_size(pos2(300.0, 150.0), vec2(280.0, 300.0))); + for junk in [[f32::NAN, 0.0, 1.0, -3.0], [5000.0, -5000.0, 1.0e9, 1.0e9], [f32::NEG_INFINITY, f32::INFINITY, f32::NAN, 0.0]] { + let r = float_rect(Some(junk), bounds, min); + assert!(r.is_finite() && bounds.contains_rect(r) && r.width() >= 200.0, "{junk:?} -> {r:?}"); + } + assert_eq!(float_rect(None, bounds, min).size(), FLOAT_DEFAULT.min(bounds.size())); +} + +#[cfg(feature = "serde")] +#[test] +fn pane_state_round_trips_through_json() { + let state = PaneState { place: Place::Docked(Edge::End), size: Some(280.0), float_rect: Some([1.0, 2.0, 270.0, 480.0]) }; + let json = serde_json::to_string(&state).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), state); +} From a09aa016e3ab3e5f6ff7b35e7835cbc5e0bfe651 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:36:18 +0000 Subject: [PATCH 23/94] panes: docs with adoption steps for WordCraft, DeckCraft, GridCraft --- docs/ui-panes.md | 106 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 docs/ui-panes.md diff --git a/docs/ui-panes.md b/docs/ui-panes.md new file mode 100644 index 0000000000..b88a7d17bf --- /dev/null +++ b/docs/ui-panes.md @@ -0,0 +1,106 @@ +# Task panes + +`craft_ui::panes` draws task panes around an app's own document: Navigation, Styles, Comments, +Format Shape and the like. Each pane is an egui side or bottom panel, or a floating frame. The +document stays the app's `CentralPanel`. + +## Panes or docking + +| Use | When | +|---|---| +| `panes` | Office-style apps (WordCraft, DeckCraft, GridCraft). A few panes at the sides of a document the app draws itself; the app's commands own which panes are open. | +| `docking` | Creative apps whose whole window is panels: tab groups, splits, stacked groups, workspaces, a protected canvas panel. See [ui-docking.md](ui-docking.md). | +| plain egui panels | Fixed view parts: slide thumbnails, notes, formula bar, sheet tabs, status bar. | +| `egui::Window` | Free tool windows that never dock (Read Aloud, Power Query). | + +`panes` needs no docking types; it uses only the docking chrome (`FloatingFrame`, `TitleBar`, +`live_move`). + +## API + +```rust +use craft_ui::panes::{Edge, PaneContent, PaneHost, PaneRequest, PaneState, Place, SidePolicy}; + +impl PaneContent for MyPanes<'_> { + fn title(&self, pane: &Pane) -> String { tr(pane.title()) } + fn body(&mut self, ui: &mut egui::Ui, pane: &Pane) { /* the pane's contents */ } + fn default_state(&self, pane: &Pane) -> PaneState { PaneState::docked(Edge::End, 250.0) } + // Optional: size_range (200..=520), movable, closable, menu (app items in the ▾ menu). +} + +// Every frame, after the top and bottom bars and before the CentralPanel: +let out = PaneHost::new("task-panes") + .rtl(ui_is_rtl) + .policy(SidePolicy::Columns) + .show(ui, &open_panes, |pane| prefs.pane_state(pane), &mut MyPanes { app }); +for request in out.requests { + match request { + PaneRequest::Close(pane) => app.run(pane.close_command()), + PaneRequest::Place(pane, place) => prefs.set_place(pane, place), + PaneRequest::Resize(pane, size) => prefs.set_size(pane, size), + PaneRequest::FloatRect(pane, rect) => prefs.set_float_rect(pane, rect), + PaneRequest::Focus(_) => {} + } +} +egui::CentralPanel::default().show(ui, |ui| document(ui)); +``` + +| Piece | Behaviour | +|---|---| +| `Edge::{Start, End, Bottom}` | Logical edges. `Start` is left, or right with `.rtl(true)`. | +| `SidePolicy::Columns` | Every docked pane shows; panes on one edge sit side by side in `open` order, the first outermost. | +| `SidePolicy::OneSlot` | One closable pane per edge: the last one in `open`. Non-closable context panes (PivotTable Fields) show beside the slot. | +| `.max_fraction(f)` | One docked pane takes at most `f` of the host's width (height for bottom panes). | +| Chrome | Title, ▾ menu (app items, Move to Start, Move to End, Move to Bottom for bottom panes, Float, Close), ×, a resize edge with pointer and arrow keys. | +| Drag out | A docked pane's title dragged more than `DOCK_SNAP` (32 pt) out of the pane floats it under the pointer when dropped; dropped within 32 pt of the host's left or right edge it docks there. | +| Floating | `FloatingFrame` with its resize handles; the title bar moves it. Escape or window focus loss during a move puts it back. A drop within 32 pt of the left or right edge docks it. Rects are clamped to the host area. | +| Focus | `out.focused` is the pane holding keyboard focus or last clicked; a click or focus in the document clears it. F6 and Shift+F6 cycle through the shown panes and then report `out.to_document`: give focus to the document. `.f6(false)` leaves F6 to the app, which calls `panes::focus_next(ctx, id, reverse)` instead. | + +State: + +- The host never stores which panes are open and never writes files. +- `states` returns the app's saved `PaneState` (place, size, float rect; serde with the `serde` + feature). Return `None` to let the host keep the state in egui memory for the session, as + egui panels keep widths today. +- Apply `Resize` and `FloatRect` as they come: they arrive every frame of a gesture, and an + Escape sends the start rect back. +- `panes::float_rect` brings a saved rect back inside the window, whatever the file says. + +## Adoption + +### WordCraft (`Columns`) + +- Add a `Pane` enum for the nine panes and implement `PaneContent` by calling the existing + bodies; drop their `header()` calls, since the host draws the title and ×. +- Build `open` each frame from the `ViewState` flags, in today's order: SmartArt Text Pane (only + while SmartArt is selected), Navigation and Clipboard at `Start`; Styles, Style Inspector, + Accessibility, Alt Text, Restrict Editing and Comments at `End`. Default widths as today. +- `Close(p)` runs the pane's existing command (`view.navigationPane {value: false}`, …). Command + ids and `nav_pane` in `ui.json` stay as they are. +- Styles takes #2584's behaviour through the host: map `StylesPaneDock::{Left, Right, Floating}` + to `Place` (`Left` is `Docked(Start)` in left-to-right interfaces), run `view.stylesPaneDock` + on `Place`, keep the float rect in UI prefs. #2584's own drag, snap and `float_rect` code goes. +- Other panes return `None` from `states`; their widths stay session-only, as now. +- Pane title bars are focusable. Check that Tab in the canvas still stays in the document, so + panes stay off its keyboard focus. Use `.f6(false)` if F6 is bound elsewhere. + +### DeckCraft (`OneSlot`) + +- `open` is `ui.pane` (one entry) at `End`; `states` returns `PaneState::docked(Edge::End, + pane_width)`; `Resize` writes `pane_width`; `Close` clears `ui.pane` as the × does today. + `size_range` is 240..=520. The `ui.json` fields stay. +- Format, Animation and Selection return `movable = true`; the rest `false`. Saving their place + needs new optional `ui.json` fields (`#[serde(default)]`). +- Thumbnails, outline, notes and the #835 canvas shell stay plain panels. +- F6 from the host closes the ui-parity F6 gap. + +### GridCraft (`OneSlot`, `.max_fraction(0.5)`) + +- `open` is the task slot pane (`grid.pane`, or "comments" while `session.comments_pane`) plus + PivotTable Fields while the active cell is in a pivot. PivotTable Fields returns + `closable = false` and `movable = false`, so it stays beside the slot. +- `Close("comments")` runs `review.showComments {on: false}`; agents still drive it through the + engine. +- No pane prefs today: return `None` from `states`. +- Code Editor (#1193) and Queries & Connections (#1203) become slot panes. The formula bar, + sheet tabs and status bar stay plain panels. From 418344c5adb97df9db45766294beea63d4c70300 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:38:00 +0000 Subject: [PATCH 24/94] docking: keyed label hook, closed panels from Workspace::apply, borrowed Floating::contains DockStyle::localized translates every *_label field through one keyed function. Workspace::apply and apply_all return the panels they closed. Floating::contains takes any borrowed form of the panel id. Found in the DesignCraft trial --- crates/ui/src/docking/labels.rs | 82 ++++++++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 1 + crates/ui/src/docking/model.rs | 8 ++- crates/ui/src/docking/model_tests.rs | 4 +- crates/ui/src/docking/workspace.rs | 20 ++++--- 5 files changed, 102 insertions(+), 13 deletions(-) create mode 100644 crates/ui/src/docking/labels.rs diff --git a/crates/ui/src/docking/labels.rs b/crates/ui/src/docking/labels.rs new file mode 100644 index 0000000000..cfc8260762 --- /dev/null +++ b/crates/ui/src/docking/labels.rs @@ -0,0 +1,82 @@ +//! One keyed hook for every label in [`DockStyle`]. + +use super::DockStyle; + +impl DockStyle { + /// Replace every `*_label` field with `translate(key)`, keeping the English default where it + /// returns `None`. An application translates the docking chrome in one place: + /// + /// ``` + /// fn dock_style(ui: &egui::Ui) -> craft_ui::docking::DockStyle { + /// craft_ui::docking::DockStyle::from_ui(ui).localized(|key| match key { + /// "dock.close" => Some("Fermer le panneau".to_owned()), + /// _ => None, + /// }) + /// } + /// ``` + /// + /// | Key | Field | English default | + /// |---|---|---| + /// | `dock.float` | `float_label` | Float panel | + /// | `dock.close` | `close_label` | Close panel | + /// | `dock.move` | `move_label` | Move to group | + /// | `dock.panels` | `panels_label` | Panels | + /// | `dock.resize` | `resize_label` | Resize panels | + /// | `dock.resizeWindow` | `resize_window_label` | Resize panel window | + /// | `dock.moveGroup` | `move_group_label` | Move tab group | + /// | `dock.closeGroup` | `close_group_label` | Close Tab Group | + /// | `dock.minimize` | `minimize_label` | Minimize | + /// | `dock.expand` | `expand_label` | Expand | + /// | `dock.floatGroup` | `float_group_label` | Float Tab Group | + /// | `dock.groupWith` | `group_with_label` | Group with | + /// | `dock.moveColumn` | `move_column_label` | Move panel column | + /// | `dock.collapseToIcons` | `collapse_to_icons_label` | Collapse to Icons | + /// | `dock.expandPanels` | `expand_panels_label` | Expand Panels | + /// | `dock.moveWindow` | `move_window_label` | Move panel window | + /// | `dock.closeWindow` | `close_window_label` | Close panel window | + /// | `dock.undock` | `undock_label` | Undock Panel | + /// | `dock.undockGroup` | `undock_group_label` | Undock Panel Group | + /// | `dock.closePanelGroup` | `close_panel_group_label` | Close Panel Group | + /// | `dock.closeOthers` | `close_others_label` | Close Other Panels in Group | + /// | `dock.maximize` | `maximize_label` | Maximize Frame | + /// | `dock.restoreFrame` | `restore_frame_label` | Restore Frame Size | + /// | `dock.newWindow` | `new_window_label` | Move Panel to New Window | + #[must_use] + pub fn localized(mut self, translate: impl Fn(&str) -> Option) -> Self { + for (key, label) in self.labels_mut() { + if let Some(text) = translate(key) { + *label = text; + } + } + self + } + + fn labels_mut(&mut self) -> [(&'static str, &mut String); 24] { + [ + ("dock.float", &mut self.float_label), + ("dock.close", &mut self.close_label), + ("dock.move", &mut self.move_label), + ("dock.panels", &mut self.panels_label), + ("dock.resize", &mut self.resize_label), + ("dock.resizeWindow", &mut self.resize_window_label), + ("dock.moveGroup", &mut self.move_group_label), + ("dock.closeGroup", &mut self.close_group_label), + ("dock.minimize", &mut self.minimize_label), + ("dock.expand", &mut self.expand_label), + ("dock.floatGroup", &mut self.float_group_label), + ("dock.groupWith", &mut self.group_with_label), + ("dock.moveColumn", &mut self.move_column_label), + ("dock.collapseToIcons", &mut self.collapse_to_icons_label), + ("dock.expandPanels", &mut self.expand_panels_label), + ("dock.moveWindow", &mut self.move_window_label), + ("dock.closeWindow", &mut self.close_window_label), + ("dock.undock", &mut self.undock_label), + ("dock.undockGroup", &mut self.undock_group_label), + ("dock.closePanelGroup", &mut self.close_panel_group_label), + ("dock.closeOthers", &mut self.close_others_label), + ("dock.maximize", &mut self.maximize_label), + ("dock.restoreFrame", &mut self.restore_frame_label), + ("dock.newWindow", &mut self.new_window_label), + ] + } +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 6ddeebf66c..f2e2a4a10f 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -7,6 +7,7 @@ pub mod chrome; mod dock_model; +mod labels; mod model; mod render; mod resize; diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 6800e56569..3d2da9babf 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -77,11 +77,13 @@ impl

Floating

{ self.groups.iter().flat_map(|group| group.panels.iter()) } - pub fn contains(&self, panel: &P) -> bool + /// True when a group of this window holds `panel`. Takes any borrowed form of `P`, such + /// as `&str` for `String` panels. + pub fn contains(&self, panel: &Q) -> bool where - P: PartialEq, + P: std::borrow::Borrow, { - self.groups.iter().any(|group| group.panels.contains(panel)) + self.panels().any(|p| p.borrow() == panel) } } diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index 88ca72f610..1309aa716b 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -167,7 +167,7 @@ fn window_docks_as_stacked_groups_or_merges_as_tabs() { fn close_group_and_close_window_record_a_restorable_location_per_member() { let mut workspace = Workspace::new(docked()); let allow = |_: &u32| Permissions::default(); - workspace.apply(Action::CloseGroup { panel: 3 }, allow).unwrap(); + assert_eq!(workspace.apply(Action::CloseGroup { panel: 3 }, allow).unwrap(), [2, 3]); assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [2, 3]); assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![4]]); workspace.set_visible(2, true, None).unwrap(); @@ -175,7 +175,7 @@ fn close_group_and_close_window_record_a_restorable_location_per_member() { assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![2, 3], vec![4]]); assert_eq!(workspace.layout.closed_by(&Action::CloseWindow { panel: 7 }).unwrap(), [6, 7, 8]); - workspace.apply(Action::CloseWindow { panel: 7 }, allow).unwrap(); + assert_eq!(workspace.apply(Action::CloseWindow { panel: 7 }, allow).unwrap(), [6, 7, 8]); assert!(workspace.layout.floating.is_empty()); assert_eq!(workspace.hidden.len(), 3); for panel in [6, 7, 8] { diff --git a/crates/ui/src/docking/workspace.rs b/crates/ui/src/docking/workspace.rs index 90fe8d6e05..81052e5659 100644 --- a/crates/ui/src/docking/workspace.rs +++ b/crates/ui/src/docking/workspace.rs @@ -80,18 +80,19 @@ impl Workspace

{ } /// Apply one action. Closed panels record where they go back, so each one can be reopened - /// with [`Self::set_visible`]. Honours [`Self::locked`]. [`Layout::closed_by`], called - /// before applying, names the panels a close action removes. - pub fn apply(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + /// with [`Self::set_visible`]. Honours [`Self::locked`]. Returns the panels the action + /// closed, in group order, so the application can release their state. + pub fn apply(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { self.apply_all([action], permissions) } - /// Apply every action in order, or none. - pub fn apply_all(&mut self, actions: impl IntoIterator>, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + /// Apply every action in order, or none. Returns the panels the actions closed, in order. + pub fn apply_all(&mut self, actions: impl IntoIterator>, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { self.validate()?; let locked = self.locked; let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) }; let mut proposed = self.clone(); + let mut all_closed = Vec::new(); for action in actions { let closed = proposed.layout.closed_by(&action)?; let locations = close_locations(&proposed.layout, &closed); @@ -100,12 +101,15 @@ impl Workspace

{ proposed.hidden.retain(|(p, _)| p != &panel); proposed.hidden.push((panel, location)); } + all_closed.extend(closed); } let visible: HashSet

= proposed.layout.panels().into_iter().cloned().collect(); proposed.hidden.retain(|(p, _)| !visible.contains(p)); + let mut seen = HashSet::new(); + all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone())); proposed.validate()?; *self = proposed; - Ok(()) + Ok(all_closed) } /// Show or hide one panel. Showing restores its recorded location, following the chain of @@ -117,10 +121,10 @@ impl Workspace

{ if !self.layout.contains(&panel) { return Ok(()); } - return self.apply(Action::Close { panel }, |_| Permissions::default()); + return self.apply(Action::Close { panel }, |_| Permissions::default()).map(drop); } if self.layout.contains(&panel) { - return self.apply(Action::Activate { panel }, |_| Permissions::default()); + return self.apply(Action::Activate { panel }, |_| Permissions::default()).map(drop); } let mut layout = self.layout.clone(); if self.restore_into(&mut layout, &panel).is_err() { From 3893c590b055b7b4b92ec665c97b9840b455e7e9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:38:00 +0000 Subject: [PATCH 25/94] docking: group float size, elided tab labels, filled ghost, drag bar grip, tab focus and double-click fixes A floated group or column keeps its width and takes the tallest member's floating size, else the docked height capped at 320 pt. Tab labels from pre-laid-out galleys are cut with an ellipsis and drawn left-aligned inside the tab, active tabs included. The group drag ghost has a translucent fill, a 2 pt outline and the members' labels. The drag bar draws a grip mark at rest. A click that expands a minimized group does not start a double-click that minimizes it again. A tab focused by the pointer shows no focus outline; keyboard focus still does. Found in the DesignCraft trial --- crates/ui/src/docking/dock_tests.rs | 8 +- crates/ui/src/docking/group_tests.rs | 3 + crates/ui/src/docking/render/group.rs | 79 ++++++++-- crates/ui/src/docking/render/preview.rs | 59 +++++-- crates/ui/src/docking/surface.rs | 2 +- crates/ui/src/docking/trial_tests.rs | 201 ++++++++++++++++++++++++ 6 files changed, 322 insertions(+), 30 deletions(-) create mode 100644 crates/ui/src/docking/trial_tests.rs diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index b719d3a72a..b924429f09 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -339,10 +339,12 @@ fn column_bar_drag_moves_the_column_and_away_from_a_dock_floats_its_groups() { assert_eq!(d.rect("column-bar", 2).left(), 240.0 + 18.0); let grab = d.rect("column-bar", 2).center(); d.hold(grab, pos2(560.0, 300.0)); - let ghost = source.translate(pos2(560.0, 300.0) - grab); - let ghost = egui::Rect::from_min_size(ghost.min.min(pos2(800.0, 600.0) - source.size()).max(Pos2::ZERO), source.size()); + // The column's width; a docked column floats at most 320 pt tall. + let size = vec2(source.width(), 320.0); + let ghost = egui::Rect::from_min_size(pos2(560.0, 300.0) - (grab - source.min), size); + let ghost = egui::Rect::from_min_size(ghost.min.min(pos2(800.0, 600.0) - size).max(Pos2::ZERO), size); assert!( - d.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == ghost && r.fill == egui::Color32::TRANSPARENT)), + d.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == ghost && r.fill != egui::Color32::TRANSPARENT)), "a ghost of the column follows the pointer" ); let out = d.step(vec![button(pos2(560.0, 300.0), false)]); diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 673b21334c..f9801054ac 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -6,6 +6,9 @@ use egui::{Color32, Context, Event, Id, Modifiers, PointerButton, RawInput, Rect const AREA: &str = "group-area"; +#[path = "trial_tests.rs"] +mod trial; + fn tabs(panels: &[u32], active: usize) -> Node { Node::Tabs { panels: panels.to_vec(), active } } diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 082439208c..4ba0c0b80f 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -1,6 +1,6 @@ -use std::{fmt::Debug, hash::Hash}; +use std::{fmt::Debug, hash::Hash, sync::Arc}; -use egui::{Key, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; +use egui::{Color32, Galley, Id, Key, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; use super::{Renderer, clamp_float, stripless}; use crate::docking::{Action, DropTarget, GroupDrag, GroupGesture, Placement, Target, begin_drag, surface::TAB_PADDING}; @@ -147,7 +147,18 @@ impl Renderer<'_, P> { if owner.kind != GroupKind::Frame && response.double_clicked() { self.output.actions.push(Action::SetMinimized { panel: owner.selected.clone(), minimized: !owner.minimized }); } - if response.has_focus() || response.hovered() { + let active = response.has_focus() || response.hovered(); + if movable { + // A grip mark at rest, centred in the bar's reserved width beside the header. + let grip = Rect::from_min_max(pos2((hit.right() - self.style.drag_bar_width).max(hit.left()), hit.top()), hit.max); + let stroke = Stroke::new(1.0, if active { self.style.text } else { self.style.inactive_text }); + let half = (hit.height() * 0.2).min(4.0); + for k in -1..=1 { + let x = grip.center().x + k as f32 * 3.0; + ui.painter().with_clip_rect(hit).line_segment([pos2(x, grip.center().y - half), pos2(x, grip.center().y + half)], stroke); + } + } + if active { ui.painter().with_clip_rect(hit).rect_stroke( hit.shrink(1.0), 0.0, @@ -200,7 +211,8 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetIconic { panel: panel.clone(), iconic: true }); } if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.float_group_label()) { - let rect = clamp_float(owner.rect.translate(vec2(24.0, 24.0)), ui.ctx().content_rect()); + let size = self.group_float_size(owner.panels, owner.rect.size()); + let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), ui.ctx().content_rect()); self.output.actions.push(Action::MoveGroup { panel: panel.clone(), to: Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) }, @@ -266,41 +278,76 @@ impl Renderer<'_, P> { response } + /// A tab's label, cut at the end with '…' to fit `width`. egui does not wrap a host's + /// pre-laid-out `WidgetText::Galley` again, so that one is laid out again from its job. + pub(super) fn tab_label(&mut self, ui: &Ui, panel: &P, label: &str, color: Color32, width: f32) -> Arc { + let galley = self.content.label(ui, panel, label, &self.style.font, color).into_galley( + ui, + Some(egui::TextWrapMode::Truncate), + width, + self.style.font.clone(), + ); + if galley.size().x <= width + 0.5 { + return galley; + } + let mut job = (*galley.job).clone(); + job.wrap = egui::text::TextWrapping::truncate_at_width(width); + ui.painter().layout_job(job) + } + + /// True while a tab's focus came from the pointer, which shows no focus outline. Tab or an + /// arrow key (keyboard navigation) clears it. + fn pointer_focus(&self, ui: &Ui, tab: Id) -> bool { + let key = tab.with("pointer-focus"); + let navigated = ui.input(|i| [Key::Tab, Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown].iter().any(|k| i.key_pressed(*k))); + if navigated { + ui.ctx().data_mut(|d| d.remove_temp::(key)); + } + ui.ctx().data(|d| d.get_temp::(key)).unwrap_or(false) + } + pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect, owner: Option<&TabGroup<'_, P>>) { let minimized = owner.filter(|owner| owner.kind != GroupKind::Frame).map(|owner| owner.minimized); let policy = self.permissions(panel); let label = self.label_of(panel); let color = if active { self.style.text } else { self.style.inactive_text }; - // A tab squeezed below its natural width cuts its label with '…' inside the padding its - // natural width was measured with, instead of letting it run under its neighbours. - let galley = self.content.label(ui, panel, &label, &self.style.font, color).into_galley( - ui, - Some(egui::TextWrapMode::Truncate), - (rect.width() - TAB_PADDING).max(0.0), - self.style.font.clone(), - ); + let galley = self.tab_label(ui, panel, &label, color, (rect.width() - TAB_PADDING).max(0.0)); let elided = galley.elided; - let response = tabs::Tab::new(self.id.with(("tab", panel)), &label, active) + let tab_id = self.id.with(("tab", panel)); + let pointer_focus = self.pointer_focus(ui, tab_id); + let response = tabs::Tab::new(tab_id, &label, active) .sense(if policy.movable { Sense::click_and_drag() } else { Sense::click() }) - .focus_stroke(Stroke::new(1.0, self.style.accent)) + .focus_stroke(if pointer_focus { Stroke::NONE } else { Stroke::new(1.0, self.style.accent) }) .show_at(ui, rect, |ui, response| { let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); painter.rect_filled(rect, 0.0, if active || response.hovered() { self.style.active_background } else { self.style.tab_background }); - painter.galley(rect.center() - galley.size() * 0.5, galley.clone(), color); + let at = pos2(rect.left() + TAB_PADDING * 0.5, rect.center().y - galley.size().y * 0.5); + painter.galley(at, galley.clone(), color); }); let response = if elided { response.on_hover_text(&label) } else { response }; self.register_interaction(ui.ctx(), response.id); + if response.is_pointer_button_down_on() || response.clicked() { + ui.ctx().data_mut(|d| d.insert_temp(tab_id.with("pointer-focus"), true)); + } + // The click that expands a minimized group is not the first half of a double-click. + let expand_key = self.id.with(("expanded-by-click", owner.map(|owner| owner.panels.first()))); if response.clicked() { self.output.actions.push(Action::Activate { panel: panel.clone() }); self.output.focused = Some(panel.clone()); if minimized == Some(true) && !active { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: false }); + let now = ui.input(|i| i.time); + ui.ctx().data_mut(|d| d.insert_temp(expand_key, now)); } } if let Some(minimized) = minimized && response.double_clicked() { - self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized }); + let (now, window) = (ui.input(|i| i.time), ui.ctx().options(|o| o.input_options.max_double_click_delay)); + let expanded_by_first_click = ui.ctx().data_mut(|d| d.remove_temp::(expand_key)).is_some_and(|t| now - t <= window); + if !expanded_by_first_click { + self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized }); + } } if policy.movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), group) { self.latch_undock(ui.ctx(), owner.map(|owner| owner.kind)); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 6d982c8886..b770016c31 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -1,10 +1,11 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Color32, Context, Key, Pos2, Rect, Stroke, StrokeKind, Vec2, vec2}; +use egui::{Color32, Context, Key, Pos2, Rect, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; use super::{Renderer, clamp_float, dock::group_action}; use crate::docking::{ Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Placement, Target, Zone, cancel_drag, dock_model::Place, resolve_drop, + surface::TAB_PADDING, }; /// Ctrl (Windows, Linux) or Cmd (macOS) held: the drop floats and no target is offered. @@ -16,7 +17,8 @@ fn float_only(ctx: &Context) -> bool { const DOCKED_FLOAT_HEIGHT: f32 = 320.0; impl Renderer<'_, P> { - pub(in crate::docking) fn finish_group_drag(&mut self, ctx: &Context) { + pub(in crate::docking) fn finish_group_drag(&mut self, ui: &Ui) { + let ctx = ui.ctx(); let key = self.id.with("group-drag"); let Some(drag) = ctx.data(|d| d.get_temp::>(key)) else { return }; if !drag.members.iter().all(|p| self.layout.contains(p) && self.permissions(p).movable) { @@ -26,7 +28,7 @@ impl Renderer<'_, P> { let (escape, focused, down, released, pointer) = ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); let pointer = pointer.filter(|p| p.is_finite()); - let ghost = pointer.map(|pointer| clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect())); + let ghost = pointer.map(|pointer| self.group_ghost(ctx, &drag, pointer)); if !escape && focused && (down || released) @@ -63,7 +65,7 @@ impl Renderer<'_, P> { } } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { self.output.group_drag = Some(drag.panel.clone()); - self.paint_group_drag(ctx, &drag, pointer, float_only); + self.paint_group_drag(ui, &drag, pointer, float_only); } } @@ -121,20 +123,35 @@ impl Renderer<'_, P> { } // No target: hosts that still apply their own policy for a whole-group release get it. self.output.group_drop = Some((drag.panel.clone(), pointer)); - let rect = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); + let rect = self.group_ghost(ctx, drag, pointer); let action = group_action(drag, Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) }); if self.layout.clone().apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() { self.output.actions.push(action); } } - /// Ghost outline at the pointer (a window moving live is its own ghost) and one - /// destination preview. - fn paint_group_drag(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + /// The ghost at the pointer (a window moving live is its own ghost) under one destination + /// preview. The ghost has a translucent fill, a 2 pt outline and the members' labels. + fn paint_group_drag(&mut self, ui: &Ui, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + let ctx = ui.ctx(); let painter = self.preview_painter(ctx); if drag.gesture != GroupGesture::Window { - let ghost = clamp_float(drag.source.translate(pointer - drag.origin), ctx.content_rect()); - painter.rect_stroke(ghost, 0.0, Stroke::new(1.0, self.style.accent.gamma_multiply(0.6)), StrokeKind::Inside); + let ghost = self.group_ghost(ctx, drag, pointer); + painter.rect(ghost, 0.0, self.style.accent.gamma_multiply(0.15), Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + let strip = Rect::from_min_size(ghost.min, vec2(ghost.width(), self.style.tab_height.min(ghost.height()))); + let labels = painter.with_clip_rect(strip.shrink(2.0)); + let mut x = strip.left() + TAB_PADDING * 0.5; + for panel in &drag.members { + let width = strip.right() - TAB_PADDING * 0.5 - x; + if width <= 0.0 { + break; + } + let label = self.label_of(panel); + let galley = self.tab_label(ui, panel, &label, self.style.text, width); + let advance = galley.size().x + TAB_PADDING; + labels.galley(pos2(x, strip.center().y - galley.size().y * 0.5), galley, self.style.text); + x += advance; + } } if float_only { return; @@ -278,6 +295,28 @@ impl Renderer<'_, P> { size.max(limits.min + header).min(limits.max + header) } + /// Size of a group or column floated by a drag or Float Tab Group: the source width, and the + /// tallest member's floating size, else the source height capped like a panel leaving a + /// dock column. A group that already floats keeps its size. + pub(super) fn group_float_size(&self, members: &[P], source: Vec2) -> Vec2 { + let place = members.first().and_then(|panel| self.layout.place(panel)); + if matches!(place, Some(Place::Floating { .. }) | None) { + return source; + } + let valid = |s: &Vec2| s.is_finite() && s.x > 0.0 && s.y > 0.0; + let host = members.iter().filter_map(|panel| self.content.floating_size(panel).filter(valid)).map(|s| s.y).reduce(f32::max); + let docked = matches!(place, Some(Place::Dock { .. })); + vec2(source.x, host.unwrap_or(if docked { source.y.min(DOCKED_FLOAT_HEIGHT) } else { source.y })) + } + + /// Where a group or column drag floats with the pointer at `pointer`, keeping the grab + /// offset, inside the window (Z2). + fn group_ghost(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2) -> Rect { + let size = if drag.gesture == GroupGesture::Window { drag.source.size() } else { self.group_float_size(&drag.members, drag.source.size()) }; + let grab = (drag.origin - drag.source.min).clamp(Vec2::ZERO, size); + clamp_float(Rect::from_min_size(pointer - grab, size), ctx.content_rect()) + } + fn tab_float_rect(&self, ctx: &Context, drag: &Drag

, pointer: Pos2) -> Rect { let size = self.float_size(&drag.panel, drag.source.size()); let grab = drag.grab.min(vec2(size.x, self.style.tab_height)); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 141f6f5d6d..2b149150e1 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -626,7 +626,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { ui.allocate_rect(rect, Sense::hover()); } renderer.floating(ui.ctx(), &view.floating); - renderer.finish_group_drag(ui.ctx()); + renderer.finish_group_drag(ui); renderer.finish_drag(ui.ctx()); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); renderer.output diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs new file mode 100644 index 0000000000..7bea2a42cf --- /dev/null +++ b/crates/ui/src/docking/trial_tests.rs @@ -0,0 +1,201 @@ +//! Fixes from the DesignCraft trial: group float size, tab label elision, the drag ghost and +//! grip, double-clicks on minimized groups, pointer focus, label keys and borrowed lookups. + +use super::*; + +/// Every shape, with nested `Shape::Vec`s flattened. +fn flat(shapes: &[egui::epaint::ClippedShape]) -> Vec<(Rect, egui::Shape)> { + fn walk(clip: Rect, shape: &egui::Shape, out: &mut Vec<(Rect, egui::Shape)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(clip, s, out)), + shape => out.push((clip, shape.clone())), + } + } + let mut out = Vec::new(); + for clipped in shapes { + walk(clipped.clip_rect, &clipped.shape, &mut out); + } + out +} + +fn texts(d: &Driver) -> Vec<(Rect, egui::epaint::TextShape)> { + flat(&d.shapes) + .into_iter() + .filter_map(|(clip, shape)| match shape { + egui::Shape::Text(text) => Some((clip, text)), + _ => None, + }) + .collect() +} + +fn rects(d: &Driver) -> Vec { + flat(&d.shapes) + .into_iter() + .filter_map(|(_, shape)| match shape { + egui::Shape::Rect(rect) => Some(rect), + _ => None, + }) + .collect() +} + +fn last_char(galley: &egui::Galley) -> Option { + galley.rows.last().and_then(|row| row.glyphs.last()).map(|glyph| glyph.chr) +} + +#[test] +fn a_full_height_docked_group_floats_at_the_host_or_capped_height_inside_the_window() { + for size in [None, Some(vec2(200.0, 150.0))] { + let mut layout = docked(); + let Some(Node::Split { first, .. }) = &mut layout.root else { panic!() }; + **first = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![2, 3], 1)], 240.0)] }; + let content = TestContent { protected: vec![0], floating_size: size, ..Default::default() }; + let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let bar = d.rect("drag-bar", 2); + let out = d.drag(bar.center(), pos2(420.0, 300.0)); + let Some(Target::Float { rect: Some([x, y, width, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) }; + match size { + Some(size) => assert_eq!(*height, size.y), + None => assert!(*height <= 320.0, "{height}"), + } + assert!(*width > 100.0 && *width <= 240.0, "{width}"); + let window = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + assert!(window.contains_rect(Rect::from_min_size(pos2(*x, *y), vec2(*width, *height))), "{x} {y} {width} {height}"); + } +} + +/// Labels as a host's pre-laid-out galleys, which egui does not wrap again. +struct GalleyLabels; + +impl DockContent for GalleyLabels { + fn body(&mut self, _: &mut egui::Ui, _: &u32) {} + fn logical_label(&self, panel: &u32) -> String { + format!("Character Styles {panel}") + } + fn label(&mut self, ui: &egui::Ui, _: &u32, logical: &str, font: &egui::FontId, color: Color32) -> egui::WidgetText { + egui::WidgetText::Galley(ui.painter().layout_no_wrap(logical.to_owned(), font.clone(), color)) + } +} + +#[test] +fn shrunk_tabs_end_their_labels_with_an_ellipsis_inside_the_tab_active_or_not() { + let panels = [1, 2, 3, 4, 5, 6]; + let layout = Layout { root: Some(tabs(&panels, 3)), floating: Vec::new() }; + let ctx = Context::default(); + let mut content = GalleyLabels; + let mut shapes = Vec::new(); + for _ in 0..2 { + let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }; + let mut full = ctx.run_ui(input, |ui| { + let style = DockStyle::from_ui(ui); + ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 400.0))), |ui| { + DockArea::new(Id::new(AREA)).show_content(ui, &layout, &style, &mut content); + }); + }); + full.textures_delta.clear(); + shapes = full.shapes; + } + let texts: Vec<_> = flat(&shapes) + .into_iter() + .filter_map(|(clip, shape)| match shape { + egui::Shape::Text(text) => Some((clip, text)), + _ => None, + }) + .collect(); + for panel in panels { + let tab = ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect; + let Some((clip, text)) = texts.iter().find(|(_, t)| t.galley.text().ends_with(&format!(" {panel}")) && tab.contains(t.pos)) else { + panic!("no label in tab {panel}") + }; + assert_eq!(last_char(&text.galley), Some('…'), "tab {panel}"); + let drawn = Rect::from_min_size(text.pos, text.galley.size()); + assert!(drawn.right() <= tab.right() + 0.5 && drawn.left() >= tab.left(), "tab {panel}: {drawn:?} in {tab:?}"); + assert!(tab.contains_rect(clip.intersect(drawn)), "tab {panel}"); + } +} + +#[test] +fn drag_bar_shows_a_grip_at_rest_and_a_group_drag_paints_a_filled_labelled_ghost() { + let mut d = Driver::new(frames()); + let visuals = d.ctx.global_style().visuals.clone(); + let bar = d.rect("drag-bar", 2); + let grip = flat(&d.shapes).into_iter().any(|(_, shape)| match shape { + egui::Shape::LineSegment { points, stroke } => { + bar.contains(points[0]) && bar.contains(points[1]) && stroke.color == visuals.weak_text_color() + } + _ => false, + }); + assert!(grip, "no grip mark in the drag bar at rest"); + + d.hold(bar.center(), pos2(150.0, 300.0)); + let fill = visuals.selection.stroke.color.gamma_multiply(0.15); + let Some(ghost) = rects(&d).into_iter().find(|r| r.fill == fill && r.stroke.width == 2.0 && r.rect.contains(pos2(150.0, 300.0))) else { + panic!("no filled ghost under the pointer") + }; + for label in ["Panel 2", "Panel 3"] { + assert!(texts(&d).iter().any(|(_, t)| t.galley.text() == label && ghost.rect.contains(t.pos)), "{label} missing from the ghost"); + } + d.step(vec![key(egui::Key::Escape)]); +} + +#[test] +fn double_click_on_a_tab_of_a_minimized_group_ends_expanded() { + let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; + let mut d = Driver::new(layout); + let minimized = |d: &Driver| d.layout.floating[0].groups[0].minimized; + let active = d.tab(6).center(); + d.click(active); + d.click(active); + assert!(minimized(&d)); + d.wait(); + + let other = d.tab(5).center(); + d.click(other); + d.click(other); + assert!(!minimized(&d)); + assert_eq!(d.layout.floating[0].groups[0].active_panel(), Some(&5)); +} + +#[test] +fn a_clicked_tab_shows_no_focus_outline_but_tab_key_focus_does() { + let mut d = Driver::new(frames()); + let accent = d.ctx.global_style().visuals.selection.stroke.color; + let id = Id::new(AREA).with(("tab", &3u32)); + let outline = d.tab(3).shrink(2.0); + let outlined = |d: &Driver| rects(d).iter().any(|r| r.rect == outline && r.stroke.width > 0.0 && r.stroke.color == accent); + + d.click(d.tab(3).center()); + // A platform may focus the clicked widget, as an AccessKit focus request does. + d.ctx.memory_mut(|m| m.request_focus(id)); + d.step(vec![]); + assert_eq!(d.ctx.memory(|m| m.focused()), Some(id)); + assert!(!outlined(&d)); + + d.ctx.memory_mut(|m| m.surrender_focus(id)); + for _ in 0..20 { + if d.ctx.memory(|m| m.focused()) == Some(id) { + break; + } + d.step(vec![key(egui::Key::Tab)]); + } + assert_eq!(d.ctx.memory(|m| m.focused()), Some(id)); + d.step(vec![]); + assert!(outlined(&d)); +} + +#[test] +fn localized_covers_every_label_and_contains_takes_a_borrowed_panel() { + let mut debug = String::new(); + let mut full = Context::default().run_ui(RawInput::default(), |ui| { + debug = format!("{:?}", DockStyle::from_ui(ui).localized(|key| Some(key.to_owned()))); + }); + full.textures_delta.clear(); + let values: Vec<&str> = debug.split("_label: \"").skip(1).filter_map(|rest| rest.split('"').next()).collect(); + assert_eq!(values.len(), 24, "{debug}"); + assert!(values.iter().all(|v| v.starts_with("dock.")), "a label without a key: {values:?}"); + let unique: std::collections::HashSet<_> = values.iter().collect(); + assert_eq!(unique.len(), values.len()); + + let window = Floating::single(vec!["swatches".to_owned()], 0, [0.0, 0.0, 200.0, 200.0]); + assert!(window.contains("swatches")); + assert!(!window.contains("layers")); +} From 0c140eb65b4f9fdb8ba18ef87764f421daf36b21 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 05:40:26 +0000 Subject: [PATCH 26/94] docking: iconic columns with flyouts, hit rects and a test driver An iconic column draws one icon per panel, a grip above each group and a separator between groups (M3). Widened past `DockStyle::iconic_label_width` it shows panel names (M4). Clicking an icon opens its group as a flyout on the canvas side; another icon switches, the same icon closes, and with Auto-Collapse Iconic Panels (default on) Escape or a press outside closes it (M5). Dragging a flyout's strip floats its group (M6), an icon drags its panel (S7) and the grip its group (S8). A drop into an iconic column makes a new icon group, previewed by the column outline and an insertion line (P9). `raise_panel` on an iconic panel opens its flyout (U3), and the column menu has the Auto-Collapse toggle as `DockEvent::ToggleAutoCollapse`. Iconic widths move to `DockStyle` (`icon_size`, `iconic_width`, `iconic_max_width`). `DockArea::hit_rects` names every gesture source the area drew last frame, and `docking::testing::DockDriver` (feature `testing`) drives an area with real egui input for application tests. Behaviour follows vectorcraft crates/ui-egui/src/dock.rs (icon column, flyout placement, names when widened) and photocraft dock.rs (auto-collapse). --- crates/ui/Cargo.toml | 2 + crates/ui/src/docking/hits.rs | 124 +++++++++ crates/ui/src/docking/iconic_tests.rs | 324 +++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 7 + crates/ui/src/docking/render/dock.rs | 35 ++- crates/ui/src/docking/render/iconic.rs | 328 ++++++++++++++++++++++++ crates/ui/src/docking/render/mod.rs | 9 +- crates/ui/src/docking/render/preview.rs | 2 +- crates/ui/src/docking/surface.rs | 36 ++- crates/ui/src/docking/testing.rs | 222 ++++++++++++++++ 10 files changed, 1073 insertions(+), 16 deletions(-) create mode 100644 crates/ui/src/docking/hits.rs create mode 100644 crates/ui/src/docking/iconic_tests.rs create mode 100644 crates/ui/src/docking/render/iconic.rs create mode 100644 crates/ui/src/docking/testing.rs diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index dd85edd4a6..b5fc3bbdd2 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -18,6 +18,8 @@ serde = { version = "1", features = ["derive"], optional = true } serde = ["dep:serde"] # Floating windows may move to their own OS windows (desktop egui backends with viewports). native-windows = [] +# `docking::testing`: a headless driver for application docking tests. +testing = [] [dev-dependencies] egui = { workspace = true, features = ["default_fonts"] } diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs new file mode 100644 index 0000000000..26c25d9197 --- /dev/null +++ b/crates/ui/src/docking/hits.rs @@ -0,0 +1,124 @@ +//! Where each docking gesture starts, for control protocols and tests. + +use std::{collections::HashMap, fmt::Debug, hash::Hash}; + +use egui::{Context, Id, Rect}; + +use super::{DockArea, Layout, Node, render::RESIZE_HANDLES}; + +/// A rendered docking control that starts a gesture. Groups, columns and windows are named by +/// their first panel. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] +pub enum Hit

{ + /// A tab: click activates, drag moves the panel (S1). + Tab(P), + /// A group's drag bar: click opens the group menu, drag moves the group (S2). + DragBar(P), + /// The top border of a group's strip: drag moves the group (S3). + Border(P), + /// The "…" button of a group whose tabs overflow; named by the active panel. + Overflow(P), + /// [D] A column bar: drag moves the column (S6). + ColumnBar(P), + /// [D] The »/« button of a column bar (M2). + Collapse(P), + /// An accordion entry's −/+ button. + StackToggle(P), + /// A floating window's title bar (S5). + Title(P), + /// A floating window's × button. + Close(P), + /// [D] A panel's icon in an iconic column (S7, M5). + Icon(P), + /// [D] The grip above an icon group (S8). + IconGrip(P), + /// A floating window's resize handle. + Resize(P, ResizeEdge), + Divider(Divider

), +} + +/// The edge or corner a floating window's resize handle moves. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum ResizeEdge { + Left, + Right, + Bottom, + BottomLeft, + BottomRight, +} + +/// A divider that resizes what is on either side of it. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] +pub enum Divider

{ + /// A split, by its path from the root (see [`super::Action::ResizeSplit`]). + Split(Vec), + /// Below the accordion entry of this panel. + Stack(P), + /// [D] The inner edge of the column holding this panel first. + Column(P), + /// Below the dock or floating group holding this panel first. + Group(P), +} + +fn key(area: Id) -> Id { + area.with("hit-rects") +} + +impl DockArea<'_, P> { + /// Every gesture source the area drew in its last frame, with its rect in points. Hosts + /// return these from a `ui.docking` control method beside the layout and `focused`; tests + /// drag from their centres. + pub fn hit_rects(ctx: &Context, id: Id) -> Vec<(Hit

, Rect)> { + ctx.data(|d| d.get_temp::, Rect)>>(key(id))).unwrap_or_default() + } +} + +/// Name the controls the renderer registered this frame and store their rects. +pub(super) fn record(ctx: &Context, area: Id, layout: &Layout

, owned: &[Id]) { + let mut names: HashMap> = HashMap::new(); + for panel in layout.panels() { + let p = || panel.clone(); + let some = Some(panel); + names.insert(area.with(("tab", panel)), Hit::Tab(p())); + names.insert(area.with(("icon", panel)), Hit::Icon(p())); + names.insert(area.with(("overflow", panel)), Hit::Overflow(p())); + names.insert(area.with(("collapse", panel)), Hit::StackToggle(p())); + names.insert(area.with(("stack-resize", panel)), Hit::Divider(Divider::Stack(p()))); + names.insert(area.with(("drag-bar", some)), Hit::DragBar(p())); + names.insert(area.with(("drag-border", some)), Hit::Border(p())); + names.insert(area.with(("icon-grip", some)), Hit::IconGrip(p())); + names.insert(area.with(("column-bar", some)), Hit::ColumnBar(p())); + names.insert(area.with(("column-collapse", some)), Hit::Collapse(p())); + names.insert(area.with(("column-resize", some)), Hit::Divider(Divider::Column(p()))); + names.insert(area.with(("group-resize", some)), Hit::Divider(Divider::Group(p()))); + names.insert(area.with(("floating-divider", some)), Hit::Divider(Divider::Group(p()))); + let title = area.with(("move-group", some)); + names.insert(title, Hit::Title(p())); + names.insert(title.with("close"), Hit::Close(p())); + let window = area.with(("floating", panel)); + let edges = [ResizeEdge::BottomRight, ResizeEdge::Left, ResizeEdge::Right, ResizeEdge::Bottom, ResizeEdge::BottomLeft]; + for (name, edge) in RESIZE_HANDLES.iter().zip(edges) { + names.insert(window.with(*name), Hit::Resize(p(), edge)); + } + } + let mut nodes = layout.root.as_ref().map(|root| vec![(root, Vec::::new())]).unwrap_or_default(); + while let Some((node, path)) = nodes.pop() { + if let Node::Split { first, second, .. } = node { + names.insert(area.with(("split", &path)), Hit::Divider(Divider::Split(path.clone()))); + let mut second_path = path.clone(); + second_path.push(true); + let mut first_path = path; + first_path.push(false); + nodes.push((second, second_path)); + nodes.push((first, first_path)); + } + } + let hits: Vec<(Hit

, Rect)> = + owned.iter().filter_map(|id| Some((names.remove(id)?, ctx.read_response(*id)?.rect))).filter(|(_, rect)| rect.is_positive()).collect(); + ctx.data_mut(|d| d.insert_temp(key(area), hits)); +} diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs new file mode 100644 index 0000000000..67e722d2c2 --- /dev/null +++ b/crates/ui/src/docking/iconic_tests.rs @@ -0,0 +1,324 @@ +//! [D] Iconic columns, flyouts and hit rects, driven through `testing::DockDriver`. + +use super::testing::DockDriver; +use super::*; +use crate::layout::{SplitAxis, SplitSize}; +use egui::{Key, Pos2, Rect, pos2, vec2}; + +struct Content; + +impl DockContent for Content { + fn body(&mut self, ui: &mut egui::Ui, _: &u32) { + ui.label("Body"); + } + fn logical_label(&self, panel: &u32) -> String { + format!("Panel {panel}") + } + fn permissions(&self, panel: &u32) -> Permissions { + if *panel == 0 { Permissions::PROTECTED } else { Permissions::default() } + } +} + +type Driver = DockDriver; + +/// A left dock with one column of `groups`, iconic when `iconic`, beside canvas 0. +fn docked(groups: &[&[u32]], iconic: bool) -> Layout { + let mut column = Column::new(groups.iter().map(|g| Group::new(g.to_vec(), 0)).collect(), 240.0); + column.iconic = iconic; + let dock = Node::Dock { side: Side::Start, columns: vec![column] }; + let canvas = Node::Tabs { panels: vec![0], active: 0 }; + Layout { + root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), first: Box::new(dock), second: Box::new(canvas) }), + floating: Vec::new(), + } +} + +fn first_column(layout: &Layout) -> Column { + match &layout.root { + Some(Node::Split { first, .. }) => match first.as_ref() { + Node::Dock { columns, .. } => columns.first().cloned().unwrap(), + other => panic!("no dock: {other:?}"), + }, + other => panic!("no split: {other:?}"), + } +} + +fn groups(layout: &Layout) -> Vec> { + first_column(layout).groups.iter().map(|g| g.panels.clone()).collect() +} + +fn hit(d: &Driver, hit: Hit) -> Rect { + d.hit(&hit).unwrap_or_else(|| panic!("{hit:?} in {:?}", d.hits())) +} + +fn open(d: &Driver) -> Option { + flyout::(&d.ctx, d.id) +} + +fn texts(d: &Driver) -> Vec { + d.shapes() + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.galley.text().to_owned()), + _ => None, + }) + .collect() +} + +const CANVAS: Pos2 = pos2(600.0, 400.0); + +#[test] +fn collapsed_column_shows_one_icon_per_panel_with_group_separators() { + let d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content); + let (one, two, three) = (hit(&d, Hit::Icon(1)), hit(&d, Hit::Icon(2)), hit(&d, Hit::Icon(3))); + let (grip1, grip3) = (hit(&d, Hit::IconGrip(1)), hit(&d, Hit::IconGrip(3))); + assert_eq!(one.width(), 36.0, "the column takes the style's iconic width"); + assert_eq!((grip1.bottom(), one.bottom()), (one.top(), two.top()), "a group's icons follow its grip and each other"); + assert_eq!(grip3.top() - two.bottom(), 7.0, "groups are apart by the separator"); + assert_eq!(three.top(), grip3.bottom()); + assert!(d.hit(&Hit::Tab(1)).is_none(), "an iconic column draws no tabs"); +} + +#[test] +fn widening_an_iconic_column_shows_labels() { + let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content); + assert!(!texts(&d).iter().any(|t| t == "Panel 1")); + let edge = hit(&d, Hit::Divider(Divider::Column(1))); + let out = d.drag(edge.center(), pos2(150.0, edge.center().y)); + assert!(out.error.is_none()); + let width = first_column(&d.layout).iconic_width.unwrap(); + assert!((100.0..=160.0).contains(&width), "{width}"); + d.settle(); + let labels = texts(&d); + assert!(["Panel 1", "Panel 2", "Panel 3"].iter().all(|l| labels.iter().any(|t| t == l)), "{labels:?}"); + let edge = hit(&d, Hit::Divider(Divider::Column(1))); + d.drag(edge.center(), pos2(20.0, edge.center().y)); + d.settle(); + assert_eq!(first_column(&d.layout).iconic_width, Some(36.0)); + assert!(!texts(&d).iter().any(|t| t == "Panel 1")); +} + +#[test] +fn icon_click_opens_a_flyout_on_the_canvas_side_and_auto_collapse_closes_it() { + let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content); + let icon = hit(&d, Hit::Icon(2)).center(); + let out = d.click(icon); + assert!(out.actions.contains(&Action::Activate { panel: 2 })); + d.settle(); + assert_eq!(open(&d), Some(2)); + let column = hit(&d, Hit::Icon(1)); + let tab = hit(&d, Hit::Tab(2)); + assert!(tab.left() >= column.right(), "the flyout opens on the canvas side: {tab:?}"); + assert!(tab.top() <= hit(&d, Hit::IconGrip(1)).bottom(), "beside its group"); + assert_eq!(first_column(&d.layout).groups.first().map(|g| g.active), Some(1)); + + // Another icon switches flyouts, the same icon closes. + d.click(hit(&d, Hit::Icon(3)).center()); + d.settle(); + assert_eq!(open(&d), Some(3)); + assert!(d.hit(&Hit::Tab(2)).is_none()); + d.click(hit(&d, Hit::Icon(3)).center()); + d.settle(); + assert_eq!(open(&d), None); + + // Escape and a press outside close it. + d.click(icon); + d.settle(); + d.key(Key::Escape); + d.settle(); + assert_eq!(open(&d), None); + d.click(icon); + d.settle(); + let inside = hit(&d, Hit::Tab(2)).center(); + d.click(inside); + d.settle(); + assert_eq!(open(&d), Some(2), "a press inside keeps it"); + d.click(CANVAS); + d.settle(); + assert_eq!(open(&d), None); + + // Auto-Collapse off: it stays until an icon closes it. + d.auto_collapse = false; + d.click(icon); + d.settle(); + d.key(Key::Escape); + d.click(CANVAS); + d.settle(); + assert_eq!(open(&d), Some(2)); + d.click(icon); + d.settle(); + assert_eq!(open(&d), None); + + // U3: raising an iconic panel, as the Window menu does, opens its flyout. + d.raise = Some(3); + d.settle(); + assert_eq!(open(&d), Some(3)); +} + +#[test] +fn auto_collapse_toggle_is_a_column_menu_event() { + use egui_kittest::{Harness, kittest::Queryable}; + let layout = docked(&[&[1, 2]], true); + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, events: &mut Vec>| { + let out = DockArea::new(egui::Id::new("menu")).show_content(ui, &layout, &DockStyle::from_ui(ui), &mut Content); + events.extend(out.events); + }, + Vec::new(), + ); + h.run_steps(2); + let bar = h.ctx.read_response(egui::Id::new("menu").with(("column-bar", Some(&1u32)))).unwrap().rect.center(); + h.input_mut().events.extend([ + egui::Event::PointerMoved(bar), + egui::Event::PointerButton { pos: bar, button: egui::PointerButton::Secondary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.run_steps(1); + h.input_mut().events.push(egui::Event::PointerButton { + pos: bar, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(2); + h.get_by_label("Auto-Collapse Iconic Panels").click(); + h.run_steps(2); + assert_eq!(h.state(), &vec![DockEvent::ToggleAutoCollapse]); +} + +#[test] +fn dragging_a_flyout_strip_floats_its_group() { + let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content); + d.click(hit(&d, Hit::Icon(1)).center()); + d.settle(); + let bar = hit(&d, Hit::DragBar(1)); + let out = d.drag(bar.center(), CANVAS); + assert!(matches!(out.actions.as_slice(), [Action::MoveGroup { panel: 1, to: Target::Float { .. } }]), "{:?}", out.actions); + assert_eq!(groups(&d.layout), vec![vec![3]]); + assert_eq!(d.layout.floating.len(), 1); + assert_eq!(d.layout.floating.first().map(|w| w.panels().copied().collect::>()), Some(vec![1, 2])); + d.settle(); + assert_eq!(open(&d), None, "the flyout closes with its group gone"); + + // A tab dragged out of a flyout floats that panel alone. + d.click(hit(&d, Hit::Icon(3)).center()); + d.settle(); + let tab = hit(&d, Hit::Tab(3)); + let out = d.drag(tab.center(), pos2(450.0, 200.0)); + assert!(matches!(out.actions.as_slice(), [Action::Float { panel: 3, .. }]), "{:?}", out.actions); +} + +#[test] +fn icon_and_icon_group_grip_drags_move_a_panel_and_a_group() { + let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content); + let before = d.layout.clone(); + // Escape, focus loss and cancel_drag end an icon drag with no change. + let icon = hit(&d, Hit::Icon(2)).center(); + d.hold(icon, CANVAS); + d.key(Key::Escape); + d.release(CANVAS); + d.hold(icon, CANVAS); + d.focus(false); + d.focus(true); + d.release(CANVAS); + d.hold(icon, CANVAS); + cancel_drag::(&d.ctx, d.id); + d.release(CANVAS); + assert_eq!(d.layout, before); + + let out = d.drag(icon, CANVAS); + let Some(Action::Float { panel: 2, rect }) = out.actions.first() else { panic!("{:?}", out.actions) }; + assert_eq!((rect[2], rect[3]), (240.0, 320.0), "a panel floated from its icon takes the column's expanded width"); + assert_eq!(groups(&d.layout), vec![vec![1], vec![3]]); + + let grip = hit(&d, Hit::IconGrip(3)).center(); + let out = d.drag(grip, pos2(450.0, 250.0)); + assert!(matches!(out.actions.as_slice(), [Action::MoveGroup { panel: 3, to: Target::Float { .. } }]), "{:?}", out.actions); + assert_eq!(groups(&d.layout), vec![vec![1]]); +} + +#[test] +fn group_dropped_on_an_iconic_column_joins_as_an_icon_group() { + let mut layout = docked(&[&[1], &[2]], true); + layout.floating.push(Floating::single(vec![5, 6], 0, [300.0, 200.0, 240.0, 200.0])); + let mut d = DockDriver::new(layout, Content); + let bar = hit(&d, Hit::DragBar(5)).center(); + let one = hit(&d, Hit::Icon(1)); + let target = pos2(one.center().x, one.bottom() - 2.0); + d.hold(bar, target); + let column = Rect::from_min_max(pos2(0.0, 14.0), pos2(36.0, 600.0)); + assert!(d.outlined(column.shrink(1.0)), "the column is outlined"); + let line = Rect::from_x_y_ranges(column.x_range(), (one.bottom() - 2.0)..=(one.bottom() + 2.0)); + assert!(d.filled(line), "with the insertion line under group 1"); + let out = d.release(target); + assert!( + out.actions.contains(&Action::MoveGroup { panel: 5, to: Target::At { anchor: 1, placement: Placement::Group { below: true } } }), + "{:?}", + out.actions + ); + assert_eq!(groups(&d.layout), vec![vec![1], vec![5, 6], vec![2]]); + assert!(first_column(&d.layout).iconic); +} + +/// Every kind of gesture source has a rect, and dragging from it does something. +#[test] +fn hit_rects_cover_every_gesture_source() { + let mut expanded = Column::new(vec![Group::new(vec![1, 2, 3, 4, 5, 6, 7], 0), Group::new(vec![8], 0)], 150.0); + expanded.width = 150.0; + let mut icons = Column::new(vec![Group::new(vec![9], 0)], 240.0); + icons.iconic = true; + let dock = Node::Dock { side: Side::Start, columns: vec![icons, expanded] }; + let stack = Node::Stack { + entries: vec![StackEntry { panel: 10, open: true, height: None }, StackEntry { panel: 11, open: true, height: None }], + }; + let frames = Node::Split { + axis: SplitAxis::Vertical, + size: SplitSize::Ratio(0.5), + first: Box::new(Node::Tabs { panels: vec![0], active: 0 }), + second: Box::new(stack), + }; + let mut window = Floating::single(vec![12], 0, [500.0, 60.0, 220.0, 300.0]); + window.groups.push(Group::new(vec![13], 0)); + let layout = Layout { + root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(200.0), first: Box::new(dock), second: Box::new(frames) }), + floating: vec![window], + }; + let d = DockDriver::new(layout.clone(), Content); + let hits = d.hits(); + let kinds = |f: &dyn Fn(&Hit) -> bool| hits.iter().filter(|(h, _)| f(h)).count(); + let expected: [(&str, &dyn Fn(&Hit) -> bool); 15] = [ + ("tab", &|h| matches!(h, Hit::Tab(_))), + ("drag bar", &|h| matches!(h, Hit::DragBar(_))), + ("border", &|h| matches!(h, Hit::Border(_))), + ("overflow", &|h| matches!(h, Hit::Overflow(_))), + ("column bar", &|h| matches!(h, Hit::ColumnBar(_))), + ("collapse", &|h| matches!(h, Hit::Collapse(_))), + ("stack toggle", &|h| matches!(h, Hit::StackToggle(_))), + ("title", &|h| matches!(h, Hit::Title(12))), + ("close", &|h| matches!(h, Hit::Close(12))), + ("icon", &|h| matches!(h, Hit::Icon(9))), + ("icon grip", &|h| matches!(h, Hit::IconGrip(9))), + ("resize", &|h| matches!(h, Hit::Resize(12, _))), + ("split", &|h| matches!(h, Hit::Divider(Divider::Split(_)))), + ("column divider", &|h| matches!(h, Hit::Divider(Divider::Column(_)))), + ("group divider", &|h| matches!(h, Hit::Divider(Divider::Group(_)))), + ]; + for (name, kind) in expected { + assert!(kinds(kind) > 0, "{name}: {hits:?}"); + } + assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Divider(Divider::Stack(10))))); + assert_eq!(hits.iter().filter(|(h, _)| matches!(h, Hit::Resize(..))).count(), 5); + for (hit, rect) in hits.iter().filter(|(h, _)| !matches!(h, Hit::Overflow(_) | Hit::Collapse(_) | Hit::StackToggle(_) | Hit::Close(_))) { + let mut d = DockDriver::new(layout.clone(), Content); + let from = rect.center(); + let moved = d.hold(from, from + vec2(-30.0, 40.0)); + let dragging = is_dragging::(&d.ctx, d.id); + let released = d.release(from + vec2(-30.0, 40.0)); + assert!(dragging || !moved.actions.is_empty() || !released.actions.is_empty(), "{hit:?} at {rect:?} does nothing"); + } + for (hit, rect) in hits.iter().filter(|(h, _)| matches!(h, Hit::Overflow(_) | Hit::Collapse(_) | Hit::StackToggle(_) | Hit::Close(_))) { + let mut d = DockDriver::new(layout.clone(), Content); + let out = d.click(rect.center()); + let opened = egui::Popup::is_any_open(&d.ctx); + assert!(opened || !out.actions.is_empty(), "{hit:?} at {rect:?} does nothing"); + } +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 6ddeebf66c..85c76545e7 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -7,13 +7,18 @@ pub mod chrome; mod dock_model; +mod hits; mod model; mod render; mod resize; mod surface; mod targets; +#[cfg(any(test, feature = "testing"))] +pub mod testing; mod workspace; +pub use hits::{Divider, Hit, ResizeEdge}; +pub use render::{close_flyout, flyout, open_flyout}; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; pub use surface::{ @@ -32,6 +37,8 @@ mod floating_tests; #[cfg(test)] mod group_tests; #[cfg(test)] +mod iconic_tests; +#[cfg(test)] mod model_tests; #[cfg(test)] mod tests; diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 3d0f7e1a79..fe5d4728e2 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -10,15 +10,11 @@ use egui::{Context, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, p use super::{GroupKind, Renderer}; use crate::docking::{ - Action, Column, Group, GroupDrag, GroupGesture, Node, Profile, Side, Target, + Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Profile, Side, Target, targets::{DockDrop, DockTarget, column_edge, horizontal_line, resolve_dock, usable, vertical_line}, }; use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; -/// Width of an iconic column without a saved width. -const ICONIC_WIDTH: f32 = 36.0; -/// Widest an iconic column gets by dragging its inner edge. -const ICONIC_MAX: f32 = 240.0; /// Width of the »/« button at the outer end of a column bar. const COLLAPSE_WIDTH: f32 = 18.0; @@ -44,8 +40,12 @@ fn side_at(edge: Edge, right_to_left: bool) -> Side { } } -pub(in crate::docking) fn column_width

(column: &Column

) -> f32 { - if column.iconic { column.iconic_width.unwrap_or(ICONIC_WIDTH) } else { column.width } +pub(in crate::docking) fn column_width

(column: &Column

, style: &DockStyle) -> f32 { + if column.iconic { + column.iconic_width.unwrap_or(style.iconic_width).clamp(style.iconic_width, style.iconic_max_width) + } else { + column.width + } } /// Heights of stacked groups in a column body `room` high. Each entry is (minimized, saved @@ -104,7 +104,7 @@ impl Renderer<'_, P> { }; let gap = self.style.gap; let room = (rect.width() - gap - self.node_limits(other).min.x).clamp(0.0, rect.width()); - let width = columns.iter().map(column_width).sum::().clamp(0.0, room); + let width = columns.iter().map(|c| column_width(c, self.style)).sum::().clamp(0.0, room); let (dock, rest) = match edge_of(side, self.style.right_to_left) { Edge::Left => ( Rect::from_min_max(rect.min, pos2(rect.left() + width, rect.bottom())), @@ -141,12 +141,12 @@ impl Renderer<'_, P> { if usable(rect) { ui.painter().rect_filled(rect, 0.0, self.style.background); } - let total: f32 = columns.iter().map(column_width).sum(); + let total: f32 = columns.iter().map(|c| column_width(c, self.style)).sum(); let mut x = outer; let mut drawn = Vec::new(); for (index, column) in columns.iter().enumerate() { let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { continue }; - let width = column_width(column).min((rect.width() - (x - outer).abs()).max(0.0)); + let width = column_width(column, self.style).min((rect.width() - (x - outer).abs()).max(0.0)); let inner = x + inward * width; let column_rect = Rect::from_x_y_ranges(x.min(inner)..=x.max(inner), rect.y_range()); self.column(ui, column, first, column_rect, edge); @@ -161,8 +161,8 @@ impl Renderer<'_, P> { } // Registered after the columns, so the narrow hit areas win at the edges. for (column, first, width, inner) in drawn { - let others = total - column_width(column); - let (lo, hi) = if column.iconic { (ICONIC_WIDTH, ICONIC_MAX) } else { self.column_bounds(column) }; + let others = total - column_width(column, self.style); + let (lo, hi) = if column.iconic { (self.style.iconic_width, self.style.iconic_max_width) } else { self.column_bounds(column) }; let hi = hi.min(room - others).max(lo.min(room - others).max(0.0)); let lo = lo.min(hi); let divider = Rect::from_x_y_ranges((inner - 1.0)..=(inner + 1.0), rect.y_range()); @@ -216,6 +216,9 @@ impl Renderer<'_, P> { let bar = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.column_bar_height).min(rect.bottom()))); self.column_bar(ui, column, first, bar, rect, edge); let body = Rect::from_min_max(pos2(rect.left(), bar.bottom()), rect.max); + if column.iconic && usable(body) { + self.iconic_column(ui, column, body, edge); + } if column.iconic || !usable(body) { ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); return; @@ -404,6 +407,9 @@ impl Renderer<'_, P> { if self.menu_action(ui, &label) { self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic }); } + if self.auto_collapse_item(ui) { + self.output.events.push(DockEvent::ToggleAutoCollapse); + } }); } @@ -411,6 +417,7 @@ impl Renderer<'_, P> { /// covers `pointer`. Covered dock targets take nothing. fn dock_covered(&self, ctx: &Context, pointer: Pos2, moving: Option<&P>) -> bool { self.blockers.iter().any(|r| r.contains(pointer)) + || self.iconic.covers(pointer) || self.layout.floating.iter().any(|window| { let Some(first) = window.panels().next() else { return false }; !moving.is_some_and(|p| window.contains(p)) @@ -486,7 +493,9 @@ impl Renderer<'_, P> { /// The insertion line of a dock target. pub(super) fn paint_dock_line(&self, ctx: &Context, line: Rect) { if usable(line) { - self.preview_painter(ctx).rect_filled(line, 1.0, self.style.accent); + let painter = self.preview_painter(ctx); + self.iconic.outline(&painter, line, self.style); + painter.rect_filled(line, 1.0, self.style.accent); } } } diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs new file mode 100644 index 0000000000..738f065706 --- /dev/null +++ b/crates/ui/src/docking/render/iconic.rs @@ -0,0 +1,328 @@ +//! [D] Iconic columns: one icon per panel, groups apart, and the flyout an icon opens. +//! +//! Behaviour follows VectorCraft `dock.rs` (icon column, flyouts beside it on the canvas side, +//! names when the column is widened) and PhotoCraft `dock.rs` (Auto-Collapse Iconic Panels). + +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Id, Key, Order, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; + +use super::{GroupKind, Renderer, dock::Edge}; +use crate::docking::{ + Column, DockStyle, Group, GroupDrag, GroupGesture, begin_drag, + chrome::{ChromeStyle, FloatingFrame}, + is_dragging, + targets::{DockDrop, DockTarget, horizontal_line, usable}, +}; + +/// Height of the grip above each icon group. +const GRIP: f32 = 6.0; +/// Room between two icon groups, with the separator line in its middle. +const SEPARATOR: f32 = 7.0; +/// Height of a flyout, or of a panel floated from an icon, when nothing else sizes it. +const FLYOUT_HEIGHT: f32 = 320.0; + +/// The panel whose icon opened the flyout of an area. +#[derive(Clone)] +struct Open

(P); + +fn key(area: Id) -> Id { + area.with("flyout") +} + +/// [D] Open the flyout of the group holding `panel`, when that group is in an iconic column. +/// The flyout shows from the next frame on. [`crate::docking::DockArea::raise_panel`] does the +/// same for a panel the Window menu opens. +pub fn open_flyout(ctx: &Context, area_id: Id, panel: P) { + ctx.data_mut(|d| d.insert_temp(key(area_id), Open(panel))); +} + +/// [D] Close the area's flyout. +pub fn close_flyout(ctx: &Context, area_id: Id) { + ctx.data_mut(|d| d.remove::>(key(area_id))); +} + +/// [D] The panel whose icon opened the area's flyout, while one is open. +pub fn flyout(ctx: &Context, area_id: Id) -> Option

{ + ctx.data(|d| d.get_temp::>(key(area_id))).map(|open| open.0) +} + +/// The flyout an iconic column asks for this frame. +struct Request

{ + group: Group

, + /// The icons of the group, where the flyout's top aligns. + icons: Rect, + /// The iconic column, which a press does not close the flyout in. + column: Rect, + edge: Edge, + /// The column's expanded width. + width: f32, +} + +/// Per-frame iconic state of a renderer. +pub(in crate::docking) struct Iconic

{ + auto_collapse: bool, + /// Iconic column bodies drawn this frame, outlined by a drop into them (P9). + columns: Vec, + /// Expanded column width of each panel drawn as an icon: a panel floated from its icon + /// takes it. + widths: Vec<(P, f32)>, + request: Option>, + /// The flyout drawn this frame; it occludes dock targets behind it. + rect: Option, +} + +impl Iconic

{ + pub(in crate::docking) fn new(auto_collapse: bool) -> Self { + Self { auto_collapse, columns: Vec::new(), widths: Vec::new(), request: None, rect: None } + } + + pub(super) fn covers(&self, pointer: Pos2) -> bool { + self.rect.is_some_and(|rect| rect.contains(pointer)) + } + + /// Outline the iconic column an insertion line lies in. + pub(super) fn outline(&self, painter: &egui::Painter, line: Rect, style: &DockStyle) { + if let Some(column) = self.columns.iter().find(|column| column.shrink(1.0).contains(line.center())) { + painter.rect_stroke(column.shrink(1.0), 0.0, Stroke::new(2.0, style.accent), StrokeKind::Inside); + } + } + + pub(super) fn float_width(&self, panel: &P) -> Option { + self.widths.iter().find(|(p, _)| p == panel).map(|(_, width)| *width) + } +} + +impl Renderer<'_, P> { + fn row_height(&self) -> f32 { + self.style.icon_size + 10.0 + } + + fn icon_group_height(&self, group: &Group

) -> f32 { + GRIP + group.panels.len() as f32 * self.row_height() + } + + /// The body of an iconic column: icon groups top to bottom, scrolling when they do not fit. + pub(super) fn iconic_column(&mut self, ui: &mut Ui, column: &Column

, body: Rect, edge: Edge) { + self.iconic.columns.push(body); + for panel in column.groups.iter().flat_map(|g| g.panels.iter()) { + self.iconic.widths.push((panel.clone(), column.width)); + } + // Opening a panel from the Window menu opens its flyout (U3). + if let Some(panel) = self.activation.as_ref().filter(|p| column.groups.iter().any(|g| g.panels.contains(p))) { + open_flyout(ui.ctx(), self.id, panel.clone()); + } + let total: f32 = column.groups.iter().map(|g| self.icon_group_height(g)).sum::() + + column.groups.len().saturating_sub(1) as f32 * SEPARATOR; + if total > body.height() + 0.5 { + let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { return }; + let mut child = + ui.new_child(UiBuilder::new().id_salt(("icon-column", first)).max_rect(body).layout(egui::Layout::top_down(egui::Align::Min))); + child.set_clip_rect(body.intersect(ui.clip_rect())); + egui::ScrollArea::vertical() + .id_salt(self.id.with(("icon-scroll", first))) + .auto_shrink([false, false]) + .scroll_source(egui::scroll_area::ScrollSource::SCROLL_BAR | egui::scroll_area::ScrollSource::MOUSE_WHEEL) + .show(&mut child, |ui| { + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), total), Sense::hover()); + self.icon_groups(ui, column, area, body, edge); + }); + } else { + self.icon_groups(ui, column, body, body, edge); + } + } + + /// Icon groups in `area` (the scrolled content when the column scrolls), their drop bands + /// clipped to the visible `view`. + fn icon_groups(&mut self, ui: &mut Ui, column: &Column

, area: Rect, view: Rect, edge: Edge) { + let open = flyout::

(ui.ctx(), self.id); + let labels = view.width() >= self.style.iconic_label_width; + let xs = view.x_range(); + let mut top = area.top(); + let mut bands = Vec::new(); + for (index, group) in column.groups.iter().enumerate() { + let Some(first) = group.panels.first() else { continue }; + if index > 0 { + let y = top + SEPARATOR * 0.5; + ui.painter().with_clip_rect(view).hline(area.x_range().shrink(4.0), y, self.style.border); + top += SEPARATOR; + } + let rect = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), self.icon_group_height(group))); + let grip = Rect::from_min_size(rect.min, vec2(rect.width(), GRIP)); + self.icon_grip(ui, group, grip, column.width); + let showing = open.as_ref().filter(|p| group.panels.contains(p)); + let mut y = grip.bottom(); + for panel in &group.panels { + let cell = Rect::from_min_size(pos2(rect.left(), y), vec2(rect.width(), self.row_height())); + self.icon(ui, panel, cell, labels, showing); + y = cell.bottom(); + } + // The state again: a click above may have opened or closed this group's flyout. + if flyout::

(ui.ctx(), self.id).is_some_and(|p| group.panels.contains(&p)) { + self.iconic.request = Some(Request { group: group.clone(), icons: rect.intersect(view), column: view, edge, width: column.width }); + } + bands.push((first.clone(), rect)); + top = rect.bottom(); + } + // P9: the upper half of an icon group inserts above it, the lower half and the room + // under the last group below it. The line sits on the group's edge. + let count = bands.len(); + for (index, (anchor, rect)) in bands.into_iter().enumerate() { + let middle = rect.center().y; + let upper_top = if index == 0 { view.top() } else { rect.top() - SEPARATOR * 0.5 }; + let lower_bottom = if index + 1 == count { view.bottom() } else { rect.bottom() + SEPARATOR * 0.5 }; + for (below, ys, line) in [(false, upper_top..=middle, rect.top()), (true, middle..=lower_bottom, rect.bottom())] { + let band = Rect::from_x_y_ranges(xs, ys).intersect(view); + if usable(band) { + let line = horizontal_line(line.clamp(view.top() + 2.0, view.bottom() - 2.0), xs); + self.dock_targets.push(DockDrop { target: DockTarget::GroupBand { anchor: anchor.clone(), below }, band, line }); + } + } + } + } + + /// The grip above an icon group drags the whole group (S8). + fn icon_grip(&mut self, ui: &mut Ui, group: &Group

, grip: Rect, width: f32) { + let Some(first) = group.panels.first() else { return }; + let movable = group.panels.iter().all(|p| self.permissions(p).movable); + let response = ui.interact(grip, self.id.with(("icon-grip", Some(first))), Sense::drag()); + let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response }; + self.register_interaction(ui.ctx(), response.id); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label)); + let color = if response.hovered() || response.dragged() { self.style.text } else { self.style.inactive_text }; + let painter = ui.painter().with_clip_rect(grip.intersect(ui.clip_rect())); + painter.hline((grip.center().x - 8.0)..=(grip.center().x + 8.0), grip.center().y - 1.0, Stroke::new(1.0, color)); + painter.hline((grip.center().x - 8.0)..=(grip.center().x + 8.0), grip.center().y + 1.0, Stroke::new(1.0, color)); + if movable && response.drag_started() { + let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center()); + let height = group.height.filter(|h| h.is_finite()).unwrap_or(FLYOUT_HEIGHT); + let source = Rect::from_min_size(grip.min, vec2(width.max(self.style.min_pane), height.max(self.style.tab_height))); + let drag = GroupDrag { + panel: first.clone(), + original: [source.left(), source.top(), source.width(), source.height()], + gesture: GroupGesture::Group, + members: group.panels.clone(), + origin, + source, + }; + ui.ctx().data_mut(|d| d.insert_temp(self.id.with("group-drag"), drag)); + close_flyout::

(ui.ctx(), self.id); + } + } + + /// One panel's icon: a click opens, switches or closes the flyout (M5); a drag moves the + /// panel (S7). `showing` is the panel whose icon opened this group's flyout. + fn icon(&mut self, ui: &mut Ui, panel: &P, cell: Rect, labels: bool, showing: Option<&P>) { + let movable = self.permissions(panel).movable; + let label = self.label_of(panel); + let response = ui.interact(cell, self.id.with(("icon", panel)), if movable { Sense::click_and_drag() } else { Sense::click() }); + self.register_interaction(ui.ctx(), response.id); + let current = showing == Some(panel); + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), current, &label)); + let painter = ui.painter().with_clip_rect(cell.intersect(ui.clip_rect())); + if current || response.hovered() { + painter.rect_filled(cell.shrink(2.0), 3.0, self.style.active_background); + } + if response.has_focus() { + painter.rect_stroke(cell.shrink(1.0), 3.0, Stroke::new(1.0, self.style.accent), StrokeKind::Inside); + } + let size = self.style.icon_size; + let inset = ((self.style.iconic_width - size) * 0.5).max(2.0); + let icon = Rect::from_min_size(pos2(cell.left() + inset, cell.center().y - size * 0.5), vec2(size, size)); + let color = if current { self.style.text } else { self.style.inactive_text }; + if let Some(source) = self.content.icon(panel) { + egui::Image::new(source).tint(color).paint_at(ui, icon.intersect(cell)); + } else { + let initial: String = label.chars().next().into_iter().flat_map(char::to_uppercase).collect(); + painter.rect_stroke(icon, 3.0, Stroke::new(1.0, color), StrokeKind::Inside); + painter.text(icon.center(), egui::Align2::CENTER_CENTER, initial, self.style.font.clone(), color); + } + if labels { + let text = self.content.label(ui, panel, &label, &self.style.font, color); + let galley = text.into_galley(ui, Some(egui::TextWrapMode::Truncate), (cell.right() - icon.right() - 12.0).max(0.0), self.style.font.clone()); + painter.galley(pos2(icon.right() + 6.0, cell.center().y - galley.size().y * 0.5), galley, color); + } else if response.hovered() && !response.dragged() { + response.clone().on_hover_text(&label); + } + if response.clicked() { + if current { + close_flyout::

(ui.ctx(), self.id); + } else { + if showing.is_none() { + ui.ctx().move_to_top(FloatingFrame::layer(self.id.with("flyout"))); + } + open_flyout(ui.ctx(), self.id, panel.clone()); + self.output.actions.push(crate::docking::Action::Activate { panel: panel.clone() }); + self.output.focused = Some(panel.clone()); + } + } + if movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), cell) { + close_flyout::

(ui.ctx(), self.id); + } + } + + /// The Auto-Collapse Iconic Panels item of a column menu (U1): true when chosen. + pub(super) fn auto_collapse_item(&mut self, ui: &mut Ui) -> bool { + let logical = self.style.auto_collapse_label.clone(); + let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text); + let mut on = self.iconic.auto_collapse; + let response = ui.add(egui::Checkbox::new(&mut on, text)); + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), self.iconic.auto_collapse, &logical)); + if response.clicked() { + ui.close(); + } + response.clicked() + } + + /// Draw the flyout an iconic column asked for, beside the column on the canvas side, or + /// forget a flyout whose group is no longer iconic. With Auto-Collapse, Escape or a press + /// outside the flyout and its column closes it. + pub(in crate::docking) fn flyout(&mut self, ctx: &Context) { + let Some(request) = self.iconic.request.take() else { + close_flyout::

(ctx, self.id); + return; + }; + let Some(active) = request.group.active_panel().cloned() else { return }; + let id = self.id.with("flyout"); + if self.iconic.auto_collapse && self.flyout_dismissed(ctx, id, request.column) { + close_flyout::

(ctx, self.id); + return; + } + let screen = ctx.content_rect(); + let bounds = self.workspace.intersect(screen); + let width = request.width.max(self.style.min_pane).min(bounds.width()); + let height = self + .content + .floating_size(&active) + .map(|size| size.y) + .or(request.group.height) + .filter(|h| h.is_finite() && *h > 0.0) + .unwrap_or(FLYOUT_HEIGHT) + .max(self.style.tab_height + self.style.min_pane) + .min(bounds.height()); + let left = match request.edge { + Edge::Left => request.column.right(), + Edge::Right => request.column.left() - width, + }; + let top = request.icons.top().min(bounds.bottom() - height).max(bounds.top()); + let rect = Rect::from_min_size(pos2(left, top), vec2(width, height)); + let style = ChromeStyle::from_dock(self.style); + let group = request.group; + let response = FloatingFrame::new(id, rect).bounds(bounds).resizable(false).show(ctx, &style, |ui, rect| { + self.group(ui, &group.panels, group.active, false, rect, GroupKind::Dock); + }); + self.iconic.rect = Some(response.rect); + } + + /// Escape (outside a drag) or a primary press outside the flyout, its column and any menu. + fn flyout_dismissed(&self, ctx: &Context, id: Id, column: Rect) -> bool { + let escape = !is_dragging::

(ctx, self.id) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)); + let press = ctx.input(|i| i.pointer.primary_pressed().then(|| i.pointer.press_origin()).flatten()); + let outside = press.is_some_and(|pos| { + let inside = ctx.memory(|m| m.area_rect(id)).is_some_and(|r| r.contains(pos)) || column.contains(pos); + let menu = ctx.layer_id_at(pos).is_some_and(|layer| matches!(layer.order, Order::Foreground | Order::Tooltip)); + !inside && !menu + }); + escape || outside + } +} diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index b8179c378b..613bf689c1 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -9,6 +9,7 @@ use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node mod dock; mod floating; mod frame; +mod iconic; #[cfg(feature = "native-windows")] mod native; @@ -16,6 +17,9 @@ pub(in crate::docking) use frame::{FrameState, view}; pub(in crate::docking) use group::GroupKind; +pub(in crate::docking) use iconic::Iconic; +pub use iconic::{close_flyout, flyout, open_flyout}; + pub(in crate::docking) use floating::RESIZE_HANDLES; mod group; mod preview; @@ -35,6 +39,8 @@ pub(super) struct Renderer<'a, P> { pub(super) owned_interactions: Vec, pub(super) output: DockOutput

, pub(super) frame: FrameState

, + /// [D] Flyout and iconic column state for this frame. + pub(super) iconic: Iconic

, } impl Renderer<'_, P> { @@ -123,6 +129,7 @@ impl Renderer<'_, P> { self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect, None); let collapse = Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max); let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click()); + self.register_interaction(ui.ctx(), response.id); response.widget_info(|| { egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), entry.open, self.label_of(&entry.panel)) }); @@ -222,7 +229,7 @@ pub(in crate::docking) fn stripless

(panels: &[P], content: &dyn DockContent

(node: &Node

, style: &DockStyle, content: &dyn DockContent

) -> PanelLimits { match node { Node::Dock { columns, .. } => { - let width: f32 = columns.iter().map(dock::column_width).sum(); + let width: f32 = columns.iter().map(|c| dock::column_width(c, style)).sum(); PanelLimits { min: vec2(width.clamp(style.min_pane, 1_000_000.0), style.min_pane), ..PanelLimits::default() } } Node::Tabs { panels, .. } => { diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 6d982c8886..734be291c4 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -269,7 +269,7 @@ impl Renderer<'_, P> { if let Some(size) = self.content.floating_size(panel).filter(|s| s.is_finite() && s.x > 0.0 && s.y > 0.0) { return size; } - let mut size = source; + let mut size = self.iconic.float_width(panel).map_or(source, |width| vec2(width, DOCKED_FLOAT_HEIGHT)); if matches!(self.layout.place(panel), Some(Place::Dock { .. })) { size.y = size.y.min(DOCKED_FLOAT_HEIGHT); } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 141f6f5d6d..8b6a4a778d 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -59,6 +59,16 @@ pub struct DockStyle { pub seam_band: f32, /// [D] Width of the band along the docked area's left and right edges that makes a new dock. pub new_dock_band: f32, + /// [D] Side of a panel icon in an iconic column; each icon row is 10 pt taller. + pub icon_size: f32, + /// [D] Width of an iconic column without a saved width, and the narrowest it gets. + pub iconic_width: f32, + /// [D] Widest an iconic column gets by dragging its inner edge. + pub iconic_max_width: f32, + /// [D] An iconic column at least this wide shows panel names beside the icons. + pub iconic_label_width: f32, + /// [D] Column menu item that toggles Auto-Collapse Iconic Panels. + pub auto_collapse_label: String, /// [D] Lay docks out right to left: `Side::Start` is the right edge. egui has no app-wide /// layout direction, so the host sets this from its locale. Frame splits keep their sides. pub right_to_left: bool, @@ -123,6 +133,11 @@ impl DockStyle { column_bar_height: 14.0, seam_band: 8.0, new_dock_band: 12.0, + icon_size: 20.0, + iconic_width: 36.0, + iconic_max_width: 240.0, + iconic_label_width: 96.0, + auto_collapse_label: "Auto-Collapse Iconic Panels".into(), right_to_left: false, move_column_label: "Move panel column".into(), collapse_to_icons_label: "Collapse to Icons".into(), @@ -153,9 +168,14 @@ impl DockStyle { self.column_bar_height, self.seam_band, self.new_dock_band, + self.icon_size, + self.iconic_width, + self.iconic_max_width, + self.iconic_label_width, ] .iter() .all(|v| v.is_finite() && (0.0..=4096.0).contains(v)) + && self.iconic_width <= self.iconic_max_width && self.tab_height > 0.0 && self.font.size > 0.0 } @@ -187,6 +207,9 @@ pub enum DockEvent

{ /// Maximize Frame: maximize the frame holding `panel`, or restore it when it is the one /// passed to [`DockArea::maximized`]. ToggleMaximize { panel: P }, + /// [D] Auto-Collapse Iconic Panels was chosen in a column menu. The host flips its + /// preference and passes it to [`DockArea::auto_collapse_iconic`]. + ToggleAutoCollapse, } /// Which panels [`DockArea::hide_panels`] hides. Protected panels always stay. @@ -448,11 +471,19 @@ pub struct DockArea<'a, P = ()> { blockers: Vec, maximized: Option

, hide: HidePanels<'a, P>, + auto_collapse: bool, } impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { pub fn new(id: Id) -> Self { - Self { id, activation: None, blockers: Vec::new(), maximized: None, hide: HidePanels::None } + Self { id, activation: None, blockers: Vec::new(), maximized: None, hide: HidePanels::None, auto_collapse: true } + } + + /// [D] Auto-Collapse Iconic Panels (default on): a flyout closes on Escape or a press + /// outside it. Off, it stays open until its icon or another icon is clicked. + pub fn auto_collapse_iconic(mut self, on: bool) -> Self { + self.auto_collapse = on; + self } /// Maximize Frame: the docked frame holding `panel` fills the area; other frames and @@ -620,14 +651,17 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { owned_interactions: Vec::new(), output: DockOutput::default(), frame, + iconic: super::render::Iconic::new(self.auto_collapse), }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); ui.allocate_rect(rect, Sense::hover()); } + renderer.flyout(ui.ctx()); renderer.floating(ui.ctx(), &view.floating); renderer.finish_group_drag(ui.ctx()); renderer.finish_drag(ui.ctx()); + super::hits::record(ui.ctx(), self.id, &view, &renderer.owned_interactions); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); renderer.output } diff --git a/crates/ui/src/docking/testing.rs b/crates/ui/src/docking/testing.rs new file mode 100644 index 0000000000..647024709c --- /dev/null +++ b/crates/ui/src/docking/testing.rs @@ -0,0 +1,222 @@ +//! Drive a [`DockArea`] with real egui input in application tests (feature `testing`). +//! +//! ```ignore +//! let mut driver = DockDriver::new(app_layout(), Panels::default()); +//! let bar = driver.hit(&Hit::DragBar(PanelId::Layers)).unwrap(); +//! driver.drag(bar.center(), egui::pos2(4.0, 300.0)); +//! assert!(driver.layout.dock_path(Side::Start).is_some()); +//! ``` + +use std::{fmt::Debug, hash::Hash}; + +use egui::{Context, Event, Id, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, UiBuilder, epaint::ClippedShape, vec2}; + +use super::{DockArea, DockContent, DockOutput, DockStyle, Hit, Layout}; + +/// Pointer travel that starts a drag before moving to its destination. +const NUDGE: egui::Vec2 = egui::Vec2::new(8.0, 6.0); + +type StyleFn = Box; + +/// A [`DockArea`] in a headless egui context, with its layout and content. Each frame advances +/// the clock by 1/60 s, so double-clicks register. [`Self::step`] applies what a frame emits, +/// the way an application's command path would. +pub struct DockDriver { + pub ctx: Context, + pub layout: Layout

, + pub content: C, + /// The area's id, for [`DockArea::hit_rects`] and the free docking functions. + pub id: Id, + /// The window, 800x600 by default. + pub screen: Rect, + /// Where the area draws inside the window; the whole window by default. + pub area: Rect, + /// Whether the window has focus. Losing it cancels gestures (C2). + pub focused: bool, + /// Modifiers held for the following events. + pub modifiers: Modifiers, + /// Passed to [`DockArea::auto_collapse_iconic`]. + pub auto_collapse: bool, + /// Passed to [`DockArea::maximized`]. + pub maximized: Option

, + /// Passed to [`DockArea::raise_panel`] on the next frame only. + pub raise: Option

, + style: Option, + shapes: Vec, + time: f64, +} + +impl> DockDriver { + /// A driver whose first frames have settled, so every control has its rect. + pub fn new(layout: Layout

, content: C) -> Self { + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut driver = Self { + ctx: Context::default(), + layout, + content, + id: Id::new("dock-driver"), + screen, + area: screen, + focused: true, + modifiers: Modifiers::NONE, + auto_collapse: true, + maximized: None, + raise: None, + style: None, + shapes: Vec::new(), + time: 0.0, + }; + driver.settle(); + driver + } + + /// Adjust the style each frame, after [`DockStyle::from_ui`]. Settles again. + pub fn with_style(mut self, style: impl Fn(&mut DockStyle) + 'static) -> Self { + self.style = Some(Box::new(style)); + self.settle(); + self + } + + /// Draw in `area` of the window. Settles again. + pub fn with_area(mut self, area: Rect) -> Self { + self.area = area; + self.settle(); + self + } + + /// Render one frame with `events` and return its output. Nothing is applied. + pub fn frame(&mut self, events: Vec) -> DockOutput

{ + let mut output = DockOutput::default(); + self.time += 1.0 / 60.0; + let input = RawInput { + screen_rect: Some(self.screen), + events: std::iter::once(Event::ModifiersChanged(self.modifiers)).chain(events).collect(), + focused: self.focused, + time: Some(self.time), + ..Default::default() + }; + let (layout, content, area, id) = (&self.layout, &mut self.content, self.area, self.id); + let (style_fn, maximized, raise, auto) = (&self.style, self.maximized.clone(), self.raise.take(), self.auto_collapse); + let mut full = self.ctx.run_ui(input, |ui| { + let mut style = DockStyle::from_ui(ui); + if let Some(adjust) = style_fn { + adjust(&mut style); + } + ui.scope_builder(UiBuilder::new().max_rect(area), |ui| { + let mut dock = DockArea::new(id).maximized(maximized.clone()).auto_collapse_iconic(auto); + if let Some(panel) = raise.clone() { + dock = dock.raise_panel(panel); + } + output = dock.show_content(ui, layout, &style, content); + }); + }); + full.textures_delta.clear(); + self.shapes = full.shapes; + output + } + + /// Render one frame and apply its actions, all or none, with the content's permissions. A + /// rejected batch is reported in the output's `error`. + pub fn step(&mut self, events: Vec) -> DockOutput

{ + let mut output = self.frame(events); + if output.error.is_none() + && let Err(error) = self.layout.apply_all(output.actions.clone(), |p| self.content.permissions(p)) + { + output.error = Some(error); + } + output + } + + /// Empty frames until moved widgets report their rects; egui reports them a frame late. + pub fn settle(&mut self) { + for _ in 0..3 { + self.step(Vec::new()); + } + } + + pub fn move_to(&mut self, pos: Pos2) -> DockOutput

{ + self.step(vec![Event::PointerMoved(pos)]) + } + + pub fn press(&mut self, pos: Pos2) -> DockOutput

{ + self.step(vec![Event::PointerMoved(pos), self.button(pos, true)]) + } + + pub fn release(&mut self, pos: Pos2) -> DockOutput

{ + self.step(vec![Event::PointerMoved(pos), self.button(pos, false)]) + } + + /// Press and release at `pos`; the output is the release frame's. + pub fn click(&mut self, pos: Pos2) -> DockOutput

{ + self.press(pos); + self.release(pos) + } + + /// Press at `from`, move past the drag threshold and on to `to`, without releasing. + pub fn hold(&mut self, from: Pos2, to: Pos2) -> DockOutput

{ + self.press(from); + self.move_to(from + NUDGE); + self.move_to(to) + } + + /// A whole drag; the output is the release frame's. + pub fn drag(&mut self, from: Pos2, to: Pos2) -> DockOutput

{ + self.hold(from, to); + self.release(to) + } + + /// Press and release `key` in one frame. + pub fn key(&mut self, key: Key) -> DockOutput

{ + let modifiers = self.modifiers; + self.step(vec![ + Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }, + Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, + ]) + } + + /// Give or take the window's focus for this and the following frames. + pub fn focus(&mut self, focused: bool) -> DockOutput

{ + self.focused = focused; + self.step(vec![Event::WindowFocused(focused)]) + } + + /// The pointer leaves the window. + pub fn leave(&mut self) -> DockOutput

{ + self.step(vec![Event::PointerGone]) + } + + /// Every gesture source of the last frame. + pub fn hits(&self) -> Vec<(Hit

, Rect)> { + DockArea::

::hit_rects(&self.ctx, self.id) + } + + /// The rect of one gesture source in the last frame. + pub fn hit(&self, hit: &Hit

) -> Option { + self.hits().into_iter().find(|(h, _)| h == hit).map(|(_, rect)| rect) + } + + /// The shapes of the last frame. + pub fn shapes(&self) -> &[ClippedShape] { + &self.shapes + } + + /// Whether the last frame filled `rect` (an insertion line or a split preview). + pub fn filled(&self, rect: Rect) -> bool { + self.shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Rect(shape) => shape.rect == rect && shape.fill != egui::Color32::TRANSPARENT, + _ => false, + }) + } + + /// Whether the last frame outlined `rect` without filling it. + pub fn outlined(&self, rect: Rect) -> bool { + self.shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Rect(shape) => shape.rect == rect && shape.fill == egui::Color32::TRANSPARENT && shape.stroke.width > 0.0, + _ => false, + }) + } + + fn button(&self, pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: self.modifiers } + } +} From 0d350d8e11797cb8c46e8acf7c92af890e5952a0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 11:59:33 +0000 Subject: [PATCH 27/94] docking: DockCommand for the shared command ids and the ui.dock operations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DockCommand

deserializes a control command's params, with its id under "command", and maps it to layout actions applied all or none. It covers the window.panel.* and window.workspace.* ids, the raw {action} form, and the ui.dock {operation, …} shape of LightCraft, PDFCraft, CADCraft and SoundCraft (open, close, activate, float, moveFloating, move, setStackOpen, resizeStack, resizeSplit), so their parsers can go without a protocol change. Named workspaces and Reset stay with the application. tests/docking_workflows.rs loads every v1 fixture, docks groups by their bars into a new dock, a bottom band and a seam, collapses and expands the column, floats it by command, drags it back, and checks the layout reads back as written. --- crates/ui/src/docking/command.rs | 476 +++++++++++++++++++++++++ crates/ui/src/docking/command_tests.rs | 267 ++++++++++++++ crates/ui/src/docking/mod.rs | 6 + crates/ui/tests/docking_workflows.rs | 183 ++++++++++ 4 files changed, 932 insertions(+) create mode 100644 crates/ui/src/docking/command.rs create mode 100644 crates/ui/src/docking/command_tests.rs diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs new file mode 100644 index 0000000000..7b7b7d2066 --- /dev/null +++ b/crates/ui/src/docking/command.rs @@ -0,0 +1,476 @@ +//! The shared docking command vocabulary (feature `serde`). +//! +//! Applications deserialize a control command's JSON params, with its id under `"command"`, +//! into [`DockCommand`] and apply it. craft-ui does not depend on `serde_json`. +//! +//! ```ignore +//! let mut params = params.clone(); +//! params["command"] = json!(id); +//! let command: DockCommand = serde_json::from_value(params)?; +//! command.apply(&mut app.workspace, |p| app.permissions(p))?; +//! ``` + +use std::{collections::HashSet, hash::Hash}; + +use serde::{Deserialize, Deserializer, Serialize}; + +use super::{Action, DockError, Layout, Permissions, Placement, Side, Target, Workspace, Zone, dock_model::Place}; +use crate::layout::SplitSize; + +/// Where a panel floats when a command gives no position or size. +const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0]; + +/// A docking command, tagged by its control id under `"command"`. +/// +/// Ids and params (`?` marks optional ones): +/// +/// | Id | Params | +/// |---|---| +/// | `window.panel.layout` | `{action}`: a serialized [`Action`] | +/// | `window.panel.move` | `{panel, anchor, zone?, before?, group?, placement?}` | +/// | `window.panel.float` | `{panel, x?, y?, width?, height?, group?, column?}` | +/// | `window.panel.dock` | `{panel, anchor?, zone?, before?, group?, column?, side?}` | +/// | `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` | +/// | `window.panel.minimize` | `{panel, minimized?}`; without `minimized` it toggles | +/// | `window.panel.iconic` | `{panel, iconic?}`; without `iconic` it toggles | +/// | `window.panel.window` | `{panel, native?}` (desktop) | +/// | `window.workspace`, `.new`, `.delete` | `{name}` | +/// | `window.workspace.reset`, `ui.dock.reset` | `{}` | +/// | `window.workspace.lock` | `{locked?}`; without `locked` it toggles | +/// | `ui.dock` | `{action}`, or `{operation, …}`, see [`DockOperation`] | +/// +/// `zone` is `tab` (the default for `move` and `dock`), `center`, `left`, `right`, `top`, +/// `bottom`, `above` or `below` (a new group in a dock column or floating stack). `before` +/// names the tab to insert before; `null` appends. `group` moves the panel's whole group, +/// `column` its dock column. `side` is `Start` or `End`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "command", bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))] +#[non_exhaustive] +pub enum DockCommand

{ + #[serde(rename = "window.panel.layout")] + Layout { action: Action

}, + #[serde(rename = "window.panel.move")] + Move { + panel: P, + anchor: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + zone: Option, + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + before: Option>, + #[serde(default)] + group: bool, + /// A serialized [`Placement`]; it takes precedence over `zone` and `before`. + #[serde(default, skip_serializing_if = "Option::is_none")] + placement: Option>, + }, + #[serde(rename = "window.panel.float")] + Float { + panel: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + x: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + y: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + height: Option, + #[serde(default)] + group: bool, + #[serde(default)] + column: bool, + }, + /// To `anchor`; else to a new column of the dock on `side` (a new dock when it has none); + /// else a floating panel joins the first dock group (or frame) as a tab, and a docked one + /// stays. A hidden panel without `anchor` and `side` is shown at its last location. + #[serde(rename = "window.panel.dock")] + Dock { + panel: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + anchor: Option

, + #[serde(default, skip_serializing_if = "Option::is_none")] + zone: Option, + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + before: Option>, + #[serde(default)] + group: bool, + #[serde(default)] + column: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + side: Option, + }, + /// Select a panel; a hidden one is shown at its last location first. + #[serde(rename = "window.panel.activate")] + Activate { panel: P }, + #[serde(rename = "window.panel.close")] + Close { panel: P }, + #[serde(rename = "window.panel.closeGroup")] + CloseGroup { panel: P }, + #[serde(rename = "window.panel.closeOthers")] + CloseOthers { panel: P }, + #[serde(rename = "window.panel.minimize")] + Minimize { + panel: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + minimized: Option, + }, + #[serde(rename = "window.panel.iconic")] + Iconic { + panel: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + iconic: Option, + }, + /// Move the panel's floating window to its own OS window (`native`, the default) or back. + /// A docked panel's group floats first. + #[serde(rename = "window.panel.window")] + Window { + panel: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + native: Option, + }, + /// Switch to a named workspace. The application owns named workspaces. + #[serde(rename = "window.workspace")] + Workspace { name: String }, + #[serde(rename = "window.workspace.new")] + NewWorkspace { name: String }, + #[serde(rename = "window.workspace.delete")] + DeleteWorkspace { name: String }, + /// Reset the current workspace to its saved or built-in arrangement (application-owned). + #[serde(rename = "window.workspace.reset", alias = "ui.dock.reset")] + ResetWorkspace {}, + #[serde(rename = "window.workspace.lock")] + Lock { + #[serde(default, skip_serializing_if = "Option::is_none")] + locked: Option, + }, + /// The `ui.dock` shape of LightCraft, PDFCraft, CADCraft and SoundCraft. + #[serde(rename = "ui.dock")] + UiDock(UiDock

), +} + +/// `ui.dock` params: a raw action, or an operation. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged, bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))] +pub enum UiDock

{ + Action { action: Action

}, + Operation(DockOperation

), +} + +/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone` +/// (default `center`) and `before`, which only applies to a centre move. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "operation", rename_all = "camelCase", bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))] +#[non_exhaustive] +pub enum DockOperation

{ + /// Show a panel at its last location and select it. + Open { panel: P }, + Close { panel: P }, + Activate { panel: P }, + Float { panel: P, rect: [f32; 4] }, + MoveFloating { panel: P, rect: [f32; 4] }, + Move { + panel: P, + target: P, + #[serde(default, skip_serializing_if = "Option::is_none")] + zone: Option, + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + before: Option>, + }, + SetStackOpen { panel: P, open: bool }, + /// `height` is required; `null` clears it. + ResizeStack { + panel: P, + #[serde(deserialize_with = "required")] + height: Option, + }, + ResizeSplit { path: Vec, size: SplitSize }, +} + +/// A drop zone by name, as control protocols write it. PascalCase [`Zone`] names also parse. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ZoneName { + Tab, + #[serde(alias = "Center")] + Center, + #[serde(alias = "Left")] + Left, + #[serde(alias = "Right")] + Right, + #[serde(alias = "Top")] + Top, + #[serde(alias = "Bottom")] + Bottom, + Above, + Below, +} + +/// A present field, `null` included: `Some(None)` for `null`, `None` when absent. +fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result, D::Error> { + T::deserialize(deserializer).map(Some) +} + +/// A required field that may be `null`. +fn required<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result { + T::deserialize(deserializer) +} + +/// `zone` and `before` as a placement. `default` is the zone when none is given. +fn placement(zone: Option, before: &Option>, default: ZoneName) -> Result, DockError> { + let before = before.clone(); + Ok(match (zone.unwrap_or(default), before) { + (ZoneName::Tab | ZoneName::Center, Some(before)) => Placement::Tab { before }, + (ZoneName::Tab, None) => Placement::Tab { before: None }, + (ZoneName::Center, None) => Placement::Split(Zone::Center), + (_, Some(_)) => return Err(DockError::InvalidPlacement), + (ZoneName::Left, None) => Placement::Split(Zone::Left), + (ZoneName::Right, None) => Placement::Split(Zone::Right), + (ZoneName::Top, None) => Placement::Split(Zone::Top), + (ZoneName::Bottom, None) => Placement::Split(Zone::Bottom), + (ZoneName::Above, None) => Placement::Group { below: false }, + (ZoneName::Below, None) => Placement::Group { below: true }, + }) +} + +/// How much of the layout a command moves. +#[derive(Clone, Copy)] +enum Unit { + Panel, + Group, + Column, +} + +impl Unit { + fn of(group: bool, column: bool) -> Self { + if column { + Self::Column + } else if group { + Self::Group + } else { + Self::Panel + } + } + + /// The action that moves this unit of `panel` to `to`. A floating panel's column is its + /// whole window. + fn to(self, layout: &Layout

, panel: &P, to: Target

) -> Result, DockError> { + let floating = matches!(layout.place(panel), Some(Place::Floating { .. })); + let panel = panel.clone(); + Ok(match (self, to) { + (Self::Panel, Target::At { anchor, placement }) => Action::Move { panel, anchor, placement }, + (Self::Panel, _) => return Err(DockError::InvalidPlacement), + (Self::Group, to) => Action::MoveGroup { panel, to }, + (Self::Column, to) if floating => Action::MoveWindow { panel, to }, + (Self::Column, to) => Action::MoveColumn { panel, to }, + }) + } +} + +impl

DockCommand

{ + /// Every command id, for an application's command registry. + pub const IDS: &'static [&'static str] = &[ + "window.panel.layout", + "window.panel.move", + "window.panel.float", + "window.panel.dock", + "window.panel.activate", + "window.panel.close", + "window.panel.closeGroup", + "window.panel.closeOthers", + "window.panel.minimize", + "window.panel.iconic", + "window.panel.window", + "window.workspace", + "window.workspace.new", + "window.workspace.delete", + "window.workspace.reset", + "window.workspace.lock", + "ui.dock", + "ui.dock.reset", + ]; + + /// Named workspaces and Reset belong to the application, which handles these commands + /// before [`Self::apply`]. + pub fn is_app_owned(&self) -> bool { + matches!(self, Self::Workspace { .. } | Self::NewWorkspace { .. } | Self::DeleteWorkspace { .. } | Self::ResetWorkspace {}) + } +} + +impl DockCommand

{ + /// The layout actions this command makes on `workspace`, to apply all or none. + /// Showing a hidden panel and Lock change more than the layout, and named workspaces + /// belong to the application: those return [`DockError::NotAllowed`]; use [`Self::apply`]. + /// A panel or anchor that is not shown returns [`DockError::MissingPanel`] or + /// [`DockError::MissingTarget`]. + pub fn to_actions(&self, workspace: &Workspace

) -> Result>, DockError> { + let layout = &workspace.layout; + let shown = |panel: &P| if layout.contains(panel) { Ok(()) } else { Err(DockError::MissingPanel) }; + let one = |action: Action

| Ok(vec![action]); + match self { + Self::Layout { action } | Self::UiDock(UiDock::Action { action }) => one(action.clone()), + Self::Move { panel, anchor, zone, before, group, placement: given } => { + shown(panel)?; + let placement = match given { + Some(placement) => placement.clone(), + None => placement(*zone, before, ZoneName::Tab)?, + }; + one(Unit::of(*group, false).to(layout, panel, Target::At { anchor: anchor.clone(), placement })?) + } + Self::Float { panel, x, y, width, height, group, column } => { + shown(panel)?; + let given = [*x, *y, *width, *height]; + let window = layout.floating.iter().find(|w| w.contains(panel)).map(|w| w.rect); + let rect = |base: [f32; 4]| { + let mut rect = base; + for (value, given) in rect.iter_mut().zip(given) { + *value = given.unwrap_or(*value); + } + rect + }; + let any = given.iter().any(Option::is_some); + match (Unit::of(*group, *column), window) { + (Unit::Panel, Some(base)) if layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1) => { + one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }) + } + (Unit::Panel, _) => one(Action::Float { panel: panel.clone(), rect: rect(DEFAULT_FLOAT) }), + (Unit::Column, Some(base)) => one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }), + (unit, _) => one(unit.to(layout, panel, Target::Float { rect: any.then(|| rect(DEFAULT_FLOAT)) })?), + } + } + Self::Dock { panel, anchor, zone, before, group, column, side } => { + shown(panel)?; + let unit = Unit::of(*group, *column); + if let Some(anchor) = anchor { + let placement = placement(*zone, before, ZoneName::Tab)?; + return one(unit.to(layout, panel, Target::At { anchor: anchor.clone(), placement })?); + } + if let Some(side) = side { + let to = match last_column(layout, *side) { + Some(anchor) => Target::At { anchor, placement: Placement::Column { after: true } }, + None => Target::NewDock { side: *side }, + }; + let unit = match (unit, &to) { + (Unit::Panel, Target::NewDock { .. }) if group_len(layout, panel) == Some(1) => Unit::Group, + (unit, _) => unit, + }; + return one(unit.to(layout, panel, to)?); + } + if !matches!(layout.place(panel), Some(Place::Floating { .. })) { + return Ok(Vec::new()); + } + let members = members(layout, panel, unit); + let panels = layout.panels(); + let free = || panels.iter().copied().filter(|p| !members.contains(p)); + let docked = free().find(|p| matches!(layout.place(p), Some(Place::Dock { .. }))); + let framed = || free().find(|p| matches!(layout.place(p), Some(Place::Node(_)))); + let anchor = docked.or_else(framed).cloned().ok_or(DockError::MissingTarget)?; + one(unit.to(layout, panel, Target::At { anchor, placement: Placement::Tab { before: None } })?) + } + Self::Activate { panel } | Self::UiDock(UiDock::Operation(DockOperation::Activate { panel } | DockOperation::Open { panel })) => { + shown(panel)?; + one(Action::Activate { panel: panel.clone() }) + } + Self::Close { panel } | Self::UiDock(UiDock::Operation(DockOperation::Close { panel })) => one(Action::Close { panel: panel.clone() }), + Self::CloseGroup { panel } => one(Action::CloseGroup { panel: panel.clone() }), + Self::CloseOthers { panel } => one(Action::CloseOthers { panel: panel.clone() }), + Self::Minimize { panel, minimized } => { + let place = layout.place(panel).ok_or(DockError::MissingPanel)?; + let current = layout.group(&place).is_some_and(|g| g.minimized); + one(Action::SetMinimized { panel: panel.clone(), minimized: minimized.unwrap_or(!current) }) + } + Self::Iconic { panel, iconic } => { + let location = layout.location(panel)?; + let current = location.group.and_then(|g| g.column).is_some_and(|c| c.iconic); + one(Action::SetIconic { panel: panel.clone(), iconic: iconic.unwrap_or(!current) }) + } + Self::Window { panel, native } => { + shown(panel)?; + if !native.unwrap_or(true) { + return one(Action::SetNative { panel: panel.clone(), rect: None }); + } + let mut actions = Vec::new(); + let mut scratch = layout.clone(); + if !scratch.floating.iter().any(|w| w.contains(panel)) { + let float = Action::MoveGroup { panel: panel.clone(), to: Target::Float { rect: None } }; + scratch.apply(float.clone())?; + actions.push(float); + } + let rect = scratch.floating.iter().find(|w| w.contains(panel)).map(|w| w.rect).ok_or(DockError::MissingPanel)?; + actions.push(Action::SetNative { panel: panel.clone(), rect: Some(rect) }); + Ok(actions) + } + Self::UiDock(UiDock::Operation(operation)) => match operation { + DockOperation::Float { panel, rect } => one(Action::Float { panel: panel.clone(), rect: *rect }), + DockOperation::MoveFloating { panel, rect } => one(Action::MoveFloating { panel: panel.clone(), rect: *rect }), + DockOperation::Move { panel, target, zone, before } => { + let placement = placement(*zone, before, ZoneName::Center)?; + one(Action::Move { panel: panel.clone(), anchor: target.clone(), placement }) + } + DockOperation::SetStackOpen { panel, open } => one(Action::SetStackOpen { panel: panel.clone(), open: *open }), + DockOperation::ResizeStack { panel, height } => one(Action::ResizeStack { panel: panel.clone(), height: *height }), + DockOperation::ResizeSplit { path, size } => one(Action::ResizeSplit { path: path.clone(), size: *size }), + DockOperation::Open { .. } | DockOperation::Close { .. } | DockOperation::Activate { .. } => unreachable!("matched above"), + }, + Self::Workspace { .. } | Self::NewWorkspace { .. } | Self::DeleteWorkspace { .. } | Self::ResetWorkspace {} | Self::Lock { .. } => { + Err(DockError::NotAllowed) + } + } + } + + /// Apply the command to `workspace`, all or nothing, and return the panels it closed so + /// the application can release their state. Showing a hidden panel restores its last + /// location; Lock sets [`Workspace::locked`]. Application-owned commands + /// ([`Self::is_app_owned`]) return [`DockError::NotAllowed`] and change nothing. + pub fn apply(&self, workspace: &mut Workspace

, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { + let show = match self { + Self::Activate { panel } + | Self::Dock { panel, anchor: None, side: None, .. } + | Self::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) => Some(panel), + _ => None, + }; + if let Some(panel) = show.filter(|p| !workspace.layout.contains(p)) { + workspace.set_visible(panel.clone(), true, None)?; + return Ok(Vec::new()); + } + if let Self::Lock { locked } = self { + workspace.locked = locked.unwrap_or(!workspace.locked); + return Ok(Vec::new()); + } + let actions = self.to_actions(workspace)?; + let before: Vec

= workspace.layout.panels().into_iter().cloned().collect(); + workspace.apply_all(actions, permissions)?; + let after: HashSet<&P> = workspace.layout.panels().into_iter().collect(); + Ok(before.into_iter().filter(|p| !after.contains(p)).collect()) + } +} + +/// The first panel of the last column of the dock on `side`. +fn last_column(layout: &Layout

, side: Side) -> Option

{ + let path = layout.dock_path(side)?; + let node = layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, &path))?; + match node { + super::Node::Dock { columns, .. } => columns.last()?.groups.first()?.panels.first().cloned(), + _ => None, + } +} + +fn group_len(layout: &Layout

, panel: &P) -> Option { + layout.place(panel).and_then(|place| layout.group(&place)).map(|g| g.panels.len()) +} + +/// The panels that move with `panel`. +fn members(layout: &Layout

, panel: &P, unit: Unit) -> Vec

{ + match unit { + Unit::Panel => vec![panel.clone()], + Unit::Group => layout.place(panel).and_then(|place| layout.group(&place)).map(|g| g.panels.clone()).unwrap_or_default(), + Unit::Column => match layout.place(panel) { + Some(Place::Dock { path, column, .. }) => match layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, &path)) { + Some(super::Node::Dock { columns, .. }) => { + columns.get(column).map(|c| c.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect()).unwrap_or_default() + } + _ => Vec::new(), + }, + Some(Place::Floating { .. }) => layout.floating.iter().find(|w| w.contains(panel)).map(|w| w.panels().cloned().collect()).unwrap_or_default(), + _ => vec![panel.clone()], + }, + } +} diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs new file mode 100644 index 0000000000..60ad359d6d --- /dev/null +++ b/crates/ui/src/docking/command_tests.rs @@ -0,0 +1,267 @@ +//! `DockCommand`: every documented shape parses and maps to atomic layout actions. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; + +use super::*; +use crate::layout::{SplitAxis, SplitSize}; + +type P = String; + +fn s(panel: &str) -> P { + panel.to_owned() +} + +fn permissions(panel: &P) -> Permissions { + if panel == "canvas" { Permissions::PROTECTED } else { Permissions::default() } +} + +/// A start dock with one column of `[layers, channels]` and `[history]` beside the canvas, a +/// floating `color`, and `swatches` hidden from history's group. +fn workspace() -> Workspace

{ + let groups = vec![Group::new(vec![s("layers"), s("channels")], 0), Group::new(vec![s("history"), s("swatches")], 0)]; + let dock = Node::Dock { side: Side::Start, columns: vec![Column::new(groups, 240.0)] }; + let canvas = Node::Tabs { panels: vec![s("canvas")], active: 0 }; + let layout = Layout { + root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), first: Box::new(dock), second: Box::new(canvas) }), + floating: vec![Floating::single(vec![s("color")], 0, [300.0, 200.0, 200.0, 150.0])], + }; + let mut workspace = Workspace::new(layout); + workspace.apply(Action::Close { panel: s("swatches") }, permissions).unwrap(); + workspace +} + +fn parse(params: Value) -> Result, serde_json::Error> { + serde_json::from_value(params) +} + +/// The actions `params` makes on a fresh workspace. +fn actions(params: Value) -> Vec> { + let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); + command.to_actions(&workspace()).unwrap_or_else(|e| panic!("{params}: {e}")) +} + +/// Apply `params` to a fresh workspace; return it and the panels closed. +fn applied(params: Value) -> (Workspace

, Vec

) { + let mut workspace = workspace(); + let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); + let closed = command.apply(&mut workspace, permissions).unwrap_or_else(|e| panic!("{params}: {e}")); + (workspace, closed) +} + +/// `params` parses but applying it fails with `error` and changes nothing. +fn rejected(params: Value, error: DockError) { + let mut workspace = workspace(); + let before = workspace.clone(); + let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); + assert_eq!(command.apply(&mut workspace, permissions), Err(error), "{params}"); + assert_eq!(workspace, before, "{params}"); +} + +fn tab(before: Option<&str>) -> Placement

{ + Placement::Tab { before: before.map(s) } +} + +#[test] +fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { + let mut seen = BTreeSet::new(); + let mut id = |params: Value| { + seen.insert(params["command"].as_str().unwrap().to_owned()); + params + }; + + // The raw action form, in both protocols. + let raw = json!({"MoveFloating": {"panel": "color", "rect": [44, 66, 360, 450]}}); + let moved = vec![Action::MoveFloating { panel: s("color"), rect: [44.0, 66.0, 360.0, 450.0] }]; + assert_eq!(actions(id(json!({"command": "window.panel.layout", "action": raw}))), moved); + assert_eq!(actions(id(json!({"command": "ui.dock", "action": raw}))), moved); + + // move: tab by default, before a tab or appended, zones, a serialized placement, a group. + let mv = |placement| vec![Action::Move { panel: s("history"), anchor: s("layers"), placement }]; + let base = json!({"command": "window.panel.move", "panel": "history", "anchor": "layers"}); + let with = |extra: Value| { + let mut params = base.clone(); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + params + }; + assert_eq!(actions(id(base.clone())), mv(tab(None))); + assert_eq!(actions(with(json!({"before": "channels"}))), mv(tab(Some("channels")))); + assert_eq!(actions(with(json!({"zone": "center", "before": null}))), mv(tab(None))); + assert_eq!(actions(with(json!({"zone": "center"}))), mv(Placement::Split(Zone::Center))); + assert_eq!(actions(with(json!({"zone": "Left"}))), mv(Placement::Split(Zone::Left))); + assert_eq!(actions(with(json!({"zone": "below"}))), mv(Placement::Group { below: true })); + assert_eq!(actions(with(json!({"placement": {"Column": {"after": true}}}))), mv(Placement::Column { after: true })); + assert_eq!( + actions(with(json!({"group": true, "zone": "above"}))), + vec![Action::MoveGroup { panel: s("history"), to: Target::At { anchor: s("layers"), placement: Placement::Group { below: false } } }] + ); + + // float: a docked panel, a lone floating panel, a group and a column. + assert_eq!( + actions(id(json!({"command": "window.panel.float", "panel": "layers", "x": 10, "y": 20}))), + vec![Action::Float { panel: s("layers"), rect: [10.0, 20.0, 260.0, 320.0] }] + ); + assert_eq!( + actions(json!({"command": "window.panel.float", "panel": "color", "width": 320})), + vec![Action::MoveFloating { panel: s("color"), rect: [300.0, 200.0, 320.0, 150.0] }] + ); + assert_eq!( + actions(json!({"command": "window.panel.float", "panel": "layers", "group": true})), + vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: None } }] + ); + assert_eq!( + actions(json!({"command": "window.panel.float", "panel": "history", "column": true})), + vec![Action::MoveColumn { panel: s("history"), to: Target::Float { rect: None } }] + ); + + // dock: to an anchor, to a side, back into the dock, and a hidden panel to its last place. + assert_eq!( + actions(id(json!({"command": "window.panel.dock", "panel": "color", "anchor": "history", "zone": "tab"}))), + vec![Action::Move { panel: s("color"), anchor: s("history"), placement: tab(None) }] + ); + assert_eq!( + actions(json!({"command": "window.panel.dock", "panel": "color", "side": "End"})), + vec![Action::MoveGroup { panel: s("color"), to: Target::NewDock { side: Side::End } }] + ); + let new_column = Target::At { anchor: s("layers"), placement: Placement::Column { after: true } }; + assert_eq!( + actions(json!({"command": "window.panel.dock", "panel": "color", "column": true, "side": "Start"})), + vec![Action::MoveWindow { panel: s("color"), to: new_column.clone() }] + ); + assert_eq!( + actions(json!({"command": "window.panel.dock", "panel": "history", "group": true, "side": "Start"})), + vec![Action::MoveGroup { panel: s("history"), to: new_column }] + ); + assert_eq!( + actions(json!({"command": "window.panel.dock", "panel": "color"})), + vec![Action::Move { panel: s("color"), anchor: s("layers"), placement: tab(None) }] + ); + assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "layers"})), vec![]); + let (shown, _) = applied(json!({"command": "window.panel.dock", "panel": "swatches"})); + assert!(shown.layout.contains(&s("swatches")) && shown.hidden.is_empty()); + + // activate shows a hidden panel; close actions report what they closed. + let (shown, _) = applied(id(json!({"command": "window.panel.activate", "panel": "swatches"}))); + assert!(shown.layout.contains(&s("swatches"))); + assert_eq!(actions(json!({"command": "window.panel.activate", "panel": "channels"})), vec![Action::Activate { panel: s("channels") }]); + assert_eq!(applied(id(json!({"command": "window.panel.close", "panel": "channels"}))).1, vec![s("channels")]); + assert_eq!(applied(id(json!({"command": "window.panel.closeGroup", "panel": "channels"}))).1, vec![s("layers"), s("channels")]); + assert_eq!(applied(id(json!({"command": "window.panel.closeOthers", "panel": "channels"}))).1, vec![s("layers")]); + + // minimize and iconic toggle without a value. + assert_eq!( + actions(id(json!({"command": "window.panel.minimize", "panel": "layers"}))), + vec![Action::SetMinimized { panel: s("layers"), minimized: true }] + ); + assert_eq!( + actions(json!({"command": "window.panel.minimize", "panel": "layers", "minimized": false})), + vec![Action::SetMinimized { panel: s("layers"), minimized: false }] + ); + assert_eq!(actions(id(json!({"command": "window.panel.iconic", "panel": "history"}))), vec![Action::SetIconic { panel: s("history"), iconic: true }]); + + // window: a floating window goes native at its rect; a docked group floats first. + assert_eq!( + actions(id(json!({"command": "window.panel.window", "panel": "color"}))), + vec![Action::SetNative { panel: s("color"), rect: Some([300.0, 200.0, 200.0, 150.0]) }] + ); + let docked = actions(json!({"command": "window.panel.window", "panel": "layers"})); + assert!( + matches!(docked.as_slice(), [Action::MoveGroup { to: Target::Float { rect: None }, .. }, Action::SetNative { rect: Some(_), .. }]), + "{docked:?}" + ); + assert_eq!(actions(json!({"command": "window.panel.window", "panel": "color", "native": false})), vec![Action::SetNative { panel: s("color"), rect: None }]); + + // Named workspaces and Reset belong to the application. + for params in [ + json!({"command": "window.workspace", "name": "Painting"}), + json!({"command": "window.workspace.new", "name": "Mine"}), + json!({"command": "window.workspace.delete", "name": "Mine"}), + json!({"command": "window.workspace.reset"}), + json!({"command": "ui.dock.reset"}), + ] { + let command = parse(id(params.clone())).unwrap(); + assert!(command.is_app_owned(), "{params}"); + rejected(params, DockError::NotAllowed); + } + assert_eq!(parse(json!({"command": "ui.dock.reset"})).unwrap(), DockCommand::ResetWorkspace {}); + + // Lock toggles or sets. + assert!(applied(id(json!({"command": "window.workspace.lock"}))).0.locked); + assert!(!applied(json!({"command": "window.workspace.lock", "locked": false})).0.locked); + + // The small apps' ui.dock operations. + let op = |params: Value| { + let mut params = params; + params["command"] = json!("ui.dock"); + params + }; + let (shown, _) = applied(op(json!({"operation": "open", "panel": "swatches"}))); + assert!(shown.layout.contains(&s("swatches"))); + assert_eq!(actions(op(json!({"operation": "close", "panel": "layers"}))), vec![Action::Close { panel: s("layers") }]); + assert_eq!(actions(op(json!({"operation": "activate", "panel": "channels"}))), vec![Action::Activate { panel: s("channels") }]); + assert_eq!( + actions(op(json!({"operation": "float", "panel": "layers", "rect": [1, 2, 300, 200]}))), + vec![Action::Float { panel: s("layers"), rect: [1.0, 2.0, 300.0, 200.0] }] + ); + assert_eq!( + actions(op(json!({"operation": "moveFloating", "panel": "color", "rect": [1, 2, 300, 200]}))), + vec![Action::MoveFloating { panel: s("color"), rect: [1.0, 2.0, 300.0, 200.0] }] + ); + let to_layers = |placement| vec![Action::Move { panel: s("color"), anchor: s("layers"), placement }]; + assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers"}))), to_layers(Placement::Split(Zone::Center))); + assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "left"}))), to_layers(Placement::Split(Zone::Left))); + assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": null}))), to_layers(tab(None))); + assert_eq!( + actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": "channels"}))), + to_layers(tab(Some("channels"))) + ); + assert_eq!( + actions(op(json!({"operation": "setStackOpen", "panel": "layers", "open": false}))), + vec![Action::SetStackOpen { panel: s("layers"), open: false }] + ); + assert_eq!( + actions(op(json!({"operation": "resizeStack", "panel": "layers", "height": null}))), + vec![Action::ResizeStack { panel: s("layers"), height: None }] + ); + assert_eq!( + actions(op(json!({"operation": "resizeStack", "panel": "layers", "height": 120}))), + vec![Action::ResizeStack { panel: s("layers"), height: Some(120.0) }] + ); + assert_eq!( + actions(op(json!({"operation": "resizeSplit", "path": [], "size": {"Ratio": 0.35}}))), + vec![Action::ResizeSplit { path: vec![], size: SplitSize::Ratio(0.35) }] + ); + + let ids: BTreeSet = DockCommand::

::IDS.iter().map(|id| (*id).to_owned()).collect(); + assert_eq!(seen, ids, "one case per id"); + + // Bad params: parse errors, or a DockError with nothing changed. + for params in [ + json!({"command": "window.panel.unknown", "panel": "layers"}), + json!({"command": "window.panel.move", "panel": "layers"}), + json!({"command": "window.panel.move", "panel": "layers", "anchor": "history", "zone": "middle"}), + json!({"command": "window.panel.minimize", "panel": "layers", "minimized": "yes"}), + op(json!({"operation": "spin", "panel": "layers"})), + op(json!({"operation": "float", "panel": "layers", "rect": [1, 2, 3]})), + op(json!({"operation": "resizeStack", "panel": "layers"})), + op(json!({"operation": "setStackOpen", "panel": "layers"})), + op(json!({"operation": "move", "panel": "layers"})), + ] { + assert!(parse(params.clone()).is_err(), "{params}"); + } + rejected(json!({"command": "window.panel.move", "panel": "layers", "anchor": "nowhere"}), DockError::MissingTarget); + rejected(json!({"command": "window.panel.move", "panel": "nowhere", "anchor": "layers"}), DockError::MissingPanel); + rejected(json!({"command": "window.panel.move", "panel": "layers", "anchor": "history", "zone": "left", "before": null}), DockError::InvalidPlacement); + rejected(json!({"command": "window.panel.float", "panel": "layers", "width": 1e30}), DockError::InvalidGeometry); + rejected(json!({"command": "window.panel.move", "panel": "canvas", "anchor": "layers"}), DockError::NotAllowed); + rejected(op(json!({"operation": "moveFloating", "panel": "color", "rect": [0, 0, -5, 10]})), DockError::InvalidGeometry); + rejected(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "top", "before": "channels"})), DockError::InvalidPlacement); + rejected(op(json!({"operation": "resizeSplit", "path": [true, true, true], "size": {"Ratio": 0.5}})), DockError::MissingTarget); + // A docked group cannot float into a native window when locked. + let mut locked = workspace(); + locked.locked = true; + let before = locked.clone(); + assert!(parse(json!({"command": "window.panel.window", "panel": "layers"})).unwrap().apply(&mut locked, permissions).is_err()); + assert_eq!(locked, before); +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 85c76545e7..b4c65efead 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -6,6 +6,8 @@ //! input and commits only a valid result; a rejected move cannot lose the source panel. pub mod chrome; +#[cfg(feature = "serde")] +mod command; mod dock_model; mod hits; mod model; @@ -17,6 +19,8 @@ mod targets; pub mod testing; mod workspace; +#[cfg(feature = "serde")] +pub use command::{DockCommand, DockOperation, UiDock, ZoneName}; pub use hits::{Divider, Hit, ResizeEdge}; pub use render::{close_flyout, flyout, open_flyout}; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; @@ -30,6 +34,8 @@ pub use workspace::Workspace; use surface::{Drag, GroupDrag, GroupGesture}; +#[cfg(all(test, feature = "serde"))] +mod command_tests; #[cfg(test)] mod dock_tests; #[cfg(test)] diff --git a/crates/ui/tests/docking_workflows.rs b/crates/ui/tests/docking_workflows.rs index 29a6c9d910..1e8ae94c5d 100644 --- a/crates/ui/tests/docking_workflows.rs +++ b/crates/ui/tests/docking_workflows.rs @@ -250,3 +250,186 @@ fn floating_brushes_merge_detach_and_redock_through_real_pointer_input() { } } } + +/// Each app's saved v1 layout goes through a docking session driven by real pointer input and a +/// command, then writes and reads back unchanged. +#[cfg(all(feature = "serde", feature = "testing"))] +mod v1_fixtures { + use craft_ui::docking::{DockCommand, DockContent, Hit, Layout, Node, Permissions, ResizeEdge, Side, testing::DockDriver}; + use egui::{Pos2, Rect, pos2}; + use serde_json::{Value, json}; + + struct Content; + + impl DockContent for Content { + fn body(&mut self, ui: &mut egui::Ui, panel: &String) { + ui.label(panel.as_str()); + } + fn logical_label(&self, panel: &String) -> String { + panel.clone() + } + fn permissions(&self, panel: &String) -> Permissions { + if panel == "canvas" { Permissions::PROTECTED } else { Permissions::default() } + } + } + + type Driver = DockDriver; + type Columns = Vec>>; + + /// App, file contents and the JSON pointer to a saved layout. + const FIXTURES: [(&str, &str, &str); 10] = [ + ("designcraft", include_str!("fixtures/v1/designcraft.json"), "/docking"), + ("designcraft", include_str!("fixtures/v1/designcraft.json"), "/customWorkspaces/0/docking"), + ("vectorcraft", include_str!("fixtures/v1/vectorcraft.json"), "/docking"), + ("lightcraft", include_str!("fixtures/v1/lightcraft.json"), "/docking/layout"), + ("pdfcraft", include_str!("fixtures/v1/pdfcraft.json"), "/docking/layout"), + ("cadcraft", include_str!("fixtures/v1/cadcraft.json"), "/workspace/docking/layout"), + ("soundcraft", include_str!("fixtures/v1/soundcraft.json"), "/docking/layout"), + ("soundcraft", include_str!("fixtures/v1/soundcraft.json"), "/mix_docking/layout"), + ("photocraft", include_str!("fixtures/v1/photocraft.json"), "/docking"), + ("photocraft", include_str!("fixtures/v1/photocraft.json"), "/panel_layout/docking"), + ]; + + /// The start dock's columns, each a list of groups. + fn start_columns(layout: &Layout) -> Columns { + fn find(node: &Node) -> Option { + match node { + Node::Dock { side: Side::Start, columns } => { + Some(columns.iter().map(|column| column.groups.iter().map(|group| group.panels.clone()).collect()).collect()) + } + Node::Split { first, second, .. } => find(first).or_else(|| find(second)), + _ => None, + } + } + layout.root.as_ref().and_then(find).unwrap_or_default() + } + + fn iconic(layout: &Layout) -> bool { + fn find(node: &Node) -> Option { + match node { + Node::Dock { side: Side::Start, columns } => columns.first().map(|column| column.iconic), + Node::Split { first, second, .. } => find(first).or_else(|| find(second)), + _ => None, + } + } + layout.root.as_ref().and_then(find).unwrap_or(false) + } + + fn hit(d: &Driver, hit: Hit) -> Rect { + d.hit(&hit).unwrap_or_else(|| panic!("{hit:?} in {:?}", d.hits())) + } + + /// A point of `from` that no floating window above it covers, as drawn last frame. + fn grab(d: &Driver, from: &Hit, panel: &String) -> Option { + let rect = d.hit(from)?; + let own = d.layout.floating.iter().position(|w| w.contains(panel)); + let windows: Vec = d + .layout + .floating + .iter() + .filter_map(|w| { + let first = w.panels().next()?.clone(); + Some(Rect::from_min_max(d.hit(&Hit::Title(first.clone()))?.min, d.hit(&Hit::Resize(first, ResizeEdge::BottomRight))?.max)) + }) + .collect(); + let covered = |p: Pos2| windows.iter().enumerate().any(|(i, w)| own.is_none_or(|own| i > own) && w.contains(p)); + let mut x = rect.left() + 4.0; + while x < rect.right() { + let p = pos2(x, rect.center().y); + if !covered(p) { + return Some(p); + } + x += 4.0; + } + None + } + + /// Drag from an uncovered point of `from` to `to`; something must change. + fn drag(d: &mut Driver, from: Hit, to: Pos2, what: &str) { + let panel = match &from { + Hit::DragBar(p) | Hit::Title(p) => p.clone(), + other => panic!("{other:?}"), + }; + let at = grab(d, &from, &panel).unwrap_or_else(|| panic!("{what}: {from:?} is covered")); + let out = d.drag(at, to); + assert!(out.error.is_none() && !out.actions.is_empty(), "{what}: {out:?}\n{:?}\n{:?}", d.layout, d.hits()); + d.settle(); + } + + fn sorted(layout: &Layout) -> Vec { + let mut panels: Vec = layout.panels().into_iter().cloned().collect(); + panels.sort(); + panels + } + + #[test] + fn v1_layouts_dock_collapse_float_redock_and_reload() { + let mut seams = Vec::new(); + for (app, text, pointer) in FIXTURES { + let at = format!("{app}{pointer}"); + let file: Value = serde_json::from_str(text).unwrap(); + let layout: Layout = serde_json::from_value(file.pointer(pointer).unwrap().clone()).unwrap_or_else(|e| panic!("{at}: {e}")); + let panels = sorted(&layout); + let mut d = Driver::new(layout, Content); + let mut bars: Vec = Vec::new(); + for (h, _) in d.hits() { + if let Hit::DragBar(panel) = h + && !bars.contains(&panel) + { + bars.push(panel); + } + } + assert!(bars.len() >= 2, "{at}: two movable groups in {bars:?}"); + + // The first group's bar dropped on the window's start edge makes a dock. + drag(&mut d, Hit::DragBar(bars[0].clone()), pos2(2.0, 300.0), &format!("{at}: new dock")); + let columns = start_columns(&d.layout); + assert!(columns.len() == 1 && columns[0].len() == 1 && columns[0][0][0] == bars[0], "{at}: {columns:?}"); + + // The second group stacks below it, and a third goes into the seam between them. + let first = hit(&d, Hit::Tab(bars[0].clone())); + let bottom = d.area.bottom(); + drag(&mut d, Hit::DragBar(bars[1].clone()), pos2(first.center().x, bottom - 10.0), &format!("{at}: stack below")); + let third = bars[2..].iter().find(|p| grab(&d, &Hit::DragBar((*p).clone()), p).is_some()).cloned(); + if let Some(third) = &third { + seams.push(at.clone()); + let second = hit(&d, Hit::Tab(bars[1].clone())); + drag(&mut d, Hit::DragBar(third.clone()), pos2(second.center().x, second.top() + 2.0), &format!("{at}: seam")); + } + let columns = start_columns(&d.layout); + let heads: Vec<&String> = columns[0].iter().map(|group| &group[0]).collect(); + let expected: Vec<&String> = match &third { + Some(third) => vec![&bars[0], third, &bars[1]], + None => vec![&bars[0], &bars[1]], + }; + assert_eq!((columns.len(), heads), (1, expected), "{at}"); + + // Collapse the column to icons and expand it again. + d.click(hit(&d, Hit::Collapse(bars[0].clone())).center()); + d.settle(); + assert!(iconic(&d.layout), "{at}: collapsed"); + assert!(d.hit(&Hit::Icon(bars[0].clone())).is_some(), "{at}: icons"); + d.click(hit(&d, Hit::Collapse(bars[0].clone())).center()); + d.settle(); + assert!(!iconic(&d.layout), "{at}: expanded"); + + // Float the column by command, then drag its window back to the start edge. + let float: DockCommand = serde_json::from_value(json!({"command": "window.panel.float", "panel": bars[0], "column": true})).unwrap(); + let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone())).unwrap(); + d.layout.apply_all(actions, |p| d.content.permissions(p)).unwrap_or_else(|e| panic!("{at}: {e}")); + d.settle(); + assert!(start_columns(&d.layout).is_empty(), "{at}: floated"); + drag(&mut d, Hit::Title(bars[0].clone()), pos2(2.0, 300.0), &format!("{at}: dock back")); + assert_eq!(start_columns(&d.layout), columns, "{at}: docked back"); + + // Nothing was lost, and the layout reads back as written. + assert_eq!(sorted(&d.layout), panels, "{at}"); + let written = serde_json::to_string(&d.layout).unwrap(); + let read: Layout = serde_json::from_str(&written).unwrap(); + read.validate().unwrap_or_else(|e| panic!("{at}: {e}")); + assert_eq!(read, d.layout, "{at}"); + } + // The fixtures with a third movable group, uncovered, try the seam. + assert_eq!(seams.len(), 6, "{seams:?}"); + } +} From b98ef89921eb3ed388be38447d364e5f1efd5107 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 12:07:14 +0000 Subject: [PATCH 28/94] docking: rewrite the docking guide for the current API docs/ui-docking.md covers the Dock and Frame profiles, the model and actions, Workspace, the renderer and DockContent, gestures, DockCommand, DockStyle::localized, hit rects and the DockDriver test driver, and links the task-pane guide. Also: ui.dock open, close and activate map in one place, the command tests build as a cfg(test) module, the hit-kind table gets a type alias, the testing example uses public API, and rustfmt. --- crates/ui/src/docking/command.rs | 46 +++- crates/ui/src/docking/command_tests.rs | 26 ++- crates/ui/src/docking/iconic_tests.rs | 9 +- crates/ui/src/docking/mod.rs | 6 +- crates/ui/src/docking/render/dock.rs | 6 +- crates/ui/src/docking/render/iconic.rs | 7 +- crates/ui/src/docking/testing.rs | 5 +- crates/ui/tests/docking_workflows.rs | 3 +- docs/ui-docking.md | 303 ++++++++++++++++--------- 9 files changed, 266 insertions(+), 145 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 7b7b7d2066..ffd066ee6c 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -162,11 +162,23 @@ pub enum UiDock

{ #[non_exhaustive] pub enum DockOperation

{ /// Show a panel at its last location and select it. - Open { panel: P }, - Close { panel: P }, - Activate { panel: P }, - Float { panel: P, rect: [f32; 4] }, - MoveFloating { panel: P, rect: [f32; 4] }, + Open { + panel: P, + }, + Close { + panel: P, + }, + Activate { + panel: P, + }, + Float { + panel: P, + rect: [f32; 4], + }, + MoveFloating { + panel: P, + rect: [f32; 4], + }, Move { panel: P, target: P, @@ -175,14 +187,20 @@ pub enum DockOperation

{ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] before: Option>, }, - SetStackOpen { panel: P, open: bool }, + SetStackOpen { + panel: P, + open: bool, + }, /// `height` is required; `null` clears it. ResizeStack { panel: P, #[serde(deserialize_with = "required")] height: Option, }, - ResizeSplit { path: Vec, size: SplitSize }, + ResizeSplit { + path: Vec, + size: SplitSize, + }, } /// A drop zone by name, as control protocols write it. PascalCase [`Zone`] names also parse. @@ -365,11 +383,11 @@ impl DockCommand

{ let anchor = docked.or_else(framed).cloned().ok_or(DockError::MissingTarget)?; one(unit.to(layout, panel, Target::At { anchor, placement: Placement::Tab { before: None } })?) } - Self::Activate { panel } | Self::UiDock(UiDock::Operation(DockOperation::Activate { panel } | DockOperation::Open { panel })) => { + Self::Activate { panel } => { shown(panel)?; one(Action::Activate { panel: panel.clone() }) } - Self::Close { panel } | Self::UiDock(UiDock::Operation(DockOperation::Close { panel })) => one(Action::Close { panel: panel.clone() }), + Self::Close { panel } => one(Action::Close { panel: panel.clone() }), Self::CloseGroup { panel } => one(Action::CloseGroup { panel: panel.clone() }), Self::CloseOthers { panel } => one(Action::CloseOthers { panel: panel.clone() }), Self::Minimize { panel, minimized } => { @@ -399,6 +417,11 @@ impl DockCommand

{ Ok(actions) } Self::UiDock(UiDock::Operation(operation)) => match operation { + DockOperation::Open { panel } | DockOperation::Activate { panel } => { + shown(panel)?; + one(Action::Activate { panel: panel.clone() }) + } + DockOperation::Close { panel } => one(Action::Close { panel: panel.clone() }), DockOperation::Float { panel, rect } => one(Action::Float { panel: panel.clone(), rect: *rect }), DockOperation::MoveFloating { panel, rect } => one(Action::MoveFloating { panel: panel.clone(), rect: *rect }), DockOperation::Move { panel, target, zone, before } => { @@ -408,7 +431,6 @@ impl DockCommand

{ DockOperation::SetStackOpen { panel, open } => one(Action::SetStackOpen { panel: panel.clone(), open: *open }), DockOperation::ResizeStack { panel, height } => one(Action::ResizeStack { panel: panel.clone(), height: *height }), DockOperation::ResizeSplit { path, size } => one(Action::ResizeSplit { path: path.clone(), size: *size }), - DockOperation::Open { .. } | DockOperation::Close { .. } | DockOperation::Activate { .. } => unreachable!("matched above"), }, Self::Workspace { .. } | Self::NewWorkspace { .. } | Self::DeleteWorkspace { .. } | Self::ResetWorkspace {} | Self::Lock { .. } => { Err(DockError::NotAllowed) @@ -469,7 +491,9 @@ fn members(layout: &Layout

, panel: &P, unit: Unit) -> V } _ => Vec::new(), }, - Some(Place::Floating { .. }) => layout.floating.iter().find(|w| w.contains(panel)).map(|w| w.panels().cloned().collect()).unwrap_or_default(), + Some(Place::Floating { .. }) => { + layout.floating.iter().find(|w| w.contains(panel)).map(|w| w.panels().cloned().collect()).unwrap_or_default() + } _ => vec![panel.clone()], }, } diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 60ad359d6d..b106a39d3e 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -1,4 +1,5 @@ //! `DockCommand`: every documented shape parses and maps to atomic layout actions. +#![cfg(feature = "serde")] use std::collections::BTreeSet; @@ -158,7 +159,10 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { actions(json!({"command": "window.panel.minimize", "panel": "layers", "minimized": false})), vec![Action::SetMinimized { panel: s("layers"), minimized: false }] ); - assert_eq!(actions(id(json!({"command": "window.panel.iconic", "panel": "history"}))), vec![Action::SetIconic { panel: s("history"), iconic: true }]); + assert_eq!( + actions(id(json!({"command": "window.panel.iconic", "panel": "history"}))), + vec![Action::SetIconic { panel: s("history"), iconic: true }] + ); // window: a floating window goes native at its rect; a docked group floats first. assert_eq!( @@ -170,7 +174,10 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { matches!(docked.as_slice(), [Action::MoveGroup { to: Target::Float { rect: None }, .. }, Action::SetNative { rect: Some(_), .. }]), "{docked:?}" ); - assert_eq!(actions(json!({"command": "window.panel.window", "panel": "color", "native": false})), vec![Action::SetNative { panel: s("color"), rect: None }]); + assert_eq!( + actions(json!({"command": "window.panel.window", "panel": "color", "native": false})), + vec![Action::SetNative { panel: s("color"), rect: None }] + ); // Named workspaces and Reset belong to the application. for params in [ @@ -210,7 +217,10 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { ); let to_layers = |placement| vec![Action::Move { panel: s("color"), anchor: s("layers"), placement }]; assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers"}))), to_layers(Placement::Split(Zone::Center))); - assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "left"}))), to_layers(Placement::Split(Zone::Left))); + assert_eq!( + actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "left"}))), + to_layers(Placement::Split(Zone::Left)) + ); assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": null}))), to_layers(tab(None))); assert_eq!( actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": "channels"}))), @@ -252,11 +262,17 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { } rejected(json!({"command": "window.panel.move", "panel": "layers", "anchor": "nowhere"}), DockError::MissingTarget); rejected(json!({"command": "window.panel.move", "panel": "nowhere", "anchor": "layers"}), DockError::MissingPanel); - rejected(json!({"command": "window.panel.move", "panel": "layers", "anchor": "history", "zone": "left", "before": null}), DockError::InvalidPlacement); + rejected( + json!({"command": "window.panel.move", "panel": "layers", "anchor": "history", "zone": "left", "before": null}), + DockError::InvalidPlacement, + ); rejected(json!({"command": "window.panel.float", "panel": "layers", "width": 1e30}), DockError::InvalidGeometry); rejected(json!({"command": "window.panel.move", "panel": "canvas", "anchor": "layers"}), DockError::NotAllowed); rejected(op(json!({"operation": "moveFloating", "panel": "color", "rect": [0, 0, -5, 10]})), DockError::InvalidGeometry); - rejected(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "top", "before": "channels"})), DockError::InvalidPlacement); + rejected( + op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "top", "before": "channels"})), + DockError::InvalidPlacement, + ); rejected(op(json!({"operation": "resizeSplit", "path": [true, true, true], "size": {"Ratio": 0.5}})), DockError::MissingTarget); // A docked group cannot float into a native window when locked. let mut locked = workspace(); diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index 67e722d2c2..cbcef4ef1b 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -21,6 +21,9 @@ impl DockContent for Content { type Driver = DockDriver; +/// A name and a test for one kind of [`Hit`]. +type Check<'a> = (&'a str, &'a dyn Fn(&Hit) -> bool); + /// A left dock with one column of `groups`, iconic when `iconic`, beside canvas 0. fn docked(groups: &[&[u32]], iconic: bool) -> Layout { let mut column = Column::new(groups.iter().map(|g| Group::new(g.to_vec(), 0)).collect(), 240.0); @@ -267,9 +270,7 @@ fn hit_rects_cover_every_gesture_source() { let mut icons = Column::new(vec![Group::new(vec![9], 0)], 240.0); icons.iconic = true; let dock = Node::Dock { side: Side::Start, columns: vec![icons, expanded] }; - let stack = Node::Stack { - entries: vec![StackEntry { panel: 10, open: true, height: None }, StackEntry { panel: 11, open: true, height: None }], - }; + let stack = Node::Stack { entries: vec![StackEntry { panel: 10, open: true, height: None }, StackEntry { panel: 11, open: true, height: None }] }; let frames = Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(0.5), @@ -285,7 +286,7 @@ fn hit_rects_cover_every_gesture_source() { let d = DockDriver::new(layout.clone(), Content); let hits = d.hits(); let kinds = |f: &dyn Fn(&Hit) -> bool| hits.iter().filter(|(h, _)| f(h)).count(); - let expected: [(&str, &dyn Fn(&Hit) -> bool); 15] = [ + let expected: [Check<'_>; 15] = [ ("tab", &|h| matches!(h, Hit::Tab(_))), ("drag bar", &|h| matches!(h, Hit::DragBar(_))), ("border", &|h| matches!(h, Hit::Border(_))), diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index b4c65efead..4c7582bff8 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -21,10 +21,10 @@ mod workspace; #[cfg(feature = "serde")] pub use command::{DockCommand, DockOperation, UiDock, ZoneName}; -pub use hits::{Divider, Hit, ResizeEdge}; -pub use render::{close_flyout, flyout, open_flyout}; pub use dock_model::{Column, ColumnLocation, Group, GroupLocation, PanelState, Side, Target}; +pub use hits::{Divider, Hit, ResizeEdge}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; +pub use render::{close_flyout, flyout, open_flyout}; pub use surface::{ DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, HidePanels, PanelLimits, Profile, begin_drag, cancel_drag, is_dragging, @@ -34,7 +34,7 @@ pub use workspace::Workspace; use surface::{Drag, GroupDrag, GroupGesture}; -#[cfg(all(test, feature = "serde"))] +#[cfg(test)] mod command_tests; #[cfg(test)] mod dock_tests; diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index fe5d4728e2..ae6646ee92 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -41,11 +41,7 @@ fn side_at(edge: Edge, right_to_left: bool) -> Side { } pub(in crate::docking) fn column_width

(column: &Column

, style: &DockStyle) -> f32 { - if column.iconic { - column.iconic_width.unwrap_or(style.iconic_width).clamp(style.iconic_width, style.iconic_max_width) - } else { - column.width - } + if column.iconic { column.iconic_width.unwrap_or(style.iconic_width).clamp(style.iconic_width, style.iconic_max_width) } else { column.width } } /// Heights of stacked groups in a column body `room` high. Each entry is (minimized, saved diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 738f065706..79a37f27bb 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -112,8 +112,8 @@ impl Renderer<'_, P> { if let Some(panel) = self.activation.as_ref().filter(|p| column.groups.iter().any(|g| g.panels.contains(p))) { open_flyout(ui.ctx(), self.id, panel.clone()); } - let total: f32 = column.groups.iter().map(|g| self.icon_group_height(g)).sum::() - + column.groups.len().saturating_sub(1) as f32 * SEPARATOR; + let total: f32 = + column.groups.iter().map(|g| self.icon_group_height(g)).sum::() + column.groups.len().saturating_sub(1) as f32 * SEPARATOR; if total > body.height() + 0.5 { let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { return }; let mut child = @@ -239,7 +239,8 @@ impl Renderer<'_, P> { } if labels { let text = self.content.label(ui, panel, &label, &self.style.font, color); - let galley = text.into_galley(ui, Some(egui::TextWrapMode::Truncate), (cell.right() - icon.right() - 12.0).max(0.0), self.style.font.clone()); + let galley = + text.into_galley(ui, Some(egui::TextWrapMode::Truncate), (cell.right() - icon.right() - 12.0).max(0.0), self.style.font.clone()); painter.galley(pos2(icon.right() + 6.0, cell.center().y - galley.size().y * 0.5), galley, color); } else if response.hovered() && !response.dragged() { response.clone().on_hover_text(&label); diff --git a/crates/ui/src/docking/testing.rs b/crates/ui/src/docking/testing.rs index 647024709c..e34cad2f36 100644 --- a/crates/ui/src/docking/testing.rs +++ b/crates/ui/src/docking/testing.rs @@ -3,8 +3,9 @@ //! ```ignore //! let mut driver = DockDriver::new(app_layout(), Panels::default()); //! let bar = driver.hit(&Hit::DragBar(PanelId::Layers)).unwrap(); -//! driver.drag(bar.center(), egui::pos2(4.0, 300.0)); -//! assert!(driver.layout.dock_path(Side::Start).is_some()); +//! driver.drag(bar.center(), egui::pos2(2.0, 300.0)); +//! driver.settle(); +//! assert!(driver.hit(&Hit::ColumnBar(PanelId::Layers)).is_some()); //! ``` use std::{fmt::Debug, hash::Hash}; diff --git a/crates/ui/tests/docking_workflows.rs b/crates/ui/tests/docking_workflows.rs index 1e8ae94c5d..ddf2eceed9 100644 --- a/crates/ui/tests/docking_workflows.rs +++ b/crates/ui/tests/docking_workflows.rs @@ -414,7 +414,8 @@ mod v1_fixtures { assert!(!iconic(&d.layout), "{at}: expanded"); // Float the column by command, then drag its window back to the start edge. - let float: DockCommand = serde_json::from_value(json!({"command": "window.panel.float", "panel": bars[0], "column": true})).unwrap(); + let float: DockCommand = + serde_json::from_value(json!({"command": "window.panel.float", "panel": bars[0], "column": true})).unwrap(); let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone())).unwrap(); d.layout.apply_all(actions, |p| d.content.permissions(p)).unwrap_or_else(|e| panic!("{at}: {e}")); d.settle(); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 8232450987..0e8b3ba6aa 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -1,151 +1,232 @@ # Panel docking -`craft_ui::docking` lets an application move the same panel between docked tabs, side splits and -floating groups. The shared layer owns placement and interaction; the application owns each -panel's contents, commands, document state and persistence policy. +`craft_ui::docking` lets the user arrange an app's panels: tab groups, docks with columns, +splits, floating windows and iconic columns. craft-ui owns the layout model, the renderer and the +gestures. The app owns panel contents, commands, document state and where layouts are saved. -## Model and transactions +Office apps that draw their own document with a few task panes beside it use +[`craft_ui::panes`](ui-panes.md) instead. -`Layout

` contains an optional root `Node

` and floating tab groups. A node can be: +## Profiles -- `Tabs`: ordered panel identities with one active index. -- `Split`: horizontal or vertical children, with a ratio or fixed first/second size. -- `Stack`: accordion entries with individual open state and optional content height. +`DockStyle::profile` picks one of two arrangements. Both use the same model and actions. -Choose a stable, nonlocalized panel ID type implementing `Clone + Eq + Hash`. Rendering also -requires `Debug + Send + Sync + 'static`. A panel identity occurs at most once in the layout. -Keep transient document/sequence tabs separate when they represent documents inside one panel. +| Profile | Arrangement | Apps | +|---|---|---| +| `Profile::Dock` (default) | Docks on the window's start and end edges. A dock has columns; a column has stacked groups and can collapse to icons. Frames (tab groups and splits) fill the space between the docks. | Creative apps with a canvas and panel docks | +| `Profile::Frame` | A split tree of tab frames. Frame menus offer Maximize Frame, Undock and Close Other Panels. Ctrl/Cmd + tab drag undocks. Drops on all four outer edges split at the root. | Apps whose whole window is frames | + +Sides are logical: `Side::Start` is the left edge, or the right edge when +`DockStyle::right_to_left` is set. egui has no app-wide direction, so the app sets it from its +locale. + +## Model + +`Layout

` holds an optional root `Node

` and a list of `Floating` windows. + +| Node | Holds | +|---|---| +| `Tabs` | A tab group: panels and the active index. | +| `Split` | Two children, horizontal or vertical, with a ratio or a fixed first or second size. | +| `Stack` | Accordion entries, each open or closed, with an optional height. | +| `Dock` | A side and its columns. A `Column` has `Group`s, a width, and `iconic`. | + +A `Floating` window has one or more stacked groups, a rect, and an optional native-window rect. +`Floating::single` makes a window with one group; `panels()` and `contains()` read it. + +`P` is the app's panel id: stable, not localized, `Clone + Eq + Hash`. The renderer also needs +`Debug + Send + Sync + 'static`. A panel occurs at most once in a layout. + +Change a layout only through `Action`s: ```rust use craft_ui::docking::{Action, Floating, Layout, Node, Placement}; let mut layout = Layout { root: Some(Node::Tabs { panels: vec!["layers", "properties"], active: 0 }), - floating: vec![Floating { - panels: vec!["brushes"], active: 0, rect: [40.0, 80.0, 240.0, 300.0], - }], + floating: vec![Floating::single(vec!["brushes"], 0, [40.0, 80.0, 240.0, 300.0])], }; layout.apply(Action::Move { - panel: "brushes", anchor: "layers", + panel: "brushes", + anchor: "layers", placement: Placement::Tab { before: Some("properties") }, })?; # Ok::<(), craft_ui::docking::DockError>(()) ``` -Every transaction validates the original layout before cloning or recursive mutation. It checks -the resulting layout before replacing the original. Missing or self targets, duplicate IDs, -invalid active indices, excessive depth/count and invalid geometry return `DockError`; they do -not remove the source panel. Tab removals retain the selected panel by identity when possible. -Empty source groups collapse. Moving within an accordion preserves its entry state and height; -unaffected split sizing and accordion entries remain unchanged. +- `Move`, `Float` and `Close` act on one panel. `MoveGroup`, `MoveColumn` and `MoveWindow` move a + group, a dock column or a floating window, named by any panel in it. +- A `Target` is `At { anchor, placement }`, `Float { rect }` or `NewDock { side }`. +- A `Placement` is a tab position, a split zone, a new group above or below, a new column, or a + new frame on an outer edge. +- Other actions select, minimize, collapse to icons, resize splits, columns and groups, and move + a floating window to its own OS window (`SetNative`, feature `native-windows`). -`OpenAt` adds a currently absent registered panel at an explicit tab or side destination. `Open` -is the simpler group-reveal operation. Registry checks remain app-owned: the shared model cannot -know whether an ID names an actual panel or whether its content is supported by the application. +Every action checks the whole result before it commits. A bad target, a duplicate id, a stale +split path or invalid geometry returns a `DockError` and leaves the layout unchanged. The source +panel is never lost. -Use `apply_with_permissions` to prevent moving/closing a document canvas or merging a panel into -it. `Permissions::PROTECTED` disallows these operations while allowing side splits around it. -An app that requires a permanently docked panel also checks that policy before accepting a -transaction; an empty shared root is valid when all panels float. +`Permissions` limit what may happen to a panel. `Permissions::PROTECTED` keeps a canvas docked +and open and takes no tabs, but allows splits beside it. `apply_with_permissions` applies them. -## Rendering and interaction +## Workspace -Existing renderers can convert their layout into the shared model for transactions and retain -their own panel chrome. `DropTarget` describes visible body/tab rectangles and whether a group -accepts tabs or splits. Supply targets back-to-front, including floating-window layer order. -`resolve_drop` returns a tab insertion or side/center placement and its preview rectangle. -The frontmost containing group blocks targets underneath even when it rejects a drop. +`Workspace

` is what an app saves: the layout, the hidden panels with where each one goes back, +an optional saved arrangement for Reset, and `locked`. -The optional `DockArea` renderer handles tab fitting and overflow, drag/drop previews, -Escape/focus-loss cancellation, split/accordion dividers and floating-group resize grips. It renders a -snapshot and returns `DockOutput.actions`; apply them through the application's command path. -With `serde` enabled, `Action` also serializes so pointer, keyboard and control-channel requests -can share that command path, including splitter changes, tab reorder and floating bounds. -Panel body callbacks receive stable global egui IDs, so moving a panel does not reset its widget -memory. The application should still keep durable panel/document data outside transient egui -widget memory. +| Method | Does | +|---|---| +| `apply`, `apply_all` | Apply actions all or none, with the app's permissions. Closed panels are recorded in `hidden`. While `locked`, moving, floating and closing are refused. | +| `set_visible(panel, visible, fallback)` | Hide a panel, or show it at its recorded place, else beside `fallback`. | +| `reconcile(registered, default)` | Fit a loaded workspace to the panels the app has now. Unknown panels move to `hidden`, so they come back when registered again. | +| `reset(default)` | Return to the saved arrangement, or to `default` for a built-in workspace. | +| `validate` | Check a loaded workspace before use. | -`DockStyle` supplies colors, font, spacing and localized action labels. `show_with_limits` also -accepts per-panel minimum/maximum sizes. Visible geometry clamps to the available area; a narrow -viewport relaxes minima proportionally. Persisted preferred sizes are unchanged by this drawing -clamp. A divider gesture produces an explicit resize action. +With the `serde` feature, `Workspace`, `Layout` and `Action` serialize. Files without a version +are v1 and load unchanged. craft-ui does not choose where files go; the app does. -Use `begin_drag` with the same area ID to carry an existing tab/header gesture into `DockArea` -when an app switches from its default arrangement to a customizable workspace. +## Rendering -Floating groups are egui areas in one viewport. Native child windows, cross-viewport drag -transport, OS window ownership and multi-monitor coordinate conversion remain the host's -responsibility. The model does not instantiate or reparent native windows. +`DockArea::new(id).show_content(ui, &layout, &style, &mut content)` draws a layout snapshot and +returns a `DockOutput`. It does not change the layout. The app applies `output.actions` through +its own command path, so pointer, keyboard and control commands share one path. -## Persistence and visibility +`DockContent

` is the app's adapter. It draws each panel body and gives its label, icon, +permissions, size limits, preferred floating size, panel menu and group header. `bare` hides the +tab strip of a lone panel. Panel bodies keep a stable egui id when they move, so widget memory +survives. -Enable `craft-ui`'s optional `serde` feature to serialize the shared model, or retain an existing -schema through an adapter. The serialization feature does not choose a filesystem location or -write preferences. Applications validate panel IDs, payload size and schema version before -committing loaded state. Bound recursive deserialization/conversion in the app as well as using -`Layout::validate`; the validator cannot retroactively protect an unbounded parser. +`DockOutput` also has: -To hide a panel without forgetting its placement, capture `Layout::location`, then close it. -Keep the resulting `Location` with the app's visibility state. `restore` uses stable neighbor -IDs, restores captured fixed sizing/floating bounds and recreates a previously closed accordion -group. If a neighbor was removed, it returns an unchanged layout and `MissingTarget`; choose an -explicit fallback such as a default side or remembered floating rectangle. Restoring multiple -panels closed from the same group in reverse close order preserves neighbor relationships. +- `focused`: the focused panel. +- `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (Frame) and + `DockEvent::ToggleAutoCollapse` (Dock). +- `error`: a rejected gesture. -## Acceptance +Builder options on `DockArea`: -The shared tests cover lossless moves, tab reorder, stale targets, atomic errors, protected -canvases, accordion state, fixed sizing, hidden-panel restoration, bounded malformed layouts, -and a deterministic sequence of 800 panel moves. Pointer tests exercise dragging a floating -panel into the main tab strip and canceling a drag. +| Option | Use | +|---|---| +| `maximized(panel)` | Maximize Frame: that frame fills the area. | +| `hide_panels(HidePanels)` | Hide panels for Tab and Shift+Tab. Protected panels stay. | +| `auto_collapse_iconic(on)` | Close a flyout on Escape or a click outside (default on). | +| `raise_panel(panel)` | Raise and focus a panel's floating window this frame. | +| `blocked_rects(rects)` | App overlays that docking gestures must ignore. | -`tests/docking_workflows.rs` renders a document and populated Layers/Properties/Brushes panels, -then uses actual pointer events to merge, detach and redock Brushes. It checks retained values -and widget identity at two widths, two display scales and both egui themes. To retain captures: +`DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome rather than on a +panel body. `begin_drag` hands a drag that started in the app's own chrome to the area. +`docking::chrome` has the floating frame and title bar for apps that draw their own windows. + +## Gestures + +- A tab drags one panel. A group's drag bar (the space beside its tabs) or its top border drags + the whole group. A column bar drags a column. A floating window's title bar drags the window. +- Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, + a filled half for a split. Escape or losing window focus cancels a drag. +- Double-click a tab or drag bar to minimize a group to its strip. +- A column's »/« button collapses it to icons, one icon per panel with a separator between groups. + Widen an iconic column to show panel names. Click an icon to open its group as a flyout on the + canvas side. Drag an icon to move its panel, or the grip above an icon group to move the group. + +## Commands + +With the `serde` feature, `DockCommand

` is the shared control vocabulary. The app puts the +command id under `"command"` in the params and deserializes them. craft-ui has no `serde_json` +dependency. + +```rust,ignore +let mut params = params.clone(); +params["command"] = json!(id); +let command: DockCommand = serde_json::from_value(params)?; +if command.is_app_owned() { + return app.workspace_command(command); +} +let closed = command.apply(&mut app.workspace, |panel| app.permissions(panel))?; +``` + +| Id | Params (`?` is optional) | +|---|---| +| `window.panel.layout` | `{action}`: a serialized `Action` | +| `window.panel.move` | `{panel, anchor, zone?, before?, group?, placement?}` | +| `window.panel.float` | `{panel, x?, y?, width?, height?, group?, column?}` | +| `window.panel.dock` | `{panel, anchor?, zone?, before?, group?, column?, side?}` | +| `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` | +| `window.panel.minimize` | `{panel, minimized?}` | +| `window.panel.iconic` | `{panel, iconic?}` | +| `window.panel.window` | `{panel, native?}` | +| `window.workspace`, `.new`, `.delete` | `{name}` | +| `window.workspace.reset`, `ui.dock.reset` | `{}` | +| `window.workspace.lock` | `{locked?}` | +| `ui.dock` | `{action}`, or `{operation, …}` | + +- `zone` is `tab`, `center`, `left`, `right`, `top`, `bottom`, `above` or `below`. `before` names + the tab to insert before; `null` appends. +- `group` moves the panel's whole group; `column` moves its dock column, or its whole window when + it floats. `side` is `Start` or `End`. +- Without a value, `minimized`, `iconic` and `locked` toggle. +- `ui.dock` operations are those of LightCraft, PDFCraft, CADCraft and SoundCraft: `open`, + `close`, `activate`, `float {rect}`, `moveFloating {rect}`, `move {target, zone?, before?}`, + `setStackOpen {open}`, `resizeStack {height}` and `resizeSplit {path, size}`. `rect` is + `[x, y, width, height]`. + +`to_actions` returns the actions a command makes without applying them. `apply` applies them all +or none and returns the panels it closed, so the app can release their state. Showing a hidden +panel and Lock change the workspace directly. Named workspaces and Reset belong to the app: +`is_app_owned` is true for them and `apply` refuses them. `DockCommand::IDS` lists every id for +the app's command registry. App-specific aliases stay in the app. + +## Labels + +Every visible and accessibility label is a `*_label` field of `DockStyle`, with an English +default. `DockStyle::localized` sets them all from one keyed lookup: + +```rust,ignore +let style = DockStyle::from_ui(ui).localized(|key| app.strings.get(key).cloned()); +``` + +Keys are `dock.close`, `dock.float`, `dock.collapseToIcons` and so on; the rustdoc of `localized` +lists them all. `DockContent::label` and `action_label` can shape panel and action text further; +the logical label stays the accessibility name. + +## Testing + +`DockArea::hit_rects(ctx, id)` lists every gesture source drawn last frame as a `Hit` with its +rect: tabs, drag bars, borders, column bars, »/« buttons, title bars, close buttons, icons, icon +grips, resize edges and dividers. It is always compiled, so an app can return it from a +`ui.docking` control method next to the layout and the focused panel. + +The `testing` feature adds `docking::testing::DockDriver`. It runs a `DockArea` in a headless +egui context with real pointer and key events, and applies the actions each frame emits. + +```rust,ignore +let mut driver = DockDriver::new(app_layout(), Panels::default()); +let bar = driver.hit(&Hit::DragBar(PanelId::Layers)).unwrap(); +driver.drag(bar.center(), egui::pos2(2.0, 300.0)); +driver.settle(); +assert!(driver.hit(&Hit::ColumnBar(PanelId::Layers)).is_some()); +``` + +It also has `press`, `release`, `click`, `hold`, `key`, `focus`, `hits`, and checks for painted +previews (`filled`, `outlined`). + +craft-ui's own tests in `crates/ui/tests/docking_workflows.rs`: + +- Load every app's v1 layout fixture, dock groups into a new dock, a bottom band and a seam, + collapse and expand the column, float it by command and drag it back, then check the layout + reads back as written. +- Render Layers, Properties and Brushes panels with real content, and merge, detach and redock + Brushes by pointer at two widths, two scales and both themes. Set `CRAFT_UI_DOCK_VISUAL_DIR` + to keep the captures: ```sh CRAFT_UI_DOCK_VISUAL_DIR=/absolute/output/path cargo test -p craft-ui --test docking_workflows --all-features ``` -These are offscreen egui checks. An adopting application still needs command, content, workspace -reload, theme and input tests using its own renderer and persistence adapter. +An adopting app still tests its own commands, contents, saved workspaces and themes. -## Application chrome and activation +## What stays in the app -`DockArea::show_customized` accepts one mutable `DockContent

` adapter, with body, -panel-menu, group-header and label methods. Apps queue commands in these callbacks and -apply them after rendering the readonly snapshot. `group_header_width` reserves a bounded -trailing portion of the existing tab strip; its child UI is clipped to that region. -Collapsed accordion entries still have panel menus; collapsing tab groups is host policy. - -`label` returns `WidgetText`, including an application-shaped galley, used for tab width, -painting and menu labels. The separate logical label callback supplies tab accessibility -text. `action_label` independently shapes the localized stock Float/Move/Close menu -text without receiving a panel identity. Its default returns unchanged logical `WidgetText`; -custom visual text never replaces the action's logical accessibility label. Panel targets -and overflow entries continue to use `label`. Original `show` and `show_with_limits` call -sites remain supported. - -Apply `Action::Activate` in the host, then use `DockArea::raise_panel(panel)` on the next -frame to raise the owning in-viewport floating layer and focus the panel tab. This request -does not mutate the serialized layout or persist z-order. Floating area identity still -derives from the first panel; native-window identity remains host-owned. - -Floating groups have a distinct 12-point grip in the existing tab strip. Moving it emits -`MoveFloating` for the whole group; dragging an individual tab detaches just that panel. -`DockOutput::group_drag` and `group_drop` expose the group identity and release position -for app-owned atomic group docking policies. Escape/lost focus restores the group's -starting rectangle. No generic group docking or app command registry is inferred. - -Hosts supply overlay rectangles via `blocked_rects` before showing the surface. These -block drop previews, release actions and float fallback at the pointer, including overlays -appearing mid-drag. Hosts must provide current overlay geometry or cancel docking when -modal state prevents interaction; later-drawn overlays cannot be discovered retroactively. - -`DockArea::chrome_has_focus(ctx, layout)` classifies focus on rendered dock tabs, -collapse buttons, overflow, split/stack dividers, floating resize corners and group -grips. It excludes panel content and custom header/menu widgets and rejects invalid -layouts. Hosts can permit global commands from chrome while reserving Enter, Space, -Tab, Escape and arrow keys for activation, traversal, cancellation and resizing. -Content widgets retain their usual keyboard ownership. The renderer owns the IDs; -hosts do not need to reconstruct them. +- The panel registry, panel contents and document state. +- Named workspaces, Reset, and when and where layouts are saved. +- Menus and key bindings outside the docking chrome. +- Native window ownership on platforms without egui viewports. From 8a0df8c12ff3a3e076fae3bd65dfdcb8b50cf8e0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 12:24:38 +0000 Subject: [PATCH 29/94] docking: fixes from DesignCraft trial step 2 - Permissions::accepts_splits; PROTECTED takes no side splits, so a group dropped on a protected canvas floats. - A press of any pointer button in a panel body, stripless panels included, reports the panel in DockOutput::focused. - Right to left, tab strips, their header and drag bar, insertion slots (DropTarget::right_to_left), accordion headers and chrome::TitleBar (ChromeStyle::right_to_left) mirror. TitleBar truncates galley titles like tab labels. - DockStyle::close_menu_items and close_button hide the built-in close controls without changing Permissions::closable. - Menu labels say what moves: Move Panel to Group (move_panel_to_label) and Move Group to (move_group_to_label). - The column bar's button has its own accessibility labels (collapse_column_label, expand_column_label). - Placement::for_zone maps zones onto what the anchor's container takes; DockCommand uses it and takes right_to_left. - Layout::apply, apply_with_permissions and apply_all return the closed panels. - Placement::Group takes an optional preferred height. --- crates/ui/src/docking/chrome.rs | 42 ++++- crates/ui/src/docking/command.rs | 60 ++++--- crates/ui/src/docking/command_tests.rs | 46 +++++- crates/ui/src/docking/dock_model.rs | 44 ++++- crates/ui/src/docking/dock_tests.rs | 4 +- crates/ui/src/docking/floating_tests.rs | 15 +- crates/ui/src/docking/group_tests.rs | 25 +-- crates/ui/src/docking/iconic_tests.rs | 3 +- crates/ui/src/docking/labels.rs | 14 +- crates/ui/src/docking/model.rs | 81 +++++++--- crates/ui/src/docking/model_tests.rs | 8 +- crates/ui/src/docking/render/dock.rs | 3 +- crates/ui/src/docking/render/floating.rs | 20 ++- crates/ui/src/docking/render/frame.rs | 2 +- crates/ui/src/docking/render/group.rs | 62 +++---- crates/ui/src/docking/render/mod.rs | 12 +- crates/ui/src/docking/surface.rs | 26 ++- crates/ui/src/docking/targets.rs | 21 ++- crates/ui/src/docking/tests.rs | 18 ++- crates/ui/src/docking/trial_tests.rs | 195 ++++++++++++++++++++++- crates/ui/tests/docking_workflows.rs | 2 +- docs/ui-docking.md | 36 +++-- 22 files changed, 587 insertions(+), 152 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index 4c8985a928..f5b6bb6be7 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -3,7 +3,11 @@ //! these; other hosts (task panes) use them with their own ids and actions. Nothing here changes //! a layout: the caller turns the responses into its own commands. -use egui::{Color32, Context, FontId, Id, Key, LayerId, Order, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetText, pos2, vec2}; +use std::sync::Arc; + +use egui::{ + Color32, Context, FontId, Galley, Id, Key, LayerId, Order, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetText, pos2, vec2, +}; use super::{DockStyle, PanelLimits, resize::AnchoredResize}; @@ -24,6 +28,8 @@ pub struct ChromeStyle { pub weak_text: Color32, pub accent: Color32, pub font: FontId, + /// Mirror the title bar: buttons at the left, the title at the right. + pub right_to_left: bool, } impl ChromeStyle { @@ -40,6 +46,7 @@ impl ChromeStyle { weak_text: style.inactive_text, accent: style.accent, font: style.font.clone(), + right_to_left: style.right_to_left, } } } @@ -248,8 +255,21 @@ pub fn clamp(rect: Rect, bounds: Rect) -> Rect { Rect::from_min_size(min, size) } +/// `text` on one line no wider than `width`, cut at the end with '…'. egui does not wrap a +/// host's pre-laid-out `WidgetText::Galley` again, so that one is laid out again from its job. +pub(super) fn truncated(ui: &Ui, text: WidgetText, width: f32, font: FontId) -> Arc { + let galley = text.into_galley(ui, Some(egui::TextWrapMode::Truncate), width, font); + if galley.size().x <= width + 0.5 { + return galley; + } + let mut job = (*galley.job).clone(); + job.wrap = egui::text::TextWrapping::truncate_at_width(width); + ui.painter().layout_job(job) +} + /// A title bar: two grip lines (or a title), an optional ▾ menu button and an optional ×, 10 pt -/// in from the right edge. The bar senses clicks and drags; double-clicks are the caller's. +/// in from the right edge, mirrored when [`ChromeStyle::right_to_left`] is set. The bar senses +/// clicks and drags; double-clicks are the caller's. pub struct TitleBar<'a> { id: Id, move_label: &'a str, @@ -274,7 +294,7 @@ impl<'a> TitleBar<'a> { Self { id, move_label, title: None, menu: None, close: None, movable: true } } - /// Text at the left instead of the grip lines. + /// Text at the leading edge instead of the grip lines, cut with '…' to fit. pub fn title(mut self, title: impl Into) -> Self { self.title = Some(title.into()); self @@ -302,17 +322,27 @@ impl<'a> TitleBar<'a> { let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); painter.rect_filled(rect, 0.0, style.title_background); let side = rect.height(); + // Laid out left to right, then mirrored in a right-to-left layout. + let mirror = |r: Rect| { + if style.right_to_left { + Rect::from_x_y_ranges((rect.left() + rect.right() - r.right())..=(rect.left() + rect.right() - r.left()), r.y_range()) + } else { + r + } + }; let close_rect = self.close.map(|_| Rect::from_center_size(pos2(rect.right() - 10.0, rect.center().y), vec2(side, side))); let menu_right = close_rect.map_or(rect.right() - 3.0, |close| close.left() - 2.0); let menu_rect = self.menu.map(|_| Rect::from_min_max(pos2(menu_right - side, rect.top()), pos2(menu_right, rect.bottom()))); let buttons = menu_rect.or(close_rect).map_or(rect.right(), |r| r.left()); - let bar_rect = Rect::from_min_max(rect.min, pos2(buttons.max(rect.left()), rect.bottom())); + let bar_rect = mirror(Rect::from_min_max(rect.min, pos2(buttons.max(rect.left()), rect.bottom()))); + let (close_rect, menu_rect) = (close_rect.map(mirror), menu_rect.map(mirror)); let bar = ui.interact(bar_rect, self.id, Sense::click_and_drag()); let bar = if self.movable { bar.on_hover_cursor(egui::CursorIcon::Grab) } else { bar }; bar.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.move_label)); if let Some(title) = self.title { - let galley = title.into_galley(ui, Some(egui::TextWrapMode::Truncate), (bar_rect.width() - 12.0).max(0.0), style.font.clone()); - painter.galley(pos2(rect.left() + 6.0, rect.center().y - galley.size().y * 0.5), galley, style.text); + let galley = truncated(ui, title, (bar_rect.width() - 12.0).max(0.0), style.font.clone()); + let x = if style.right_to_left { bar_rect.right() - 6.0 - galley.size().x } else { bar_rect.left() + 6.0 }; + painter.galley(pos2(x, rect.center().y - galley.size().y * 0.5), galley, style.text); } else { let grip = Stroke::new(0.6, style.weak_text); for k in 0..2 { diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index da75068b16..e0b26d6070 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -7,7 +7,7 @@ //! let mut params = params.clone(); //! params["command"] = json!(id); //! let command: DockCommand = serde_json::from_value(params)?; -//! command.apply(&mut app.workspace, |p| app.permissions(p))?; +//! command.apply(&mut app.workspace, style.right_to_left, |p| app.permissions(p))?; //! ``` use std::hash::Hash; @@ -40,7 +40,8 @@ const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0]; /// | `ui.dock` | `{action}`, or `{operation, …}`, see [`DockOperation`] | /// /// `zone` is `tab` (the default for `move` and `dock`), `center`, `left`, `right`, `top`, -/// `bottom`, `above` or `below` (a new group in a dock column or floating stack). `before` +/// `bottom`, `above` or `below` (a new group in a dock column or floating stack). The side +/// zones map onto the anchor's container with [`Placement::for_zone`]. `before` /// names the tab to insert before; `null` appends. `group` moves the panel's whole group, /// `column` its dock column. `side` is `Start` or `End`. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -232,21 +233,29 @@ fn required<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> T::deserialize(deserializer) } -/// `zone` and `before` as a placement. `default` is the zone when none is given. -fn placement(zone: Option, before: &Option>, default: ZoneName) -> Result, DockError> { - let before = before.clone(); - Ok(match (zone.unwrap_or(default), before) { - (ZoneName::Tab | ZoneName::Center, Some(before)) => Placement::Tab { before }, - (ZoneName::Tab, None) => Placement::Tab { before: None }, - (ZoneName::Center, None) => Placement::Split(Zone::Center), - (_, Some(_)) => return Err(DockError::InvalidPlacement), - (ZoneName::Left, None) => Placement::Split(Zone::Left), - (ZoneName::Right, None) => Placement::Split(Zone::Right), - (ZoneName::Top, None) => Placement::Split(Zone::Top), - (ZoneName::Bottom, None) => Placement::Split(Zone::Bottom), - (ZoneName::Above, None) => Placement::Group { below: false }, - (ZoneName::Below, None) => Placement::Group { below: true }, - }) +/// Where a command puts what it moves relative to `anchor`: `zone` and `before`, with side +/// zones mapped by [`Placement::for_zone`]. `default` is the zone when none is given. +struct Zoned<'a, P> { + layout: &'a Layout

, + right_to_left: bool, +} + +impl Zoned<'_, P> { + fn placement(&self, anchor: &P, zone: Option, before: &Option>, default: ZoneName) -> Result, DockError> { + let side = |zone| Placement::for_zone(self.layout, anchor, zone, self.right_to_left); + Ok(match (zone.unwrap_or(default), before.clone()) { + (ZoneName::Tab | ZoneName::Center, Some(before)) => Placement::Tab { before }, + (ZoneName::Tab, None) => Placement::Tab { before: None }, + (ZoneName::Center, None) => Placement::Split(Zone::Center), + (_, Some(_)) => return Err(DockError::InvalidPlacement), + (ZoneName::Left, None) => side(Zone::Left)?, + (ZoneName::Right, None) => side(Zone::Right)?, + (ZoneName::Top, None) => side(Zone::Top)?, + (ZoneName::Bottom, None) => side(Zone::Bottom)?, + (ZoneName::Above, None) => Placement::Group { below: false, height: None }, + (ZoneName::Below, None) => Placement::Group { below: true, height: None }, + }) + } } /// How much of the layout a command moves. @@ -319,8 +328,13 @@ impl DockCommand

{ /// belong to the application: those return [`DockError::NotAllowed`]; use [`Self::apply`]. /// A panel or anchor that is not shown returns [`DockError::MissingPanel`] or /// [`DockError::MissingTarget`]. - pub fn to_actions(&self, workspace: &Workspace

) -> Result>, DockError> { + /// + /// `left`, `right`, `top` and `bottom` zones follow [`Placement::for_zone`]: beside a docked + /// anchor they make a new column or group, and `right_to_left` is the + /// [`super::DockStyle::right_to_left`] the layout is drawn with. + pub fn to_actions(&self, workspace: &Workspace

, right_to_left: bool) -> Result>, DockError> { let layout = &workspace.layout; + let zoned = Zoned { layout, right_to_left }; let shown = |panel: &P| if layout.contains(panel) { Ok(()) } else { Err(DockError::MissingPanel) }; let one = |action: Action

| Ok(vec![action]); match self { @@ -329,7 +343,7 @@ impl DockCommand

{ shown(panel)?; let placement = match given { Some(placement) => placement.clone(), - None => placement(*zone, before, ZoneName::Tab)?, + None => zoned.placement(anchor, *zone, before, ZoneName::Tab)?, }; one(Unit::of(*group, false).to(layout, panel, Target::At { anchor: anchor.clone(), placement })?) } @@ -358,7 +372,7 @@ impl DockCommand

{ shown(panel)?; let unit = Unit::of(*group, *column); if let Some(anchor) = anchor { - let placement = placement(*zone, before, ZoneName::Tab)?; + let placement = zoned.placement(anchor, *zone, before, ZoneName::Tab)?; return one(unit.to(layout, panel, Target::At { anchor: anchor.clone(), placement })?); } if let Some(side) = side { @@ -425,7 +439,7 @@ impl DockCommand

{ DockOperation::Float { panel, rect } => one(Action::Float { panel: panel.clone(), rect: *rect }), DockOperation::MoveFloating { panel, rect } => one(Action::MoveFloating { panel: panel.clone(), rect: *rect }), DockOperation::Move { panel, target, zone, before } => { - let placement = placement(*zone, before, ZoneName::Center)?; + let placement = zoned.placement(target, *zone, before, ZoneName::Center)?; one(Action::Move { panel: panel.clone(), anchor: target.clone(), placement }) } DockOperation::SetStackOpen { panel, open } => one(Action::SetStackOpen { panel: panel.clone(), open: *open }), @@ -442,7 +456,7 @@ impl DockCommand

{ /// the application can release their state. Showing a hidden panel restores its last /// location; Lock sets [`Workspace::locked`]. Application-owned commands /// ([`Self::is_app_owned`]) return [`DockError::NotAllowed`] and change nothing. - pub fn apply(&self, workspace: &mut Workspace

, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { + pub fn apply(&self, workspace: &mut Workspace

, right_to_left: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { let show = match self { Self::Activate { panel } | Self::Dock { panel, anchor: None, side: None, .. } @@ -457,7 +471,7 @@ impl DockCommand

{ workspace.locked = locked.unwrap_or(!workspace.locked); return Ok(Vec::new()); } - let actions = self.to_actions(workspace)?; + let actions = self.to_actions(workspace, right_to_left)?; workspace.apply_all(actions, permissions) } } diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index b106a39d3e..c84051bf74 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -40,14 +40,14 @@ fn parse(params: Value) -> Result, serde_json::Error> { /// The actions `params` makes on a fresh workspace. fn actions(params: Value) -> Vec> { let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); - command.to_actions(&workspace()).unwrap_or_else(|e| panic!("{params}: {e}")) + command.to_actions(&workspace(), false).unwrap_or_else(|e| panic!("{params}: {e}")) } /// Apply `params` to a fresh workspace; return it and the panels closed. fn applied(params: Value) -> (Workspace

, Vec

) { let mut workspace = workspace(); let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); - let closed = command.apply(&mut workspace, permissions).unwrap_or_else(|e| panic!("{params}: {e}")); + let closed = command.apply(&mut workspace, false, permissions).unwrap_or_else(|e| panic!("{params}: {e}")); (workspace, closed) } @@ -56,7 +56,7 @@ fn rejected(params: Value, error: DockError) { let mut workspace = workspace(); let before = workspace.clone(); let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); - assert_eq!(command.apply(&mut workspace, permissions), Err(error), "{params}"); + assert_eq!(command.apply(&mut workspace, false, permissions), Err(error), "{params}"); assert_eq!(workspace, before, "{params}"); } @@ -90,12 +90,15 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { assert_eq!(actions(with(json!({"before": "channels"}))), mv(tab(Some("channels")))); assert_eq!(actions(with(json!({"zone": "center", "before": null}))), mv(tab(None))); assert_eq!(actions(with(json!({"zone": "center"}))), mv(Placement::Split(Zone::Center))); - assert_eq!(actions(with(json!({"zone": "Left"}))), mv(Placement::Split(Zone::Left))); - assert_eq!(actions(with(json!({"zone": "below"}))), mv(Placement::Group { below: true })); + assert_eq!(actions(with(json!({"zone": "Left"}))), mv(Placement::Column { after: false })); + assert_eq!(actions(with(json!({"zone": "below"}))), mv(Placement::Group { below: true, height: None })); assert_eq!(actions(with(json!({"placement": {"Column": {"after": true}}}))), mv(Placement::Column { after: true })); assert_eq!( actions(with(json!({"group": true, "zone": "above"}))), - vec![Action::MoveGroup { panel: s("history"), to: Target::At { anchor: s("layers"), placement: Placement::Group { below: false } } }] + vec![Action::MoveGroup { + panel: s("history"), + to: Target::At { anchor: s("layers"), placement: Placement::Group { below: false, height: None } } + }] ); // float: a docked panel, a lone floating panel, a group and a column. @@ -219,7 +222,7 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers"}))), to_layers(Placement::Split(Zone::Center))); assert_eq!( actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "zone": "left"}))), - to_layers(Placement::Split(Zone::Left)) + to_layers(Placement::Column { after: false }) ); assert_eq!(actions(op(json!({"operation": "move", "panel": "color", "target": "layers", "before": null}))), to_layers(tab(None))); assert_eq!( @@ -278,6 +281,33 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { let mut locked = workspace(); locked.locked = true; let before = locked.clone(); - assert!(parse(json!({"command": "window.panel.window", "panel": "layers"})).unwrap().apply(&mut locked, permissions).is_err()); + assert!(parse(json!({"command": "window.panel.window", "panel": "layers"})).unwrap().apply(&mut locked, false, permissions).is_err()); assert_eq!(locked, before); } + +#[test] +fn side_zones_map_to_the_placement_the_anchor_container_takes_in_either_direction() { + let command = + |zone: &str, anchor: &str| parse(json!({"command": "window.panel.move", "panel": "history", "anchor": anchor, "zone": zone})).unwrap(); + let placed = |zone: &str, anchor: &str, rtl: bool| match command(zone, anchor).to_actions(&workspace(), rtl) { + Ok(actions) => match actions.as_slice() { + [Action::Move { placement, .. }] => Ok(placement.clone()), + other => panic!("{other:?}"), + }, + Err(error) => Err(error), + }; + // A start dock is on the left edge left to right, on the right edge right to left. + assert_eq!(placed("right", "layers", false), Ok(Placement::Column { after: true })); + assert_eq!(placed("right", "layers", true), Ok(Placement::Column { after: false })); + assert_eq!(placed("left", "layers", true), Ok(Placement::Column { after: true })); + assert_eq!(placed("top", "layers", false), Ok(Placement::Group { below: false, height: None })); + assert_eq!(placed("bottom", "color", false), Ok(Placement::Group { below: true, height: None })); + assert_eq!(placed("left", "color", false), Err(DockError::InvalidPlacement)); + assert_eq!(placed("left", "canvas", true), Ok(Placement::Split(Zone::Left))); + + let (workspace, _) = applied(json!({"command": "window.panel.move", "panel": "history", "anchor": "layers", "zone": "right"})); + let Some(Node::Split { first, .. }) = &workspace.layout.root else { panic!() }; + let Node::Dock { columns, .. } = &**first else { panic!() }; + assert_eq!(columns.len(), 2); + assert_eq!(columns[1].groups[0].panels, vec![s("history")]); +} diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index 7049543f81..ea88d380fb 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -6,7 +6,7 @@ use std::hash::Hash; -use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, Node, Placement, Zone, valid_rect, valid_width}; +use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, Node, Placement, Zone, valid_height, valid_rect, valid_width}; use crate::layout::{SplitAxis, SplitSize}; /// Width of a new column when nothing better is known. @@ -84,6 +84,39 @@ pub enum Target

{ Float { rect: Option<[f32; 4]> }, } +impl Placement

{ + /// The placement for a drop zone on `anchor`'s group, in the vocabulary its container + /// accepts. `zone` is physical: `Left` is the left half on screen in either direction. + /// + /// | Anchor in | `Center` | `Top`, `Bottom` | `Left`, `Right` | + /// |---|---|---|---| + /// | the split tree | [`Placement::Split`] | `Split` | `Split` | + /// | a dock column | `Split(Center)` (join as tabs) | [`Placement::Group`] above or below | [`Placement::Column`] on that side | + /// | a floating window | `Split(Center)` | `Group` above or below | [`DockError::InvalidPlacement`] | + /// + /// A dock's `Column { after }` counts from its window edge, which depends on the dock's + /// side and `right_to_left` (see [`Side`]); this picks `after` so the new column lands on + /// the zone's side of the anchor's column. + pub fn for_zone(layout: &Layout

, anchor: &P, zone: Zone, right_to_left: bool) -> Result { + let place = layout.place(anchor).ok_or(DockError::MissingTarget)?; + Ok(match (place, zone) { + (Place::Node(_), zone) | (_, zone @ Zone::Center) => Placement::Split(zone), + (Place::Dock { .. } | Place::Floating { .. }, Zone::Top | Zone::Bottom) => Placement::Group { below: zone == Zone::Bottom, height: None }, + (Place::Floating { .. }, _) => return Err(DockError::InvalidPlacement), + (Place::Dock { path, .. }, _) => { + let side = match layout.root.as_ref().and_then(|root| node_at(root, &path)) { + Some(Node::Dock { side, .. }) => *side, + _ => return Err(DockError::MissingTarget), + }; + // The physical edge of the dock: Start is left in a left-to-right layout. + let left_edge = (side == Side::Start) != right_to_left; + // `after` is away from the window edge: rightwards for a left dock. + Placement::Column { after: (zone == Zone::Right) == left_edge } + } + }) + } +} + /// What the Window menu shows for a panel. The model does not track the z-order of floating /// windows, so `Front` means "showing": the active tab of an expanded group in an expanded column. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -501,7 +534,14 @@ impl Layout

{ *node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) }; Ok(()) } - Placement::Group { below } => { + Placement::Group { below, height } => { + if !valid_height(height) { + return Err(DockError::InvalidGeometry); + } + let mut moving = moving; + if height.is_some() { + moving.groups.iter_mut().for_each(|group| group.height = height); + } let (groups, index) = match &place { Place::Dock { group, .. } => (&mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups, *group), Place::Floating { window, group } => { diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index b924429f09..b49c60a58d 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -211,7 +211,7 @@ fn group_dropped_on_a_seam_inserts_between_and_shows_a_horizontal_line() { d.hold(bar(&d, 5), seam); assert!(d.painted(hline(307.0, 0.0..=240.0)), "a horizontal line across the column at the seam"); let out = d.step(vec![button(seam, false)]); - assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Group { below: true } }))); + assert_eq!(moved(&out.actions), Some((5, &Target::At { anchor: 2, placement: Placement::Group { below: true, height: None } }))); assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![5], vec![3]]]); assert!(d.layout.floating.is_empty()); } @@ -220,7 +220,7 @@ fn group_dropped_on_a_seam_inserts_between_and_shows_a_horizontal_line() { fn a_tab_dropped_on_a_seam_or_column_edge_moves_only_that_panel() { let mut d = Driver::new(docked(Side::Start, &[&[&[2, 3], &[4]]])); let out = d.drag(d.tab(3).center(), pos2(120.0, 309.0)); - assert_eq!(out.actions, vec![Action::Move { panel: 3, anchor: 2, placement: Placement::Group { below: true } }]); + assert_eq!(out.actions, vec![Action::Move { panel: 3, anchor: 2, placement: Placement::Group { below: true, height: None } }]); assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2], vec![3], vec![4]]]); d.settle(); d.drag(d.tab(4).center(), pos2(246.0, 200.0)); diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 2f7cfb58a8..008994c8fa 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -204,7 +204,8 @@ fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_gro // Released over another window's lower band: its groups stack below that window's. let out = d.drag(title, pos2(660.0, 480.0)); assert!( - out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::At { anchor: 8, placement: Placement::Group { below: true } } }), + out.actions + .contains(&Action::MoveWindow { panel: 5, to: Target::At { anchor: 8, placement: Placement::Group { below: true, height: None } } }), "{:?}", out.actions ); @@ -237,7 +238,8 @@ fn title_bar_drag_onto_dock_targets_docks_the_window() { let seam = pos2(120.0, d.tab(4).unwrap().top()); let out = d.drag(title, seam); assert!( - out.actions.contains(&Action::MoveWindow { panel: 8, to: Target::At { anchor: 2, placement: Placement::Group { below: true } } }), + out.actions + .contains(&Action::MoveWindow { panel: 8, to: Target::At { anchor: 2, placement: Placement::Group { below: true, height: None } } }), "{:?}", out.actions ); @@ -262,7 +264,8 @@ fn floating_stack_seams_and_bands_insert_groups() { let bar = d.response(Id::new(AREA).with(("drag-bar", Some(&6u32)))).unwrap().center(); let out = d.drag(bar, pos2(660.0, 360.0)); assert!( - out.actions.contains(&Action::MoveGroup { panel: 6, to: Target::At { anchor: 8, placement: Placement::Group { below: false } } }), + out.actions + .contains(&Action::MoveGroup { panel: 6, to: Target::At { anchor: 8, placement: Placement::Group { below: false, height: None } } }), "{:?}", out.actions ); @@ -274,7 +277,11 @@ fn floating_stack_seams_and_bands_insert_groups() { let tab = d.tab(8).unwrap().center(); let seam = pos2(420.0, 237.0); let out = d.drag(tab, seam); - assert!(out.actions.contains(&Action::Move { panel: 8, anchor: 5, placement: Placement::Group { below: true } }), "{:?}", out.actions); + assert!( + out.actions.contains(&Action::Move { panel: 8, anchor: 5, placement: Placement::Group { below: true, height: None } }), + "{:?}", + out.actions + ); assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![8], vec![6, 7]]); // The divider between two open groups resizes both. diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index f9801054ac..0577a628ec 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -89,6 +89,8 @@ struct Driver { modifiers: Modifiers, focused: bool, transparent: bool, + /// Applied to the style every frame. + tweak: fn(&mut DockStyle), shapes: Vec, time: f64, } @@ -107,6 +109,7 @@ impl Driver { modifiers: Modifiers::NONE, focused: true, transparent: false, + tweak: |_| {}, shapes: Vec::new(), time: 0.0, }; @@ -126,13 +129,14 @@ impl Driver { time: Some(self.time), ..Default::default() }; - let (layout, content, area, transparent) = (&self.layout, &mut self.content, self.area, self.transparent); + let (layout, content, area, transparent, tweak) = (&self.layout, &mut self.content, self.area, self.transparent, self.tweak); let mut full = self.ctx.run_ui(input, |ui| { let mut style = DockStyle::from_ui(ui); if transparent { style.background = Color32::TRANSPARENT; style.tab_background = Color32::TRANSPARENT; } + tweak(&mut style); ui.scope_builder(UiBuilder::new().max_rect(area), |ui| { output = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content); }); @@ -274,21 +278,24 @@ fn top_border_drags_the_group_and_the_menu_button_only_clicks() { } #[test] -fn group_drop_on_a_frame_edge_splits_and_on_a_protected_canvas_centre_floats() { +fn group_drop_on_a_frame_edge_splits_and_on_a_protected_canvas_floats() { let canvas = || TestContent { protected: vec![1], ..Default::default() }; let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0)); - let mut d = Driver::with(frames(), canvas(), area); + let mut d = Driver::with(frames(), TestContent::default(), area); let out = d.drag(d.rect("drag-bar", 2).center(), pos2(20.0, 300.0)); assert!(matches!(moved_group(&out.actions), Some(Target::At { anchor: 1, placement: Placement::Split(Zone::Left) })), "{:?}", out.actions); let Some(Node::Split { first, second, .. }) = &d.layout.root else { panic!() }; assert_eq!(**first, tabs(&[2, 3], 1)); assert_eq!(**second, tabs(&[1], 0)); - // The canvas centre takes nothing: no join, no preview; the group floats there. - let mut d = Driver::with(frames(), canvas(), area); - let out = d.drag(d.rect("drag-bar", 2).center(), pos2(150.0, 300.0)); - assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); - assert_eq!(d.layout.root, Some(tabs(&[1], 0))); + // A protected canvas takes nothing, at its centre or its edge: no join, no split, no + // preview; the group floats there. + for at in [pos2(150.0, 300.0), pos2(20.0, 300.0)] { + let mut d = Driver::with(frames(), canvas(), area); + let out = d.drag(d.rect("drag-bar", 2).center(), at); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); + assert_eq!(d.layout.root, Some(tabs(&[1], 0))); + } } #[test] @@ -508,7 +515,7 @@ fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() { 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); - for label in ["Close Tab Group", "Minimize", "Float Tab Group", "Group with"] { + for label in ["Close Tab Group", "Minimize", "Float Tab Group", "Move Group to"] { assert_eq!(h.query_all_by_label(label).count(), 1, "{label}"); } h.get_by_label("Close Tab Group").click(); diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index cbcef4ef1b..62a2473b5d 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -254,7 +254,8 @@ fn group_dropped_on_an_iconic_column_joins_as_an_icon_group() { assert!(d.filled(line), "with the insertion line under group 1"); let out = d.release(target); assert!( - out.actions.contains(&Action::MoveGroup { panel: 5, to: Target::At { anchor: 1, placement: Placement::Group { below: true } } }), + out.actions + .contains(&Action::MoveGroup { panel: 5, to: Target::At { anchor: 1, placement: Placement::Group { below: true, height: None } } }), "{:?}", out.actions ); diff --git a/crates/ui/src/docking/labels.rs b/crates/ui/src/docking/labels.rs index 623c38e13b..7e8a60ee83 100644 --- a/crates/ui/src/docking/labels.rs +++ b/crates/ui/src/docking/labels.rs @@ -19,7 +19,7 @@ impl DockStyle { /// |---|---|---| /// | `dock.float` | `float_label` | Float panel | /// | `dock.close` | `close_label` | Close panel | - /// | `dock.move` | `move_label` | Move to group | + /// | `dock.movePanelTo` | `move_panel_to_label` | Move Panel to Group | /// | `dock.panels` | `panels_label` | Panels | /// | `dock.resize` | `resize_label` | Resize panels | /// | `dock.resizeWindow` | `resize_window_label` | Resize panel window | @@ -28,10 +28,12 @@ impl DockStyle { /// | `dock.minimize` | `minimize_label` | Minimize | /// | `dock.expand` | `expand_label` | Expand | /// | `dock.floatGroup` | `float_group_label` | Float Tab Group | - /// | `dock.groupWith` | `group_with_label` | Group with | + /// | `dock.moveGroupTo` | `move_group_to_label` | Move Group to | /// | `dock.moveColumn` | `move_column_label` | Move panel column | /// | `dock.collapseToIcons` | `collapse_to_icons_label` | Collapse to Icons | /// | `dock.expandPanels` | `expand_panels_label` | Expand Panels | + /// | `dock.collapseColumn` | `collapse_column_label` | Collapse column to icons | + /// | `dock.expandColumn` | `expand_column_label` | Expand column | /// | `dock.moveWindow` | `move_window_label` | Move panel window | /// | `dock.closeWindow` | `close_window_label` | Close panel window | /// | `dock.undock` | `undock_label` | Undock Panel | @@ -52,11 +54,11 @@ impl DockStyle { self } - fn labels_mut(&mut self) -> [(&'static str, &mut String); 25] { + fn labels_mut(&mut self) -> [(&'static str, &mut String); 27] { [ ("dock.float", &mut self.float_label), ("dock.close", &mut self.close_label), - ("dock.move", &mut self.move_label), + ("dock.movePanelTo", &mut self.move_panel_to_label), ("dock.panels", &mut self.panels_label), ("dock.resize", &mut self.resize_label), ("dock.resizeWindow", &mut self.resize_window_label), @@ -65,10 +67,12 @@ impl DockStyle { ("dock.minimize", &mut self.minimize_label), ("dock.expand", &mut self.expand_label), ("dock.floatGroup", &mut self.float_group_label), - ("dock.groupWith", &mut self.group_with_label), + ("dock.moveGroupTo", &mut self.move_group_to_label), ("dock.moveColumn", &mut self.move_column_label), ("dock.collapseToIcons", &mut self.collapse_to_icons_label), ("dock.expandPanels", &mut self.expand_panels_label), + ("dock.collapseColumn", &mut self.collapse_column_label), + ("dock.expandColumn", &mut self.expand_column_label), ("dock.moveWindow", &mut self.move_window_label), ("dock.closeWindow", &mut self.close_window_label), ("dock.undock", &mut self.undock_label), diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 3d2da9babf..75391f6e48 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -158,7 +158,7 @@ impl

Default for Layout

{ } } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[non_exhaustive] pub enum Placement

{ @@ -168,7 +168,13 @@ pub enum Placement

{ /// `Tabs` and `Stack` nodes only. Split(Zone), /// A new group above or below the anchor's group, in a dock column or a floating stack. - Group { below: bool }, + /// `height` is the inserted group's preferred height ([`super::Group::height`]); `None` + /// keeps a moved group's own height, or shares the free height for a new group. + Group { + below: bool, + #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))] + height: Option, + }, /// A new column before (towards the window edge) or after the anchor's column. Column { after: bool }, /// A new frame along one edge of the docked layout, a quarter of its width or height: the @@ -306,29 +312,39 @@ pub enum Action

{ }, } -/// Rendering and command adapters can protect a document canvas while leaving panels movable. +/// What may happen to a panel. [`Layout::apply_with_permissions`] enforces these for every +/// action, whoever issues it. They also decide which gestures and menu items the renderer +/// offers; [`super::DockStyle::close_menu_items`] and [`super::DockStyle::close_button`] hide +/// the built-in close controls of a panel that stays closable by command. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, + /// Other panels may join this panel's group as tabs. pub accepts_tabs: bool, + /// Other panels may split this panel's frame (`Placement::Split` with a side zone). + /// Outer-edge frames ([`Placement::Edge`]) are not splits of the anchor. + pub accepts_splits: bool, } impl Default for Permissions { fn default() -> Self { - Self { movable: true, floatable: true, closable: true, accepts_tabs: true } + Self { movable: true, floatable: true, closable: true, accepts_tabs: true, accepts_splits: true } } } impl Permissions { - pub const PROTECTED: Self = Self { movable: false, floatable: false, closable: false, accepts_tabs: false }; + /// A document canvas: it stays docked and open, and takes neither tabs nor side splits. + /// A group dropped on it floats there. An application that opens panels beside its canvas + /// uses `Permissions { accepts_splits: true, ..Permissions::PROTECTED }`. + pub const PROTECTED: Self = Self { movable: false, floatable: false, closable: false, accepts_tabs: false, accepts_splits: false }; - /// Lock Workspace: nothing moves, floats or closes; tab drops keep their policy. + /// Lock Workspace: nothing moves, floats or closes; tab and split drops keep their policy. /// [`super::Workspace::apply`] applies this when the workspace is locked; an application /// with a global lock preference applies it in its own permissions callback. pub fn locked(self) -> Self { - Self { movable: false, floatable: false, closable: false, accepts_tabs: self.accepts_tabs } + Self { movable: false, floatable: false, closable: false, ..self } } } @@ -380,7 +396,7 @@ fn valid_size(size: SplitSize) -> bool { } } -fn valid_height(height: Option) -> bool { +pub(super) fn valid_height(height: Option) -> bool { height.is_none_or(|v| v.is_finite() && (0.0..=MAX_EXTENT).contains(&v)) } @@ -504,7 +520,7 @@ impl Layout

{ } /// The panels `panel` can join as a tab: every other panel whose permissions accept tabs. - /// A "Move to group" menu with an empty answer has nothing to offer and stays hidden. + /// A "Move Panel to Group" menu with an empty answer has nothing to offer and stays hidden. pub fn move_targets(&self, panel: &P, permissions: impl Fn(&P) -> Permissions) -> Vec<&P> { self.panels().into_iter().filter(|target| *target != panel && permissions(target).accepts_tabs).collect() } @@ -540,10 +556,10 @@ impl Layout

{ let first = |g: Option<&Group

>| g.and_then(|g| g.panels.first()).cloned(); if let Some(anchor) = first(groups.get(group + 1)) { location.anchor = Some(anchor); - location.placement = Placement::Group { below: false }; + location.placement = Placement::Group { below: false, height: None }; } else if let Some(anchor) = first(group.checked_sub(1).and_then(|i| groups.get(i))) { location.anchor = Some(anchor); - location.placement = Placement::Group { below: true }; + location.placement = Placement::Group { below: true, height: None }; } else if groups.len() == 1 && let Place::Dock { path, column, .. } = &place && let Some(Node::Dock { columns, .. }) = self.root.as_ref().and_then(|root| node_at(root, path)) @@ -686,21 +702,23 @@ impl Layout

{ Ok(()) } - pub fn apply(&mut self, action: Action

) -> Result<(), DockError> { + /// [`Self::apply_with_permissions`] with default permissions. + pub fn apply(&mut self, action: Action

) -> Result, DockError> { self.apply_with_permissions(action, |_| Permissions::default()) } - /// Check application policy before making an atomic change. The callback must be stable - /// throughout one call. Registry validation remains with the application, particularly Open. - pub fn apply_with_permissions(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + /// Check application policy before making an atomic change, and return the panels the + /// action closed (see [`Self::closed_by`]) so the application can release their state. + /// The callback must be stable throughout one call. Registry validation remains with the + /// application, particularly Open. + pub fn apply_with_permissions(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { self.validate()?; match &action { Action::Move { panel, anchor, placement } | Action::OpenAt { panel, anchor, placement } => { if !permissions(panel).movable { return Err(DockError::NotAllowed); } - let tab = matches!(placement, Placement::Tab { .. } | Placement::Split(Zone::Center)); - if tab && !permissions(anchor).accepts_tabs { + if !placement_allowed(placement, permissions(anchor)) { return Err(DockError::NotAllowed); } } @@ -715,9 +733,7 @@ impl Layout

{ } match to { Target::Float { .. } if members.iter().any(|p| !permissions(p).floatable) => return Err(DockError::NotAllowed), - Target::At { anchor, placement: Placement::Tab { .. } | Placement::Split(Zone::Center) } - if !members.contains(anchor) && !permissions(anchor).accepts_tabs => - { + Target::At { anchor, placement } if !members.contains(anchor) && !placement_allowed(placement, permissions(anchor)) => { return Err(DockError::NotAllowed); } _ => {} @@ -735,26 +751,29 @@ impl Layout

{ } _ => {} } + let closed = self.closed_by(&action)?; let mut proposed = self.clone(); proposed.apply_inner(action)?; proposed.validate()?; *self = proposed; - Ok(()) + Ok(closed) } /// Apply every action in order, or none: the first rejection leaves the layout unchanged. - pub fn apply_all(&mut self, actions: impl IntoIterator>, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { + /// Returns every panel the actions closed, in order. + pub fn apply_all(&mut self, actions: impl IntoIterator>, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { let mut proposed = self.clone(); + let mut closed = Vec::new(); for action in actions { - proposed.apply_with_permissions(action, &permissions)?; + closed.extend(proposed.apply_with_permissions(action, &permissions)?); } *self = proposed; - Ok(()) + Ok(closed) } /// The panels a close action (`Close`, `CloseGroup`, `CloseWindow`, `CloseOthers`) would - /// remove, in group order, so the application can release their state once the action is - /// applied. Empty for other actions. + /// remove, in group order. Empty for other actions. The apply methods return the same + /// list; this one answers before applying. pub fn closed_by(&self, action: &Action

) -> Result, DockError> { Ok(match action { Action::Close { panel } => vec![panel.clone()], @@ -990,6 +1009,16 @@ impl Layout

{ } } +/// Whether the anchor's permissions take this placement: tabs need `accepts_tabs`, side +/// splits `accepts_splits`. +fn placement_allowed

(placement: &Placement

, anchor: Permissions) -> bool { + match placement { + Placement::Tab { .. } | Placement::Split(Zone::Center) => anchor.accepts_tabs, + Placement::Split(_) => anchor.accepts_splits, + _ => true, + } +} + fn unit_of

(action: &Action

) -> Unit { match action { Action::MoveColumn { .. } => Unit::Column, diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index 1309aa716b..5a6843eb6d 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -62,9 +62,9 @@ fn panels_of(groups: &[Group]) -> Vec> { #[test] fn group_moves_keep_order_active_tab_and_minimized_state() { let targets = [ - Target::At { anchor: 5, placement: Placement::Group { below: true } }, + Target::At { anchor: 5, placement: Placement::Group { below: true, height: None } }, Target::At { anchor: 5, placement: Placement::Column { after: true } }, - Target::At { anchor: 8, placement: Placement::Group { below: false } }, + Target::At { anchor: 8, placement: Placement::Group { below: false, height: None } }, Target::NewDock { side: Side::Start }, Target::Float { rect: Some([20.0, 20.0, 200.0, 300.0]) }, Target::Float { rect: None }, @@ -143,7 +143,7 @@ fn column_moves_and_floats_keep_every_group() { #[test] fn window_docks_as_stacked_groups_or_merges_as_tabs() { let mut layout = docked(); - layout.apply(Action::MoveWindow { panel: 8, to: Target::At { anchor: 4, placement: Placement::Group { below: true } } }).unwrap(); + layout.apply(Action::MoveWindow { panel: 8, to: Target::At { anchor: 4, placement: Placement::Group { below: true, height: None } } }).unwrap(); assert_eq!(panels_of(&dock(&layout, Side::End)[0].groups), [vec![2, 3], vec![4], vec![6, 7], vec![8]]); assert!(layout.floating.is_empty()); @@ -287,7 +287,7 @@ fn locked_workspace_rejects_structure_but_allows_activate_open_minimize_and_resi Action::Move { panel: 2, anchor: 5, placement: Placement::Tab { before: None } }, Action::MoveGroup { panel: 2, to: Target::Float { rect: None } }, Action::MoveColumn { panel: 5, to: Target::NewDock { side: Side::Start } }, - Action::MoveWindow { panel: 6, to: Target::At { anchor: 4, placement: Placement::Group { below: true } } }, + Action::MoveWindow { panel: 6, to: Target::At { anchor: 4, placement: Placement::Group { below: true, height: None } } }, Action::Float { panel: 4, rect: [0.0, 0.0, 100.0, 100.0] }, Action::MoveFloating { panel: 6, rect: [0.0, 0.0, 100.0, 100.0] }, Action::Close { panel: 4 }, diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index ae6646ee92..32d7240a8b 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -346,7 +346,8 @@ impl Renderer<'_, P> { if usable(button) { let response = ui.interact(button, self.id.with(("column-collapse", Some(first))), Sense::click()); self.register_interaction(ui.ctx(), response.id); - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &label)); + let button_label = if column.iconic { &self.style.expand_column_label } else { &self.style.collapse_column_label }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), button_label)); // The arrows point where the column goes: towards the window edge when it collapses. let glyph = if (edge == Edge::Left) != column.iconic { "«" } else { "»" }; let color = if response.hovered() || response.has_focus() { self.style.text } else { self.style.inactive_text }; diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index becbd1dca8..1ac0b65f42 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -109,7 +109,7 @@ impl Renderer<'_, P> { fn title_bar(&mut self, ui: &mut Ui, window: &Floating

, title: Rect, rect: Rect, style: &ChromeStyle) { let Some(first) = window.panels().next() else { return }; let movable = window.panels().all(|p| self.permissions(p).movable); - let closable = window.panels().all(|p| self.permissions(p).closable); + let closable = self.style.close_button && window.panels().all(|p| self.permissions(p).closable); let (move_label, close_label) = (self.style.move_window_label.clone(), self.style.close_window_label.clone()); let mut bar = TitleBar::new(self.id.with(("move-group", Some(first))), &move_label).movable(movable); if closable { @@ -256,7 +256,7 @@ impl Renderer<'_, P> { let anchor = members.first()?.clone(); return Some(DropProposal { anchor, - placement: Placement::Group { below: true }, + placement: Placement::Group { below: true, height: None }, preview: Rect::NOTHING, insertion: None, noop: true, @@ -266,7 +266,13 @@ impl Renderer<'_, P> { Some(panel) => (panel, true), None => (anchor(b)?, false), }; - return Some(DropProposal { anchor, placement: Placement::Group { below }, preview: Rect::NOTHING, insertion: Some(line), noop: false }); + return Some(DropProposal { + anchor, + placement: Placement::Group { below, height: None }, + preview: Rect::NOTHING, + insertion: Some(line), + noop: false, + }); } let (panels, rect, strip) = hit.groups.iter().find(|(_, rect, _)| rect.contains(pointer))?; if strip.contains(pointer) || same(panels) { @@ -281,7 +287,13 @@ impl Renderer<'_, P> { return None; }; let insertion = Some(line(if below { rect.bottom() } else { rect.top() })); - Some(DropProposal { anchor: anchor(panels)?, placement: Placement::Group { below }, preview: Rect::NOTHING, insertion, noop: false }) + Some(DropProposal { + anchor: anchor(panels)?, + placement: Placement::Group { below, height: None }, + preview: Rect::NOTHING, + insertion, + noop: false, + }) } /// What a group drag carries: the whole window rect for the only group of a floating diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index d39235bcc2..0296daf6ff 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -213,7 +213,7 @@ impl Renderer<'_, P> { pub(super) fn frame_items(&mut self, ui: &mut egui::Ui, owner: &TabGroup<'_, P>, panel: &P) { if self.style.profile == Profile::Frame { let others = owner.panels.iter().filter(|p| *p != panel).all(|p| self.permissions(p).closable); - if owner.panels.len() > 1 && others && self.menu_action(ui, &self.style.close_others_label.clone()) { + if owner.panels.len() > 1 && others && self.style.close_menu_items && self.menu_action(ui, &self.style.close_others_label.clone()) { self.output.actions.push(Action::CloseOthers { panel: panel.clone() }); } if owner.kind == GroupKind::Frame { diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 4ba0c0b80f..2d1bc6f9a7 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -33,7 +33,8 @@ impl Renderer<'_, P> { pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, minimized: bool, rect: Rect, kind: GroupKind) { let Some(selected) = panels.get(active) else { return }; let policy = self.permissions(selected); - let splits = kind == GroupKind::Frame; + let splits = kind == GroupKind::Frame && policy.accepts_splits; + let rtl = self.style.right_to_left; if stripless(panels, &*self.content) { self.contents(ui, selected, rect); self.targets.push(DropTarget { @@ -43,6 +44,7 @@ impl Renderer<'_, P> { tabs: vec![(selected.clone(), Rect::NOTHING)], allow_splits: splits, accepts_tabs: policy.accepts_tabs, + right_to_left: rtl, }); return; } @@ -50,10 +52,19 @@ impl Renderer<'_, P> { let strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.tab_height).min(rect.bottom()))); ui.painter().rect_filled(strip, 0.0, self.style.tab_background); let floating = matches!(kind, GroupKind::Floating { .. }); + // Laid out left to right, then mirrored in a right-to-left layout: tabs from the right + // edge, the header (the host's ≡) at the left. + let mirror = |r: Rect| { + if rtl { + Rect::from_x_y_ranges((strip.left() + strip.right() - r.right())..=(strip.left() + strip.right() - r.left()), r.y_range()) + } else { + r + } + }; let requested = self.content.group_header_width(panels, selected, floating); let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 }; if header_width > 0.0 { - let header = Rect::from_min_max(pos2(strip.right() - header_width, strip.top()), strip.max); + let header = mirror(Rect::from_min_max(pos2(strip.right() - header_width, strip.top()), strip.max)); let mut child = ui.new_child(UiBuilder::new().id(self.id.with(("header", selected))).max_rect(header)); child.set_clip_rect(header.intersect(ui.clip_rect())); self.content.group_header(&mut child, panels, selected, floating); @@ -78,13 +89,13 @@ impl Renderer<'_, P> { let mut shown = Vec::new(); for (index, width) in &fit.shown { let Some(panel) = panels.get(*index) else { continue }; - let tab = Rect::from_min_size(pos2(x, strip.top()), vec2(*width, strip.height())); + let tab = mirror(Rect::from_min_size(pos2(x, strip.top()), vec2(*width, strip.height()))); self.tab(ui, panel, tab, *index == active, rect, Some(&owner)); shown.push((panel.clone(), tab)); x += width; } if !fit.overflow.is_empty() && fit.overflow_width > 0.0 { - let overflow = Rect::from_min_size(pos2(x, strip.top()), vec2(fit.overflow_width, strip.height())); + let overflow = mirror(Rect::from_min_size(pos2(x, strip.top()), vec2(fit.overflow_width, strip.height()))); let response = ui.interact(overflow, self.id.with(("overflow", selected)), Sense::click()); self.register_interaction(ui.ctx(), response.id); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.panels_label)); @@ -104,10 +115,11 @@ impl Renderer<'_, P> { }); x += fit.overflow_width; } - let bar = Rect::from_min_max(pos2(x.min(strip.right() - header_width), strip.top()), pos2(strip.right() - header_width, strip.bottom())); + let bar = + mirror(Rect::from_min_max(pos2(x.min(strip.right() - header_width), strip.top()), pos2(strip.right() - header_width, strip.bottom()))); self.group_handle(ui, "drag-bar", bar, &owner, movable); // Registered last, so the band wins over the tabs below it. - let border = Rect::from_min_max(strip.min, pos2(strip.right() - header_width, (strip.top() + BORDER_BAND).min(strip.bottom()))); + let border = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, (strip.top() + BORDER_BAND).min(strip.bottom())))); self.group_handle(ui, "drag-border", border, &owner, movable); // Logical order, hidden tabs included without a hit area, for no-op detection. let tabs = @@ -119,6 +131,7 @@ impl Renderer<'_, P> { tabs, allow_splits: splits, accepts_tabs: policy.accepts_tabs, + right_to_left: rtl, }); if !minimized { self.contents(ui, selected, Rect::from_min_max(pos2(rect.left(), strip.bottom()), rect.max)); @@ -150,7 +163,11 @@ impl Renderer<'_, P> { let active = response.has_focus() || response.hovered(); if movable { // A grip mark at rest, centred in the bar's reserved width beside the header. - let grip = Rect::from_min_max(pos2((hit.right() - self.style.drag_bar_width).max(hit.left()), hit.top()), hit.max); + let grip = if self.style.right_to_left { + Rect::from_min_max(hit.min, pos2((hit.left() + self.style.drag_bar_width).min(hit.right()), hit.bottom())) + } else { + Rect::from_min_max(pos2((hit.right() - self.style.drag_bar_width).max(hit.left()), hit.top()), hit.max) + }; let stroke = Stroke::new(1.0, if active { self.style.text } else { self.style.inactive_text }); let half = (hit.height() * 0.2).min(4.0); for k in -1..=1 { @@ -192,10 +209,10 @@ impl Renderer<'_, P> { } /// The group items of the menu tail: Close Tab Group, Minimize or Expand, Float Tab Group - /// and Group with. `panel` is the panel whose menu this is. + /// and Move Group to. `panel` is the panel whose menu this is. fn group_menu(&mut self, ui: &mut Ui, owner: &TabGroup<'_, P>, panel: &P) { let all = |check: &dyn Fn(crate::docking::Permissions) -> bool| owner.panels.iter().all(|p| check(self.permissions(p))); - let closable = all(&|p| p.closable); + let closable = self.style.close_menu_items && all(&|p| p.closable); let movable = all(&|p| p.movable); let floatable = movable && all(&|p| p.floatable); if closable && self.menu_action(ui, &self.close_group_label()) { @@ -220,7 +237,7 @@ impl Renderer<'_, P> { } let targets = if movable { self.group_targets(owner.panels) } else { Vec::new() }; if !targets.is_empty() { - let logical = self.style.group_with_label.clone(); + let logical = self.style.move_group_to_label.clone(); let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text); let response = ui.menu_button(text, |ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { @@ -278,21 +295,10 @@ impl Renderer<'_, P> { response } - /// A tab's label, cut at the end with '…' to fit `width`. egui does not wrap a host's - /// pre-laid-out `WidgetText::Galley` again, so that one is laid out again from its job. + /// A tab's label, cut at the end with '…' to fit `width`. pub(super) fn tab_label(&mut self, ui: &Ui, panel: &P, label: &str, color: Color32, width: f32) -> Arc { - let galley = self.content.label(ui, panel, label, &self.style.font, color).into_galley( - ui, - Some(egui::TextWrapMode::Truncate), - width, - self.style.font.clone(), - ); - if galley.size().x <= width + 0.5 { - return galley; - } - let mut job = (*galley.job).clone(); - job.wrap = egui::text::TextWrapping::truncate_at_width(width); - ui.painter().layout_job(job) + let text = self.content.label(ui, panel, label, &self.style.font, color); + crate::docking::chrome::truncated(ui, text, width, self.style.font.clone()) } /// True while a tab's focus came from the pointer, which shows no focus outline. Tab or an @@ -369,7 +375,7 @@ impl Renderer<'_, P> { let targets: Vec

= if policy.movable { self.layout.move_targets(panel, |p| self.permissions(p)).into_iter().cloned().collect() } else { Vec::new() }; if !targets.is_empty() { - let text = self.content.action_label(ui, &self.style.move_label, &self.style.font, self.style.text); + let text = self.content.action_label(ui, &self.style.move_panel_to_label, &self.style.font, self.style.text); let response = ui.menu_button(text, |ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { for target in &targets { @@ -384,9 +390,11 @@ impl Renderer<'_, P> { } }); }); - response.response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_label)); + response + .response + .widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_panel_to_label)); } - if policy.closable { + if policy.closable && self.style.close_menu_items { let text = self.content.action_label(ui, &self.style.close_label, &self.style.font, self.style.text); let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.close_label)); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 613bf689c1..37414bc78f 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -127,7 +127,11 @@ impl Renderer<'_, P> { let panel_rect = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), (top + header + share).min(rect.bottom()))); let title_rect = Rect::from_min_max(panel_rect.min, pos2(panel_rect.right(), (top + header).min(panel_rect.bottom()))); self.tab(ui, &entry.panel, title_rect, entry.open, panel_rect, None); - let collapse = Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max); + let collapse = if self.style.right_to_left { + Rect::from_min_max(title_rect.min, pos2((title_rect.left() + 18.0).min(title_rect.right()), title_rect.bottom())) + } else { + Rect::from_min_max(pos2((title_rect.right() - 18.0).max(title_rect.left()), title_rect.top()), title_rect.max) + }; let response = ui.interact(collapse, self.id.with(("collapse", &entry.panel)), Sense::click()); self.register_interaction(ui.ctx(), response.id); response.widget_info(|| { @@ -152,8 +156,9 @@ impl Renderer<'_, P> { rect: panel_rect, tab_strip: Some(title_rect), tabs: vec![(entry.panel.clone(), title_rect)], - allow_splits: true, + allow_splits: self.permissions(&entry.panel).accepts_splits, accepts_tabs: self.permissions(&entry.panel).accepts_tabs, + right_to_left: self.style.right_to_left, }); top = panel_rect.bottom(); if entry.open && remaining > 0.0 { @@ -211,7 +216,8 @@ impl Renderer<'_, P> { ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); child.set_clip_rect(rect.intersect(ui.clip_rect())); self.content.body(&mut child, panel); - if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.primary_pressed()) { + // Any button: a canvas pans with the middle button and opens menus with the secondary. + if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.any_pressed()) { self.output.focused = Some(panel.clone()); } } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index c0b5e0044c..66c0ad8c67 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -28,7 +28,8 @@ pub struct DockStyle { /// Localize these action labels in the application adapter. pub float_label: String, pub close_label: String, - pub move_label: String, + /// Tab menu item that moves one panel into another group (submenu of target panels). + pub move_panel_to_label: String, pub panels_label: String, pub resize_label: String, pub resize_window_label: String, @@ -38,7 +39,8 @@ pub struct DockStyle { pub minimize_label: String, pub expand_label: String, pub float_group_label: String, - pub group_with_label: String, + /// Group menu item that moves the whole group into another group (submenu of targets). + pub move_group_to_label: String, /// Minimum width of the drag bar left of the group header. Tabs shrink, then overflow, /// before the bar narrows. pub drag_bar_width: f32, @@ -74,8 +76,12 @@ pub struct DockStyle { pub right_to_left: bool, /// [D] Accessibility label of a column bar. pub move_column_label: String, + /// [D] Column menu and group menu items. pub collapse_to_icons_label: String, pub expand_panels_label: String, + /// [D] Accessibility labels of the column bar's »/« button, distinct from the menu items. + pub collapse_column_label: String, + pub expand_column_label: String, pub move_window_label: String, pub close_window_label: String, /// Frame profile menu labels. @@ -87,6 +93,12 @@ pub struct DockStyle { pub restore_frame_label: String, /// Shown where native windows are available (feature `native-windows`). pub new_window_label: String, + /// Show the built-in Close items in tab and group menus (Close panel, Close Tab Group, + /// Close Other Panels in Group) for closable panels. A host that draws its own Close items + /// turns this off and keeps [`Permissions::closable`], so its close actions still apply. + pub close_menu_items: bool, + /// Show × on the title bar of a floating window whose panels are all closable. + pub close_button: bool, } /// Which arrangement a [`DockStyle`] renders and labels. @@ -114,7 +126,7 @@ impl DockStyle { font: FontId::proportional(12.0), float_label: "Float panel".into(), close_label: "Close panel".into(), - move_label: "Move to group".into(), + move_panel_to_label: "Move Panel to Group".into(), panels_label: "Panels".into(), resize_label: "Resize panels".into(), resize_window_label: "Resize panel window".into(), @@ -123,7 +135,7 @@ impl DockStyle { minimize_label: "Minimize".into(), expand_label: "Expand".into(), float_group_label: "Float Tab Group".into(), - group_with_label: "Group with".into(), + move_group_to_label: "Move Group to".into(), drag_bar_width: 40.0, floating_background: visuals.window_fill, floating_stroke: visuals.window_stroke, @@ -142,6 +154,8 @@ impl DockStyle { move_column_label: "Move panel column".into(), collapse_to_icons_label: "Collapse to Icons".into(), expand_panels_label: "Expand Panels".into(), + collapse_column_label: "Collapse column to icons".into(), + expand_column_label: "Expand column".into(), move_window_label: "Move panel window".into(), close_window_label: "Close panel window".into(), undock_label: "Undock Panel".into(), @@ -151,6 +165,8 @@ impl DockStyle { maximize_label: "Maximize Frame".into(), restore_frame_label: "Restore Frame Size".into(), new_window_label: "Move Panel to New Window".into(), + close_menu_items: true, + close_button: true, } } @@ -185,6 +201,8 @@ impl DockStyle { pub struct DockOutput

{ pub actions: Vec>, pub error: Option, + /// The panel the user focused this frame: a clicked tab or menu entry, a drop, a raised + /// window, or a press of any pointer button in a panel body, stripless panels included. pub focused: Option

, /// Whole-floating-group gesture identity; host may display its own group drop preview. pub group_drag: Option

, diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index cd370e5abc..3f94615391 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -12,6 +12,9 @@ pub struct DropTarget

{ pub tabs: Vec<(P, Rect)>, pub allow_splits: bool, pub accepts_tabs: bool, + /// The strip runs right to left: the first tab is rightmost, and an insertion slot sits + /// at the right edge of the tab it precedes. + pub right_to_left: bool, } #[derive(Clone, Debug, PartialEq)] @@ -70,11 +73,18 @@ pub fn tab_insertion_marker(target: &DropTarget

, before: Option<&P>) - return None; } let index = before.and_then(|before| target.tabs.iter().position(|(panel, _)| panel == before)); + let rtl = target.right_to_left; + let leading = |rect: &Rect| if rtl { rect.right() } else { rect.left() }; + let visible = || target.tabs.iter().filter(|(_, rect)| usable(*rect)).map(|(_, rect)| rect); let x = index .and_then(|index| target.tabs.get(index..)) - .and_then(|tabs| tabs.iter().find(|(_, rect)| usable(*rect)).map(|(_, rect)| rect.left())) + .and_then(|tabs| tabs.iter().find(|(_, rect)| usable(*rect)).map(|(_, rect)| leading(rect))) .unwrap_or_else(|| { - target.tabs.iter().filter(|(_, rect)| usable(*rect)).map(|(_, rect)| rect.right()).fold(strip.left(), f32::max).min(strip.right()) + if rtl { + visible().map(|rect| rect.left()).fold(strip.right(), f32::min).max(strip.left()) + } else { + visible().map(|rect| rect.right()).fold(strip.left(), f32::max).min(strip.right()) + } }); let width = strip.width().min(2.0); let left = (x - width * 0.5).max(strip.left()).min((strip.right() - width).max(strip.left())); @@ -98,7 +108,8 @@ pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarg if !target.accepts_tabs { return None; } - let before = target.tabs.iter().filter(|(_, r)| usable(*r)).find(|(_, r)| pointer.x < r.center().x); + let ahead = |r: &Rect| if target.right_to_left { pointer.x > r.center().x } else { pointer.x < r.center().x }; + let before = target.tabs.iter().filter(|(_, r)| usable(*r)).find(|(_, r)| ahead(r)); let before_panel = before.map(|(p, _)| p.clone()); let insertion = tab_insertion_marker(target, before_panel.as_ref())?; let old_order: Vec<_> = target.tabs.iter().map(|(p, _)| p).collect(); @@ -176,8 +187,8 @@ impl DockTarget

{ pub(super) fn to(&self) -> Target

{ match self { Self::ColumnEdge { anchor, after } => Target::At { anchor: anchor.clone(), placement: Placement::Column { after: *after } }, - Self::Seam { anchor } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: true } }, - Self::GroupBand { anchor, below } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: *below } }, + Self::Seam { anchor } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: true, height: None } }, + Self::GroupBand { anchor, below } => Target::At { anchor: anchor.clone(), placement: Placement::Group { below: *below, height: None } }, Self::NewDock { side } => Target::NewDock { side: *side }, } } diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 618ca2680d..ac07024934 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -61,7 +61,7 @@ fn move_targets_skip_the_panel_itself_and_protected_anchors() { let guarded = |p: &u32| if *p == 3 { Permissions::PROTECTED } else { Permissions::default() }; assert!(!layout.move_targets(&1, guarded).contains(&&3)); - // A lone panel has nowhere to go — its "Move to group" menu hides + // A lone panel has nowhere to go — its "Move Panel to Group" menu hides // (storytold/lightcraft#1768). let single = Layout { root: Some(tabs(&[1], 0)), floating: Vec::new() }; assert!(single.move_targets(&1, all).is_empty()); @@ -135,13 +135,15 @@ fn protected_canvas_remains_present_and_cannot_be_grouped_with_panels() { move_to(1, 3, Zone::Center), move_to(3, 1, Zone::Center), Action::OpenAt { panel: 1, anchor: 3, placement: Placement::Tab { before: None } }, + Action::OpenAt { panel: 7, anchor: 1, placement: Placement::Split(Zone::Left) }, ] { let mut next = layout.clone(); assert_eq!(next.apply_with_permissions(action, permissions), Err(DockError::NotAllowed)); assert_eq!(next, layout); } + let beside = |panel: &u32| if *panel == 1 { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }; let mut next = layout; - next.apply_with_permissions(Action::OpenAt { panel: 7, anchor: 1, placement: Placement::Split(Zone::Left) }, permissions).unwrap(); + next.apply_with_permissions(Action::OpenAt { panel: 7, anchor: 1, placement: Placement::Split(Zone::Left) }, beside).unwrap(); assert!(next.contains(&1) && next.contains(&7)); } @@ -229,6 +231,7 @@ fn target(anchor: u32, members: &[u32], rect: Rect) -> DropTarget { .collect(), allow_splits: true, accepts_tabs: true, + right_to_left: false, } } @@ -266,7 +269,7 @@ fn long_action_sequence_never_loses_or_duplicates_a_panel() { 2 => Placement::Split(Zone::Top), 3 => Placement::Split(Zone::Bottom), 4 => Placement::Split(Zone::Center), - 5 => Placement::Group { below: seed & 1 == 0 }, + 5 => Placement::Group { below: seed & 1 == 0, height: None }, _ => Placement::Column { after: seed & 2 == 0 }, }; let to = match (seed >> 32) % 4 { @@ -1244,7 +1247,7 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() { 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)); - for logical in ["Float panel", "Move to group", "Close panel"] { + for logical in ["Float panel", "Move Panel to Group", "Close panel"] { assert!( h.output().shapes.iter().any(|shape| paints(&shape.shape, &format!("Action visual: {logical}"))), "custom action must paint: {logical}" @@ -1381,6 +1384,7 @@ fn returning_to_a_singleton_or_floating_source_body_is_an_explicit_noop() { tabs: panels.iter().map(|id| (*id, Rect::NOTHING)).collect(), allow_splits, accepts_tabs: true, + right_to_left: false, }; let proposal = resolve_drop(&1, rect.center(), &[target]).unwrap(); assert!(proposal.noop); @@ -1441,6 +1445,7 @@ fn unchanged_tab_slots_are_explicit_noops_with_bounded_insertion_markers() { ], allow_splits: true, accepts_tabs: true, + right_to_left: false, }; for (panel, positions) in [(1, [10.0, 50.0]), (2, [70.0, 110.0]), (3, [130.0, 210.0])] { for x in positions { @@ -1522,6 +1527,7 @@ fn overflow_noop_detection_uses_logical_order_including_hidden_tabs() { ], allow_splits: true, accepts_tabs: true, + right_to_left: false, }; assert!(resolve_drop(&1, pos2(10.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); // Before the next visible tab crosses hidden tab 2 and really changes the order. @@ -1542,6 +1548,7 @@ fn insertion_markers_stay_inside_clipped_and_singleton_strips() { tabs: vec![(1, Rect::from_min_size(pos2(tab_left, 20.0), vec2(60.0, 30.0)))], allow_splits: true, accepts_tabs: true, + right_to_left: false, }; for x in [rect.left(), rect.center().x, rect.right()] { let proposal = resolve_drop(&1, pos2(x, 25.0), std::slice::from_ref(&target)).unwrap(); @@ -1557,7 +1564,8 @@ fn insertion_markers_stay_inside_clipped_and_singleton_strips() { #[test] fn insertion_marker_handles_subpixel_strip_crossing_zero_without_panicking() { let rect = Rect::from_min_max(pos2(-0.001, 0.0), pos2(0.002, 30.0)); - let target = DropTarget { anchor: 1, rect, tab_strip: Some(rect), tabs: vec![(1, rect)], allow_splits: true, accepts_tabs: true }; + let target = + DropTarget { anchor: 1, rect, tab_strip: Some(rect), tabs: vec![(1, rect)], allow_splits: true, accepts_tabs: true, right_to_left: false }; let proposal = resolve_drop(&1, pos2(0.0, 12.0), &[target]).unwrap(); assert!(proposal.noop); assert!(rect.contains_rect(proposal.insertion.unwrap())); diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 9ce80b53ad..f7612993c2 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -1,5 +1,7 @@ //! Fixes from the DesignCraft trial: group float size, tab label elision, the drag ghost and -//! grip, double-clicks on minimized groups, pointer focus, label keys and borrowed lookups. +//! grip, double-clicks on minimized groups, pointer focus, label keys and borrowed lookups; then +//! split permissions, body focus, right-to-left strips, close controls, menu and button names, +//! zone mapping, closed panels from `apply` and group heights. use super::*; @@ -190,7 +192,7 @@ fn localized_covers_every_label_and_contains_takes_a_borrowed_panel() { }); full.textures_delta.clear(); let values: Vec<&str> = debug.split("_label: \"").skip(1).filter_map(|rest| rest.split('"').next()).collect(); - assert_eq!(values.len(), 25, "{debug}"); + assert_eq!(values.len(), 27, "{debug}"); assert!(values.iter().all(|v| v.starts_with("dock.")), "a label without a key: {values:?}"); let unique: std::collections::HashSet<_> = values.iter().collect(); assert_eq!(unique.len(), values.len()); @@ -199,3 +201,192 @@ fn localized_covers_every_label_and_contains_takes_a_borrowed_panel() { assert!(window.contains("swatches")); assert!(!window.contains("layers")); } + +const AREA_600: Rect = Rect { min: pos2(0.0, 0.0), max: pos2(600.0, 600.0) }; + +#[test] +fn a_protected_canvas_takes_no_side_split_and_a_group_dropped_on_its_edge_floats() { + let protected = |p: &u32| if *p == 0 { Permissions::PROTECTED } else { Permissions::default() }; + let split = Action::Move { panel: 4, anchor: 0, placement: Placement::Split(Zone::Left) }; + let mut layout = docked(); + assert_eq!(layout.apply_with_permissions(split.clone(), protected), Err(DockError::NotAllowed)); + let opt_in = |p: &u32| if *p == 0 { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }; + assert!(layout.apply_with_permissions(split, opt_in).is_ok()); + + let mut d = Driver::with(docked(), TestContent { protected: vec![0], ..Default::default() }, AREA_600); + let bar = d.rect("drag-bar", 2); + let out = d.drag(bar.center(), pos2(300.0, 300.0)); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); +} + +#[test] +fn a_press_in_a_stripless_panel_reports_it_focused() { + let mut d = Driver::with(docked(), TestContent { protected: vec![0], ..Default::default() }, AREA_600); + for pressed in [PointerButton::Primary, PointerButton::Secondary, PointerButton::Middle] { + let at = pos2(420.0, 300.0); + let press = Event::PointerButton { pos: at, button: pressed, pressed: true, modifiers: Modifiers::NONE }; + let out = d.step(vec![Event::PointerMoved(at), press]); + assert_eq!(out.focused, Some(0), "{pressed:?}"); + d.step(vec![Event::PointerButton { pos: at, button: pressed, pressed: false, modifiers: Modifiers::NONE }]); + d.step(vec![key(egui::Key::Escape)]); + } +} + +#[test] +fn right_to_left_mirrors_the_tab_strip_and_its_insertion_slots() { + let mut d = Driver::with(frames(), TestContent { header: 30.0, ..Default::default() }, AREA_600); + d.tweak = |style| style.right_to_left = true; + d.step(vec![]); + d.step(vec![]); + let (first, second, bar) = (d.tab(2), d.tab(3), d.rect("drag-bar", 2)); + assert!((first.right() - 600.0).abs() < 1.0, "the first tab starts at the right edge: {first:?}"); + assert!(second.right() <= first.left() + 0.5, "{first:?} {second:?}"); + assert!(bar.right() <= second.left() + 0.5 && bar.left() >= 304.0 + 30.0 - 0.5, "the bar sits between the tabs and the header: {bar:?}"); + + // Just right of the first tab's centre is before it in a right-to-left strip. + let out = d.drag(d.tab(1).center(), pos2(first.center().x + 6.0, first.center().y)); + assert!(out.actions.contains(&Action::Move { panel: 1, anchor: 3, placement: Placement::Tab { before: Some(2) } }), "{:?}", out.actions); + + let strip = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 20.0)); + let target = DropTarget { + anchor: 1, + rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 80.0)), + tab_strip: Some(strip), + tabs: vec![(1, Rect::from_min_max(pos2(60.0, 0.0), pos2(100.0, 20.0))), (2, Rect::from_min_max(pos2(20.0, 0.0), pos2(60.0, 20.0)))], + allow_splits: true, + accepts_tabs: true, + right_to_left: true, + }; + let drop = |x: f32| resolve_drop(&9, pos2(x, 10.0), std::slice::from_ref(&target)).unwrap(); + assert_eq!((drop(90.0).placement, drop(90.0).insertion.unwrap().center().x), (Placement::Tab { before: Some(1) }, 99.0)); + assert_eq!((drop(70.0).placement, drop(70.0).insertion.unwrap().center().x), (Placement::Tab { before: Some(2) }, 60.0)); + assert_eq!((drop(10.0).placement, drop(10.0).insertion.unwrap().center().x), (Placement::Tab { before: None }, 20.0)); +} + +#[test] +fn a_right_to_left_title_bar_puts_its_buttons_left_and_cuts_a_galley_title() { + let ctx = Context::default(); + let mut shapes = Vec::new(); + let mut rects = (Rect::NOTHING, Rect::NOTHING, Rect::NOTHING); + let bar = Rect::from_min_size(pos2(10.0, 10.0), vec2(120.0, 18.0)); + for _ in 0..2 { + let mut full = ctx.run_ui(RawInput::default(), |ui| { + let mut style = DockStyle::from_ui(ui); + style.right_to_left = true; + let chrome = chrome::ChromeStyle::from_dock(&style); + let title = egui::WidgetText::Galley(ui.painter().layout_no_wrap("Paragraph Styles and More".into(), style.font.clone(), style.text)); + let shown = chrome::TitleBar::new(Id::new("title"), "Move").title(title).menu("Menu").close("Close").show(ui, bar, &chrome); + rects = (shown.bar.rect, shown.menu.unwrap().rect, shown.close.unwrap().rect); + }); + full.textures_delta.clear(); + shapes = full.shapes; + } + let (grip, menu, close) = rects; + assert!(close.center().x < menu.center().x && menu.right() <= grip.left() + 0.5, "{close:?} {menu:?} {grip:?}"); + assert!((grip.right() - bar.right()).abs() < 0.5); + let title = flat(&shapes) + .into_iter() + .find_map(|(_, shape)| match shape { + egui::Shape::Text(text) if text.galley.text().starts_with("Para") => Some(text), + _ => None, + }) + .unwrap(); + assert_eq!(last_char(&title.galley), Some('…')); + assert!(title.pos.x + title.galley.size().x <= grip.right() + 0.5 && title.pos.x >= grip.left()); +} + +#[test] +fn hidden_close_controls_leave_closing_to_the_host() { + let layout = Layout { root: Some(tabs(&[1, 2], 0)), floating: vec![Floating::single(vec![5, 6], 0, [80.0, 70.0, 300.0, 220.0])] }; + let close = Id::new(AREA).with(("move-group", Some(&5u32))).with("close"); + let mut d = Driver::new(layout); + assert!(d.ctx.read_response(close).is_some()); + d.tweak = |style| { + style.close_button = false; + style.close_menu_items = false; + }; + d.step(vec![]); + d.step(vec![]); + assert!(d.ctx.read_response(close).is_none()); + let at = d.tab(1).center(); + let secondary = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; + d.step(vec![Event::PointerMoved(at), secondary(true)]); + d.step(vec![secondary(false)]); + d.step(vec![]); + let painted = |d: &Driver, label: &str| texts(d).iter().any(|(_, t)| t.galley.text() == label); + assert!(painted(&d, "Float panel"), "the tab menu is open"); + assert!(!painted(&d, "Close panel") && !painted(&d, "Close Tab Group")); + // The panels stay closable: the host's own Close applies and reports what it closed. + assert_eq!(d.layout.apply_with_permissions(Action::CloseWindow { panel: 5 }, |p| d.content.permissions(p)), Ok(vec![5, 6])); +} + +#[test] +fn apply_all_returns_every_panel_its_actions_closed() { + let mut layout = Layout { root: Some(tabs(&[1, 2, 3], 0)), floating: vec![Floating::single(vec![5, 6], 0, [80.0, 70.0, 300.0, 220.0])] }; + let closed = layout + .apply_all([Action::Activate { panel: 2 }, Action::CloseOthers { panel: 2 }, Action::CloseWindow { panel: 6 }], |_| Permissions::default()); + assert_eq!(closed, Ok(vec![1, 3, 5, 6])); + assert_eq!(layout.apply(Action::Close { panel: 2 }), Ok(vec![2])); +} + +#[test] +fn the_column_button_and_the_column_menu_item_have_distinct_names() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, content: &mut TestContent| { + DockArea::new(Id::new(AREA)).show_content(ui, &docked(), &DockStyle::from_ui(ui), content); + }, + TestContent { protected: vec![0], ..Default::default() }, + ); + h.run_steps(2); + assert_eq!(h.query_all_by_label("Collapse column to icons").count(), 1); + assert_eq!(h.query_all_by_label("Collapse to Icons").count(), 0); + let at = h.ctx.read_response(Id::new(AREA).with(("column-bar", Some(&2u32)))).unwrap().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_eq!(h.query_all_by_label("Collapse to Icons").count(), 1); + assert_eq!(h.query_all_by_label("Collapse column to icons").count(), 1); +} + +#[test] +fn for_zone_maps_side_zones_onto_columns_groups_and_splits() { + let layout = Layout { root: docked().root, floating: vec![Floating::single(vec![5], 0, [300.0, 80.0, 200.0, 200.0])] }; + let zone = |anchor, zone, rtl| Placement::for_zone(&layout, &anchor, zone, rtl); + assert_eq!(zone(2, Zone::Right, false), Ok(Placement::Column { after: true })); + assert_eq!(zone(2, Zone::Right, true), Ok(Placement::Column { after: false })); + assert_eq!(zone(4, Zone::Bottom, false), Ok(Placement::Group { below: true, height: None })); + assert_eq!(zone(2, Zone::Center, false), Ok(Placement::Split(Zone::Center))); + assert_eq!(zone(5, Zone::Top, false), Ok(Placement::Group { below: false, height: None })); + assert_eq!(zone(5, Zone::Left, false), Err(DockError::InvalidPlacement)); + assert_eq!(zone(0, Zone::Left, true), Ok(Placement::Split(Zone::Left))); + assert_eq!(zone(9, Zone::Left, false), Err(DockError::MissingTarget)); + + // An end dock mirrors a start dock. + let mut end = docked(); + let Some(Node::Split { first, second, size, .. }) = &mut end.root else { panic!() }; + std::mem::swap(first, second); + *size = SplitSize::FixedSecond(240.0); + let Node::Dock { side, .. } = &mut **second else { panic!() }; + *side = Side::End; + assert_eq!(Placement::for_zone(&end, &2, Zone::Left, false), Ok(Placement::Column { after: true })); + assert_eq!(Placement::for_zone(&end, &2, Zone::Left, true), Ok(Placement::Column { after: false })); +} + +#[test] +fn a_group_placement_gives_the_inserted_group_its_height() { + let mut layout = docked(); + let below = |height| Placement::Group { below: true, height }; + layout.apply(Action::OpenAt { panel: 7, anchor: 4, placement: below(Some(180.0)) }).unwrap(); + layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 7, placement: below(Some(90.0)) } }).unwrap(); + layout.apply(Action::OpenAt { panel: 8, anchor: 4, placement: below(None) }).unwrap(); + let Some(Node::Split { first, .. }) = &layout.root else { panic!() }; + let Node::Dock { columns, .. } = &**first else { panic!() }; + let heights: Vec<_> = columns[0].groups.iter().map(|g| (g.panels.clone(), g.height)).collect(); + assert_eq!(heights, vec![(vec![4], None), (vec![8], None), (vec![7], Some(180.0)), (vec![2, 3], Some(90.0))]); + assert_eq!(layout.apply(Action::OpenAt { panel: 9, anchor: 4, placement: below(Some(f32::NAN)) }), Err(DockError::InvalidGeometry)); +} diff --git a/crates/ui/tests/docking_workflows.rs b/crates/ui/tests/docking_workflows.rs index ddf2eceed9..aa7f2e3bb8 100644 --- a/crates/ui/tests/docking_workflows.rs +++ b/crates/ui/tests/docking_workflows.rs @@ -416,7 +416,7 @@ mod v1_fixtures { // Float the column by command, then drag its window back to the start edge. let float: DockCommand = serde_json::from_value(json!({"command": "window.panel.float", "panel": bars[0], "column": true})).unwrap(); - let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone())).unwrap(); + let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone()), false).unwrap(); d.layout.apply_all(actions, |p| d.content.permissions(p)).unwrap_or_else(|e| panic!("{at}: {e}")); d.settle(); assert!(start_columns(&d.layout).is_empty(), "{at}: floated"); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 0e8b3ba6aa..96ea7ae368 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -18,7 +18,10 @@ Office apps that draw their own document with a few task panes beside it use Sides are logical: `Side::Start` is the left edge, or the right edge when `DockStyle::right_to_left` is set. egui has no app-wide direction, so the app sets it from its -locale. +locale. Right to left, tab strips also mirror: the first tab is rightmost, the group header and +drag bar are at the left, and drop insertion slots follow. Accordion headers and floating title +bars (`chrome::TitleBar`, through `ChromeStyle::right_to_left`) mirror too. Frame splits keep +their sides. ## Model @@ -57,17 +60,25 @@ layout.apply(Action::Move { - `Move`, `Float` and `Close` act on one panel. `MoveGroup`, `MoveColumn` and `MoveWindow` move a group, a dock column or a floating window, named by any panel in it. - A `Target` is `At { anchor, placement }`, `Float { rect }` or `NewDock { side }`. -- A `Placement` is a tab position, a split zone, a new group above or below, a new column, or a - new frame on an outer edge. +- A `Placement` is a tab position, a split zone, a new group above or below (with an optional + preferred `height`), a new column, or a new frame on an outer edge. +- Containers take different placements: a dock column takes groups and columns, not splits. + `Placement::for_zone(layout, anchor, zone, right_to_left)` maps a left, right, top, bottom or + centre zone onto what the anchor's container takes: a split in the frame tree, a new column on + that side or a new group above or below in a dock, a group above or below in a floating window. - Other actions select, minimize, collapse to icons, resize splits, columns and groups, and move a floating window to its own OS window (`SetNative`, feature `native-windows`). Every action checks the whole result before it commits. A bad target, a duplicate id, a stale split path or invalid geometry returns a `DockError` and leaves the layout unchanged. The source -panel is never lost. +panel is never lost. `apply`, `apply_with_permissions` and `apply_all` return the panels the +actions closed, so the app can release their state; `closed_by` lists them before applying. -`Permissions` limit what may happen to a panel. `Permissions::PROTECTED` keeps a canvas docked -and open and takes no tabs, but allows splits beside it. `apply_with_permissions` applies them. +`Permissions` limit what may happen to a panel: `movable`, `floatable`, `closable`, +`accepts_tabs` and `accepts_splits`. `apply_with_permissions` enforces them for every action, +whoever issues it. `Permissions::PROTECTED` keeps a canvas docked and open and takes neither tabs +nor side splits; a group dropped on it floats there. An app that opens panels beside its canvas +uses `Permissions { accepts_splits: true, ..Permissions::PROTECTED }`. ## Workspace @@ -98,7 +109,8 @@ survives. `DockOutput` also has: -- `focused`: the focused panel. +- `focused`: the panel the user focused this frame: a clicked tab, a drop, a raised window, or a + press of any pointer button in a panel body, bare and protected panels included. - `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (Frame) and `DockEvent::ToggleAutoCollapse` (Dock). - `error`: a rejected gesture. @@ -113,6 +125,10 @@ Builder options on `DockArea`: | `raise_panel(panel)` | Raise and focus a panel's floating window this frame. | | `blocked_rects(rects)` | App overlays that docking gestures must ignore. | +`DockStyle::close_menu_items` and `DockStyle::close_button` hide the built-in Close menu items +and the floating window ×. They hide controls only: a panel that stays `closable` still closes +by the app's own Close items and commands. + `DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome rather than on a panel body. `begin_drag` hands a drag that started in the app's own chrome to the area. `docking::chrome` has the floating frame and title bar for apps that draw their own windows. @@ -141,7 +157,7 @@ let command: DockCommand = serde_json::from_value(params)?; if command.is_app_owned() { return app.workspace_command(command); } -let closed = command.apply(&mut app.workspace, |panel| app.permissions(panel))?; +let closed = command.apply(&mut app.workspace, style.right_to_left, |panel| app.permissions(panel))?; ``` | Id | Params (`?` is optional) | @@ -160,7 +176,9 @@ let closed = command.apply(&mut app.workspace, |panel| app.permissions(panel))?; | `ui.dock` | `{action}`, or `{operation, …}` | - `zone` is `tab`, `center`, `left`, `right`, `top`, `bottom`, `above` or `below`. `before` names - the tab to insert before; `null` appends. + the tab to insert before; `null` appends. `left`, `right`, `top` and `bottom` follow + `Placement::for_zone`, so beside a docked panel they make a new column or group. `apply` and + `to_actions` take the layout's `right_to_left` for that. - `group` moves the panel's whole group; `column` moves its dock column, or its whole window when it floats. `side` is `Start` or `End`. - Without a value, `minimized`, `iconic` and `locked` toggle. From 6820f9810924ed7b2c21d2f2037014715fa1d46c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 12:25:49 +0000 Subject: [PATCH 30/94] panes: reserve the exact pane size, clip the body and name each title bar A docked pane draws its body in a child ui clipped to the pane, so a body wider than the pane no longer shifts a right or bottom pane's reserved rect into the document. PaneLabels::move_pane takes {title}, so each title bar's accessible name includes its pane ("Move Styles pane"). Pane title bars mirror with .rtl(true). --- crates/ui/src/panes/mod.rs | 21 +++++++++++++++------ crates/ui/src/panes/tests.rs | 34 ++++++++++++++++++++++++++++++++++ docs/ui-panes.md | 3 ++- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/crates/ui/src/panes/mod.rs b/crates/ui/src/panes/mod.rs index c90fb9f431..961c80538f 100644 --- a/crates/ui/src/panes/mod.rs +++ b/crates/ui/src/panes/mod.rs @@ -152,7 +152,8 @@ pub struct PaneLabels { pub move_bottom: String, pub float: String, pub close: String, - /// Accessibility label of the title bar. + /// Accessibility label of the title bar. `{title}` is replaced with the pane's title, so + /// each title bar has its own name. pub move_pane: String, /// Accessibility label of the resize edges. pub resize: String, @@ -167,7 +168,7 @@ impl Default for PaneLabels { move_bottom: "Move to Bottom".into(), float: "Float".into(), close: "Close".into(), - move_pane: "Move pane".into(), + move_pane: "Move {title} pane".into(), resize: "Resize pane".into(), } } @@ -325,7 +326,7 @@ impl PaneHost { ) -> PaneOutput

{ let ctx = ui.ctx().clone(); let bounds = ui.available_rect_before_wrap(); - let style = ChromeStyle::from_ui(ui); + let style = ChromeStyle { right_to_left: self.rtl, ..ChromeStyle::from_ui(ui) }; let key = memory_id(self.id); let mut memory = ctx.data(|data| data.get_temp::(key)).unwrap_or_default(); let mut requests = Vec::new(); @@ -494,10 +495,17 @@ impl PaneHost { let title = Rect::from_min_size(top.min, vec2(top.width(), TITLE_BAR_HEIGHT)); ui.allocate_rect(title, Sense::hover()); let bar = self.chrome(ui, title, s, content, style, focus, bounds, requests); - Frame::NONE.inner_margin(self.margin).show(ui, |ui| { + // The pane reserves exactly its size and clips its body. egui cuts a panel wider + // than its exact size at its outer edge, so a wide body would shift a right or + // bottom pane's reserved rect inwards and the document would draw over the pane. + let body = Rect::from_min_max(pos2(top.left(), title.bottom()), top.max); + let mut child = ui.new_child(UiBuilder::new().max_rect(body).layout(*ui.layout())); + child.set_clip_rect(body.intersect(ui.clip_rect())); + Frame::NONE.inner_margin(self.margin).show(&mut child, |ui| { ui.set_min_width(ui.available_width()); content.body(ui, &s.pane); }); + ui.allocate_rect(body, Sense::hover()); bar }); let rect = shown.response.rect; @@ -661,8 +669,9 @@ impl PaneHost { ) -> Response { let movable = content.movable(&s.pane); let closable = content.closable(&s.pane); - let mut bar = - TitleBar::new(s.id.with("title"), &self.labels.move_pane).title(content.title(&s.pane)).menu(&self.labels.menu).movable(movable); + let title = content.title(&s.pane); + let move_label = self.labels.move_pane.replace("{title}", &title); + let mut bar = TitleBar::new(s.id.with("title"), &move_label).title(title).menu(&self.labels.menu).movable(movable); if closable { bar = bar.close(&self.labels.close); } diff --git a/crates/ui/src/panes/tests.rs b/crates/ui/src/panes/tests.rs index 837760be03..16ea6dd044 100644 --- a/crates/ui/src/panes/tests.rs +++ b/crates/ui/src/panes/tests.rs @@ -306,3 +306,37 @@ fn pane_state_round_trips_through_json() { let json = serde_json::to_string(&state).unwrap(); assert_eq!(serde_json::from_str::(&json).unwrap(), state); } + +#[test] +fn a_body_wider_than_its_pane_is_clipped_and_the_document_starts_at_the_pane_edge() { + struct Wide; + impl PaneContent for Wide { + fn title(&self, pane: &Pane) -> String { + format!("{pane:?}") + } + fn body(&mut self, ui: &mut Ui, _: &Pane) { + ui.allocate_exact_size(vec2(400.0, 40.0), Sense::hover()); + } + fn default_state(&self, pane: &Pane) -> PaneState { + PaneState::docked(if *pane == Pane::Comments { Edge::End } else { Edge::Start }, 250.0) + } + } + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, document: &mut Rect| { + PaneHost::new("panes").show(ui, &[Pane::Nav, Pane::Comments], |_| None, &mut Wide); + *document = ui.available_rect_before_wrap(); + }, + Rect::NOTHING, + ); + h.run_steps(2); + let document = *h.state(); + assert_eq!(document.left(), L + 250.0, "{document:?}"); + assert_eq!(document.right(), R - 250.0, "{document:?}"); +} + +#[test] +fn each_title_bar_is_named_after_its_pane() { + let h = harness(App::new(&[Pane::Nav, Pane::Comments])); + assert_eq!(h.query_all_by_label("Move Nav pane").count(), 1); + assert_eq!(h.query_all_by_label("Move Comments pane").count(), 1); +} diff --git a/docs/ui-panes.md b/docs/ui-panes.md index b88a7d17bf..fd3d9a9119 100644 --- a/docs/ui-panes.md +++ b/docs/ui-panes.md @@ -51,7 +51,8 @@ egui::CentralPanel::default().show(ui, |ui| document(ui)); | `SidePolicy::Columns` | Every docked pane shows; panes on one edge sit side by side in `open` order, the first outermost. | | `SidePolicy::OneSlot` | One closable pane per edge: the last one in `open`. Non-closable context panes (PivotTable Fields) show beside the slot. | | `.max_fraction(f)` | One docked pane takes at most `f` of the host's width (height for bottom panes). | -| Chrome | Title, ▾ menu (app items, Move to Start, Move to End, Move to Bottom for bottom panes, Float, Close), ×, a resize edge with pointer and arrow keys. | +| Chrome | Title, ▾ menu (app items, Move to Start, Move to End, Move to Bottom for bottom panes, Float, Close), ×, a resize edge with pointer and arrow keys. The title bar mirrors with `.rtl(true)`. Its accessible name is `PaneLabels::move_pane` with `{title}` replaced by the pane's title ("Move Styles pane"). | +| Size | A docked pane reserves exactly its size and clips its body, so a body wider than the pane never pushes into the document. | | Drag out | A docked pane's title dragged more than `DOCK_SNAP` (32 pt) out of the pane floats it under the pointer when dropped; dropped within 32 pt of the host's left or right edge it docks there. | | Floating | `FloatingFrame` with its resize handles; the title bar moves it. Escape or window focus loss during a move puts it back. A drop within 32 pt of the left or right edge docks it. Rects are clamped to the host area. | | Focus | `out.focused` is the pane holding keyboard focus or last clicked; a click or focus in the document clears it. F6 and Shift+F6 cycle through the shown panes and then report `out.to_document`: give focus to the document. `.f6(false)` leaves F6 to the app, which calls `panes::focus_next(ctx, id, reverse)` instead. | From f4f9e5b206a721d28ea1214ef8bf85b8e30bb779 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 12:26:31 +0000 Subject: [PATCH 31/94] docking: one drop preview painter for docking and panes chrome::drop_preview draws the accent outline, filled or not, for every docking destination and drag ghost and for the pane host's drop preview. --- crates/ui/src/docking/chrome.rs | 7 +++++++ crates/ui/src/docking/render/preview.rs | 20 +++++++------------- crates/ui/src/panes/mod.rs | 11 ++--------- docs/ui-docking.md | 3 ++- 4 files changed, 18 insertions(+), 23 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index f5b6bb6be7..3aeab52912 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -245,6 +245,13 @@ impl<'a> FloatingFrame<'a> { } } +/// A drop preview: a 2 pt accent outline inside `rect`, filled with 15% accent when `filled`. +/// Docking and the pane host draw every destination and drag ghost with it. +pub fn drop_preview(painter: &egui::Painter, rect: Rect, accent: Color32, filled: bool) { + let fill = if filled { accent.gamma_multiply(0.15) } else { Color32::TRANSPARENT }; + painter.rect(rect, 0.0, fill, Stroke::new(2.0, accent), StrokeKind::Inside); +} + /// Keep `rect` inside `bounds`, shrinking it when it is larger. pub fn clamp(rect: Rect, bounds: Rect) -> Rect { if !super::targets::usable(bounds) { diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 985b4dd763..2ab0a836f9 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -1,8 +1,9 @@ use std::{fmt::Debug, hash::Hash}; -use egui::{Color32, Context, Key, Pos2, Rect, Stroke, StrokeKind, Ui, Vec2, pos2, vec2}; +use egui::{Context, Key, Pos2, Rect, Ui, Vec2, pos2, vec2}; use super::{Renderer, clamp_float, dock::group_action}; +use crate::docking::chrome::drop_preview; use crate::docking::{ Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Placement, Target, Zone, cancel_drag, dock_model::Place, resolve_drop, surface::TAB_PADDING, @@ -137,7 +138,7 @@ impl Renderer<'_, P> { let painter = self.preview_painter(ctx); if drag.gesture != GroupGesture::Window { let ghost = self.group_ghost(ctx, drag, pointer); - painter.rect(ghost, 0.0, self.style.accent.gamma_multiply(0.15), Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + drop_preview(&painter, ghost, self.style.accent, true); let strip = Rect::from_min_size(ghost.min, vec2(ghost.width(), self.style.tab_height.min(ghost.height()))); let labels = painter.with_clip_rect(strip.shrink(2.0)); let mut x = strip.left() + TAB_PADDING * 0.5; @@ -164,9 +165,8 @@ impl Renderer<'_, P> { } if let Some(proposal) = self.group_proposal(drag, pointer).filter(|p| !p.noop) { let split = matches!(proposal.placement, Placement::Split(zone) | Placement::Edge(zone) if zone != Zone::Center); - let fill = if split { self.style.accent.gamma_multiply(0.15) } else { Color32::TRANSPARENT }; if crate::docking::targets::usable(proposal.preview) { - painter.rect(proposal.preview.shrink(1.0), 0.0, fill, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, split); } if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); @@ -256,19 +256,13 @@ impl Renderer<'_, P> { let same_group = proposal.insertion.is_some() && self.targets.iter().any(|target| target.rect == proposal.preview && target.tabs.iter().any(|(panel, _)| panel == &drag.panel)); if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) { - painter.rect( - proposal.preview.shrink(1.0), - 0.0, - self.style.accent.gamma_multiply(0.15), - Stroke::new(2.0, self.style.accent), - StrokeKind::Inside, - ); + drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, true); } if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); } } else if let Some(rect) = floating_rect { - painter.rect_stroke(rect, 0.0, Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + drop_preview(&painter, rect, self.style.accent, false); } } @@ -348,7 +342,7 @@ impl Renderer<'_, P> { if !released { let painter = self.preview_painter(ctx); if let Some(rect) = feedback.preview.filter(|rect| crate::docking::targets::usable(*rect)) { - painter.rect(rect, 0.0, self.style.accent.gamma_multiply(0.15), Stroke::new(2.0, self.style.accent), StrokeKind::Inside); + drop_preview(&painter, rect, self.style.accent, true); } if let Some(rect) = feedback.insertion.filter(|rect| crate::docking::targets::usable(*rect)) { painter.rect_filled(rect, 0.0, self.style.accent); diff --git a/crates/ui/src/panes/mod.rs b/crates/ui/src/panes/mod.rs index 961c80538f..9e2aeca4e5 100644 --- a/crates/ui/src/panes/mod.rs +++ b/crates/ui/src/panes/mod.rs @@ -11,10 +11,7 @@ use std::fmt::Debug; use std::hash::Hash; use std::ops::RangeInclusive; -use egui::{ - Color32, Context, Frame, Id, Key, LayerId, Margin, Modifiers, Order, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, pos2, - vec2, -}; +use egui::{Context, Frame, Id, Key, LayerId, Margin, Modifiers, Order, Pos2, Rect, Response, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; use crate::docking::PanelLimits; use crate::docking::chrome::{self, ChromeStyle, FloatingFrame, MoveStep, TitleBar}; @@ -599,7 +596,7 @@ impl PaneHost { Some(_) => Rect::from_x_y_ranges(bounds.right() - rect.width()..=bounds.right(), bounds.y_range()), None => float, }; - paint_preview(preview, shape, style.accent); + chrome::drop_preview(preview, shape.shrink(1.0), style.accent, true); } #[allow(clippy::too_many_arguments)] @@ -714,10 +711,6 @@ impl PaneHost { } } -fn paint_preview(painter: &egui::Painter, rect: Rect, accent: Color32) { - painter.rect(rect.shrink(1.0), 0.0, accent.gamma_multiply(0.15), Stroke::new(2.0, accent), StrokeKind::Inside); -} - fn rect_array(rect: Rect) -> [f32; 4] { [rect.min.x, rect.min.y, rect.width(), rect.height()] } diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 96ea7ae368..35c8612aab 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -131,7 +131,8 @@ by the app's own Close items and commands. `DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome rather than on a panel body. `begin_drag` hands a drag that started in the app's own chrome to the area. -`docking::chrome` has the floating frame and title bar for apps that draw their own windows. +`docking::chrome` has the floating frame, the title bar and `drop_preview` (the drop preview +docking and `craft_ui::panes` both draw) for apps that draw their own windows. ## Gestures From d91e5f6aea2772899bb314092605cf13beec30ee Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:04:52 +0000 Subject: [PATCH 32/94] docking: paint panel icons in code with DockContent::paint_icon --- crates/ui/src/docking/iconic_tests.rs | 43 ++++++++++++++++++++++++++ crates/ui/src/docking/render/iconic.rs | 14 +++++---- crates/ui/src/docking/surface.rs | 10 ++++++ docs/ui-docking.md | 3 +- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index 62a2473b5d..b9ad4a88bf 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -324,3 +324,46 @@ fn hit_rects_cover_every_gesture_source() { assert!(opened || !out.actions.is_empty(), "{hit:?} at {rect:?} does nothing"); } } + +/// Paints panel 1's icon as a dot in code; panel 2 has neither a painted icon nor an image. +struct Painted; + +impl DockContent for Painted { + fn body(&mut self, _: &mut egui::Ui, _: &u32) {} + fn logical_label(&self, panel: &u32) -> String { + format!("Panel {panel}") + } + fn paint_icon(&mut self, painter: &egui::Painter, rect: Rect, panel: &u32, color: egui::Color32) -> bool { + if *panel != 1 { + return false; + } + painter.circle_filled(rect.center(), 3.0, color); + true + } +} + +#[test] +fn an_icon_painted_in_code_replaces_the_initial_and_others_fall_back() { + let d = DockDriver::new(docked(&[&[1, 2]], true), Painted); + let (one, two) = (d.hit(&Hit::Icon(1)).unwrap(), d.hit(&Hit::Icon(2)).unwrap()); + let dots: Vec = d + .shapes() + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Circle(circle) if circle.radius == 3.0 => Some(circle.center), + _ => None, + }) + .collect(); + assert_eq!(dots.len(), 1, "{dots:?}"); + assert!(one.contains(dots[0]) && !two.contains(dots[0]), "the dot sits in panel 1's cell: {dots:?}"); + let initials: Vec = d + .shapes() + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "P" => Some(text.pos), + _ => None, + }) + .collect(); + assert_eq!(initials.len(), 1, "only panel 2 draws its initial: {initials:?}"); + assert!(two.contains(initials[0])); +} diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 79a37f27bb..7b908b4a1c 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -230,12 +230,14 @@ impl Renderer<'_, P> { let inset = ((self.style.iconic_width - size) * 0.5).max(2.0); let icon = Rect::from_min_size(pos2(cell.left() + inset, cell.center().y - size * 0.5), vec2(size, size)); let color = if current { self.style.text } else { self.style.inactive_text }; - if let Some(source) = self.content.icon(panel) { - egui::Image::new(source).tint(color).paint_at(ui, icon.intersect(cell)); - } else { - let initial: String = label.chars().next().into_iter().flat_map(char::to_uppercase).collect(); - painter.rect_stroke(icon, 3.0, Stroke::new(1.0, color), StrokeKind::Inside); - painter.text(icon.center(), egui::Align2::CENTER_CENTER, initial, self.style.font.clone(), color); + if !self.content.paint_icon(&painter, icon, panel, color) { + if let Some(source) = self.content.icon(panel) { + egui::Image::new(source).tint(color).paint_at(ui, icon.intersect(cell)); + } else { + let initial: String = label.chars().next().into_iter().flat_map(char::to_uppercase).collect(); + painter.rect_stroke(icon, 3.0, Stroke::new(1.0, color), StrokeKind::Inside); + painter.text(icon.center(), egui::Align2::CENTER_CENTER, initial, self.style.font.clone(), color); + } } if labels { let text = self.content.label(ui, panel, &label, &self.style.font, color); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 66c0ad8c67..619a87cf7b 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -371,9 +371,16 @@ pub trait DockContent

{ fn floating_size(&self, _panel: &P) -> Option { None } + /// An image for the panel's icon, tinted with the icon color. [`Self::paint_icon`] goes first. fn icon(&self, _panel: &P) -> Option> { None } + /// Paint the panel's icon in code into `rect` with `color`, and return true. False draws + /// [`Self::icon`], or the label's initial when that is `None`. `painter` is clipped to the + /// icon's cell. + fn paint_icon(&mut self, _painter: &egui::Painter, _rect: Rect, _panel: &P, _color: Color32) -> bool { + false + } /// Whether the panel may move to a native OS window (feature `native-windows`). fn allow_native(&self, _panel: &P) -> bool { false @@ -455,6 +462,9 @@ impl + ?Sized> DockContent

for Overrides<'_, P, C> { fn icon(&self, panel: &P) -> Option> { self.inner.icon(panel) } + fn paint_icon(&mut self, painter: &egui::Painter, rect: Rect, panel: &P, color: Color32) -> bool { + self.inner.paint_icon(painter, rect, panel, color) + } fn allow_native(&self, panel: &P) -> bool { self.inner.allow_native(panel) } diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 35c8612aab..0434d20d13 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -104,7 +104,8 @@ its own command path, so pointer, keyboard and control commands share one path. `DockContent

` is the app's adapter. It draws each panel body and gives its label, icon, permissions, size limits, preferred floating size, panel menu and group header. `bare` hides the -tab strip of a lone panel. Panel bodies keep a stable egui id when they move, so widget memory +tab strip of a lone panel. An icon is an image (`icon`), or drawn in code by `paint_icon`, which +gets a painter, the icon rect and the tint color and returns true when it painted. Panel bodies keep a stable egui id when they move, so widget memory survives. `DockOutput` also has: From f46828ea48eadc3aac415768e079a4a780a0696d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:07:03 +0000 Subject: [PATCH 33/94] docking: float commands without a rect at the drag size inside the dock area --- crates/ui/src/docking/command.rs | 71 ++++++++++++++++++++++--- crates/ui/src/docking/command_tests.rs | 45 ++++++++++++++++ crates/ui/src/docking/mod.rs | 4 +- crates/ui/src/docking/render/dock.rs | 1 + crates/ui/src/docking/render/group.rs | 1 + crates/ui/src/docking/render/iconic.rs | 5 +- crates/ui/src/docking/render/mod.rs | 2 + crates/ui/src/docking/render/preview.rs | 17 ++++++ crates/ui/src/docking/surface.rs | 64 ++++++++++++++++++++++ docs/ui-docking.md | 10 +++- 10 files changed, 208 insertions(+), 12 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index e0b26d6070..58ef542dd4 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -7,17 +7,18 @@ //! let mut params = params.clone(); //! params["command"] = json!(id); //! let command: DockCommand = serde_json::from_value(params)?; -//! command.apply(&mut app.workspace, style.right_to_left, |p| app.permissions(p))?; +//! let space = float_space(ctx, DOCK_ID).unwrap_or_else(|| FloatSpace::new(ctx.content_rect())); +//! command.apply_in(&mut app.workspace, style.right_to_left, &space, |p| app.permissions(p))?; //! ``` use std::hash::Hash; use serde::{Deserialize, Deserializer, Serialize}; -use super::{Action, DockError, Layout, Permissions, Placement, Side, Target, Workspace, Zone, dock_model::Place}; +use super::{Action, DockError, FloatSpace, Layout, Permissions, Placement, Side, Target, Workspace, Zone, dock_model::Place}; use crate::layout::SplitSize; -/// Where a panel floats when a command gives no position or size. +/// Where a panel floats when a command gives no position or size and no [`FloatSpace`]. const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0]; /// A docking command, tagged by its control id under `"command"`. @@ -332,7 +333,23 @@ impl DockCommand

{ /// `left`, `right`, `top` and `bottom` zones follow [`Placement::for_zone`]: beside a docked /// anchor they make a new column or group, and `right_to_left` is the /// [`super::DockStyle::right_to_left`] the layout is drawn with. + /// + /// A `window.panel.float` without a rect floats at 48, 48 in window coordinates; use + /// [`Self::to_actions_in`] to float inside the dock area instead. pub fn to_actions(&self, workspace: &Workspace

, right_to_left: bool) -> Result>, DockError> { + self.actions(workspace, right_to_left, None) + } + + /// Like [`Self::to_actions`], with `window.panel.float` floating into `space`: what it moves + /// takes the size a drag would float it at, inside the dock area and clear of the app's + /// menu bar. Pass [`super::float_space`] of the area that draws `workspace`. Given `x`, `y`, + /// `width` and `height` replace the matching values, and a group or column that is already + /// a whole floating window keeps its rect. + pub fn to_actions_in(&self, workspace: &Workspace

, right_to_left: bool, space: &FloatSpace

) -> Result>, DockError> { + self.actions(workspace, right_to_left, Some(space)) + } + + fn actions(&self, workspace: &Workspace

, right_to_left: bool, space: Option<&FloatSpace

>) -> Result>, DockError> { let layout = &workspace.layout; let zoned = Zoned { layout, right_to_left }; let shown = |panel: &P| if layout.contains(panel) { Ok(()) } else { Err(DockError::MissingPanel) }; @@ -359,13 +376,32 @@ impl DockCommand

{ rect }; let any = given.iter().any(Option::is_some); - match (Unit::of(*group, *column), window) { + let unit = Unit::of(*group, *column); + let whole_window = layout.floating.iter().any(|w| w.contains(panel) && w.groups.len() == 1); + // The rect a drag would float the unit at, inside the area. + let placed = space.map(|space| { + let docked = layout.location(panel).ok().and_then(|l| l.group).and_then(|g| g.column).map(|c| c.width); + let fallback = egui::vec2(docked.filter(|_| !matches!(unit, Unit::Panel)).unwrap_or(DEFAULT_FLOAT[2]), DEFAULT_FLOAT[3]); + let size = match unit { + Unit::Panel => space.panel(panel), + Unit::Group => space.group(panel), + Unit::Column => space.column(panel), + }; + space.place(size.unwrap_or(fallback)) + }); + match (unit, window) { (Unit::Panel, Some(base)) if layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1) => { one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }) } - (Unit::Panel, _) => one(Action::Float { panel: panel.clone(), rect: rect(DEFAULT_FLOAT) }), + (Unit::Panel, _) => one(Action::Float { panel: panel.clone(), rect: rect(placed.unwrap_or(DEFAULT_FLOAT)) }), (Unit::Column, Some(base)) => one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }), - (unit, _) => one(unit.to(layout, panel, Target::Float { rect: any.then(|| rect(DEFAULT_FLOAT)) })?), + (Unit::Group, Some(_)) if whole_window => { + one(unit.to(layout, panel, Target::Float { rect: any.then(|| rect(DEFAULT_FLOAT)) })?) + } + (unit, _) => { + let float = placed.map(rect).or_else(|| any.then(|| rect(DEFAULT_FLOAT))); + one(unit.to(layout, panel, Target::Float { rect: float })?) + } } } Self::Dock { panel, anchor, zone, before, group, column, side } => { @@ -457,6 +493,27 @@ impl DockCommand

{ /// location; Lock sets [`Workspace::locked`]. Application-owned commands /// ([`Self::is_app_owned`]) return [`DockError::NotAllowed`] and change nothing. pub fn apply(&self, workspace: &mut Workspace

, right_to_left: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { + self.apply_with(workspace, right_to_left, None, permissions) + } + + /// Like [`Self::apply`], floating into `space` as [`Self::to_actions_in`] does. + pub fn apply_in( + &self, + workspace: &mut Workspace

, + right_to_left: bool, + space: &FloatSpace

, + permissions: impl Fn(&P) -> Permissions, + ) -> Result, DockError> { + self.apply_with(workspace, right_to_left, Some(space), permissions) + } + + fn apply_with( + &self, + workspace: &mut Workspace

, + right_to_left: bool, + space: Option<&FloatSpace

>, + permissions: impl Fn(&P) -> Permissions, + ) -> Result, DockError> { let show = match self { Self::Activate { panel } | Self::Dock { panel, anchor: None, side: None, .. } @@ -471,7 +528,7 @@ impl DockCommand

{ workspace.locked = locked.unwrap_or(!workspace.locked); return Ok(Vec::new()); } - let actions = self.to_actions(workspace, right_to_left)?; + let actions = self.actions(workspace, right_to_left, space)?; workspace.apply_all(actions, permissions) } } diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index c84051bf74..34f93c5faf 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -311,3 +311,48 @@ fn side_zones_map_to_the_placement_the_anchor_container_takes_in_either_directio assert_eq!(columns.len(), 2); assert_eq!(columns[1].groups[0].panels, vec![s("history")]); } + +/// `layers` prefers 200x150 when it floats. +struct Sized; + +impl DockContent

for Sized { + fn body(&mut self, _: &mut egui::Ui, _: &P) {} + fn permissions(&self, panel: &P) -> Permissions { + permissions(panel) + } + fn floating_size(&self, panel: &P) -> Option { + (panel == "layers").then_some(egui::vec2(200.0, 150.0)) + } +} + +#[test] +fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { + // The area starts under a 30 pt menu bar. + let area = egui::Rect::from_min_max(egui::pos2(0.0, 30.0), egui::pos2(800.0, 600.0)); + let d = testing::DockDriver::new(workspace().layout, Sized).with_area(area); + let space = float_space::

(&d.ctx, d.id).expect("the area records its float space"); + assert_eq!(space.area, area); + let float = |params: Value| parse(params).unwrap().to_actions_in(&workspace(), false, &space).unwrap(); + + let panel = float(json!({"command": "window.panel.float", "panel": "layers"})); + assert_eq!(panel, vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 150.0] }], "floating_size, inset in the area"); + let [Action::MoveGroup { to: Target::Float { rect: Some([x, y, width, height]) }, .. }] = + float(json!({"command": "window.panel.float", "panel": "history", "group": true}))[..] + else { + panic!() + }; + assert_eq!([x, y], [24.0, 54.0]); + assert!(width > 100.0 && width <= 240.0 && height <= 320.0, "the docked group's size, capped: {width}x{height}"); + + // Given values stay exactly; a lone floating window keeps its rect. + let given = float(json!({"command": "window.panel.float", "panel": "layers", "x": 5, "y": 6, "width": 100, "height": 90})); + assert_eq!(given, vec![Action::Float { panel: s("layers"), rect: [5.0, 6.0, 100.0, 90.0] }]); + let color = float(json!({"command": "window.panel.float", "panel": "color", "group": true})); + assert_eq!(color, vec![Action::MoveGroup { panel: s("color"), to: Target::Float { rect: None } }]); + + // Without recorded sizes a unit floats at the layout's size, shrunk into a small area. + let small = FloatSpace::new(egui::Rect::from_min_size(egui::pos2(0.0, 30.0), egui::vec2(200.0, 200.0))); + let applied = + parse(json!({"command": "window.panel.float", "panel": "layers", "group": true})).unwrap().to_actions_in(&workspace(), false, &small); + assert_eq!(applied, Ok(vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: Some([0.0, 30.0, 200.0, 200.0]) } }])); +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index f3c8c62317..b8462ec329 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -27,8 +27,8 @@ pub use hits::{Divider, Hit, ResizeEdge}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; pub use render::{close_flyout, flyout, open_flyout}; pub use surface::{ - DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, HidePanels, PanelLimits, Profile, begin_drag, cancel_drag, - is_dragging, + DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, FloatSpace, HidePanels, PanelLimits, Profile, begin_drag, + cancel_drag, float_space, is_dragging, }; pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect}; pub use workspace::Workspace; diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 32d7240a8b..86c57be58d 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -209,6 +209,7 @@ impl Renderer<'_, P> { if !usable(rect) { return; } + self.record_column_float(column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect(), rect); let bar = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.column_bar_height).min(rect.bottom()))); self.column_bar(ui, column, first, bar, rect, edge); let body = Rect::from_min_max(pos2(rect.left(), bar.bottom()), rect.max); diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 2d1bc6f9a7..74912e9687 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -32,6 +32,7 @@ const BORDER_BAND: f32 = 4.0; impl Renderer<'_, P> { pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, minimized: bool, rect: Rect, kind: GroupKind) { let Some(selected) = panels.get(active) else { return }; + self.record_float(panels, rect.size(), rect.size()); let policy = self.permissions(selected); let splits = kind == GroupKind::Frame && policy.accepts_splits; let rtl = self.style.right_to_left; diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 7b908b4a1c..59e2512483 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -188,6 +188,9 @@ impl Renderer<'_, P> { let response = ui.interact(grip, self.id.with(("icon-grip", Some(first))), Sense::drag()); let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response }; self.register_interaction(ui.ctx(), response.id); + let height = group.height.filter(|h| h.is_finite()).unwrap_or(FLYOUT_HEIGHT); + let source = Rect::from_min_size(grip.min, vec2(width.max(self.style.min_pane), height.max(self.style.tab_height))); + self.record_float(&group.panels, vec2(grip.width(), self.row_height()), source.size()); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label)); let color = if response.hovered() || response.dragged() { self.style.text } else { self.style.inactive_text }; let painter = ui.painter().with_clip_rect(grip.intersect(ui.clip_rect())); @@ -195,8 +198,6 @@ impl Renderer<'_, P> { painter.hline((grip.center().x - 8.0)..=(grip.center().x + 8.0), grip.center().y + 1.0, Stroke::new(1.0, color)); if movable && response.drag_started() { let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center()); - let height = group.height.filter(|h| h.is_finite()).unwrap_or(FLYOUT_HEIGHT); - let source = Rect::from_min_size(grip.min, vec2(width.max(self.style.min_pane), height.max(self.style.tab_height))); let drag = GroupDrag { panel: first.clone(), original: [source.left(), source.top(), source.width(), source.height()], diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 37414bc78f..d5cdd4b9db 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -41,6 +41,8 @@ pub(super) struct Renderer<'a, P> { pub(super) frame: FrameState

, /// [D] Flyout and iconic column state for this frame. pub(super) iconic: Iconic

, + /// What a drag would float from each drawn panel, group and column, for commands. + pub(super) float_space: crate::docking::FloatSpace

, } impl Renderer<'_, P> { diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 2ab0a836f9..5d66298048 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -289,6 +289,23 @@ impl Renderer<'_, P> { size.max(limits.min + header).min(limits.max + header) } + /// Record what a drag floats from `panels`, one group drawn at `group` whose panels drag + /// from `panel` rects, for commands that float without a rect. + pub(super) fn record_float(&mut self, panels: &[P], panel: Vec2, group: Vec2) { + let group = self.group_float_size(panels, group); + for p in panels { + let size = self.float_size(p, panel); + self.float_space.panels.push((p.clone(), size)); + self.float_space.groups.push((p.clone(), group)); + } + } + + /// Record what a drag floats from a dock column drawn at `rect`. + pub(super) fn record_column_float(&mut self, members: Vec

, rect: Rect) { + let size = self.group_float_size(&members, rect.size()); + self.float_space.columns.extend(members.into_iter().map(|p| (p, size))); + } + /// Size of a group or column floated by a drag or Float Tab Group: the source width, and the /// tallest member's floating size, else the source height capped like a panel leaving a /// dock column. A group that already floats keeps its size. diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 619a87cf7b..ce06a9b963 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -218,6 +218,68 @@ impl

Default for DockOutput

{ } } +/// Room between the dock area's top-left corner and a unit a command floats. +const FLOAT_INSET: f32 = 24.0; + +/// Where a docking command floats a panel, group or column when it gives no rect (see +/// `DockCommand::to_actions_in`, feature `serde`). [`DockArea`] records one each frame; read it +/// with [`float_space`]. +#[derive(Clone, Debug, PartialEq)] +pub struct FloatSpace

{ + /// The rect the area drew in. A floated unit goes inside it, 24 points from its top-left + /// corner, so it stays clear of the app's menu bar. + pub area: Rect, + /// What a drag floats from each drawn panel: the panel alone, its group and its dock column. + pub(super) panels: Vec<(P, Vec2)>, + pub(super) groups: Vec<(P, Vec2)>, + pub(super) columns: Vec<(P, Vec2)>, +} + +impl FloatSpace

{ + /// An area with no recorded sizes: commands float units at the layout's sizes. + pub fn new(area: Rect) -> Self { + Self { area, panels: Vec::new(), groups: Vec::new(), columns: Vec::new() } + } +} + +/// Lookups for `DockCommand`, which needs feature `serde`. +#[cfg_attr(not(feature = "serde"), allow(dead_code))] +impl FloatSpace

{ + pub(super) fn panel(&self, panel: &P) -> Option { + Self::find(&self.panels, panel) + } + + pub(super) fn group(&self, panel: &P) -> Option { + Self::find(&self.groups, panel) + } + + pub(super) fn column(&self, panel: &P) -> Option { + Self::find(&self.columns, panel) + } + + /// The first record wins: an iconic panel is recorded at its icon before its flyout. + fn find(sizes: &[(P, Vec2)], panel: &P) -> Option { + sizes.iter().find(|(p, _)| p == panel).map(|(_, size)| *size) + } + + /// `[x, y, width, height]` of `size` inside the area, inset from its top-left corner and + /// shrunk to fit. + pub(super) fn place(&self, size: Vec2) -> [f32; 4] { + let size = size.min(self.area.size()); + let min = (self.area.min + Vec2::splat(FLOAT_INSET)).min(self.area.max - size).max(self.area.min); + [min.x, min.y, size.x, size.y] + } +} + +/// The [`FloatSpace`] the area recorded on its last frame. +pub fn float_space(ctx: &Context, area_id: Id) -> Option> { + ctx.data(|d| d.get_temp(float_space_key(area_id))) +} + +fn float_space_key(area: Id) -> Id { + area.with("float-space") +} + /// A request for host state outside the layout. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -680,6 +742,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { output: DockOutput::default(), frame, iconic: super::render::Iconic::new(self.auto_collapse), + float_space: FloatSpace::new(rect), }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); @@ -690,6 +753,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { renderer.finish_group_drag(ui); renderer.finish_drag(ui.ctx()); super::hits::record(ui.ctx(), self.id, &view, &renderer.owned_interactions); + ui.ctx().data_mut(|d| d.insert_temp(float_space_key(self.id), renderer.float_space)); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); renderer.output } diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 0434d20d13..3ab542f59b 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -159,7 +159,8 @@ let command: DockCommand = serde_json::from_value(params)?; if command.is_app_owned() { return app.workspace_command(command); } -let closed = command.apply(&mut app.workspace, style.right_to_left, |panel| app.permissions(panel))?; +let space = float_space(ctx, DOCK_ID).unwrap_or_else(|| FloatSpace::new(ctx.content_rect())); +let closed = command.apply_in(&mut app.workspace, style.right_to_left, &space, |panel| app.permissions(panel))?; ``` | Id | Params (`?` is optional) | @@ -183,6 +184,13 @@ let closed = command.apply(&mut app.workspace, style.right_to_left, |panel| app. `to_actions` take the layout's `right_to_left` for that. - `group` moves the panel's whole group; `column` moves its dock column, or its whole window when it floats. `side` is `Start` or `End`. +- `window.panel.float` without a rect floats what it moves at the size a drag floats it at: the + panel's `floating_size`, else its docked group or column size, capped like a drag. It goes + inside the dock area, 24 points from its top-left corner, so it stays clear of the menu bar. + The area records that geometry in a `FloatSpace` each frame; `float_space(ctx, id)` reads it + and `apply_in` and `to_actions_in` take it. `x`, `y`, `width` and `height` replace the matching + values, and a group or column that is already a whole floating window keeps its rect. + `apply` and `to_actions` have no area and float at 48, 48 in window coordinates. - Without a value, `minimized`, `iconic` and `locked` toggle. - `ui.dock` operations are those of LightCraft, PDFCraft, CADCraft and SoundCraft: `open`, `close`, `activate`, `float {rect}`, `moveFloating {rect}`, `move {target, zone?, before?}`, From 3aded979b5f04a1ace40ccea5ad70236667338f9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:07:52 +0000 Subject: [PATCH 34/94] docking: report flyout changes with DockEvent::FlyoutChanged --- crates/ui/src/docking/render/iconic.rs | 15 ++++++++ crates/ui/src/docking/surface.rs | 6 ++++ crates/ui/src/docking/trial_tests.rs | 49 +++++++++++++++++++++++++- docs/ui-docking.md | 4 ++- 4 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 59e2512483..4b7b3a045d 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -47,6 +47,10 @@ pub fn flyout(ctx: &Context, area_id: Id) -> O ctx.data(|d| d.get_temp::>(key(area_id))).map(|open| open.0) } +/// The flyout last reported by [`crate::docking::DockEvent::FlyoutChanged`]. +#[derive(Clone)] +struct Reported

(Option

); + /// The flyout an iconic column asks for this frame. struct Request

{ group: Group

, @@ -318,6 +322,17 @@ impl Renderer<'_, P> { self.iconic.rect = Some(response.rect); } + /// Report a flyout that differs from the last one reported. + pub(in crate::docking) fn report_flyout(&mut self, ctx: &Context) { + let shown = flyout::

(ctx, self.id); + let key = self.id.with("flyout-reported"); + let reported = ctx.data(|d| d.get_temp::>(key)).and_then(|r| r.0); + if shown != reported { + ctx.data_mut(|d| d.insert_temp(key, Reported(shown.clone()))); + self.output.events.push(crate::docking::DockEvent::FlyoutChanged { panel: shown }); + } + } + /// Escape (outside a drag) or a primary press outside the flyout, its column and any menu. fn flyout_dismissed(&self, ctx: &Context, id: Id, column: Rect) -> bool { let escape = !is_dragging::

(ctx, self.id) && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index ce06a9b963..73d4108ab0 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -290,6 +290,11 @@ pub enum DockEvent

{ /// [D] Auto-Collapse Iconic Panels was chosen in a column menu. The host flips its /// preference and passes it to [`DockArea::auto_collapse_iconic`]. ToggleAutoCollapse, + /// [D] The area's flyout opened, switched to another panel or closed (`None`), whatever + /// changed it: an icon, Escape, a press outside, a raised panel, a group that is no longer + /// iconic, or [`super::open_flyout`] and [`super::close_flyout`]. It comes once per change, + /// in the frame that draws the change. + FlyoutChanged { panel: Option

}, } /// Which panels [`DockArea::hide_panels`] hides. Protected panels always stay. @@ -752,6 +757,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { renderer.floating(ui.ctx(), &view.floating); renderer.finish_group_drag(ui); renderer.finish_drag(ui.ctx()); + renderer.report_flyout(ui.ctx()); super::hits::record(ui.ctx(), self.id, &view, &renderer.owned_interactions); ui.ctx().data_mut(|d| d.insert_temp(float_space_key(self.id), renderer.float_space)); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index f7612993c2..3036490e96 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -1,7 +1,7 @@ //! Fixes from the DesignCraft trial: group float size, tab label elision, the drag ghost and //! grip, double-clicks on minimized groups, pointer focus, label keys and borrowed lookups; then //! split permissions, body focus, right-to-left strips, close controls, menu and button names, -//! zone mapping, closed panels from `apply` and group heights. +//! zone mapping, closed panels from `apply`, group heights and flyout events. use super::*; @@ -390,3 +390,50 @@ fn a_group_placement_gives_the_inserted_group_its_height() { assert_eq!(heights, vec![(vec![4], None), (vec![8], None), (vec![7], Some(180.0)), (vec![2, 3], Some(90.0))]); assert_eq!(layout.apply(Action::OpenAt { panel: 9, anchor: 4, placement: below(Some(f32::NAN)) }), Err(DockError::InvalidGeometry)); } + +struct Icons; + +impl DockContent for Icons { + fn body(&mut self, _: &mut egui::Ui, _: &u32) {} +} + +#[test] +fn every_flyout_change_reports_one_event_whatever_caused_it() { + use crate::docking::testing::DockDriver; + let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)], 240.0); + column.iconic = true; + let dock = Node::Dock { side: Side::Start, columns: vec![column] }; + let canvas = Node::Tabs { panels: vec![0], active: 0 }; + let layout = Layout { + root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), first: Box::new(dock), second: Box::new(canvas) }), + floating: Vec::new(), + }; + let mut d = DockDriver::new(layout, Icons); + let flyouts = |outputs: Vec>| -> Vec> { + outputs + .into_iter() + .flat_map(|out| out.events) + .filter_map(|event| match event { + DockEvent::FlyoutChanged { panel } => Some(panel), + _ => None, + }) + .collect() + }; + let icon = |d: &DockDriver, panel| d.hit(&Hit::Icon(panel)).unwrap().center(); + let quiet = |d: &mut DockDriver| (0..3).map(|_| d.step(Vec::new())).collect::>(); + + let (one, two) = (icon(&d, 1), icon(&d, 2)); + assert_eq!(flyouts(vec![d.press(one), d.release(one)]), [Some(1)], "an icon opens it"); + assert_eq!(flyouts(quiet(&mut d)), [], "an open flyout reports nothing more"); + assert_eq!(flyouts(vec![d.press(two), d.release(two)]), [Some(2)], "another icon switches it"); + assert_eq!(flyouts(vec![d.key(egui::Key::Escape)]), [None], "Escape closes it"); + open_flyout(&d.ctx, d.id, 3u32); + assert_eq!(flyouts(vec![d.step(Vec::new())]), [Some(3)], "open_flyout"); + close_flyout::(&d.ctx, d.id); + assert_eq!(flyouts(vec![d.step(Vec::new())]), [None], "close_flyout"); + d.raise = Some(1); + assert_eq!(flyouts(vec![d.step(Vec::new())]), [Some(1)], "raising an iconic panel opens it"); + let outside = pos2(600.0, 400.0); + assert_eq!(flyouts(vec![d.press(outside), d.release(outside)]), [None], "a press outside closes it"); + assert_eq!(flyouts(quiet(&mut d)), []); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 3ab542f59b..400e288831 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -113,7 +113,9 @@ survives. - `focused`: the panel the user focused this frame: a clicked tab, a drop, a raised window, or a press of any pointer button in a panel body, bare and protected panels included. - `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (Frame) and - `DockEvent::ToggleAutoCollapse` (Dock). + `DockEvent::ToggleAutoCollapse` (Dock), and `DockEvent::FlyoutChanged { panel }` (Dock): the + flyout opened, switched or closed (`None`). It comes once per change, whatever made it: an + icon, Escape, a press outside, a raised panel, `open_flyout` or `close_flyout`. - `error`: a rejected gesture. Builder options on `DockArea`: From 6261d9d39a0a109a832685f37af6ce75321caea1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:11:07 +0000 Subject: [PATCH 35/94] docking: DockCommand takes the float space --- crates/ui/src/docking/command.rs | 78 ++++++++------------------ crates/ui/src/docking/command_tests.rs | 24 ++++---- crates/ui/src/docking/surface.rs | 9 ++- crates/ui/tests/docking_workflows.rs | 3 +- docs/ui-docking.md | 9 +-- 5 files changed, 52 insertions(+), 71 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 58ef542dd4..3ae6d2aea6 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -8,19 +8,18 @@ //! params["command"] = json!(id); //! let command: DockCommand = serde_json::from_value(params)?; //! let space = float_space(ctx, DOCK_ID).unwrap_or_else(|| FloatSpace::new(ctx.content_rect())); -//! command.apply_in(&mut app.workspace, style.right_to_left, &space, |p| app.permissions(p))?; +//! command.apply(&mut app.workspace, style.right_to_left, &space, |p| app.permissions(p))?; //! ``` use std::hash::Hash; use serde::{Deserialize, Deserializer, Serialize}; -use super::{Action, DockError, FloatSpace, Layout, Permissions, Placement, Side, Target, Workspace, Zone, dock_model::Place}; +use super::{ + Action, DockError, FloatSpace, Layout, Permissions, Placement, Side, Target, Workspace, Zone, dock_model::Place, surface::DEFAULT_FLOAT, +}; use crate::layout::SplitSize; -/// Where a panel floats when a command gives no position or size and no [`FloatSpace`]. -const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0]; - /// A docking command, tagged by its control id under `"command"`. /// /// Ids and params (`?` marks optional ones): @@ -334,22 +333,12 @@ impl DockCommand

{ /// anchor they make a new column or group, and `right_to_left` is the /// [`super::DockStyle::right_to_left`] the layout is drawn with. /// - /// A `window.panel.float` without a rect floats at 48, 48 in window coordinates; use - /// [`Self::to_actions_in`] to float inside the dock area instead. - pub fn to_actions(&self, workspace: &Workspace

, right_to_left: bool) -> Result>, DockError> { - self.actions(workspace, right_to_left, None) - } - - /// Like [`Self::to_actions`], with `window.panel.float` floating into `space`: what it moves - /// takes the size a drag would float it at, inside the dock area and clear of the app's - /// menu bar. Pass [`super::float_space`] of the area that draws `workspace`. Given `x`, `y`, - /// `width` and `height` replace the matching values, and a group or column that is already - /// a whole floating window keeps its rect. - pub fn to_actions_in(&self, workspace: &Workspace

, right_to_left: bool, space: &FloatSpace

) -> Result>, DockError> { - self.actions(workspace, right_to_left, Some(space)) - } - - fn actions(&self, workspace: &Workspace

, right_to_left: bool, space: Option<&FloatSpace

>) -> Result>, DockError> { + /// `space` is where `window.panel.float` floats what it moves when it gives no rect: at the + /// size a drag would float it at, inside the dock area and clear of the app's menu bar. Pass + /// [`super::float_space`] of the area that draws `workspace`. Given `x`, `y`, `width` and + /// `height` replace the matching values, and a group or column that is already a whole + /// floating window keeps its rect. + pub fn to_actions(&self, workspace: &Workspace

, right_to_left: bool, space: &FloatSpace

) -> Result>, DockError> { let layout = &workspace.layout; let zoned = Zoned { layout, right_to_left }; let shown = |panel: &P| if layout.contains(panel) { Ok(()) } else { Err(DockError::MissingPanel) }; @@ -377,31 +366,26 @@ impl DockCommand

{ }; let any = given.iter().any(Option::is_some); let unit = Unit::of(*group, *column); - let whole_window = layout.floating.iter().any(|w| w.contains(panel) && w.groups.len() == 1); + let lone = layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1); + let whole = layout.floating.iter().any(|w| w.contains(panel) && w.groups.len() == 1); // The rect a drag would float the unit at, inside the area. - let placed = space.map(|space| { + let placed = || { let docked = layout.location(panel).ok().and_then(|l| l.group).and_then(|g| g.column).map(|c| c.width); - let fallback = egui::vec2(docked.filter(|_| !matches!(unit, Unit::Panel)).unwrap_or(DEFAULT_FLOAT[2]), DEFAULT_FLOAT[3]); + let fallback = egui::vec2(docked.filter(|_| !matches!(unit, Unit::Panel)).unwrap_or(DEFAULT_FLOAT.x), DEFAULT_FLOAT.y); let size = match unit { Unit::Panel => space.panel(panel), Unit::Group => space.group(panel), Unit::Column => space.column(panel), }; - space.place(size.unwrap_or(fallback)) - }); + rect(space.place(size.unwrap_or(fallback))) + }; match (unit, window) { - (Unit::Panel, Some(base)) if layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1) => { - one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }) - } - (Unit::Panel, _) => one(Action::Float { panel: panel.clone(), rect: rect(placed.unwrap_or(DEFAULT_FLOAT)) }), + (Unit::Panel, Some(base)) if lone => one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }), (Unit::Column, Some(base)) => one(Action::MoveFloating { panel: panel.clone(), rect: rect(base) }), - (Unit::Group, Some(_)) if whole_window => { - one(unit.to(layout, panel, Target::Float { rect: any.then(|| rect(DEFAULT_FLOAT)) })?) - } - (unit, _) => { - let float = placed.map(rect).or_else(|| any.then(|| rect(DEFAULT_FLOAT))); - one(unit.to(layout, panel, Target::Float { rect: float })?) - } + // Without given values the window keeps its rect and native state. + (Unit::Group, Some(base)) if whole => one(unit.to(layout, panel, Target::Float { rect: any.then(|| rect(base)) })?), + (Unit::Panel, _) => one(Action::Float { panel: panel.clone(), rect: placed() }), + (unit, _) => one(unit.to(layout, panel, Target::Float { rect: Some(placed()) })?), } } Self::Dock { panel, anchor, zone, before, group, column, side } => { @@ -492,27 +476,13 @@ impl DockCommand

{ /// the application can release their state. Showing a hidden panel restores its last /// location; Lock sets [`Workspace::locked`]. Application-owned commands /// ([`Self::is_app_owned`]) return [`DockError::NotAllowed`] and change nothing. - pub fn apply(&self, workspace: &mut Workspace

, right_to_left: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { - self.apply_with(workspace, right_to_left, None, permissions) - } - - /// Like [`Self::apply`], floating into `space` as [`Self::to_actions_in`] does. - pub fn apply_in( + /// `space` is where `window.panel.float` floats, as for [`Self::to_actions`]. + pub fn apply( &self, workspace: &mut Workspace

, right_to_left: bool, space: &FloatSpace

, permissions: impl Fn(&P) -> Permissions, - ) -> Result, DockError> { - self.apply_with(workspace, right_to_left, Some(space), permissions) - } - - fn apply_with( - &self, - workspace: &mut Workspace

, - right_to_left: bool, - space: Option<&FloatSpace

>, - permissions: impl Fn(&P) -> Permissions, ) -> Result, DockError> { let show = match self { Self::Activate { panel } @@ -528,7 +498,7 @@ impl DockCommand

{ workspace.locked = locked.unwrap_or(!workspace.locked); return Ok(Vec::new()); } - let actions = self.actions(workspace, right_to_left, space)?; + let actions = self.to_actions(workspace, right_to_left, space)?; workspace.apply_all(actions, permissions) } } diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 34f93c5faf..4f2be2f616 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -33,6 +33,11 @@ fn workspace() -> Workspace

{ workspace } +/// An 800x600 dock area that has drawn nothing. +fn space() -> FloatSpace

{ + FloatSpace::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))) +} + fn parse(params: Value) -> Result, serde_json::Error> { serde_json::from_value(params) } @@ -40,14 +45,14 @@ fn parse(params: Value) -> Result, serde_json::Error> { /// The actions `params` makes on a fresh workspace. fn actions(params: Value) -> Vec> { let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); - command.to_actions(&workspace(), false).unwrap_or_else(|e| panic!("{params}: {e}")) + command.to_actions(&workspace(), false, &space()).unwrap_or_else(|e| panic!("{params}: {e}")) } /// Apply `params` to a fresh workspace; return it and the panels closed. fn applied(params: Value) -> (Workspace

, Vec

) { let mut workspace = workspace(); let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); - let closed = command.apply(&mut workspace, false, permissions).unwrap_or_else(|e| panic!("{params}: {e}")); + let closed = command.apply(&mut workspace, false, &space(), permissions).unwrap_or_else(|e| panic!("{params}: {e}")); (workspace, closed) } @@ -56,7 +61,7 @@ fn rejected(params: Value, error: DockError) { let mut workspace = workspace(); let before = workspace.clone(); let command = parse(params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); - assert_eq!(command.apply(&mut workspace, false, permissions), Err(error), "{params}"); + assert_eq!(command.apply(&mut workspace, false, &space(), permissions), Err(error), "{params}"); assert_eq!(workspace, before, "{params}"); } @@ -112,11 +117,11 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { ); assert_eq!( actions(json!({"command": "window.panel.float", "panel": "layers", "group": true})), - vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: None } }] + vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: Some([24.0, 24.0, 240.0, 320.0]) } }] ); assert_eq!( actions(json!({"command": "window.panel.float", "panel": "history", "column": true})), - vec![Action::MoveColumn { panel: s("history"), to: Target::Float { rect: None } }] + vec![Action::MoveColumn { panel: s("history"), to: Target::Float { rect: Some([24.0, 24.0, 240.0, 320.0]) } }] ); // dock: to an anchor, to a side, back into the dock, and a hidden panel to its last place. @@ -281,7 +286,7 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { let mut locked = workspace(); locked.locked = true; let before = locked.clone(); - assert!(parse(json!({"command": "window.panel.window", "panel": "layers"})).unwrap().apply(&mut locked, false, permissions).is_err()); + assert!(parse(json!({"command": "window.panel.window", "panel": "layers"})).unwrap().apply(&mut locked, false, &space(), permissions).is_err()); assert_eq!(locked, before); } @@ -289,7 +294,7 @@ fn dock_commands_parse_every_documented_shape_and_map_to_atomic_actions() { fn side_zones_map_to_the_placement_the_anchor_container_takes_in_either_direction() { let command = |zone: &str, anchor: &str| parse(json!({"command": "window.panel.move", "panel": "history", "anchor": anchor, "zone": zone})).unwrap(); - let placed = |zone: &str, anchor: &str, rtl: bool| match command(zone, anchor).to_actions(&workspace(), rtl) { + let placed = |zone: &str, anchor: &str, rtl: bool| match command(zone, anchor).to_actions(&workspace(), rtl, &space()) { Ok(actions) => match actions.as_slice() { [Action::Move { placement, .. }] => Ok(placement.clone()), other => panic!("{other:?}"), @@ -332,7 +337,7 @@ fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { let d = testing::DockDriver::new(workspace().layout, Sized).with_area(area); let space = float_space::

(&d.ctx, d.id).expect("the area records its float space"); assert_eq!(space.area, area); - let float = |params: Value| parse(params).unwrap().to_actions_in(&workspace(), false, &space).unwrap(); + let float = |params: Value| parse(params).unwrap().to_actions(&workspace(), false, &space).unwrap(); let panel = float(json!({"command": "window.panel.float", "panel": "layers"})); assert_eq!(panel, vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 150.0] }], "floating_size, inset in the area"); @@ -352,7 +357,6 @@ fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { // Without recorded sizes a unit floats at the layout's size, shrunk into a small area. let small = FloatSpace::new(egui::Rect::from_min_size(egui::pos2(0.0, 30.0), egui::vec2(200.0, 200.0))); - let applied = - parse(json!({"command": "window.panel.float", "panel": "layers", "group": true})).unwrap().to_actions_in(&workspace(), false, &small); + let applied = parse(json!({"command": "window.panel.float", "panel": "layers", "group": true})).unwrap().to_actions(&workspace(), false, &small); assert_eq!(applied, Ok(vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: Some([0.0, 30.0, 200.0, 200.0]) } }])); } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 73d4108ab0..26c92c1e53 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -221,8 +221,12 @@ impl

Default for DockOutput

{ /// Room between the dock area's top-left corner and a unit a command floats. const FLOAT_INSET: f32 = 24.0; +/// Size a command floats a panel at when its [`FloatSpace`] never drew it. +#[cfg_attr(not(feature = "serde"), allow(dead_code))] +pub(super) const DEFAULT_FLOAT: Vec2 = Vec2::new(260.0, 320.0); + /// Where a docking command floats a panel, group or column when it gives no rect (see -/// `DockCommand::to_actions_in`, feature `serde`). [`DockArea`] records one each frame; read it +/// `DockCommand::to_actions`, feature `serde`). [`DockArea`] records one each frame; read it /// with [`float_space`]. #[derive(Clone, Debug, PartialEq)] pub struct FloatSpace

{ @@ -236,7 +240,8 @@ pub struct FloatSpace

{ } impl FloatSpace

{ - /// An area with no recorded sizes: commands float units at the layout's sizes. + /// An area with no recorded sizes: commands float a panel at 260x320, and a group or + /// column at its dock column's width (else 260) by 320. pub fn new(area: Rect) -> Self { Self { area, panels: Vec::new(), groups: Vec::new(), columns: Vec::new() } } diff --git a/crates/ui/tests/docking_workflows.rs b/crates/ui/tests/docking_workflows.rs index aa7f2e3bb8..3f46b5219e 100644 --- a/crates/ui/tests/docking_workflows.rs +++ b/crates/ui/tests/docking_workflows.rs @@ -416,7 +416,8 @@ mod v1_fixtures { // Float the column by command, then drag its window back to the start edge. let float: DockCommand = serde_json::from_value(json!({"command": "window.panel.float", "panel": bars[0], "column": true})).unwrap(); - let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone()), false).unwrap(); + let space = craft_ui::docking::float_space(&d.ctx, d.id).unwrap(); + let actions = float.to_actions(&craft_ui::docking::Workspace::new(d.layout.clone()), false, &space).unwrap(); d.layout.apply_all(actions, |p| d.content.permissions(p)).unwrap_or_else(|e| panic!("{at}: {e}")); d.settle(); assert!(start_columns(&d.layout).is_empty(), "{at}: floated"); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 400e288831..3dd4603671 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -162,7 +162,7 @@ if command.is_app_owned() { return app.workspace_command(command); } let space = float_space(ctx, DOCK_ID).unwrap_or_else(|| FloatSpace::new(ctx.content_rect())); -let closed = command.apply_in(&mut app.workspace, style.right_to_left, &space, |panel| app.permissions(panel))?; +let closed = command.apply(&mut app.workspace, style.right_to_left, &space, |panel| app.permissions(panel))?; ``` | Id | Params (`?` is optional) | @@ -190,9 +190,10 @@ let closed = command.apply_in(&mut app.workspace, style.right_to_left, &space, | panel's `floating_size`, else its docked group or column size, capped like a drag. It goes inside the dock area, 24 points from its top-left corner, so it stays clear of the menu bar. The area records that geometry in a `FloatSpace` each frame; `float_space(ctx, id)` reads it - and `apply_in` and `to_actions_in` take it. `x`, `y`, `width` and `height` replace the matching - values, and a group or column that is already a whole floating window keeps its rect. - `apply` and `to_actions` have no area and float at 48, 48 in window coordinates. + and `apply` and `to_actions` take it. Before the area has drawn, `FloatSpace::new(area)` floats + a panel at 260x320 and a group or column at its column width by 320. `x`, `y`, `width` and + `height` replace the matching values, and a group or column that is already a whole floating + window keeps its rect. - Without a value, `minimized`, `iconic` and `locked` toggle. - `ui.dock` operations are those of LightCraft, PDFCraft, CADCraft and SoundCraft: `open`, `close`, `activate`, `float {rect}`, `moveFloating {rect}`, `move {target, zone?, before?}`, From c715d3f25fdfd615ae1685daa328776e9d7ad9a8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:22:34 +0000 Subject: [PATCH 36/94] docking: hosts seed a FloatSpace with panel sizes --- crates/ui/src/docking/command_tests.rs | 11 +++++++++++ crates/ui/src/docking/surface.rs | 7 +++++++ docs/ui-docking.md | 4 +++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 4f2be2f616..e109a08cf4 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -359,4 +359,15 @@ fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { let small = FloatSpace::new(egui::Rect::from_min_size(egui::pos2(0.0, 30.0), egui::vec2(200.0, 200.0))); let applied = parse(json!({"command": "window.panel.float", "panel": "layers", "group": true})).unwrap().to_actions(&workspace(), false, &small); assert_eq!(applied, Ok(vec![Action::MoveGroup { panel: s("layers"), to: Target::Float { rect: Some([0.0, 30.0, 200.0, 200.0]) } }])); + + // A host seeds the size of a panel the area never drew; a recorded size still wins. + let seeded = FloatSpace::new(area).with_panel_size(s("layers"), egui::vec2(180.0, 240.0)); + let applied = parse(json!({"command": "window.panel.float", "panel": "layers"})).unwrap().to_actions(&workspace(), false, &seeded); + assert_eq!(applied, Ok(vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 180.0, 240.0] }])); + let recorded = space.clone().with_panel_size(s("layers"), egui::vec2(180.0, 240.0)); + assert_eq!(float_with(&recorded, "layers"), vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 150.0] }]); +} + +fn float_with(space: &FloatSpace

, panel: &str) -> Vec> { + parse(json!({"command": "window.panel.float", "panel": panel})).unwrap().to_actions(&workspace(), false, space).unwrap() } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 26c92c1e53..dc8f1419aa 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -245,6 +245,13 @@ impl FloatSpace

{ pub fn new(area: Rect) -> Self { Self { area, panels: Vec::new(), groups: Vec::new(), columns: Vec::new() } } + + /// Adds the size a command floats `panel` at alone when the area has not drawn it, such as + /// a hidden panel or a headless run. A size the area recorded for the panel takes precedence. + pub fn with_panel_size(mut self, panel: P, size: Vec2) -> Self { + self.panels.push((panel, size)); + self + } } /// Lookups for `DockCommand`, which needs feature `serde`. diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 3dd4603671..9705a62033 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -191,7 +191,9 @@ let closed = command.apply(&mut app.workspace, style.right_to_left, &space, |pan inside the dock area, 24 points from its top-left corner, so it stays clear of the menu bar. The area records that geometry in a `FloatSpace` each frame; `float_space(ctx, id)` reads it and `apply` and `to_actions` take it. Before the area has drawn, `FloatSpace::new(area)` floats - a panel at 260x320 and a group or column at its column width by 320. `x`, `y`, `width` and + a panel at 260x320 and a group or column at its column width by 320. + `FloatSpace::with_panel_size(panel, size)` gives a panel the area has not drawn (a hidden + panel, a headless run) the host's own size; a size the area recorded wins. `x`, `y`, `width` and `height` replace the matching values, and a group or column that is already a whole floating window keeps its rect. - Without a value, `minimized`, `iconic` and `locked` toggle. From 5d5d11f8546990ff508eae1442e894151660d8b7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:30:02 +0000 Subject: [PATCH 37/94] docking: window.panel.dock to a side without a dock moves one panel of a shared group Action::MovePanel moves one panel to a Target; NewDock and Float give it a group of its own. DockCommand::Dock with a side that has no dock used to fail with InvalidPlacement for a panel that shares its group. --- crates/ui/src/docking/command.rs | 2 +- crates/ui/src/docking/command_tests.rs | 10 ++++++++++ crates/ui/src/docking/model.rs | 25 +++++++++++++++++++++++++ docs/ui-docking.md | 4 ++-- 4 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 3ae6d2aea6..7a146f959e 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -284,7 +284,7 @@ impl Unit { let panel = panel.clone(); Ok(match (self, to) { (Self::Panel, Target::At { anchor, placement }) => Action::Move { panel, anchor, placement }, - (Self::Panel, _) => return Err(DockError::InvalidPlacement), + (Self::Panel, to) => Action::MovePanel { panel, to }, (Self::Group, to) => Action::MoveGroup { panel, to }, (Self::Column, to) if floating => Action::MoveWindow { panel, to }, (Self::Column, to) => Action::MoveColumn { panel, to }, diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index e109a08cf4..905e145269 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -371,3 +371,13 @@ fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { fn float_with(space: &FloatSpace

, panel: &str) -> Vec> { parse(json!({"command": "window.panel.float", "panel": panel})).unwrap().to_actions(&workspace(), false, space).unwrap() } + +#[test] +fn dock_to_a_side_without_a_dock_takes_one_panel_out_of_a_shared_group() { + let params = json!({"command": "window.panel.dock", "panel": "layers", "side": "End"}); + assert_eq!(actions(params.clone()), vec![Action::MovePanel { panel: s("layers"), to: Target::NewDock { side: Side::End } }]); + let (workspace, _) = applied(params); + let side = |panel: &str| workspace.layout.location(&s(panel)).unwrap().group.and_then(|g| g.column).map(|c| c.side); + assert_eq!(side("layers"), Some(Side::End)); + assert_eq!(side("channels"), Some(Side::Start)); +} diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 75391f6e48..690137bb21 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -310,6 +310,12 @@ pub enum Action

{ panel: P, rect: Option<[f32; 4]>, }, + /// Move one panel, without the rest of its group. `Target::At` is [`Action::Move`]; + /// `NewDock` and `Float` give the panel a group of its own. + MovePanel { + panel: P, + to: Target

, + }, } /// What may happen to a panel. [`Layout::apply_with_permissions`] enforces these for every @@ -726,6 +732,18 @@ impl Layout

{ Action::Close { panel } if !permissions(panel).closable => return Err(DockError::NotAllowed), Action::MoveFloating { panel, .. } if !permissions(panel).movable => return Err(DockError::NotAllowed), Action::Open { anchor: Some(anchor), .. } if !permissions(anchor).accepts_tabs => return Err(DockError::NotAllowed), + Action::MovePanel { panel, to } => { + let policy = permissions(panel); + let allowed = policy.movable + && match to { + Target::Float { .. } => policy.floatable, + Target::At { anchor, placement } => placement_allowed(placement, permissions(anchor)), + Target::NewDock { .. } => true, + }; + if !allowed { + return Err(DockError::NotAllowed); + } + } Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } | Action::MoveWindow { panel, to } => { let members = self.members(panel, unit_of(&action))?; if members.iter().any(|p| !permissions(p).movable) { @@ -899,6 +917,13 @@ impl Layout

{ let moving = self.take_unit(panel, unit)?; self.insert_moving(moving, to.clone()) } + Action::MovePanel { panel, to } => match to { + Target::At { anchor, placement } => self.apply_inner(Action::Move { panel, anchor, placement }), + to => { + let entry = self.take(&panel).ok_or(DockError::MissingPanel)?; + self.insert_moving(Moving::group(Group::new(vec![entry.panel], 0)), to) + } + }, Action::CloseGroup { ref panel } | Action::CloseWindow { ref panel } => self.take_unit(panel, unit_of(&action)).map(|_| ()), Action::CloseOthers { panel } => { for other in self.members(&panel, Unit::Group)? { diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 9705a62033..336367e7e2 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -57,8 +57,8 @@ layout.apply(Action::Move { # Ok::<(), craft_ui::docking::DockError>(()) ``` -- `Move`, `Float` and `Close` act on one panel. `MoveGroup`, `MoveColumn` and `MoveWindow` move a - group, a dock column or a floating window, named by any panel in it. +- `Move`, `MovePanel`, `Float` and `Close` act on one panel. `MoveGroup`, `MoveColumn` and + `MoveWindow` move a group, a dock column or a floating window, named by any panel in it. - A `Target` is `At { anchor, placement }`, `Float { rect }` or `NewDock { side }`. - A `Placement` is a tab position, a split zone, a new group above or below (with an optional preferred `height`), a new column, or a new frame on an outer edge. From b64cc4eac6d787564fbd959a7fc543e5df5f779e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:30:02 +0000 Subject: [PATCH 38/94] docking: window.panel.minimize toggles an accordion entry both ways Without minimized the command read only dock and floating groups, so a closed accordion entry stayed closed. --- crates/ui/src/docking/command.rs | 9 ++++++++- crates/ui/src/docking/command_tests.rs | 11 +++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 7a146f959e..11a0a8df50 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -426,7 +426,14 @@ impl DockCommand

{ Self::CloseOthers { panel } => one(Action::CloseOthers { panel: panel.clone() }), Self::Minimize { panel, minimized } => { let place = layout.place(panel).ok_or(DockError::MissingPanel)?; - let current = layout.group(&place).is_some_and(|g| g.minimized); + // An accordion entry is minimized while it is closed. + let current = match &place { + Place::Node(path) => match layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, path)) { + Some(super::Node::Stack { entries }) => entries.iter().any(|e| &e.panel == panel && !e.open), + _ => false, + }, + place => layout.group(place).is_some_and(|g| g.minimized), + }; one(Action::SetMinimized { panel: panel.clone(), minimized: minimized.unwrap_or(!current) }) } Self::Iconic { panel, iconic } => { diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 905e145269..307d8a86a3 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -381,3 +381,14 @@ fn dock_to_a_side_without_a_dock_takes_one_panel_out_of_a_shared_group() { assert_eq!(side("layers"), Some(Side::End)); assert_eq!(side("channels"), Some(Side::Start)); } + +#[test] +fn minimize_without_a_value_toggles_an_accordion_entry_both_ways() { + let entry = |panel: &str| StackEntry { panel: s(panel), open: true, height: None }; + let mut workspace = Workspace::new(Layout { root: Some(Node::Stack { entries: vec![entry("layers"), entry("history")] }), floating: Vec::new() }); + let toggle = parse(json!({"command": "window.panel.minimize", "panel": "layers"})).unwrap(); + toggle.apply(&mut workspace, false, &space(), permissions).unwrap(); + assert_eq!(workspace.layout.panel_state(&s("layers")), PanelState::Open); + toggle.apply(&mut workspace, false, &space(), permissions).unwrap(); + assert_eq!(workspace.layout.panel_state(&s("layers")), PanelState::Front); +} From 4325b9ccc1ce67670a702254b2f1eeeb3c746c95 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:30:02 +0000 Subject: [PATCH 39/94] docking: move_targets skips the panel's own group Moving a panel to a tab of its own group only reorders it, so a panel whose only other tabs are in its group gets no "Move Panel to Group" menu. --- crates/ui/src/docking/model.rs | 11 ++++++++--- crates/ui/src/docking/tests.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 690137bb21..f4a0471aeb 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -525,10 +525,15 @@ impl Layout

{ self.panels().contains(&panel) } - /// The panels `panel` can join as a tab: every other panel whose permissions accept tabs. - /// A "Move Panel to Group" menu with an empty answer has nothing to offer and stays hidden. + /// The panels `panel` can join as a tab: every panel in another group whose permissions + /// accept tabs. A "Move Panel to Group" menu with an empty answer has nothing to offer and + /// stays hidden. pub fn move_targets(&self, panel: &P, permissions: impl Fn(&P) -> Permissions) -> Vec<&P> { - self.panels().into_iter().filter(|target| *target != panel && permissions(target).accepts_tabs).collect() + let own = self.place(panel); + self.panels() + .into_iter() + .filter(|target| *target != panel && permissions(target).accepts_tabs && (own.is_none() || self.place(target) != own)) + .collect() } /// Capture a panel's nearest surviving group/split neighbor before hiding it. diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index ac07024934..76124f5c00 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -67,6 +67,15 @@ fn move_targets_skip_the_panel_itself_and_protected_anchors() { assert!(single.move_targets(&1, all).is_empty()); } +#[test] +fn move_targets_skip_the_panels_own_group() { + let layout = sample(); + let all = |_: &u32| Permissions::default(); + assert_eq!(layout.move_targets(&3, all), vec![&1, &5, &6]); + let pair = Layout { root: Some(tabs(&[1, 2], 0)), floating: Vec::new() }; + assert!(pair.move_targets(&1, all).is_empty()); +} + #[test] fn invalid_moves_are_atomic_including_after_a_source_would_have_been_removed() { let layout = sample(); From 9359332fd7e61076f33c10a1ae97a0cfcf3a0177 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:30:02 +0000 Subject: [PATCH 40/94] panes: the API example gives the document focus on to_document --- docs/ui-panes.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/ui-panes.md b/docs/ui-panes.md index fd3d9a9119..43d6f5b5c4 100644 --- a/docs/ui-panes.md +++ b/docs/ui-panes.md @@ -42,7 +42,13 @@ for request in out.requests { PaneRequest::Focus(_) => {} } } -egui::CentralPanel::default().show(ui, |ui| document(ui)); +egui::CentralPanel::default().show(ui, |ui| { + let response = document(ui); + if out.to_document { + // F6 or Shift+F6 left the panes: the document takes keyboard focus. + response.request_focus(); + } +}); ``` | Piece | Behaviour | From bfda13d2afd92947f2fe0f671385d350b4d5932a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:32:15 +0000 Subject: [PATCH 41/94] docking: a tab dragged to an edge without a dock makes one A tab that shares its group moves alone into the new dock with Action::MovePanel, as window.panel.dock does (P6). --- crates/ui/src/docking/dock_tests.rs | 10 ++++++++++ crates/ui/src/docking/render/dock.rs | 8 +++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index b49c60a58d..9a17ed7e57 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -281,6 +281,16 @@ fn group_dropped_on_the_window_edge_without_a_dock_makes_a_new_dock() { } } +#[test] +fn tab_dragged_to_the_window_edge_without_a_dock_makes_a_dock_of_that_panel() { + let mut d = testing::DockDriver::new(docked(Side::Start, &[&[&[2, 3]]]), TestContent::default()); + let tab = d.hit(&Hit::Tab(3)).unwrap_or_else(|| panic!("{:?}", d.hits())); + let out = d.drag(tab.center(), pos2(795.0, 300.0)); + assert!(out.actions.contains(&Action::MovePanel { panel: 3, to: Target::NewDock { side: Side::End } }), "{:?}", out.actions); + assert_eq!(columns(&d.layout, Side::End), vec![vec![vec![3]]]); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2]]]); +} + #[test] fn a_column_takes_groups_anywhere_in_it_and_as_tabs() { let windows = [(5, [400.0, 40.0, 150.0, 120.0]), (6, [400.0, 220.0, 150.0, 120.0]), (7, [400.0, 400.0, 150.0, 120.0])]; diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 86c57be58d..c2822cb67a 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -461,8 +461,9 @@ impl Renderer<'_, P> { self.checked(action).map(|action| (action, drop.line)) } - /// The dock target a single tab drag would take: a new group or column of that panel. A new - /// dock only takes a panel that is alone in its group. + /// The dock target a single tab drag would take: a new group, column or dock of that panel. + /// A panel alone in its group takes the group's state to a new dock; one that shares its + /// group leaves the other tabs behind (P6). pub(super) fn dock_tab_proposal(&self, ctx: &Context, panel: &P, pointer: Pos2) -> Option<(Option>, Rect)> { if self.dock_covered(ctx, pointer, None) { return None; @@ -476,7 +477,8 @@ impl Renderer<'_, P> { { Action::MoveGroup { panel: panel.clone(), to } } - Target::NewDock { .. } | Target::Float { .. } => return None, + to @ Target::NewDock { .. } => Action::MovePanel { panel: panel.clone(), to }, + Target::Float { .. } => return None, }; self.checked(action).map(|action| (action, drop.line)) } From e1b7733a1d30e868a474a96ee6f3cdd60bcde847 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 14:00:03 +0000 Subject: [PATCH 42/94] docking: tabs keep their names and the rest go to the overflow menu --- crates/ui/README.md | 6 +++ crates/ui/src/docking/render/group.rs | 9 +++- crates/ui/src/docking/surface.rs | 4 +- crates/ui/src/docking/tests.rs | 76 ++++++++++++++++++++------- crates/ui/src/docking/trial_tests.rs | 65 ++++++++++++----------- crates/ui/src/tabs/mod.rs | 47 ++++++++++++++++- crates/ui/src/tabs/tests.rs | 42 +++++++++++++++ docs/ui-docking.md | 9 ++++ 8 files changed, 203 insertions(+), 55 deletions(-) diff --git a/crates/ui/README.md b/crates/ui/README.md index a321c8dae7..593a628d88 100644 --- a/crates/ui/README.md +++ b/crates/ui/README.md @@ -108,6 +108,12 @@ tabs before hiding them, keeps input order and retains the selected tab. Tiny st its width to zero. Negative/non-finite dimensions become zero and large dimensions are bounded. The work is linear in tab count with at most 32 fitting passes; the caller caps its own tab count. +`tabs::fit_whole(natural_widths, selected, available, overflow_width)` keeps every shown tab at its +natural width and sends the rest to overflow. Tabs are shown in order up to the first that does not +fit; the selected tab is always shown in its logical place, taking the place of the last tabs that +fit when it lies past them. Only a selected tab wider than the strip minus the overflow button is +narrowed. Docking tab strips use this policy. + `tabs::Tab` registers a tab at a supplied rectangle and invokes the application's painter: ```rust diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 74912e9687..ebcf61f791 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -29,6 +29,9 @@ pub(super) struct TabGroup<'a, P> { /// The top band of a strip that drags the whole group. const BORDER_BAND: f32 = 4.0; +/// Width of the "…" button that lists the panels a strip has no room for. +const OVERFLOW_WIDTH: f32 = 22.0; + impl Renderer<'_, P> { pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, minimized: bool, rect: Rect, kind: GroupKind) { let Some(selected) = panels.get(active) else { return }; @@ -70,7 +73,7 @@ impl Renderer<'_, P> { child.set_clip_rect(header.intersect(ui.clip_rect())); self.content.group_header(&mut child, panels, selected, floating); } - // The drag bar keeps its reserved width: tabs shrink, then overflow, before it narrows. + // The drag bar keeps its reserved width: tabs overflow before it narrows. let bar_width = self.style.drag_bar_width.clamp(0.0, (strip.width() - header_width).max(0.0)); let tabs_width = (strip.width() - header_width - bar_width).max(0.0); let widths: Vec = panels @@ -84,7 +87,9 @@ impl Renderer<'_, P> { + TAB_PADDING }) .collect(); - let fit = tabs::fit(&widths, active, tabs_width, 40.0, 22.0); + // Tabs keep their full names; the rest go to the overflow menu. Only an active tab wider + // than the strip is cut, with its name in a tooltip. + let fit = tabs::fit_whole(&widths, active, tabs_width, OVERFLOW_WIDTH); let owner = TabGroup { panels, selected, minimized, kind, rect }; let mut x = strip.left(); let mut shown = Vec::new(); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index dc8f1419aa..c50bf0db87 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -41,8 +41,8 @@ pub struct DockStyle { pub float_group_label: String, /// Group menu item that moves the whole group into another group (submenu of targets). pub move_group_to_label: String, - /// Minimum width of the drag bar left of the group header. Tabs shrink, then overflow, - /// before the bar narrows. + /// Minimum width of the drag bar left of the group header. Tabs overflow before the bar + /// narrows. pub drag_bar_width: f32, /// Painted under every floating window, so it stays opaque when the panel colours are not. pub floating_background: Color32, diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 76124f5c00..013bb27462 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1246,7 +1246,7 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() { CustomContent { labels: vec![], headers: 0, menus: 0, bodies: 0 }, ); h.run_steps(2); - let tab = Id::new("action-label-test").with(("tab", &5_u32)); + let tab = Id::new("action-label-test").with(("tab", &6_u32)); let at = h.ctx.read_response(tab).unwrap().rect.center(); h.input_mut().events.extend([ Event::PointerMoved(at), @@ -1271,13 +1271,51 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() { } #[test] -fn tab_labels_that_do_not_fit_are_truncated_inside_their_tab_and_named_in_a_tooltip() { +fn a_narrow_strip_shows_whole_tabs_and_lists_the_others_in_the_overflow_menu() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + fn elided(shape: &egui::Shape) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.elided, + egui::Shape::Vec(shapes) => shapes.iter().any(elided), + _ => false, + } + } + let area = Id::new("whole-tabs"); + let layout = Layout { root: Some(tabs(&[1, 2, 3, 4, 5, 6], 5)), floating: vec![] }; + let mut h = Harness::builder().with_size(vec2(260.0, 240.0)).build_ui(move |ui| { + DockArea::new(area).show( + ui, + &layout, + &DockStyle::from_ui(ui), + |panel| format!("Panel {panel}"), + |_| Permissions::default(), + |_: &mut egui::Ui, _: &u32| {}, + ); + }); + h.run_steps(2); + let shown: Vec = (1..=6).filter(|p| h.ctx.read_response(area.with(("tab", p))).is_some()).collect(); + assert!((2..6).contains(&shown.len()), "{shown:?}"); + // The active last tab takes the place of the last tab that fits; the others keep their order. + let mut expected: Vec = (1..shown.len() as u32).collect(); + expected.push(6); + assert_eq!(shown, expected); + assert!(h.output().shapes.iter().all(|shape| !elided(&shape.shape)), "every shown tab keeps its full name"); + h.get_by_role_and_label(Role::Button, "Panels").click(); + h.run_steps(2); + let listed: Vec = (1..=6).filter(|p| h.query_by_role_and_label(Role::Button, &format!("Panel {p}")).is_some()).collect(); + let hidden: Vec = (1..=6).filter(|p| !shown.contains(p)).collect(); + assert_eq!(listed, hidden, "the overflow menu lists exactly the hidden panels"); +} + +#[test] +fn only_an_active_tab_wider_than_the_strip_is_truncated_and_named_in_a_tooltip() { let ctx = Context::default(); ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); let layout = Layout { root: Some(tabs(&[1, 2, 3], 0)), floating: vec![] }; let label = |p: &u32| format!("Eigenschaften und Anpassungen {p}"); let run = |events: Vec| { - let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 200.0))), events, ..Default::default() }; + let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(150.0, 200.0))), events, ..Default::default() }; let mut output = ctx.run_ui(input, |ui| { DockArea::new(Id::new("truncate")).show( ui, @@ -1295,23 +1333,23 @@ fn tab_labels_that_do_not_fit_are_truncated_inside_their_tab_and_named_in_a_tool }; run(vec![]); let shapes = run(vec![]); - let tab = |p: u32| ctx.read_response(Id::new("truncate").with(("tab", &p))).unwrap().rect; - for p in 1..=3 { - let tab = tab(p); - // The clip rect would hide an overflowing label; what is laid out must itself fit. - let painted: Vec = shapes - .iter() - .filter(|shape| matches!(&shape.shape, egui::Shape::Text(_))) - .map(|shape| shape.shape.visual_bounding_rect()) - .filter(|r| tab.contains(r.center())) - .collect(); - assert_eq!(painted.len(), 1, "tab {p}: {painted:?}"); - assert!(tab.contains_rect(painted[0]), "tab {p}: label {:?} overflows {tab:?}", painted[0]); - } - let at = tab(2).center(); - run(vec![Event::PointerMoved(at)]); + let tab = |p: u32| ctx.read_response(Id::new("truncate").with(("tab", &p))).map(|response| response.rect); + assert!(tab(2).is_none() && tab(3).is_none(), "the other tabs overflow instead of shrinking"); + let active = tab(1).unwrap(); + // The clip rect would hide an overflowing label; what is laid out must itself fit. + let painted: Vec<&egui::epaint::TextShape> = shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if active.contains(text.visual_bounding_rect().center()) => Some(text), + _ => None, + }) + .collect(); + assert_eq!(painted.len(), 1, "{painted:?}"); + assert!(painted[0].galley.elided); + assert!(active.contains_rect(painted[0].visual_bounding_rect()), "label {:?} overflows {active:?}", painted[0].visual_bounding_rect()); + run(vec![Event::PointerMoved(active.center())]); let shapes = run(vec![]); - let full = label(&2); + let full = label(&1); // An elided galley still reports its whole text, so the cut tab label alone would match. assert!( shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == full && !text.galley.elided)), diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 3036490e96..9338199bff 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -79,39 +79,44 @@ impl DockContent for GalleyLabels { } #[test] -fn shrunk_tabs_end_their_labels_with_an_ellipsis_inside_the_tab_active_or_not() { +fn galley_labels_stay_whole_and_only_an_over_wide_active_tab_ends_with_an_ellipsis_inside_it() { let panels = [1, 2, 3, 4, 5, 6]; let layout = Layout { root: Some(tabs(&panels, 3)), floating: Vec::new() }; - let ctx = Context::default(); - let mut content = GalleyLabels; - let mut shapes = Vec::new(); - for _ in 0..2 { - let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }; - let mut full = ctx.run_ui(input, |ui| { - let style = DockStyle::from_ui(ui); - ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 400.0))), |ui| { - DockArea::new(Id::new(AREA)).show_content(ui, &layout, &style, &mut content); + for width in [320.0, 90.0] { + let ctx = Context::default(); + let mut content = GalleyLabels; + let mut shapes = Vec::new(); + for _ in 0..2 { + let input = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }; + let mut full = ctx.run_ui(input, |ui| { + let style = DockStyle::from_ui(ui); + ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 400.0))), |ui| { + DockArea::new(Id::new(AREA)).show_content(ui, &layout, &style, &mut content); + }); }); - }); - full.textures_delta.clear(); - shapes = full.shapes; - } - let texts: Vec<_> = flat(&shapes) - .into_iter() - .filter_map(|(clip, shape)| match shape { - egui::Shape::Text(text) => Some((clip, text)), - _ => None, - }) - .collect(); - for panel in panels { - let tab = ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect; - let Some((clip, text)) = texts.iter().find(|(_, t)| t.galley.text().ends_with(&format!(" {panel}")) && tab.contains(t.pos)) else { - panic!("no label in tab {panel}") - }; - assert_eq!(last_char(&text.galley), Some('…'), "tab {panel}"); - let drawn = Rect::from_min_size(text.pos, text.galley.size()); - assert!(drawn.right() <= tab.right() + 0.5 && drawn.left() >= tab.left(), "tab {panel}: {drawn:?} in {tab:?}"); - assert!(tab.contains_rect(clip.intersect(drawn)), "tab {panel}"); + full.textures_delta.clear(); + shapes = full.shapes; + } + let texts: Vec<_> = flat(&shapes) + .into_iter() + .filter_map(|(clip, shape)| match shape { + egui::Shape::Text(text) => Some((clip, text)), + _ => None, + }) + .collect(); + let shown: Vec = panels.into_iter().filter(|p| ctx.read_response(Id::new(AREA).with(("tab", p))).is_some()).collect(); + assert!(shown.contains(&4) && shown.len() < panels.len(), "{width}: {shown:?}"); + for panel in shown { + let tab = ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().rect; + let Some((clip, text)) = texts.iter().find(|(_, t)| t.galley.text().ends_with(&format!(" {panel}")) && tab.contains(t.pos)) else { + panic!("no label in tab {panel}") + }; + let cut = width < 100.0; + assert_eq!(last_char(&text.galley), if cut { Some('…') } else { char::from_digit(panel, 10) }, "{width}: tab {panel}"); + let drawn = Rect::from_min_size(text.pos, text.galley.size()); + assert!(drawn.right() <= tab.right() + 0.5 && drawn.left() >= tab.left(), "tab {panel}: {drawn:?} in {tab:?}"); + assert!(tab.contains_rect(clip.intersect(drawn)), "tab {panel}"); + } } } diff --git a/crates/ui/src/tabs/mod.rs b/crates/ui/src/tabs/mod.rs index e82dcca1ac..e8b20378e4 100644 --- a/crates/ui/src/tabs/mod.rs +++ b/crates/ui/src/tabs/mod.rs @@ -1,8 +1,9 @@ //! Tab fitting and accessible tab interactions without owning a dock or document model. //! //! The caller owns identity, localization, selection, painting, overflow menus and drag actions. -//! [`fit`] only assigns widths; [`Tab`] returns the complete egui response, including double-click -//! and drag phases, so a panel strip can collapse, reorder or tear off according to its app. +//! [`fit`] (tabs shrink before they overflow) and [`fit_whole`] (tabs keep their full width) only +//! assign widths; [`Tab`] returns the complete egui response, including double-click and drag +//! phases, so a panel strip can collapse, reorder or tear off according to its app. use egui::{Id, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2}; @@ -70,6 +71,48 @@ pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, TabFit { shown, overflow, overflow_width } } +/// Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. +/// +/// Tabs are shown in input order up to the first one that does not fit beside the selected tab +/// and an overflow button of `overflow_width`. The selected tab (or the final tab if `selected` +/// is out of bounds) is always shown, in its logical place: when it lies past that run, it takes +/// the place of the last tabs that fit. Only a selected tab wider than the strip minus the button +/// gets less than its natural width; its painter elides the label. A lone tab never reserves a +/// button. +/// +/// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never +/// exceed the sanitized available width. Work and storage are linear in the input count. +pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit { + let available = extent(available); + let natural: Vec = natural.iter().map(|&w| extent(w)).collect(); + if natural.iter().map(|&w| f64::from(w)).sum::() <= f64::from(available) { + return TabFit { shown: natural.into_iter().enumerate().collect(), ..Default::default() }; + } + if let [width] = natural[..] { + return TabFit { shown: vec![(0, width.min(available))], ..Default::default() }; + } + let overflow_width = extent(overflow_width).min(available); + let budget = available - overflow_width; + let selected = selected.min(natural.len().saturating_sub(1)); + let active = natural.get(selected).copied().unwrap_or(0.0).min(budget); + let mut room = f64::from(budget - active); + let mut shown = Vec::new(); + let mut overflow = Vec::new(); + let mut full = false; + for (i, &width) in natural.iter().enumerate() { + if i == selected { + shown.push((i, active)); + } else if !full && f64::from(width) <= room { + room -= f64::from(width); + shown.push((i, width)); + } else { + full = true; + overflow.push(i); + } + } + TabFit { shown, overflow, overflow_width } +} + fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec<(usize, f32)> { let width = |i: usize| natural.get(i).copied().unwrap_or(0.0); let sum_at = |cap: f32| indices.iter().map(|&i| f64::from(width(i).min(cap.max(width(i).min(minimum))))).sum::(); diff --git a/crates/ui/src/tabs/tests.rs b/crates/ui/src/tabs/tests.rs index 6fb37e3149..13dcb70225 100644 --- a/crates/ui/src/tabs/tests.rs +++ b/crates/ui/src/tabs/tests.rs @@ -72,6 +72,48 @@ fn many_tabs_keep_the_last_selected_without_quadratic_membership_scans() { assert!(total(&f) <= 240.001); } +#[test] +fn whole_tabs_keep_their_width_and_the_selected_tab_replaces_the_last_that_fits() { + let natural = [60.0, 70.0, 80.0, 50.0, 90.0, 40.0]; + // 200 points: 22 for the button leaves 178. + let f = fit_whole(&natural, 0, 200.0, 22.0); + assert_eq!(f.shown, [(0, 60.0), (1, 70.0)]); + assert_eq!(f.overflow, [2, 3, 4, 5]); + assert_eq!(f.overflow_width, 22.0); + // The last tab, selected, takes the place of tab 1 and keeps its order. + let f = fit_whole(&natural, 5, 200.0, 22.0); + assert_eq!(f.shown, [(0, 60.0), (1, 70.0), (5, 40.0)]); + assert_eq!(f.overflow, [2, 3, 4]); + let f = fit_whole(&natural, 4, 200.0, 22.0); + assert_eq!(f.shown, [(0, 60.0), (4, 90.0)]); + assert_eq!(f.overflow, [1, 2, 3, 5]); + // Everything fits: no button. + let f = fit_whole(&natural, 4, 390.0, 22.0); + assert_eq!(f.shown.len(), 6); + assert!(f.overflow.is_empty() && f.overflow_width == 0.0); +} + +#[test] +fn only_a_selected_tab_wider_than_the_strip_is_narrowed() { + let f = fit_whole(&[60.0, 300.0, 70.0], 1, 200.0, 22.0); + assert_eq!(f.shown, [(1, 178.0)]); + assert_eq!(f.overflow, [0, 2]); + for selected in [0, 1, 2, usize::MAX] { + for available in [0.0, 1.0, 21.0, 22.0, 100.0, 200.0, 500.0] { + let natural = [60.0, 300.0, 70.0]; + let f = fit_whole(&natural, selected, available, 22.0); + let selected = selected.min(2); + assert!(f.shown.iter().all(|&(i, w)| i == selected || w == natural[i]), "{selected} at {available}: {f:?}"); + assert!(f.shown.iter().any(|&(i, _)| i == selected)); + assert_eq!(f.shown.len() + f.overflow.len(), 3); + assert!(total(&f) <= available + 0.001, "{available}: {f:?}"); + } + } + assert_eq!(fit_whole(&[80.0], 0, 10.0, 22.0).shown, [(0, 10.0)]); + let f = fit_whole(&[f32::NAN, f32::INFINITY, -5.0, 30.0], usize::MAX, f32::NAN, f32::MAX); + assert!(f.shown.iter().all(|&(_, w)| w.is_finite() && w >= 0.0) && total(&f) == 0.0); +} + struct TabTest { ctx: Context, labels: [String; 2], diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 336367e7e2..8a01aa5f36 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -137,6 +137,15 @@ panel body. `begin_drag` hands a drag that started in the app's own chrome to th `docking::chrome` has the floating frame, the title bar and `drop_preview` (the drop preview docking and `craft_ui::panes` both draw) for apps that draw their own windows. +## Tab strips + +Every shown tab carries its panel's full name. Tabs that do not fit go to the "…" button at the +end of the strip, whose menu lists the hidden panels; choosing one makes it active. The active tab +is always shown, in its logical place: when it lies past the tabs that fit, it takes the place of +the last of them. Only an active tab wider than the strip alone is cut with "…", and its tooltip +names it in full. The drag bar keeps its reserved width until the tabs overflow. A tab dropped on +the "…" button goes to the end of the group. + ## Gestures - A tab drags one panel. A group's drag bar (the space beside its tabs) or its top border drags From a014337eb2e7f1b440bf34017d46aaf1d41b4bcd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 14:02:59 +0000 Subject: [PATCH 43/94] docking: a floated group takes its content height --- crates/ui/src/docking/command_tests.rs | 5 ++- crates/ui/src/docking/group_tests.rs | 54 +++++++++++++++++++++++-- crates/ui/src/docking/iconic_tests.rs | 6 ++- crates/ui/src/docking/render/iconic.rs | 8 +++- crates/ui/src/docking/render/mod.rs | 1 + crates/ui/src/docking/render/preview.rs | 52 +++++++++++++++++++----- crates/ui/src/docking/surface.rs | 34 ++++++++++++++-- crates/ui/src/docking/trial_tests.rs | 4 +- docs/ui-docking.md | 22 +++++++++- 9 files changed, 158 insertions(+), 28 deletions(-) diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 307d8a86a3..78d46dd49d 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -340,7 +340,8 @@ fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { let float = |params: Value| parse(params).unwrap().to_actions(&workspace(), false, &space).unwrap(); let panel = float(json!({"command": "window.panel.float", "panel": "layers"})); - assert_eq!(panel, vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 150.0] }], "floating_size, inset in the area"); + // The floating_size width, and an empty body's least fitted height under its 150 points. + assert_eq!(panel, vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 120.0] }], "floating_size, inset in the area"); let [Action::MoveGroup { to: Target::Float { rect: Some([x, y, width, height]) }, .. }] = float(json!({"command": "window.panel.float", "panel": "history", "group": true}))[..] else { @@ -365,7 +366,7 @@ fn float_without_a_rect_takes_the_drag_size_inside_the_dock_area() { let applied = parse(json!({"command": "window.panel.float", "panel": "layers"})).unwrap().to_actions(&workspace(), false, &seeded); assert_eq!(applied, Ok(vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 180.0, 240.0] }])); let recorded = space.clone().with_panel_size(s("layers"), egui::vec2(180.0, 240.0)); - assert_eq!(float_with(&recorded, "layers"), vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 150.0] }]); + assert_eq!(float_with(&recorded, "layers"), vec![Action::Float { panel: s("layers"), rect: [24.0, 54.0, 200.0, 120.0] }]); } fn float_with(space: &FloatSpace

, panel: &str) -> Vec> { diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 0577a628ec..71c9f1135d 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -50,11 +50,16 @@ struct TestContent { floating_size: Option, host_owned: bool, whole_group: bool, + /// Height every body takes; `None` draws a one-line label. + body_height: Option, } impl DockContent for TestContent { fn body(&mut self, ui: &mut egui::Ui, _: &u32) { - ui.label("Body"); + match self.body_height { + Some(height) => _ = ui.allocate_exact_size(vec2(10.0, height), egui::Sense::hover()), + None => _ = ui.label("Body"), + } } fn logical_label(&self, panel: &u32) -> String { format!("Panel {panel}") @@ -349,12 +354,12 @@ fn group_drag_escape_focus_loss_pointer_exit_and_cancel_drag_leave_the_layout_un } #[test] -fn floated_panel_uses_floating_size_not_the_column_height() { +fn floated_panel_fits_its_content_up_to_floating_size_not_the_column_height() { for size in [Some(vec2(200.0, 150.0)), None] { let mut layout = docked(); let Some(Node::Split { first, .. }) = &mut layout.root else { panic!() }; **first = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![2, 3], 1)], 240.0)] }; - let content = TestContent { protected: vec![0], floating_size: size, ..Default::default() }; + let content = TestContent { protected: vec![0], floating_size: size, body_height: Some(200.0), ..Default::default() }; let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); let out = d.drag(d.tab(3).center(), pos2(700.0, 100.0)); let Some([_, _, width, height]) = out.actions.iter().find_map(|a| match a { @@ -363,9 +368,10 @@ fn floated_panel_uses_floating_size_not_the_column_height() { }) else { panic!("{:?}", out.actions) }; + let fitted = crate::docking::chrome::TITLE_HEIGHT + d.rect("drag-bar", 2).height() + 200.0; match size { Some(size) => assert_eq!((width, height), (size.x, size.y)), - None => assert!(height <= 320.0, "{height}"), + None => assert_eq!(height, fitted), } } } @@ -542,3 +548,43 @@ fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() { assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![5], 0)]); assert_eq!(d.layout.floating[1].groups, vec![Group::new(vec![6, 7], 1)]); } + +#[test] +fn a_short_docked_panel_floats_at_its_content_height_up_to_its_floating_size() { + let title = crate::docking::chrome::TITLE_HEIGHT; + let float = |body: f32, floating_size: Option| { + let content = TestContent { body_height: Some(body), floating_size, ..Default::default() }; + let mut d = Driver::with(docked(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let strip = d.rect("drag-bar", 4).height(); + let recorded = crate::docking::float_space::(&d.ctx, Id::new(AREA)).unwrap().panel(&4).unwrap(); + let target = pos2(400.0, 300.0); + d.hold(d.tab(4).center(), target); + d.modifiers = Modifiers::COMMAND; + let out = d.step(vec![button(target, false)]); + let Some([_, _, width, height]) = out.actions.iter().find_map(|a| match a { + Action::Float { panel: 4, rect } => Some(*rect), + _ => None, + }) else { + panic!("{:?}", out.actions) + }; + assert_eq!(recorded, vec2(width, height), "a command floats at the size a drag does"); + (strip, vec2(width, height)) + }; + let (strip, size) = float(150.0, None); + assert_eq!(size.y, title + strip + 150.0); + assert_eq!(float(0.0, None).1.y, 120.0, "an empty panel floats at the least fitted height"); + assert_eq!(float(600.0, None).1.y, 320.0, "a tall docked panel keeps the docked cap"); + // The host's floating size gives the width and the most height. + assert_eq!(float(150.0, Some(vec2(300.0, 360.0))).1, vec2(300.0, title + strip + 150.0)); + assert_eq!(float(150.0, Some(vec2(300.0, 160.0))).1, vec2(300.0, 160.0)); + + // A group takes its active panel's content height. + let content = TestContent { body_height: Some(150.0), ..Default::default() }; + let mut d = Driver::with(docked(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let target = pos2(400.0, 300.0); + d.hold(d.rect("drag-bar", 2).center(), target); + d.modifiers = Modifiers::COMMAND; + let out = d.step(vec![button(target, false)]); + let Some(Target::Float { rect: Some([_, _, _, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) }; + assert_eq!(*height, title + strip + 150.0); +} diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index b9ad4a88bf..a90cc2981c 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -193,9 +193,13 @@ fn dragging_a_flyout_strip_floats_its_group() { let mut d = DockDriver::new(docked(&[&[1, 2], &[3]], true), Content); d.click(hit(&d, Hit::Icon(1)).center()); d.settle(); + // A one-line body: the flyout and the floated group take the least fitted height. + let flyout = d.ctx.memory(|m| m.area_rect(d.id.with("flyout"))).unwrap(); + assert_eq!(flyout.height(), 120.0); let bar = hit(&d, Hit::DragBar(1)); let out = d.drag(bar.center(), CANVAS); - assert!(matches!(out.actions.as_slice(), [Action::MoveGroup { panel: 1, to: Target::Float { .. } }]), "{:?}", out.actions); + let [Action::MoveGroup { panel: 1, to: Target::Float { rect: Some(rect) } }] = out.actions.as_slice() else { panic!("{:?}", out.actions) }; + assert_eq!(rect[3], 120.0); assert_eq!(groups(&d.layout), vec![vec![3]]); assert_eq!(d.layout.floating.len(), 1); assert_eq!(d.layout.floating.first().map(|w| w.panels().copied().collect::>()), Some(vec![1, 2])); diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 4b7b3a045d..1be3872f8c 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -299,13 +299,17 @@ impl Renderer<'_, P> { let screen = ctx.content_rect(); let bounds = self.workspace.intersect(screen); let width = request.width.max(self.style.min_pane).min(bounds.width()); - let height = self + let max = self .content .floating_size(&active) .map(|size| size.y) .or(request.group.height) .filter(|h| h.is_finite() && *h > 0.0) - .unwrap_or(FLYOUT_HEIGHT) + .unwrap_or(FLYOUT_HEIGHT); + // A flyout fits the content its panel last drew, up to that height. + let height = self + .fitted_height(&active, self.style.tab_height, max) + .unwrap_or(max) .max(self.style.tab_height + self.style.min_pane) .min(bounds.height()); let left = match request.edge { diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index d5cdd4b9db..d099edeb26 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -218,6 +218,7 @@ impl Renderer<'_, P> { ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); child.set_clip_rect(rect.intersect(ui.clip_rect())); self.content.body(&mut child, panel); + self.float_space.record_content(panel.clone(), child.min_rect().height()); // Any button: a canvas pans with the middle button and opens menus with the secondary. if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.any_pressed()) { self.output.focused = Some(panel.clone()); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 5d66298048..13f36e5ab6 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -5,7 +5,9 @@ use egui::{Context, Key, Pos2, Rect, Ui, Vec2, pos2, vec2}; use super::{Renderer, clamp_float, dock::group_action}; use crate::docking::chrome::drop_preview; use crate::docking::{ - Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Placement, Target, Zone, cancel_drag, dock_model::Place, resolve_drop, + Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Node, Placement, Target, Zone, cancel_drag, + dock_model::{Place, node_at}, + resolve_drop, surface::TAB_PADDING, }; @@ -17,6 +19,9 @@ fn float_only(ctx: &Context) -> bool { /// Height of a panel floated out of a dock column when the host gives no floating size. const DOCKED_FLOAT_HEIGHT: f32 = 320.0; +/// Least height of a floating window or flyout fitted to a short panel's content. +pub(super) const MIN_FITTED_HEIGHT: f32 = 120.0; + impl Renderer<'_, P> { pub(in crate::docking) fn finish_group_drag(&mut self, ui: &Ui) { let ctx = ui.ctx(); @@ -274,21 +279,30 @@ impl Renderer<'_, P> { } /// Size of a panel floated by a drag or the Float menu: the host's floating size, else the - /// source size within the panel limits. A panel leaving a dock column does not take the - /// column's height. + /// source size within the panel limits. Out of a dock column, or with a floating size, the + /// height fits the content the panel last drew, up to that height (320 in a dock). pub(super) fn float_size(&self, panel: &P, source: Vec2) -> Vec2 { + let chrome = self.style.title_height + self.style.tab_height; if let Some(size) = self.content.floating_size(panel).filter(|s| s.is_finite() && s.x > 0.0 && s.y > 0.0) { - return size; + return vec2(size.x, self.fitted_height(panel, chrome, size.y).unwrap_or(size.y)); } let mut size = self.iconic.float_width(panel).map_or(source, |width| vec2(width, DOCKED_FLOAT_HEIGHT)); if matches!(self.layout.place(panel), Some(Place::Dock { .. })) { - size.y = size.y.min(DOCKED_FLOAT_HEIGHT); + size.y = self.fitted_height(panel, chrome, DOCKED_FLOAT_HEIGHT).unwrap_or(size.y.min(DOCKED_FLOAT_HEIGHT)); } let limits = self.limits(panel); let header = vec2(0.0, self.style.tab_height); size.max(limits.min + header).min(limits.max + header) } + /// Height of a window around `panel`'s group: `chrome` (title bar and tab strip) and the + /// content height the panel last drew, at least [`MIN_FITTED_HEIGHT`] and at most `max`. + /// `None` for a panel the area has not drawn. + pub(super) fn fitted_height(&self, panel: &P, chrome: f32, max: f32) -> Option { + let content = self.float_space.content(panel)?; + Some((chrome + content).max(MIN_FITTED_HEIGHT).min(max)) + } + /// Record what a drag floats from `panels`, one group drawn at `group` whose panels drag /// from `panel` rects, for commands that float without a rect. pub(super) fn record_float(&mut self, panels: &[P], panel: Vec2, group: Vec2) { @@ -307,17 +321,33 @@ impl Renderer<'_, P> { } /// Size of a group or column floated by a drag or Float Tab Group: the source width, and the - /// tallest member's floating size, else the source height capped like a panel leaving a - /// dock column. A group that already floats keeps its size. + /// tallest member's floating height, else the source height capped like a panel leaving a + /// dock column. A group fits that height to its active panel's content. A group that already + /// floats keeps its size. pub(super) fn group_float_size(&self, members: &[P], source: Vec2) -> Vec2 { - let place = members.first().and_then(|panel| self.layout.place(panel)); - if matches!(place, Some(Place::Floating { .. }) | None) { + let Some(place) = members.first().and_then(|panel| self.layout.place(panel)) else { return source }; + if matches!(place, Place::Floating { .. }) { return source; } let valid = |s: &Vec2| s.is_finite() && s.x > 0.0 && s.y > 0.0; let host = members.iter().filter_map(|panel| self.content.floating_size(panel).filter(valid)).map(|s| s.y).reduce(f32::max); - let docked = matches!(place, Some(Place::Dock { .. })); - vec2(source.x, host.unwrap_or(if docked { source.y.min(DOCKED_FLOAT_HEIGHT) } else { source.y })) + let docked = matches!(place, Place::Dock { .. }); + let chrome = self.style.title_height + self.style.tab_height; + let max = host.or(docked.then_some(DOCKED_FLOAT_HEIGHT)); + let fitted = max.and_then(|max| self.group_active(members, &place).and_then(|active| self.fitted_height(active, chrome, max))); + vec2(source.x, fitted.or(host).unwrap_or(if docked { source.y.min(DOCKED_FLOAT_HEIGHT) } else { source.y })) + } + + /// The active panel of the group at `place` when `members` are that whole group. + fn group_active<'a>(&'a self, members: &[P], place: &Place) -> Option<&'a P> { + let (panels, active) = match place { + Place::Node(path) => match self.layout.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Tabs { panels, active }) => (panels, *active), + _ => return None, + }, + _ => self.layout.group(place).map(|group| (&group.panels, group.active))?, + }; + (panels.len() == members.len() && members.iter().all(|m| panels.contains(m))).then(|| panels.get(active)).flatten() } /// Where a group or column drag floats with the pointer at `pointer`, keeping the grab diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index c50bf0db87..f53707f097 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -237,13 +237,16 @@ pub struct FloatSpace

{ pub(super) panels: Vec<(P, Vec2)>, pub(super) groups: Vec<(P, Vec2)>, pub(super) columns: Vec<(P, Vec2)>, + /// The height each panel's content used when it was last drawn, which fits a floated group + /// to its content. + pub(super) contents: Vec<(P, f32)>, } impl FloatSpace

{ /// An area with no recorded sizes: commands float a panel at 260x320, and a group or /// column at its dock column's width (else 260) by 320. pub fn new(area: Rect) -> Self { - Self { area, panels: Vec::new(), groups: Vec::new(), columns: Vec::new() } + Self { area, panels: Vec::new(), groups: Vec::new(), columns: Vec::new(), contents: Vec::new() } } /// Adds the size a command floats `panel` at alone when the area has not drawn it, such as @@ -254,6 +257,16 @@ impl FloatSpace

{ } } +impl FloatSpace

{ + pub(super) fn record_content(&mut self, panel: P, height: f32) { + let height = if height.is_finite() { height.max(0.0) } else { 0.0 }; + match self.contents.iter_mut().find(|(p, _)| *p == panel) { + Some((_, recorded)) => *recorded = height, + None => self.contents.push((panel, height)), + } + } +} + /// Lookups for `DockCommand`, which needs feature `serde`. #[cfg_attr(not(feature = "serde"), allow(dead_code))] impl FloatSpace

{ @@ -269,6 +282,10 @@ impl FloatSpace

{ Self::find(&self.columns, panel) } + pub(super) fn content(&self, panel: &P) -> Option { + self.contents.iter().find(|(p, _)| p == panel).map(|(_, height)| *height) + } + /// The first record wins: an iconic panel is recorded at its icon before its flyout. fn find(sizes: &[(P, Vec2)], panel: &P) -> Option { sizes.iter().find(|(p, _)| p == panel).map(|(_, size)| *size) @@ -445,8 +462,11 @@ pub trait DockContent

{ fn limits(&self, _panel: &P) -> PanelLimits { PanelLimits::default() } - /// Preferred floating size, independent of the current dock geometry. `None` falls back - /// to the panel limits. + /// Preferred floating size, independent of the current dock geometry: the width of a + /// floated panel and the most height it takes. A floated panel or group, and a flyout, fit + /// their height to the content the active panel last drew (at least 120 points), up to this + /// height, or up to 320 out of a dock when this is `None`. A rect a command gives and a + /// window the user resized keep their size. fn floating_size(&self, _panel: &P) -> Option { None } @@ -759,7 +779,13 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { output: DockOutput::default(), frame, iconic: super::render::Iconic::new(self.auto_collapse), - float_space: FloatSpace::new(rect), + float_space: FloatSpace { + // A panel keeps the content height it last drew while hidden or minimized. + contents: float_space::

(ui.ctx(), self.id) + .map(|space| space.contents.into_iter().filter(|(panel, _)| layout.contains(panel)).collect()) + .unwrap_or_default(), + ..FloatSpace::new(rect) + }, }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 9338199bff..584f28e994 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -50,14 +50,14 @@ fn a_full_height_docked_group_floats_at_the_host_or_capped_height_inside_the_win let mut layout = docked(); let Some(Node::Split { first, .. }) = &mut layout.root else { panic!() }; **first = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![2, 3], 1)], 240.0)] }; - let content = TestContent { protected: vec![0], floating_size: size, ..Default::default() }; + let content = TestContent { protected: vec![0], floating_size: size, body_height: Some(600.0), ..Default::default() }; let mut d = Driver::with(layout, content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); let bar = d.rect("drag-bar", 2); let out = d.drag(bar.center(), pos2(420.0, 300.0)); let Some(Target::Float { rect: Some([x, y, width, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) }; match size { Some(size) => assert_eq!(*height, size.y), - None => assert!(*height <= 320.0, "{height}"), + None => assert_eq!(*height, 320.0), } assert!(*width > 100.0 && *width <= 240.0, "{width}"); let window = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 8a01aa5f36..c764303304 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -146,6 +146,24 @@ the last of them. Only an active tab wider than the strip alone is cut with "… names it in full. The drag bar keeps its reserved width until the tabs overflow. A tab dropped on the "…" button goes to the end of the group. +## Floating size + +A panel or group floated by a drag, a menu or a command without a rect takes its content height: +the title bar, the tab strip and the height the active panel's content used when it was last +drawn (the content ui's `min_rect`), at least 120 points. The most it takes is the height of +`DockContent::floating_size`, or 320 points for a panel or group leaving a dock. A short panel +therefore floats as a short window. A panel's width is its `floating_size` width, else its docked +width; a group keeps its docked width. +A flyout fits its content the same way, without the title bar. + +- A panel the area has not drawn floats at the `floating_size` height, else the docked height + capped at 320, or at a `FloatSpace::with_panel_size` size for commands. +- A group from a frame without a `floating_size` keeps its frame size. A dock column of several + groups floats at the tallest `floating_size` height, else its column height capped at 320. +- A rect from a command and a window the user resized keep their size; floating windows are not + refitted while open. +- Docked layout does not change: a column's last group still fills the column. + ## Gestures - A tab drags one panel. A group's drag bar (the space beside its tabs) or its top border drags @@ -195,8 +213,8 @@ let closed = command.apply(&mut app.workspace, style.right_to_left, &space, |pan `to_actions` take the layout's `right_to_left` for that. - `group` moves the panel's whole group; `column` moves its dock column, or its whole window when it floats. `side` is `Start` or `End`. -- `window.panel.float` without a rect floats what it moves at the size a drag floats it at: the - panel's `floating_size`, else its docked group or column size, capped like a drag. It goes +- `window.panel.float` without a rect floats what it moves at the size a drag floats it at (see + Floating size). It goes inside the dock area, 24 points from its top-left corner, so it stays clear of the menu bar. The area records that geometry in a `FloatSpace` each frame; `float_space(ctx, id)` reads it and `apply` and `to_actions` take it. Before the area has drawn, `FloatSpace::new(area)` floats From 13be52fbaa2c4936c8d7b3d2b5abe6ab72892123 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 14:05:26 +0000 Subject: [PATCH 44/94] docking: focus only follows the user's input --- crates/ui/src/docking/group_tests.rs | 37 ++++++++++++++++++++ crates/ui/src/docking/render/floating.rs | 2 -- crates/ui/src/docking/render/native.rs | 1 - crates/ui/src/docking/surface.rs | 43 +++++++++++++++++++++--- crates/ui/src/docking/tests.rs | 3 +- docs/ui-docking.md | 11 +++--- 6 files changed, 85 insertions(+), 12 deletions(-) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 71c9f1135d..85ff550633 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -588,3 +588,40 @@ fn a_short_docked_panel_floats_at_its_content_height_up_to_its_floating_size() { let Some(Target::Float { rect: Some([_, _, _, height]) }) = moved_group(&out.actions) else { panic!("{:?}", out.actions) }; assert_eq!(*height, title + strip + 150.0); } + +#[test] +fn tab_focus_follows_only_the_users_input() { + let mut d = Driver::new(docked()); + let tab = Id::new(AREA).with(("tab", &4u32)); + // Keyboard focus as Tab gives it. + d.ctx.memory_mut(|m| m.request_focus(tab)); + d.step(vec![]); + assert!(d.ctx.memory(|m| m.has_focus(tab))); + + // A reset that moves the panel takes its focus away and reports no new focus. + let mut reset = docked(); + let Some(Node::Split { first, .. }) = &mut reset.root else { panic!() }; + let Node::Dock { columns, .. } = first.as_mut() else { panic!() }; + columns[0].groups.reverse(); + d.layout = reset; + let out = d.step(vec![]); + assert_eq!(out.focused, None); + d.step(vec![]); + assert_eq!(d.ctx.memory(|m| m.focused()), None, "the moved tab gives up keyboard focus"); + + // A user drag keeps the dragged tab's focus where the user put it. + let mut d = Driver::new(docked()); + d.ctx.memory_mut(|m| m.request_focus(tab)); + d.drag(d.tab(4).center(), d.tab(2).center()); + d.step(vec![]); + assert!(d.layout.place(&4) != docked().place(&4)); + assert!(d.ctx.memory(|m| m.has_focus(tab)), "a tab moved by the user keeps focus"); + + // A closed panel's tab gives focus up too. + let out = d.step(vec![]); + assert!(out.actions.is_empty()); + d.layout.apply(Action::Close { panel: 4 }).unwrap(); + d.step(vec![]); + d.step(vec![]); + assert_eq!(d.ctx.memory(|m| m.focused()), None); +} diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 1ac0b65f42..bfcabce0db 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -66,8 +66,6 @@ impl Renderer<'_, P> { let id = self.id.with(("floating", first)); if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { ctx.move_to_top(FloatingFrame::layer(id)); - ctx.memory_mut(|memory| memory.request_focus(self.id.with(("tab", self.activation.as_ref().unwrap_or(first))))); - self.output.focused = self.activation.clone(); } let movable = window.panels().all(|panel| self.permissions(panel).movable); let style = ChromeStyle::from_dock(self.style); diff --git a/crates/ui/src/docking/render/native.rs b/crates/ui/src/docking/render/native.rs index 05fe819667..94627bd1a0 100644 --- a/crates/ui/src/docking/render/native.rs +++ b/crates/ui/src/docking/render/native.rs @@ -79,7 +79,6 @@ impl Renderer<'_, P> { .with_min_inner_size(MIN_SIZE); if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { ctx.send_viewport_cmd_to(viewport, ViewportCommand::Focus); - self.output.focused = self.activation.clone(); } let (targets, stacks) = (self.targets.len(), self.frame.stacks.len()); let (closed, placed) = ctx.show_viewport_immediate(viewport, builder, |ui, class| { diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index f53707f097..fb09250335 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -201,8 +201,9 @@ impl DockStyle { pub struct DockOutput

{ pub actions: Vec>, pub error: Option, - /// The panel the user focused this frame: a clicked tab or menu entry, a drop, a raised - /// window, or a press of any pointer button in a panel body, stripless panels included. + /// The panel the user focused this frame: a clicked tab or menu entry, a drop, or a press + /// of any pointer button in a panel body, stripless panels included. Only user input sets + /// it; [`DockArea::raise_panel`] and host commands do not. pub focused: Option

, /// Whole-floating-group gesture identity; host may display its own group drop preview. pub group_drag: Option

, @@ -309,6 +310,37 @@ fn float_space_key(area: Id) -> Id { area.with("float-space") } +/// The panel whose tab held keyboard focus at the end of the last frame, where it was, and +/// whether that frame's own actions may have moved it. +type TabFocus

= (P, super::dock_model::Place, bool); + +fn tab_focus_key(area: Id) -> Id { + area.with("tab-focus") +} + +/// Keyboard focus stays on a tab only while its panel stays where the user put it: a panel +/// hidden, closed or moved by the host (a command or a workspace reset) gives focus up. +fn release_moved_tab_focus(ctx: &Context, area: Id, layout: &Layout

) { + let Some((panel, place, moved_by_area)) = ctx.data(|d| d.get_temp::>(tab_focus_key(area))) else { return }; + let tab = area.with(("tab", &panel)); + let place_now = layout.place(&panel); + if ctx.memory(|m| m.has_focus(tab)) && (place_now.is_none() || (place_now != Some(place) && !moved_by_area)) { + ctx.memory_mut(|m| m.surrender_focus(tab)); + } +} + +fn record_tab_focus(ctx: &Context, area: Id, layout: &Layout

, acted: bool) { + let focused = ctx.memory(|m| m.focused()); + let tab = focused.and_then(|id| layout.panels().into_iter().find(|panel| area.with(("tab", *panel)) == id)); + let record = tab.and_then(|panel| Some((panel.clone(), layout.place(panel)?, acted))); + ctx.data_mut(|d| match record { + Some(record) => { + d.insert_temp(tab_focus_key(area), record); + } + None => d.remove::>(tab_focus_key(area)), + }); +} + /// A request for host state outside the layout. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -692,8 +724,9 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { false } - /// Raise and focus a panel's owning floating area on this frame. Apply Activate through - /// the application's command path as well to select its tab. + /// Raise a panel's floating window (or open its flyout) on this frame. Apply Activate + /// through the application's command path as well to select its tab. A raise is not user + /// input: it moves no keyboard focus and is not reported as [`DockOutput::focused`]. pub fn raise_panel(mut self, panel: P) -> Self { self.activation = Some(panel); self @@ -764,6 +797,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { cancel_drag::

(ui.ctx(), self.id); return DockOutput { error: Some(DockError::InvalidGeometry), ..Default::default() }; } + release_moved_tab_focus(ui.ctx(), self.id, layout); let (view, frame) = super::render::view(layout, self.maximized.as_ref(), self.hide, &*content); let mut renderer = Renderer { id: self.id, @@ -797,6 +831,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { renderer.finish_drag(ui.ctx()); renderer.report_flyout(ui.ctx()); super::hits::record(ui.ctx(), self.id, &view, &renderer.owned_interactions); + record_tab_focus(ui.ctx(), self.id, layout, !renderer.output.actions.is_empty()); ui.ctx().data_mut(|d| d.insert_temp(float_space_key(self.id), renderer.float_space)); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); renderer.output diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 013bb27462..f934f9d1fc 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -912,7 +912,8 @@ fn custom_chrome_shaped_labels_and_programmatic_raise_are_available() { custom_frame(&ctx, &layout, &mut content, vec![], &[], false); } let out = custom_frame(&ctx, &layout, &mut content, vec![], &[], true); - assert_eq!(out.focused, Some(5)); + assert_eq!(out.focused, None, "a programmatic raise is not user focus"); + assert_eq!(ctx.memory(|m| m.focused()), None, "a raise draws no keyboard-focus ring"); assert!(out.actions.is_empty()); assert!(content.headers >= 3 && content.bodies >= 3); assert!(content.labels.iter().any(|s| s == "Logical 5")); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index c764303304..bcd62c86e0 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -110,8 +110,10 @@ survives. `DockOutput` also has: -- `focused`: the panel the user focused this frame: a clicked tab, a drop, a raised window, or a - press of any pointer button in a panel body, bare and protected panels included. +- `focused`: the panel the user focused this frame: a clicked tab, a drop, or a press of any + pointer button in a panel body, bare and protected panels included. Commands, `raise_panel` and + workspace resets never set it; a host that tracks the last focused panel clears it when a reset + or command hides, closes or moves that panel. - `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (Frame) and `DockEvent::ToggleAutoCollapse` (Dock), and `DockEvent::FlyoutChanged { panel }` (Dock): the flyout opened, switched or closed (`None`). It comes once per change, whatever made it: an @@ -125,7 +127,7 @@ Builder options on `DockArea`: | `maximized(panel)` | Maximize Frame: that frame fills the area. | | `hide_panels(HidePanels)` | Hide panels for Tab and Shift+Tab. Protected panels stay. | | `auto_collapse_iconic(on)` | Close a flyout on Escape or a click outside (default on). | -| `raise_panel(panel)` | Raise and focus a panel's floating window this frame. | +| `raise_panel(panel)` | Raise a panel's floating window, or open its flyout, this frame. It moves no keyboard focus and does not set `DockOutput::focused`. | | `blocked_rects(rects)` | App overlays that docking gestures must ignore. | `DockStyle::close_menu_items` and `DockStyle::close_button` hide the built-in Close menu items @@ -133,7 +135,8 @@ and the floating window ×. They hide controls only: a panel that stays `closabl by the app's own Close items and commands. `DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome rather than on a -panel body. `begin_drag` hands a drag that started in the app's own chrome to the area. +panel body. Focus follows only the user's input: a tab keeps keyboard focus until a command or a +workspace reset hides, closes or moves its panel, and then gives it up. `begin_drag` hands a drag that started in the app's own chrome to the area. `docking::chrome` has the floating frame, the title bar and `drop_preview` (the drop preview docking and `craft_ui::panes` both draw) for apps that draw their own windows. From 787b70627461a3c988157ed776e8f6051cbc94c3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 15:37:00 +0000 Subject: [PATCH 45/94] docs: say when a tab is cut and that the drag bar keeps its width --- docs/ui-docking.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/ui-docking.md b/docs/ui-docking.md index bcd62c86e0..a9862d813e 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -145,9 +145,10 @@ docking and `craft_ui::panes` both draw) for apps that draw their own windows. Every shown tab carries its panel's full name. Tabs that do not fit go to the "…" button at the end of the strip, whose menu lists the hidden panels; choosing one makes it active. The active tab is always shown, in its logical place: when it lies past the tabs that fit, it takes the place of -the last of them. Only an active tab wider than the strip alone is cut with "…", and its tooltip -names it in full. The drag bar keeps its reserved width until the tabs overflow. A tab dropped on -the "…" button goes to the end of the group. +the last of them. Only an active tab wider than the room beside the "…" button, or a lone tab +wider than the strip, is cut with "…", and its tooltip names it in full. The drag bar always keeps +its reserved width: tabs go to the overflow menu before it narrows, and only a strip narrower than +the bar itself shrinks it. A tab dropped on the "…" button goes to the end of the group. ## Floating size From d3079230dadf36b5e77fd9c3b08fcad193ad637a Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:54:23 +0000 Subject: [PATCH 46/94] docking: group_header_width gets the tab strip width A header that draws its own tabs, such as a timeline's open sequences, sizes them to the room the strip has. --- crates/ui/src/docking/group_tests.rs | 6 +++++- crates/ui/src/docking/render/group.rs | 2 +- crates/ui/src/docking/surface.rs | 10 +++++++--- crates/ui/src/docking/tests.rs | 2 +- docs/ui-docking.md | 5 +++-- 5 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 85ff550633..81b0c32fff 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -47,6 +47,8 @@ struct TestContent { protected: Vec, header: f32, header_clicks: usize, + /// The strip width the last header was sized for. + strip_width: std::cell::Cell, floating_size: Option, host_owned: bool, whole_group: bool, @@ -74,7 +76,8 @@ impl DockContent for TestContent { self.whole_group |= request.whole_group; self.host_owned.then(DropFeedback::default) } - fn group_header_width(&self, _: &[u32], _: &u32, _: bool) -> f32 { + fn group_header_width(&self, _: &[u32], _: &u32, _: bool, strip_width: f32) -> f32 { + self.strip_width.set(strip_width); self.header } fn group_header(&mut self, ui: &mut egui::Ui, _: &[u32], _: &u32, _: bool) { @@ -253,6 +256,7 @@ fn drag_bar_survives_a_strip_full_of_tabs() { let bar = d.rect("drag-bar", 1); assert!(bar.width() >= 40.0, "{bar:?}"); assert_eq!(bar.right(), 300.0 - 24.0, "the bar ends at the header"); + assert_eq!(d.content.strip_width.get(), 300.0, "the header is sized for the whole strip"); assert!(d.ctx.read_response(Id::new(AREA).with(("overflow", &1u32))).is_some(), "tabs overflow before the bar narrows"); let out = d.drag(bar.center(), pos2(500.0, 300.0)); assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index ebcf61f791..b87dfca249 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -65,7 +65,7 @@ impl Renderer<'_, P> { r } }; - let requested = self.content.group_header_width(panels, selected, floating); + let requested = self.content.group_header_width(panels, selected, floating, strip.width()); let header_width = if requested.is_finite() { requested.clamp(0.0, strip.width()) } else { 0.0 }; if header_width > 0.0 { let header = mirror(Rect::from_min_max(pos2(strip.right() - header_width, strip.top()), strip.max)); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index fb09250335..411fb03aa6 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -535,9 +535,13 @@ pub trait DockContent

{ logical.into() } fn panel_menu(&mut self, _ui: &mut Ui, _panel: &P) {} - fn group_header_width(&self, _panels: &[P], _active: &P, _floating: bool) -> f32 { + /// Width of the group header at the strip's end (the host's ≡ and its own tabs). + /// `strip_width` is the whole tab strip; the header gets at most that, and the drag bar and + /// the group's tabs share what is left. + fn group_header_width(&self, _panels: &[P], _active: &P, _floating: bool, _strip_width: f32) -> f32 { 0.0 } + /// Draw the group header into `ui.max_rect()`, sized by [`Self::group_header_width`]. fn group_header(&mut self, _ui: &mut Ui, _panels: &[P], _active: &P, _floating: bool) {} } @@ -614,8 +618,8 @@ impl + ?Sized> DockContent

for Overrides<'_, P, C> { fn panel_menu(&mut self, ui: &mut Ui, panel: &P) { self.inner.panel_menu(ui, panel); } - fn group_header_width(&self, panels: &[P], active: &P, floating: bool) -> f32 { - self.inner.group_header_width(panels, active, floating) + fn group_header_width(&self, panels: &[P], active: &P, floating: bool, strip_width: f32) -> f32 { + self.inner.group_header_width(panels, active, floating, strip_width) } fn group_header(&mut self, ui: &mut Ui, panels: &[P], active: &P, floating: bool) { self.inner.group_header(ui, panels, active, floating); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index f934f9d1fc..4668b1ebc0 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -871,7 +871,7 @@ impl DockContent for CustomContent { self.menus += 1; ui.button("App menu").clicked(); } - fn group_header_width(&self, _: &[u32], _: &u32, _: bool) -> f32 { + fn group_header_width(&self, _: &[u32], _: &u32, _: bool, _: f32) -> f32 { 40.0 } fn group_header(&mut self, ui: &mut egui::Ui, _: &[u32], _: &u32, _: bool) { diff --git a/docs/ui-docking.md b/docs/ui-docking.md index a9862d813e..7ca9779dd5 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -103,8 +103,9 @@ returns a `DockOutput`. It does not change the layout. The app applies `output.a its own command path, so pointer, keyboard and control commands share one path. `DockContent

` is the app's adapter. It draws each panel body and gives its label, icon, -permissions, size limits, preferred floating size, panel menu and group header. `bare` hides the -tab strip of a lone panel. An icon is an image (`icon`), or drawn in code by `paint_icon`, which +permissions, size limits, preferred floating size, panel menu and group header. The group header +sits at the end of the tab strip; `group_header_width` gets the strip width, so a header that +draws its own tabs can size them to the room left. `bare` hides the tab strip of a lone panel. An icon is an image (`icon`), or drawn in code by `paint_icon`, which gets a painter, the icon rect and the tint color and returns true when it painted. Panel bodies keep a stable egui id when they move, so widget memory survives. From b94df6c8b6e979672bf96157ca68096c718d0ab3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:55:43 +0000 Subject: [PATCH 47/94] docking: wheel selects tabs and middle click closes a tab Both are on in the Frame profile and off by default in the Dock profile; DockStyle::wheel_selects_tabs and middle_click_closes_tabs set them. A middle click closes only a closable panel. --- crates/ui/src/docking/group_tests.rs | 37 +++++++++++++++++++++ crates/ui/src/docking/render/group.rs | 46 +++++++++++++++++++++++++++ crates/ui/src/docking/surface.rs | 16 ++++++++++ docs/ui-docking.md | 3 ++ 4 files changed, 102 insertions(+) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 81b0c32fff..cad73cfcf1 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -629,3 +629,40 @@ fn tab_focus_follows_only_the_users_input() { d.step(vec![]); assert_eq!(d.ctx.memory(|m| m.focused()), None); } + +#[test] +fn frame_tabs_follow_the_wheel_and_close_on_a_middle_click() { + let second = |d: &Driver| match &d.layout.root { + Some(Node::Split { second, .. }) => (**second).clone(), + _ => panic!("{:?}", d.layout.root), + }; + let wheel = |unit, y| Event::MouseWheel { unit, delta: vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE }; + let middle = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Middle, pressed, modifiers: Modifiers::NONE }; + + // Off by default in the Dock profile. + let mut d = Driver::new(frames()); + let over = d.tab(2).center(); + d.step(vec![Event::PointerMoved(over), wheel(egui::MouseWheelUnit::Line, 1.0)]); + d.step(vec![middle(over, true)]); + d.step(vec![middle(over, false)]); + assert_eq!(second(&d), tabs(&[2, 3], 1)); + + let mut d = Driver::new(frames()); + d.tweak = |style| style.profile = Profile::Frame; + d.step(vec![]); + let over = d.tab(2).center(); + d.step(vec![Event::PointerMoved(over), wheel(egui::MouseWheelUnit::Line, 1.0)]); + assert_eq!(second(&d), tabs(&[2, 3], 0), "wheel up selects the previous tab"); + d.step(vec![wheel(egui::MouseWheelUnit::Line, 1.0)]); + assert_eq!(second(&d), tabs(&[2, 3], 0), "and stops at the first"); + d.step(vec![wheel(egui::MouseWheelUnit::Point, -30.0)]); + assert_eq!(second(&d), tabs(&[2, 3], 0), "trackpad scrolling adds up to a notch"); + let out = d.step(vec![wheel(egui::MouseWheelUnit::Point, -30.0)]); + assert_eq!(second(&d), tabs(&[2, 3], 1)); + assert_eq!(out.focused, Some(3)); + + d.step(vec![middle(over, true)]); + let out = d.step(vec![middle(over, false)]); + assert_eq!(out.actions, vec![Action::Close { panel: 2 }]); + assert_eq!(second(&d), tabs(&[3], 0)); +} diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index b87dfca249..cb44cd8ac8 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -32,6 +32,9 @@ const BORDER_BAND: f32 = 4.0; /// Width of the "…" button that lists the panels a strip has no room for. const OVERFLOW_WIDTH: f32 = 22.0; +/// Points of smooth (trackpad) scrolling that make one wheel notch. +const WHEEL_NOTCH: f32 = 40.0; + impl Renderer<'_, P> { pub(super) fn group(&mut self, ui: &mut Ui, panels: &[P], active: usize, minimized: bool, rect: Rect, kind: GroupKind) { let Some(selected) = panels.get(active) else { return }; @@ -127,6 +130,10 @@ impl Renderer<'_, P> { // Registered last, so the band wins over the tabs below it. let border = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, (strip.top() + BORDER_BAND).min(strip.bottom())))); self.group_handle(ui, "drag-border", border, &owner, movable); + if self.style.wheel_selects_tabs() { + let tabs_area = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, strip.bottom()))); + self.wheel_tabs(ui, tabs_area, panels, active); + } // Logical order, hidden tabs included without a hit area, for no-op detection. let tabs = panels.iter().map(|panel| (panel.clone(), shown.iter().find(|(p, _)| p == panel).map_or(Rect::NOTHING, |(_, rect)| *rect))).collect(); @@ -200,6 +207,42 @@ impl Renderer<'_, P> { egui::Popup::menu(&response).open_memory(command).show(|ui| self.group_menu(ui, owner, owner.selected)); } + /// The wheel over a group's strip: down selects the next tab, up the previous, one tab per + /// notch, stopping at the ends. Trackpad scrolling adds up to a notch. + fn wheel_tabs(&mut self, ui: &Ui, strip: Rect, panels: &[P], active: usize) { + let key = self.id.with(("tab-wheel", panels.first())); + if !ui.rect_contains_pointer(strip) { + ui.ctx().data_mut(|d| d.remove::(key)); + return; + } + let notches: f32 = ui.input(|i| { + i.events + .iter() + .map(|event| match event { + egui::Event::MouseWheel { unit, delta, modifiers, .. } if !modifiers.command && !modifiers.ctrl => match unit { + egui::MouseWheelUnit::Point => delta.y / WHEEL_NOTCH, + egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, + }, + _ => 0.0, + }) + .sum() + }); + if notches == 0.0 || !notches.is_finite() { + return; + } + let total = ui.ctx().data(|d| d.get_temp::(key)).unwrap_or(0.0) + notches; + let steps = total.trunc(); + ui.ctx().data_mut(|d| d.insert_temp(key, total - steps)); + // A wheel turned down scrolls content up: a negative delta selects the next tab. + let to = (active as i64 - steps as i64).clamp(0, panels.len().saturating_sub(1) as i64) as usize; + if to != active + && let Some(panel) = panels.get(to) + { + self.output.actions.push(Action::Activate { panel: panel.clone() }); + self.output.focused = Some(panel.clone()); + } + } + fn start_group_drag(&mut self, ui: &Ui, panels: &[P], rect: Rect) { let Some(first) = panels.first() else { return }; let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(rect.center()); @@ -361,6 +404,9 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized }); } } + if self.style.middle_click_closes_tabs() && policy.closable && response.clicked_by(egui::PointerButton::Middle) { + self.output.actions.push(Action::Close { panel: panel.clone() }); + } if policy.movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), group) { self.latch_undock(ui.ctx(), owner.map(|owner| owner.kind)); } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 411fb03aa6..99a8e4b9b5 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -99,6 +99,12 @@ pub struct DockStyle { pub close_menu_items: bool, /// Show × on the title bar of a floating window whose panels are all closable. pub close_button: bool, + /// The mouse wheel over a tab strip selects the next or previous tab, one per notch. + /// `None`: on in [`Profile::Frame`], off in [`Profile::Dock`]. + pub wheel_selects_tabs: Option, + /// A middle click on a tab closes its panel when the panel is closable. `None`: on in + /// [`Profile::Frame`], off in [`Profile::Dock`]. + pub middle_click_closes_tabs: Option, } /// Which arrangement a [`DockStyle`] renders and labels. @@ -167,9 +173,19 @@ impl DockStyle { new_window_label: "Move Panel to New Window".into(), close_menu_items: true, close_button: true, + wheel_selects_tabs: None, + middle_click_closes_tabs: None, } } + pub(super) fn wheel_selects_tabs(&self) -> bool { + self.wheel_selects_tabs.unwrap_or(self.profile == Profile::Frame) + } + + pub(super) fn middle_click_closes_tabs(&self) -> bool { + self.middle_click_closes_tabs.unwrap_or(self.profile == Profile::Frame) + } + pub(super) fn valid(&self) -> bool { [ self.tab_height, diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 7ca9779dd5..d159c88755 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -176,6 +176,9 @@ A flyout fits its content the same way, without the title bar. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. - Double-click a tab or drag bar to minimize a group to its strip. +- In the Frame profile, the mouse wheel over a tab strip selects the next or previous tab, and a + middle click on a closable panel's tab closes it. `DockStyle::wheel_selects_tabs` and + `middle_click_closes_tabs` turn either on or off in any profile. - A column's »/« button collapses it to icons, one icon per panel with a separator between groups. Widen an iconic column to show panel names. Click an icon to open its group as a flyout on the canvas side. Drag an icon to move its panel, or the grip above an icon group to move the group. From 30cebdc0f2d57941669cda8490394b4e4e5211fe Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:57:14 +0000 Subject: [PATCH 48/94] docking: content that fills its body floats at floating_size or 320 A panel body that reaches the bottom of its rect has no height of its own, so a floated panel or group falls back to floating_size, else 320 points, instead of the whole frame height. A body in a window fitted to its recorded height keeps that height. Panels leaving a frame fit their content like panels leaving a dock. --- crates/ui/src/docking/group_tests.rs | 27 +++++++++++++++++++++++ crates/ui/src/docking/render/mod.rs | 2 +- crates/ui/src/docking/render/preview.rs | 13 +++++++---- crates/ui/src/docking/surface.rs | 29 ++++++++++++++++++------- docs/ui-docking.md | 8 ++++--- 5 files changed, 63 insertions(+), 16 deletions(-) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index cad73cfcf1..62d6013f23 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -54,10 +54,16 @@ struct TestContent { whole_group: bool, /// Height every body takes; `None` draws a one-line label. body_height: Option, + /// Every body takes its whole rect. + fill: bool, } impl DockContent for TestContent { fn body(&mut self, ui: &mut egui::Ui, _: &u32) { + if self.fill { + ui.allocate_rect(ui.max_rect(), egui::Sense::hover()); + return; + } match self.body_height { Some(height) => _ = ui.allocate_exact_size(vec2(10.0, height), egui::Sense::hover()), None => _ = ui.label("Body"), @@ -593,6 +599,27 @@ fn a_short_docked_panel_floats_at_its_content_height_up_to_its_floating_size() { assert_eq!(*height, title + strip + 150.0); } +#[test] +fn a_panel_that_fills_its_frame_floats_at_its_floating_size_or_320() { + let float = |floating_size: Option| { + let content = TestContent { fill: true, floating_size, ..Default::default() }; + let mut d = Driver::with(frames(), content, Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 600.0))); + let target = pos2(400.0, 300.0); + d.hold(d.tab(3).center(), target); + d.modifiers = Modifiers::COMMAND; + let out = d.step(vec![button(target, false)]); + out.actions + .iter() + .find_map(|a| match a { + Action::Float { panel: 3, rect } => Some(rect[3]), + _ => None, + }) + .unwrap_or_else(|| panic!("{:?}", out.actions)) + }; + assert_eq!(float(None), 320.0); + assert_eq!(float(Some(vec2(300.0, 400.0))), 400.0); +} + #[test] fn tab_focus_follows_only_the_users_input() { let mut d = Driver::new(docked()); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index d099edeb26..167f68d908 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -218,7 +218,7 @@ impl Renderer<'_, P> { ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); child.set_clip_rect(rect.intersect(ui.clip_rect())); self.content.body(&mut child, panel); - self.float_space.record_content(panel.clone(), child.min_rect().height()); + self.float_space.record_content(panel.clone(), child.min_rect().height(), rect.height()); // Any button: a canvas pans with the middle button and opens menus with the secondary. if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.any_pressed()) { self.output.focused = Some(panel.clone()); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 13f36e5ab6..861e9afd75 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -279,16 +279,21 @@ impl Renderer<'_, P> { } /// Size of a panel floated by a drag or the Float menu: the host's floating size, else the - /// source size within the panel limits. Out of a dock column, or with a floating size, the - /// height fits the content the panel last drew, up to that height (320 in a dock). + /// source size within the panel limits. Out of a dock or frame, or with a floating size, the + /// height fits the content the panel last drew, up to that height (else 320). Content that + /// filled its body floats at that height. pub(super) fn float_size(&self, panel: &P, source: Vec2) -> Vec2 { let chrome = self.style.title_height + self.style.tab_height; if let Some(size) = self.content.floating_size(panel).filter(|s| s.is_finite() && s.x > 0.0 && s.y > 0.0) { return vec2(size.x, self.fitted_height(panel, chrome, size.y).unwrap_or(size.y)); } let mut size = self.iconic.float_width(panel).map_or(source, |width| vec2(width, DOCKED_FLOAT_HEIGHT)); - if matches!(self.layout.place(panel), Some(Place::Dock { .. })) { - size.y = self.fitted_height(panel, chrome, DOCKED_FLOAT_HEIGHT).unwrap_or(size.y.min(DOCKED_FLOAT_HEIGHT)); + if matches!(self.layout.place(panel), Some(Place::Dock { .. } | Place::Node(_))) { + size.y = match self.fitted_height(panel, chrome, DOCKED_FLOAT_HEIGHT) { + Some(height) => height, + None if self.float_space.filled(panel) => DOCKED_FLOAT_HEIGHT, + None => size.y.min(DOCKED_FLOAT_HEIGHT), + }; } let limits = self.limits(panel); let header = vec2(0.0, self.style.tab_height); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 99a8e4b9b5..9c1dc6b3fb 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -255,8 +255,8 @@ pub struct FloatSpace

{ pub(super) groups: Vec<(P, Vec2)>, pub(super) columns: Vec<(P, Vec2)>, /// The height each panel's content used when it was last drawn, which fits a floated group - /// to its content. - pub(super) contents: Vec<(P, f32)>, + /// to its content; `None` for content that filled its body. + pub(super) contents: Vec<(P, Option)>, } impl FloatSpace

{ @@ -275,9 +275,16 @@ impl FloatSpace

{ } impl FloatSpace

{ - pub(super) fn record_content(&mut self, panel: P, height: f32) { - let height = if height.is_finite() { height.max(0.0) } else { 0.0 }; - match self.contents.iter_mut().find(|(p, _)| *p == panel) { + /// Record the height `panel`'s content used in a body `available` tall. Content that + /// reaches the body's bottom filled it and has no height of its own, unless the body was + /// sized to the height recorded before (a fitted window). + pub(super) fn record_content(&mut self, panel: P, used: f32, available: f32) { + const TOLERANCE: f32 = 1.0; + let used = if used.is_finite() { used.max(0.0) } else { 0.0 }; + let recorded = self.contents.iter_mut().find(|(p, _)| *p == panel); + let fitted = recorded.as_ref().and_then(|(_, height)| *height).is_some_and(|height| height >= available - TOLERANCE); + let height = (used < available - TOLERANCE || fitted).then_some(used); + match recorded { Some((_, recorded)) => *recorded = height, None => self.contents.push((panel, height)), } @@ -299,8 +306,13 @@ impl FloatSpace

{ Self::find(&self.columns, panel) } + /// Whether `panel`'s content filled its body when it was last drawn. + pub(super) fn filled(&self, panel: &P) -> bool { + self.contents.iter().any(|(p, height)| p == panel && height.is_none()) + } + pub(super) fn content(&self, panel: &P) -> Option { - self.contents.iter().find(|(p, _)| p == panel).map(|(_, height)| *height) + self.contents.iter().find(|(p, _)| p == panel).and_then(|(_, height)| *height) } /// The first record wins: an iconic panel is recorded at its icon before its flyout. @@ -513,8 +525,9 @@ pub trait DockContent

{ /// Preferred floating size, independent of the current dock geometry: the width of a /// floated panel and the most height it takes. A floated panel or group, and a flyout, fit /// their height to the content the active panel last drew (at least 120 points), up to this - /// height, or up to 320 out of a dock when this is `None`. A rect a command gives and a - /// window the user resized keep their size. + /// height, or up to 320 out of a dock when this is `None`. Content that filled its body + /// takes this height, else 320. A rect a command gives and a window the user resized keep + /// their size. fn floating_size(&self, _panel: &P) -> Option { None } diff --git a/docs/ui-docking.md b/docs/ui-docking.md index d159c88755..86d9212140 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -156,9 +156,11 @@ the bar itself shrinks it. A tab dropped on the "…" button goes to the end of A panel or group floated by a drag, a menu or a command without a rect takes its content height: the title bar, the tab strip and the height the active panel's content used when it was last drawn (the content ui's `min_rect`), at least 120 points. The most it takes is the height of -`DockContent::floating_size`, or 320 points for a panel or group leaving a dock. A short panel -therefore floats as a short window. A panel's width is its `floating_size` width, else its docked -width; a group keeps its docked width. +`DockContent::floating_size`, or 320 points for a panel leaving a dock or frame and a group +leaving a dock. A short panel therefore floats as a short window. Content that reaches the bottom +of its body (a panel that allocates its whole rect) has no height of its own: it floats at the +`floating_size` height, else at 320 points. A panel's width is its `floating_size` width, else +its docked width; a group keeps its docked width. A flyout fits its content the same way, without the title bar. - A panel the area has not drawn floats at the `floating_size` height, else the docked height From 89849272a060e13fd53857ef59891aa6b8fc13ec Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:58:10 +0000 Subject: [PATCH 49/94] docking: public widget ids and floating window layers DockArea::hit_id gives the egui id of the control a Hit names, and DockArea::floating_layer the layer of a floating window, so apps and their tests stop rebuilding internal ids. The divider between stacked groups has one id in docks and floating windows. --- crates/ui/src/docking/floating_tests.rs | 2 +- crates/ui/src/docking/hits.rs | 89 +++++++++++++++++------- crates/ui/src/docking/render/floating.rs | 2 +- crates/ui/src/docking/surface.rs | 2 +- crates/ui/src/docking/tests.rs | 5 +- docs/ui-docking.md | 5 ++ 6 files changed, 77 insertions(+), 28 deletions(-) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 008994c8fa..5e3c1ba79b 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -286,7 +286,7 @@ fn floating_stack_seams_and_bands_insert_groups() { // The divider between two open groups resizes both. let mut d = Driver::new(workspace(), Profile::Dock); - let divider = d.response(Id::new(AREA).with(("floating-divider", Some(&5u32)))).unwrap().center(); + let divider = d.response(DockArea::hit_id(Id::new(AREA), &Hit::Divider(Divider::Group(5u32)))).unwrap().center(); d.drag(divider, divider + vec2(0.0, 40.0)); let heights: Vec<_> = window_of(&d.layout, 5).unwrap().groups.iter().map(|g| g.height.unwrap()).collect(); assert!((heights[0] - 181.5).abs() < 2.0 && (heights[1] - 101.5).abs() < 2.0, "{heights:?}"); diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index 26c25d9197..e772896737 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -2,9 +2,9 @@ use std::{collections::HashMap, fmt::Debug, hash::Hash}; -use egui::{Context, Id, Rect}; +use egui::{Context, Id, LayerId, Order, Rect}; -use super::{DockArea, Layout, Node, render::RESIZE_HANDLES}; +use super::{DockArea, Floating, Layout, Node, render::RESIZE_HANDLES}; /// A rendered docking control that starts a gesture. Groups, columns and windows are named by /// their first panel. @@ -76,40 +76,81 @@ impl DockArea<'_, P> { pub fn hit_rects(ctx: &Context, id: Id) -> Vec<(Hit

, Rect)> { ctx.data(|d| d.get_temp::, Rect)>>(key(id))).unwrap_or_default() } + + /// The egui widget id of the control `hit` names in the area `id`, for tests and + /// automation that focus a control or read its response. + pub fn hit_id(id: Id, hit: &Hit

) -> Id { + match hit { + Hit::Tab(p) => id.with(("tab", p)), + Hit::Icon(p) => id.with(("icon", p)), + Hit::Overflow(p) => id.with(("overflow", p)), + Hit::StackToggle(p) => id.with(("collapse", p)), + Hit::Divider(Divider::Stack(p)) => id.with(("stack-resize", p)), + Hit::DragBar(p) => id.with(("drag-bar", Some(p))), + Hit::Border(p) => id.with(("drag-border", Some(p))), + Hit::IconGrip(p) => id.with(("icon-grip", Some(p))), + Hit::ColumnBar(p) => id.with(("column-bar", Some(p))), + Hit::Collapse(p) => id.with(("column-collapse", Some(p))), + Hit::Divider(Divider::Column(p)) => id.with(("column-resize", Some(p))), + Hit::Divider(Divider::Group(p)) => id.with(("group-resize", Some(p))), + Hit::Divider(Divider::Split(path)) => id.with(("split", path)), + Hit::Title(p) => id.with(("move-group", Some(p))), + Hit::Close(p) => id.with(("move-group", Some(p))).with("close"), + Hit::Resize(p, edge) => { + let name = match edge { + ResizeEdge::BottomRight => RESIZE_HANDLES[0], + ResizeEdge::Left => RESIZE_HANDLES[1], + ResizeEdge::Right => RESIZE_HANDLES[2], + ResizeEdge::Bottom => RESIZE_HANDLES[3], + ResizeEdge::BottomLeft => RESIZE_HANDLES[4], + }; + id.with(("floating", p)).with(name) + } + } + } + + /// The egui layer of a floating window in the area `id`; `None` for an empty window. Of two + /// layers, the later in `ctx.memory(|m| m.layer_ids())` is drawn on top, and + /// `ctx.memory(|m| m.area_rect(layer.id))` is the window's rect. + pub fn floating_layer(id: Id, window: &Floating

) -> Option { + window.panels().next().map(|first| LayerId::new(Order::Middle, id.with(("floating", first)))) + } } /// Name the controls the renderer registered this frame and store their rects. pub(super) fn record(ctx: &Context, area: Id, layout: &Layout

, owned: &[Id]) { let mut names: HashMap> = HashMap::new(); + let mut name = |hit: Hit

| { + names.insert(DockArea::

::hit_id(area, &hit), hit); + }; for panel in layout.panels() { let p = || panel.clone(); - let some = Some(panel); - names.insert(area.with(("tab", panel)), Hit::Tab(p())); - names.insert(area.with(("icon", panel)), Hit::Icon(p())); - names.insert(area.with(("overflow", panel)), Hit::Overflow(p())); - names.insert(area.with(("collapse", panel)), Hit::StackToggle(p())); - names.insert(area.with(("stack-resize", panel)), Hit::Divider(Divider::Stack(p()))); - names.insert(area.with(("drag-bar", some)), Hit::DragBar(p())); - names.insert(area.with(("drag-border", some)), Hit::Border(p())); - names.insert(area.with(("icon-grip", some)), Hit::IconGrip(p())); - names.insert(area.with(("column-bar", some)), Hit::ColumnBar(p())); - names.insert(area.with(("column-collapse", some)), Hit::Collapse(p())); - names.insert(area.with(("column-resize", some)), Hit::Divider(Divider::Column(p()))); - names.insert(area.with(("group-resize", some)), Hit::Divider(Divider::Group(p()))); - names.insert(area.with(("floating-divider", some)), Hit::Divider(Divider::Group(p()))); - let title = area.with(("move-group", some)); - names.insert(title, Hit::Title(p())); - names.insert(title.with("close"), Hit::Close(p())); - let window = area.with(("floating", panel)); - let edges = [ResizeEdge::BottomRight, ResizeEdge::Left, ResizeEdge::Right, ResizeEdge::Bottom, ResizeEdge::BottomLeft]; - for (name, edge) in RESIZE_HANDLES.iter().zip(edges) { - names.insert(window.with(*name), Hit::Resize(p(), edge)); + for hit in [ + Hit::Tab(p()), + Hit::Icon(p()), + Hit::Overflow(p()), + Hit::StackToggle(p()), + Hit::Divider(Divider::Stack(p())), + Hit::DragBar(p()), + Hit::Border(p()), + Hit::IconGrip(p()), + Hit::ColumnBar(p()), + Hit::Collapse(p()), + Hit::Divider(Divider::Column(p())), + Hit::Divider(Divider::Group(p())), + Hit::Title(p()), + Hit::Close(p()), + ] { + name(hit); + } + for edge in [ResizeEdge::BottomRight, ResizeEdge::Left, ResizeEdge::Right, ResizeEdge::Bottom, ResizeEdge::BottomLeft] { + name(Hit::Resize(p(), edge)); } } let mut nodes = layout.root.as_ref().map(|root| vec![(root, Vec::::new())]).unwrap_or_default(); while let Some((node, path)) = nodes.pop() { if let Node::Split { first, second, .. } = node { - names.insert(area.with(("split", &path)), Hit::Divider(Divider::Split(path.clone()))); + name(Hit::Divider(Divider::Split(path.clone()))); let mut second_path = path.clone(); second_path.push(true); let mut first_path = path; diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index bfcabce0db..1e46077f64 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -196,7 +196,7 @@ impl Renderer<'_, P> { let pair_size = a.height() + b.height(); let (lo, hi) = if pair_size >= 2.0 * least { (least, pair_size - least) } else { (a.height(), a.height()) }; let response = ResizeHandle::new( - self.id.with(("floating-divider", upper.panels.first())), + self.id.with(("group-resize", upper.panels.first())), SplitAxis::Vertical, divider, &self.style.resize_label, diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 9c1dc6b3fb..1a162b68d1 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -712,7 +712,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name))) || matches(self.id.with(("move-group", Some(first))).with("close")) }) - || floating.groups.iter().any(|g| matches(self.id.with(("floating-divider", g.panels.first())))) + || floating.groups.iter().any(|g| matches(self.id.with(("group-resize", g.panels.first())))) { return true; } diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 4668b1ebc0..d2e9ae7618 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -537,7 +537,10 @@ fn focused_floating_resize_grip_accepts_both_arrow_axes_and_releases_tab() { for _ in 0..3 { step(&ctx, &mut layout, Vec::new()); } - let id = Id::new("test-area").with(("floating", &5u32)).with("resize"); + let id = DockArea::hit_id(Id::new("test-area"), &Hit::Resize(5u32, ResizeEdge::BottomRight)); + let layer = DockArea::floating_layer(Id::new("test-area"), &layout.floating[0]).unwrap(); + let [x, y, width, height] = layout.floating[0].rect; + assert_eq!(ctx.memory(|m| m.area_rect(layer.id)), Some(Rect::from_min_size(pos2(x, y), vec2(width, height)))); ctx.memory_mut(|memory| memory.request_focus(id)); let key = |key| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; step(&ctx, &mut layout, vec![key(egui::Key::ArrowRight), key(egui::Key::ArrowDown)]); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 86d9212140..86bc07791a 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -265,6 +265,11 @@ rect: tabs, drag bars, borders, column bars, »/« buttons, title bars, close bu grips, resize edges and dividers. It is always compiled, so an app can return it from a `ui.docking` control method next to the layout and the focused panel. +`DockArea::hit_id(id, &hit)` is the egui widget id of a control, for tests and automation that +focus it or read its response. `DockArea::floating_layer(id, &window)` is a floating window's +egui layer: compare its place in `memory.layer_ids()` with another layer to tell whether the +window covers it, and read its rect with `memory.area_rect(layer.id)`. + The `testing` feature adds `docking::testing::DockDriver`. It runs a `DockArea` in a headless egui context with real pointer and key events, and applies the actions each frame emits. From 38e2b27a303945f16265549a61119a96c25c936c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:59:02 +0000 Subject: [PATCH 50/94] docking: window.panel.dock with an edge zone and no anchor docks at that edge A left, right, top or bottom zone without anchor or side maps to Placement::Edge, anchored on any docked panel that does not move. A hidden panel is shown and moved in one step, all or nothing. --- crates/ui/src/docking/command.rs | 48 +++++++++++++++++++++++--- crates/ui/src/docking/command_tests.rs | 12 +++++++ docs/ui-docking.md | 2 ++ 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 11a0a8df50..ad51a3af3d 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -81,8 +81,10 @@ pub enum DockCommand

{ column: bool, }, /// To `anchor`; else to a new column of the dock on `side` (a new dock when it has none); - /// else a floating panel joins the first dock group (or frame) as a tab, and a docked one - /// stays. A hidden panel without `anchor` and `side` is shown at its last location. + /// else with a `left`, `right`, `top` or `bottom` zone to a new frame on that outer edge + /// ([`Placement::Edge`]); else a floating panel joins the first dock group (or frame) as a + /// tab, and a docked one stays. A hidden panel without `anchor` and `side` is shown at its + /// last location, then moved to the edge a zone names. #[serde(rename = "window.panel.dock")] Dock { panel: P, @@ -406,10 +408,22 @@ impl DockCommand

{ }; return one(unit.to(layout, panel, to)?); } + let members = members(layout, panel, unit); + if let Some(zone) = self.edge() { + if before.is_some() { + return Err(DockError::InvalidPlacement); + } + let anchor = layout + .panels() + .into_iter() + .find(|p| !members.contains(p) && matches!(layout.place(p), Some(Place::Dock { .. } | Place::Node(_)))) + .cloned() + .ok_or(DockError::MissingTarget)?; + return one(unit.to(layout, panel, Target::At { anchor, placement: Placement::Edge(zone) })?); + } if !matches!(layout.place(panel), Some(Place::Floating { .. })) { return Ok(Vec::new()); } - let members = members(layout, panel, unit); let panels = layout.panels(); let free = || panels.iter().copied().filter(|p| !members.contains(p)); let docked = free().find(|p| matches!(layout.place(p), Some(Place::Dock { .. }))); @@ -498,8 +512,16 @@ impl DockCommand

{ _ => None, }; if let Some(panel) = show.filter(|p| !workspace.layout.contains(p)) { - workspace.set_visible(panel.clone(), true, None)?; - return Ok(Vec::new()); + if self.edge().is_none() { + workspace.set_visible(panel.clone(), true, None)?; + return Ok(Vec::new()); + } + // Shown, then moved to the edge, all or nothing. + let mut shown = workspace.clone(); + shown.set_visible(panel.clone(), true, None)?; + let closed = shown.apply_all(self.to_actions(&shown, right_to_left, space)?, permissions)?; + *workspace = shown; + return Ok(closed); } if let Self::Lock { locked } = self { workspace.locked = locked.unwrap_or(!workspace.locked); @@ -510,6 +532,22 @@ impl DockCommand

{ } } +impl

DockCommand

{ + /// The outer edge `window.panel.dock` goes to: a side zone without an anchor or side. + fn edge(&self) -> Option { + match self { + Self::Dock { anchor: None, side: None, zone: Some(zone), .. } => match zone { + ZoneName::Left => Some(Zone::Left), + ZoneName::Right => Some(Zone::Right), + ZoneName::Top => Some(Zone::Top), + ZoneName::Bottom => Some(Zone::Bottom), + _ => None, + }, + _ => None, + } + } +} + /// The first panel of the last column of the dock on `side`. fn last_column(layout: &Layout

, side: Side) -> Option

{ let path = layout.dock_path(side)?; diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 78d46dd49d..1a8a6bf264 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -393,3 +393,15 @@ fn minimize_without_a_value_toggles_an_accordion_entry_both_ways() { toggle.apply(&mut workspace, false, &space(), permissions).unwrap(); assert_eq!(workspace.layout.panel_state(&s("layers")), PanelState::Front); } + +#[test] +fn dock_with_a_side_zone_and_no_anchor_makes_an_outer_edge_frame() { + let edge = |panel: &str, zone| Action::Move { panel: s(panel), anchor: s("layers"), placement: Placement::Edge(zone) }; + assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "color", "zone": "left"})), vec![edge("color", Zone::Left)]); + assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "history", "zone": "bottom"})), vec![edge("history", Zone::Bottom)]); + let (moved, _) = applied(json!({"command": "window.panel.dock", "panel": "color", "zone": "right"})); + assert!(matches!(moved.layout.place(&s("color")), Some(crate::docking::dock_model::Place::Node(_))), "{:?}", moved.layout); + let (shown, _) = applied(json!({"command": "window.panel.dock", "panel": "swatches", "zone": "top"})); + assert!(matches!(shown.layout.place(&s("swatches")), Some(crate::docking::dock_model::Place::Node(_))) && shown.hidden.is_empty(), "{:?}", shown.layout); + rejected(json!({"command": "window.panel.dock", "panel": "color", "zone": "left", "before": null}), DockError::InvalidPlacement); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 86bc07791a..befbf0b616 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -223,6 +223,8 @@ let closed = command.apply(&mut app.workspace, style.right_to_left, &space, |pan `to_actions` take the layout's `right_to_left` for that. - `group` moves the panel's whole group; `column` moves its dock column, or its whole window when it floats. `side` is `Start` or `End`. +- `window.panel.dock` with `left`, `right`, `top` or `bottom` and no `anchor` or `side` makes a + new frame on that outer edge (`Placement::Edge`). A hidden panel is shown first. - `window.panel.float` without a rect floats what it moves at the size a drag floats it at (see Floating size). It goes inside the dock area, 24 points from its top-left corner, so it stays clear of the menu bar. From 877f676e199cd3d4bed134c5930eae16923ff9e8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:59:33 +0000 Subject: [PATCH 51/94] docking: menu item labels in title case Float Panel, Close Panel and Move Group To match the other menu items. Control names that only screen readers announce stay in sentence case. --- crates/ui/src/docking/group_tests.rs | 2 +- crates/ui/src/docking/labels.rs | 10 ++++++---- crates/ui/src/docking/render/group.rs | 2 +- crates/ui/src/docking/surface.rs | 8 ++++---- crates/ui/src/docking/tests.rs | 2 +- crates/ui/src/docking/trial_tests.rs | 4 ++-- docs/ui-docking.md | 2 +- 7 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 62d6013f23..e6f62fcdab 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -531,7 +531,7 @@ fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() { 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); - for label in ["Close Tab Group", "Minimize", "Float Tab Group", "Move Group to"] { + for label in ["Close Tab Group", "Minimize", "Float Tab Group", "Move Group To"] { assert_eq!(h.query_all_by_label(label).count(), 1, "{label}"); } h.get_by_label("Close Tab Group").click(); diff --git a/crates/ui/src/docking/labels.rs b/crates/ui/src/docking/labels.rs index 7e8a60ee83..4a4799c598 100644 --- a/crates/ui/src/docking/labels.rs +++ b/crates/ui/src/docking/labels.rs @@ -4,7 +4,9 @@ use super::DockStyle; impl DockStyle { /// Replace every `*_label` field with `translate(key)`, keeping the English default where it - /// returns `None`. An application translates the docking chrome in one place: + /// returns `None`. The defaults of menu items are in title case; those of controls, which + /// only screen readers announce, in sentence case. An application translates the docking + /// chrome in one place: /// /// ``` /// fn dock_style(ui: &egui::Ui) -> craft_ui::docking::DockStyle { @@ -17,8 +19,8 @@ impl DockStyle { /// /// | Key | Field | English default | /// |---|---|---| - /// | `dock.float` | `float_label` | Float panel | - /// | `dock.close` | `close_label` | Close panel | + /// | `dock.float` | `float_label` | Float Panel | + /// | `dock.close` | `close_label` | Close Panel | /// | `dock.movePanelTo` | `move_panel_to_label` | Move Panel to Group | /// | `dock.panels` | `panels_label` | Panels | /// | `dock.resize` | `resize_label` | Resize panels | @@ -28,7 +30,7 @@ impl DockStyle { /// | `dock.minimize` | `minimize_label` | Minimize | /// | `dock.expand` | `expand_label` | Expand | /// | `dock.floatGroup` | `float_group_label` | Float Tab Group | - /// | `dock.moveGroupTo` | `move_group_to_label` | Move Group to | + /// | `dock.moveGroupTo` | `move_group_to_label` | Move Group To | /// | `dock.moveColumn` | `move_column_label` | Move panel column | /// | `dock.collapseToIcons` | `collapse_to_icons_label` | Collapse to Icons | /// | `dock.expandPanels` | `expand_panels_label` | Expand Panels | diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index cb44cd8ac8..e38208a1a9 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -258,7 +258,7 @@ impl Renderer<'_, P> { } /// The group items of the menu tail: Close Tab Group, Minimize or Expand, Float Tab Group - /// and Move Group to. `panel` is the panel whose menu this is. + /// and Move Group To. `panel` is the panel whose menu this is. fn group_menu(&mut self, ui: &mut Ui, owner: &TabGroup<'_, P>, panel: &P) { let all = |check: &dyn Fn(crate::docking::Permissions) -> bool| owner.panels.iter().all(|p| check(self.permissions(p))); let closable = self.style.close_menu_items && all(&|p| p.closable); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 1a162b68d1..1a93cac245 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -93,7 +93,7 @@ pub struct DockStyle { pub restore_frame_label: String, /// Shown where native windows are available (feature `native-windows`). pub new_window_label: String, - /// Show the built-in Close items in tab and group menus (Close panel, Close Tab Group, + /// Show the built-in Close items in tab and group menus (Close Panel, Close Tab Group, /// Close Other Panels in Group) for closable panels. A host that draws its own Close items /// turns this off and keeps [`Permissions::closable`], so its close actions still apply. pub close_menu_items: bool, @@ -130,8 +130,8 @@ impl DockStyle { border: visuals.widgets.noninteractive.bg_stroke, accent: visuals.selection.stroke.color, font: FontId::proportional(12.0), - float_label: "Float panel".into(), - close_label: "Close panel".into(), + float_label: "Float Panel".into(), + close_label: "Close Panel".into(), move_panel_to_label: "Move Panel to Group".into(), panels_label: "Panels".into(), resize_label: "Resize panels".into(), @@ -141,7 +141,7 @@ impl DockStyle { minimize_label: "Minimize".into(), expand_label: "Expand".into(), float_group_label: "Float Tab Group".into(), - move_group_to_label: "Move Group to".into(), + move_group_to_label: "Move Group To".into(), drag_bar_width: 40.0, floating_background: visuals.window_fill, floating_stroke: visuals.window_stroke, diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index d2e9ae7618..7dc09345b5 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1260,7 +1260,7 @@ fn popup_action_labels_use_custom_visual_text_and_logical_accessibility() { 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)); - for logical in ["Float panel", "Move Panel to Group", "Close panel"] { + for logical in ["Float Panel", "Move Panel to Group", "Close Panel"] { assert!( h.output().shapes.iter().any(|shape| paints(&shape.shape, &format!("Action visual: {logical}"))), "custom action must paint: {logical}" diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 584f28e994..2afee3cbe0 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -319,8 +319,8 @@ fn hidden_close_controls_leave_closing_to_the_host() { d.step(vec![secondary(false)]); d.step(vec![]); let painted = |d: &Driver, label: &str| texts(d).iter().any(|(_, t)| t.galley.text() == label); - assert!(painted(&d, "Float panel"), "the tab menu is open"); - assert!(!painted(&d, "Close panel") && !painted(&d, "Close Tab Group")); + assert!(painted(&d, "Float Panel"), "the tab menu is open"); + assert!(!painted(&d, "Close Panel") && !painted(&d, "Close Tab Group")); // The panels stay closable: the host's own Close applies and reports what it closed. assert_eq!(d.layout.apply_with_permissions(Action::CloseWindow { panel: 5 }, |p| d.content.permissions(p)), Ok(vec![5, 6])); } diff --git a/docs/ui-docking.md b/docs/ui-docking.md index befbf0b616..1a1aae4de4 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -250,7 +250,7 @@ the app's command registry. App-specific aliases stay in the app. ## Labels Every visible and accessibility label is a `*_label` field of `DockStyle`, with an English -default. `DockStyle::localized` sets them all from one keyed lookup: +default: title case for menu items, sentence case for names only screen readers announce. `DockStyle::localized` sets them all from one keyed lookup: ```rust,ignore let style = DockStyle::from_ui(ui).localized(|key| app.strings.get(key).cloned()); From a76d196b80b06c98b34b6a78a973d4b02a810e54 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 01:00:22 +0000 Subject: [PATCH 52/94] docking: dividers and resize grips keep focus after a pointer drag Arrow keys resize the handle right after a drag. Focus that came from the pointer draws no highlight until a key is pressed, and hovering still focuses nothing. --- crates/ui/src/docking/chrome.rs | 6 ++---- crates/ui/src/docking/tests.rs | 2 +- crates/ui/src/layout/mod.rs | 1 + crates/ui/src/layout/resize.rs | 25 ++++++++++++++++++------- crates/ui/src/layout/tests.rs | 15 ++++++++------- docs/ui-docking.md | 4 +++- 6 files changed, 33 insertions(+), 20 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index 3aeab52912..a9024e7d20 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -194,6 +194,7 @@ impl<'a> FloatingFrame<'a> { started = Some(response.id); } } + let quiet = crate::layout::pointer_focus(ui, &response); let mut delta = Vec2::ZERO; if response.has_focus() { ui.memory_mut(|memory| { @@ -230,13 +231,10 @@ impl<'a> FloatingFrame<'a> { { resized = Some(next); } - if response.drag_stopped() { - response.surrender_focus(); - } if cancelled || !ui.input(|input| input.pointer.primary_down()) { ui.ctx().data_mut(|data| data.remove::(anchor_id)); } - if name == "resize" && (response.hovered() || response.dragged() || response.has_focus()) { + if name == "resize" && (response.hovered() || response.dragged() || (response.has_focus() && !quiet)) { ui.painter().line_segment([handle.left_bottom(), handle.right_top()], Stroke::new(2.0, style.accent)); } responses.push(response); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 7dc09345b5..e752bb5141 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1478,7 +1478,7 @@ fn pointer_floating_resize_stops_at_edges_and_waits_for_cursor_to_return() { step(&ctx, &mut layout, vec![Event::PointerMoved(start)]); assert_eq!(layout.floating[0].rect, original, "{name}: returning to the original handle restores its geometry"); step(&ctx, &mut layout, vec![pointer_button(start, false)]); - assert!(!ctx.memory(|memory| memory.has_focus(id))); + assert!(ctx.memory(|memory| memory.has_focus(id)), "{name}: the grip keeps keyboard focus after the drag"); } } diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs index 335dd072c8..92cff1989a 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -9,6 +9,7 @@ mod resize; mod toolbar; pub use geometry::{SplitAxis, SplitLayout, SplitSize, split_rect}; +pub(crate) use resize::pointer_focus; pub use resize::{ResizeHandle, ResizeHandleStyle, ResizeResponse}; pub use toolbar::{ToolbarFit, fit_toolbar}; diff --git a/crates/ui/src/layout/resize.rs b/crates/ui/src/layout/resize.rs index c0de628fbf..422c654674 100644 --- a/crates/ui/src/layout/resize.rs +++ b/crates/ui/src/layout/resize.rs @@ -24,7 +24,8 @@ pub struct ResizeResponse { /// A focusable divider with pointer, arrow-key and accessibility resizing. /// /// This widget never stores or changes a pane size. IDs and labels are separate, so translated -/// labels do not change identity. Pointer drags retain egui's immediate `Sense::drag` behavior. +/// labels do not change identity. Pointer drags retain egui's immediate `Sense::drag` behavior +/// and leave keyboard focus on the handle, highlighted once a key is pressed. /// Only arrows along the split axis are consumed, while this handle has focus. Tab remains /// available for normal focus traversal. pub struct ResizeHandle<'a> { @@ -82,15 +83,12 @@ impl<'a> ResizeHandle<'a> { let mut response = ui.interact(if valid { hit } else { inert }, self.id, if valid { Sense::drag() } else { Sense::hover() }); let enabled = valid && response.enabled(); let mut delta = 0.0; - // Pointer resizing borrows focus only for the gesture. Keyboard focus acquired - // through traversal remains intact until the user chooses another control. - if response.drag_stopped() { - response.surrender_focus(); - } + let mut quiet = false; if enabled { if response.drag_started() { response.request_focus(); } + quiet = pointer_focus(ui, &response); if response.dragged() { let drag = response.drag_delta(); delta = match self.axis { @@ -181,7 +179,7 @@ impl<'a> ResizeHandle<'a> { if enabled { let fill = if response.dragged() { Some(self.style.dragged) - } else if response.has_focus() { + } else if response.has_focus() && !quiet { Some(self.style.focused) } else if response.hovered() { Some(self.style.hovered) @@ -201,3 +199,16 @@ impl<'a> ResizeHandle<'a> { ResizeResponse { response, delta } } } + +/// A pointer drag focuses its handle, and the handle keeps focus after the release so arrow +/// keys resize it right away. That focus draws no highlight until a key is pressed. Call after +/// the handle requests focus; true while its focus came from the pointer. +pub(crate) fn pointer_focus(ui: &Ui, response: &Response) -> bool { + let key = response.id.with("pointer-focus"); + if response.drag_started() { + ui.ctx().data_mut(|d| d.insert_temp(key, true)); + } else if !response.has_focus() || ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) { + ui.ctx().data_mut(|d| d.remove::(key)); + } + ui.ctx().data(|d| d.get_temp::(key)).unwrap_or(false) +} diff --git a/crates/ui/src/layout/tests.rs b/crates/ui/src/layout/tests.rs index 1a23ac02d3..660eb1112e 100644 --- a/crates/ui/src/layout/tests.rs +++ b/crates/ui/src/layout/tests.rs @@ -171,14 +171,15 @@ fn resize_handle_preserves_pointer_drag_lifecycle_and_reports_per_frame_delta() let (response, _) = h.frame(vec![pointer(center + vec2(16.0, 0.0), false)]); assert!(response.response.drag_stopped()); assert_eq!(response.delta, 0.0); - assert!(!response.response.has_focus(), "pointer release must not leave a sticky focus highlight"); + assert!(response.response.has_focus(), "a pointer drag leaves keyboard focus on the handle"); let (_, output) = h.frame(vec![Event::PointerMoved(pos2(300.0, 180.0))]); - assert!( - !output - .shapes - .iter() - .any(|shape| { matches!(&shape.shape, egui::epaint::Shape::Rect(rect) if rect.rect == h.rect && rect.fill == Color32::BLUE) }) - ); + let handle = h.rect; + let highlighted = + |output: &FullOutput| output.shapes.iter().any(|shape| matches!(&shape.shape, egui::epaint::Shape::Rect(rect) if rect.rect == handle && rect.fill == Color32::BLUE)); + assert!(!highlighted(&output), "focus from the pointer draws no highlight"); + let (response, output) = h.frame(vec![key(Key::ArrowRight)]); + assert_eq!(response.delta, 8.0, "arrow keys resize right after the drag"); + assert!(highlighted(&output)); assert_eq!(h.value, 100.0, "the component never owns pane state"); } diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 1a1aae4de4..9a0e924e6c 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -137,7 +137,9 @@ by the app's own Close items and commands. `DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome rather than on a panel body. Focus follows only the user's input: a tab keeps keyboard focus until a command or a -workspace reset hides, closes or moves its panel, and then gives it up. `begin_drag` hands a drag that started in the app's own chrome to the area. +workspace reset hides, closes or moves its panel, and then gives it up. A divider or a floating +window's resize grip keeps keyboard focus after a pointer drag, so arrow keys resize it right +away; its focus highlight shows once a key is pressed. Hovering focuses nothing. `begin_drag` hands a drag that started in the app's own chrome to the area. `docking::chrome` has the floating frame, the title bar and `drop_preview` (the drop preview docking and `craft_ui::panes` both draw) for apps that draw their own windows. From 95c81fa6de8d511924d7b9d83990767bbad5bd69 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 01:00:30 +0000 Subject: [PATCH 53/94] docking: say that the drag bar's menu opens on a right click A left click on the drag bar focuses it and opens nothing, as designed; the Hit::DragBar docs said otherwise. --- crates/ui/src/docking/hits.rs | 3 ++- crates/ui/src/docking/render/group.rs | 5 +++-- docs/ui-docking.md | 2 ++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index e772896737..baff650887 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -14,7 +14,8 @@ use super::{DockArea, Floating, Layout, Node, render::RESIZE_HANDLES}; pub enum Hit

{ /// A tab: click activates, drag moves the panel (S1). Tab(P), - /// A group's drag bar: click opens the group menu, drag moves the group (S2). + /// A group's drag bar: drag moves the group; a right click, Enter or Space opens the group + /// menu (S2). DragBar(P), /// The top border of a group's strip: drag moves the group (S3). Border(P), diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index e38208a1a9..0c01112e10 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -152,8 +152,9 @@ impl Renderer<'_, P> { ui.painter().rect_stroke(rect, 0.0, self.style.border, StrokeKind::Inside); } - /// The drag bar (`drag-bar`: click, double-click, menu and drag) or the top border band - /// (`drag-border`: drag only). Both move the whole group. + /// The drag bar (`drag-bar`: drag, double-click, and the group menu on a right click, Enter + /// or Space) or the top border band (`drag-border`: drag only). Both move the whole group; + /// a left click on the bar only focuses it. fn group_handle(&mut self, ui: &mut Ui, name: &'static str, hit: Rect, owner: &TabGroup<'_, P>, movable: bool) { if !crate::docking::targets::usable(hit) { return; diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 9a0e924e6c..c971e84705 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -180,6 +180,8 @@ A flyout fits its content the same way, without the title bar. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. - Double-click a tab or drag bar to minimize a group to its strip. +- Right-click a tab for its menu, or a drag bar for the group menu; Enter or Space on a focused + drag bar opens it too. A left click on the drag bar only focuses it. - In the Frame profile, the mouse wheel over a tab strip selects the next or previous tab, and a middle click on a closable panel's tab closes it. `DockStyle::wheel_selects_tabs` and `middle_click_closes_tabs` turn either on or off in any profile. From 3600104e7632336be5312b6e6f62b5acf2ea37e7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 01:00:56 +0000 Subject: [PATCH 54/94] docking: rustfmt the new tests --- crates/ui/src/docking/command_tests.rs | 6 +++++- crates/ui/src/layout/tests.rs | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 1a8a6bf264..1f07116999 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -402,6 +402,10 @@ fn dock_with_a_side_zone_and_no_anchor_makes_an_outer_edge_frame() { let (moved, _) = applied(json!({"command": "window.panel.dock", "panel": "color", "zone": "right"})); assert!(matches!(moved.layout.place(&s("color")), Some(crate::docking::dock_model::Place::Node(_))), "{:?}", moved.layout); let (shown, _) = applied(json!({"command": "window.panel.dock", "panel": "swatches", "zone": "top"})); - assert!(matches!(shown.layout.place(&s("swatches")), Some(crate::docking::dock_model::Place::Node(_))) && shown.hidden.is_empty(), "{:?}", shown.layout); + assert!( + matches!(shown.layout.place(&s("swatches")), Some(crate::docking::dock_model::Place::Node(_))) && shown.hidden.is_empty(), + "{:?}", + shown.layout + ); rejected(json!({"command": "window.panel.dock", "panel": "color", "zone": "left", "before": null}), DockError::InvalidPlacement); } diff --git a/crates/ui/src/layout/tests.rs b/crates/ui/src/layout/tests.rs index 660eb1112e..72544c5074 100644 --- a/crates/ui/src/layout/tests.rs +++ b/crates/ui/src/layout/tests.rs @@ -174,8 +174,9 @@ fn resize_handle_preserves_pointer_drag_lifecycle_and_reports_per_frame_delta() assert!(response.response.has_focus(), "a pointer drag leaves keyboard focus on the handle"); let (_, output) = h.frame(vec![Event::PointerMoved(pos2(300.0, 180.0))]); let handle = h.rect; - let highlighted = - |output: &FullOutput| output.shapes.iter().any(|shape| matches!(&shape.shape, egui::epaint::Shape::Rect(rect) if rect.rect == handle && rect.fill == Color32::BLUE)); + let highlighted = |output: &FullOutput| { + output.shapes.iter().any(|shape| matches!(&shape.shape, egui::epaint::Shape::Rect(rect) if rect.rect == handle && rect.fill == Color32::BLUE)) + }; assert!(!highlighted(&output), "focus from the pointer draws no highlight"); let (response, output) = h.frame(vec![key(Key::ArrowRight)]); assert_eq!(response.delta, 8.0, "arrow keys resize right after the drag"); From ceb75f965e30d7de7deaf336728ac26f9121c7c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:24:45 +0000 Subject: [PATCH 55/94] ui: use US spelling --- crates/ui/src/docking/chrome.rs | 12 ++++++------ crates/ui/src/docking/command.rs | 2 +- crates/ui/src/docking/group_tests.rs | 2 +- crates/ui/src/docking/hits.rs | 2 +- crates/ui/src/docking/model.rs | 2 +- crates/ui/src/docking/render/dock.rs | 2 +- crates/ui/src/docking/render/group.rs | 2 +- crates/ui/src/docking/render/iconic.rs | 2 +- crates/ui/src/docking/render/preview.rs | 2 +- crates/ui/src/docking/surface.rs | 4 ++-- crates/ui/src/docking/trial_tests.rs | 4 ++-- crates/ui/src/docking/workspace.rs | 2 +- crates/ui/src/panes/mod.rs | 12 ++++++------ crates/ui/src/panes/tests.rs | 2 +- docs/ui-docking.md | 2 +- docs/ui-panes.md | 4 ++-- 16 files changed, 29 insertions(+), 29 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index a9024e7d20..3d445e82b0 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -17,7 +17,7 @@ pub const TITLE_HEIGHT: f32 = 14.0; /// Names of the resize handles, appended to the frame id: `id.with(name)`. pub const RESIZE_HANDLES: [&str; 5] = ["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left"]; -/// Colours and font of the frame and title bar. +/// Colors and font of the frame and title bar. #[derive(Clone, Debug)] pub struct ChromeStyle { /// Painted under the contents, so the window stays opaque when the contents are not. @@ -168,7 +168,7 @@ impl<'a> FloatingFrame<'a> { let mut started = None; let mut responses = Vec::new(); let limits = PanelLimits { min: self.limits.min.max(vec2(40.0, TITLE_HEIGHT + 20.0)).min(self.limits.max), ..self.limits }; - let cancelled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused); + let canceled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused); for (name, handle, direction) in handles(rect) { if !super::targets::usable(handle) { continue; @@ -226,12 +226,12 @@ impl<'a> FloatingFrame<'a> { None }; if response.enabled() - && !cancelled + && !canceled && let Some(next) = next.filter(|next| *next != rect) { resized = Some(next); } - if cancelled || !ui.input(|input| input.pointer.primary_down()) { + if canceled || !ui.input(|input| input.pointer.primary_down()) { ui.ctx().data_mut(|data| data.remove::(anchor_id)); } if name == "resize" && (response.hovered() || response.dragged() || (response.has_focus() && !quiet)) { @@ -387,7 +387,7 @@ pub enum MoveStep { /// The rect follows the pointer, inside the bounds. Moving(Rect), /// Escape or window focus loss ended the move: the rect it started from. - Cancelled(Rect), + Canceled(Rect), /// Released over `pointer`, with the rect where it was dropped. Dropped { rect: Rect, pointer: Pos2 }, } @@ -407,7 +407,7 @@ pub fn live_move(ctx: &Context, bar: &Response, rect: Rect, bounds: Rect) -> Opt let forget = || ctx.data_mut(|data| data.remove::<(Rect, Pos2)>(key)); if ctx.input(|input| input.key_pressed(Key::Escape) || !input.focused) { forget(); - return Some(MoveStep::Cancelled(start)); + return Some(MoveStep::Canceled(start)); } let pointer = ctx.pointer_latest_pos().unwrap_or(origin); let moved = clamp(start.translate(pointer - origin), bounds); diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index ad51a3af3d..e377f256c2 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -159,7 +159,7 @@ pub enum UiDock

{ } /// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone` -/// (default `center`) and `before`, which only applies to a centre move. +/// (default `center`) and `before`, which only applies to a center move. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "operation", rename_all = "camelCase", bound(serialize = "P: Serialize", deserialize = "P: Deserialize<'de>"))] #[non_exhaustive] diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index e6f62fcdab..cdcfab2494 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -303,7 +303,7 @@ fn group_drop_on_a_frame_edge_splits_and_on_a_protected_canvas_floats() { assert_eq!(**first, tabs(&[2, 3], 1)); assert_eq!(**second, tabs(&[1], 0)); - // A protected canvas takes nothing, at its centre or its edge: no join, no split, no + // A protected canvas takes nothing, at its center or its edge: no join, no split, no // preview; the group floats there. for at in [pos2(150.0, 300.0), pos2(20.0, 300.0)] { let mut d = Driver::with(frames(), canvas(), area); diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index baff650887..053732bb0f 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -73,7 +73,7 @@ fn key(area: Id) -> Id { impl DockArea<'_, P> { /// Every gesture source the area drew in its last frame, with its rect in points. Hosts /// return these from a `ui.docking` control method beside the layout and `focused`; tests - /// drag from their centres. + /// drag from their centers. pub fn hit_rects(ctx: &Context, id: Id) -> Vec<(Hit

, Rect)> { ctx.data(|d| d.get_temp::, Rect)>>(key(id))).unwrap_or_default() } diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index f4a0471aeb..3ca0c100c4 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -563,7 +563,7 @@ impl Layout

{ if location.anchor.is_some() { return Ok(location); } - // Alone in its group: anchor to the neighbouring group, then the neighbouring column. + // Alone in its group: anchor to the neighboring group, then the neighboring column. let first = |g: Option<&Group

>| g.and_then(|g| g.panels.first()).cloned(); if let Some(anchor) = first(groups.get(group + 1)) { location.anchor = Some(anchor); diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index c2822cb67a..3709d1694a 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -1,7 +1,7 @@ //! [D] The dock profile: side docks of columns, each a column bar above stacked groups. //! //! Columns run from the window edge inwards. Every column's inner edge resizes it; the last -//! column's inner edge is the dock's inner edge. Behaviour follows VectorCraft `floating.rs` +//! column's inner edge is the dock's inner edge. Behavior follows VectorCraft `floating.rs` //! (column layout, drop geometry) and PhotoCraft `dock.rs` (group heights). use std::{fmt::Debug, hash::Hash}; diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 0c01112e10..74a33b06da 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -176,7 +176,7 @@ impl Renderer<'_, P> { } let active = response.has_focus() || response.hovered(); if movable { - // A grip mark at rest, centred in the bar's reserved width beside the header. + // A grip mark at rest, centerd in the bar's reserved width beside the header. let grip = if self.style.right_to_left { Rect::from_min_max(hit.min, pos2((hit.left() + self.style.drag_bar_width).min(hit.right()), hit.bottom())) } else { diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 1be3872f8c..8949e334bc 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -1,6 +1,6 @@ //! [D] Iconic columns: one icon per panel, groups apart, and the flyout an icon opens. //! -//! Behaviour follows VectorCraft `dock.rs` (icon column, flyouts beside it on the canvas side, +//! Behavior follows VectorCraft `dock.rs` (icon column, flyouts beside it on the canvas side, //! names when the column is widened) and PhotoCraft `dock.rs` (Auto-Collapse Iconic Panels). use std::{fmt::Debug, hash::Hash}; diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 861e9afd75..aff38e9571 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -77,7 +77,7 @@ impl Renderer<'_, P> { /// The valid target under the pointer for a whole group. A target holding the group /// itself is a no-op proposal; a target the model would reject is no target. A window - /// moving live looks through itself and does not split frames or join a body's centre. + /// moving live looks through itself and does not split frames or join a body's center. pub(super) fn group_proposal(&self, drag: &GroupDrag

, pointer: Pos2) -> Option> { let window = drag.gesture == GroupGesture::Window; let valid = |proposal: DropProposal

| { diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 1a93cac245..36b037b3f6 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -44,7 +44,7 @@ pub struct DockStyle { /// Minimum width of the drag bar left of the group header. Tabs overflow before the bar /// narrows. pub drag_bar_width: f32, - /// Painted under every floating window, so it stays opaque when the panel colours are not. + /// Painted under every floating window, so it stays opaque when the panel colors are not. pub floating_background: Color32, pub floating_stroke: Stroke, /// Dock: docks, columns and stacked groups. Frame: a split tree of tab frames, with @@ -454,7 +454,7 @@ pub(super) enum GroupGesture { pub(super) struct GroupDrag

{ /// The first member; identifies the gesture. pub(super) panel: P, - /// The floating window rect at the press, restored when a window move is cancelled. + /// The floating window rect at the press, restored when a window move is canceled. pub(super) original: [f32; 4], pub(super) gesture: GroupGesture, pub(super) members: Vec

, diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 2afee3cbe0..15b4535d76 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -121,7 +121,7 @@ fn galley_labels_stay_whole_and_only_an_over_wide_active_tab_ends_with_an_ellips } #[test] -fn drag_bar_shows_a_grip_at_rest_and_a_group_drag_paints_a_filled_labelled_ghost() { +fn drag_bar_shows_a_grip_at_rest_and_a_group_drag_paints_a_filled_labeled_ghost() { let mut d = Driver::new(frames()); let visuals = d.ctx.global_style().visuals.clone(); let bar = d.rect("drag-bar", 2); @@ -248,7 +248,7 @@ fn right_to_left_mirrors_the_tab_strip_and_its_insertion_slots() { assert!(second.right() <= first.left() + 0.5, "{first:?} {second:?}"); assert!(bar.right() <= second.left() + 0.5 && bar.left() >= 304.0 + 30.0 - 0.5, "the bar sits between the tabs and the header: {bar:?}"); - // Just right of the first tab's centre is before it in a right-to-left strip. + // Just right of the first tab's center is before it in a right-to-left strip. let out = d.drag(d.tab(1).center(), pos2(first.center().x + 6.0, first.center().y)); assert!(out.actions.contains(&Action::Move { panel: 1, anchor: 3, placement: Placement::Tab { before: Some(2) } }), "{:?}", out.actions); diff --git a/crates/ui/src/docking/workspace.rs b/crates/ui/src/docking/workspace.rs index 81052e5659..06cc91bc6f 100644 --- a/crates/ui/src/docking/workspace.rs +++ b/crates/ui/src/docking/workspace.rs @@ -80,7 +80,7 @@ impl Workspace

{ } /// Apply one action. Closed panels record where they go back, so each one can be reopened - /// with [`Self::set_visible`]. Honours [`Self::locked`]. Returns the panels the action + /// with [`Self::set_visible`]. Honors [`Self::locked`]. Returns the panels the action /// closed, in group order, so the application can release their state. pub fn apply(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { self.apply_all([action], permissions) diff --git a/crates/ui/src/panes/mod.rs b/crates/ui/src/panes/mod.rs index 9e2aeca4e5..75b20ddd46 100644 --- a/crates/ui/src/panes/mod.rs +++ b/crates/ui/src/panes/mod.rs @@ -202,7 +202,7 @@ struct Memory { #[derive(Clone, Copy, Debug)] struct DragOut { pane: Id, - cancelled: bool, + canceled: bool, } struct Shown

{ @@ -556,11 +556,11 @@ impl PaneHost { requests: &mut Vec>, ) { if bar.drag_started() { - memory.drag_out = Some(DragOut { pane: s.id, cancelled: false }); + memory.drag_out = Some(DragOut { pane: s.id, canceled: false }); } let Some(mut drag) = memory.drag_out.filter(|d| d.pane == s.id) else { return }; if ctx.input(|input| input.key_pressed(Key::Escape) || !input.focused) { - drag.cancelled = true; + drag.canceled = true; } let near = rect.expand(DOCK_SNAP); let Some(pointer) = ctx.pointer_latest_pos() else { return }; @@ -570,7 +570,7 @@ impl PaneHost { let target = self.snap(pointer, bounds); if bar.drag_stopped() { memory.drag_out = None; - if drag.cancelled || !outside { + if drag.canceled || !outside { return; } match target { @@ -588,7 +588,7 @@ impl PaneHost { return; } memory.drag_out = Some(drag); - if drag.cancelled || !outside { + if drag.canceled || !outside { return; } let shape = match target.map(|t| self.side(t)) { @@ -635,7 +635,7 @@ impl PaneHost { } if content.movable(&s.pane) { match chrome::live_move(ctx, &shown.inner, shown.rect, bounds) { - Some(MoveStep::Moving(next) | MoveStep::Cancelled(next)) if next != shown.rect => { + Some(MoveStep::Moving(next) | MoveStep::Canceled(next)) if next != shown.rect => { requests.push(PaneRequest::FloatRect(s.pane.clone(), rect_array(next))); } Some(MoveStep::Dropped { rect, pointer }) => { diff --git a/crates/ui/src/panes/tests.rs b/crates/ui/src/panes/tests.rs index 16ea6dd044..e8ab8527b3 100644 --- a/crates/ui/src/panes/tests.rs +++ b/crates/ui/src/panes/tests.rs @@ -1,4 +1,4 @@ -//! Behaviour tests for the pane host, driven by egui pointer and key events in an 800 × 600 +//! Behavior tests for the pane host, driven by egui pointer and key events in an 800 × 600 //! window. The harness's root ui has an 8 pt margin, so the host spans x 8..792, y 8..592. use std::collections::HashMap; diff --git a/docs/ui-docking.md b/docs/ui-docking.md index c971e84705..122f0bae86 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -64,7 +64,7 @@ layout.apply(Action::Move { preferred `height`), a new column, or a new frame on an outer edge. - Containers take different placements: a dock column takes groups and columns, not splits. `Placement::for_zone(layout, anchor, zone, right_to_left)` maps a left, right, top, bottom or - centre zone onto what the anchor's container takes: a split in the frame tree, a new column on + center zone onto what the anchor's container takes: a split in the frame tree, a new column on that side or a new group above or below in a dock, a group above or below in a floating window. - Other actions select, minimize, collapse to icons, resize splits, columns and groups, and move a floating window to its own OS window (`SetNative`, feature `native-windows`). diff --git a/docs/ui-panes.md b/docs/ui-panes.md index 43d6f5b5c4..b9c859ab64 100644 --- a/docs/ui-panes.md +++ b/docs/ui-panes.md @@ -51,7 +51,7 @@ egui::CentralPanel::default().show(ui, |ui| { }); ``` -| Piece | Behaviour | +| Piece | Behavior | |---|---| | `Edge::{Start, End, Bottom}` | Logical edges. `Start` is left, or right with `.rtl(true)`. | | `SidePolicy::Columns` | Every docked pane shows; panes on one edge sit side by side in `open` order, the first outermost. | @@ -84,7 +84,7 @@ State: Accessibility, Alt Text, Restrict Editing and Comments at `End`. Default widths as today. - `Close(p)` runs the pane's existing command (`view.navigationPane {value: false}`, …). Command ids and `nav_pane` in `ui.json` stay as they are. -- Styles takes #2584's behaviour through the host: map `StylesPaneDock::{Left, Right, Floating}` +- Styles takes #2584's behavior through the host: map `StylesPaneDock::{Left, Right, Floating}` to `Place` (`Left` is `Docked(Start)` in left-to-right interfaces), run `view.stylesPaneDock` on `Place`, keep the float rect in UI prefs. #2584's own drag, snap and `float_rect` code goes. - Other panes return `None` from `states`; their widths stay session-only, as now. From cef258a356b7fa475af8418ee3d73699a3e52ccb Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:42:36 +0000 Subject: [PATCH 56/94] docking: a column's first tab docks beside its own column A dock target named by the dragged panel itself anchors on another panel of the same group or column, or leaves the panel in place when it is alone there, instead of failing with InvalidPlacement. --- crates/ui/src/docking/dock_tests.rs | 23 +++++++++++++++++++++++ crates/ui/src/docking/render/dock.rs | 12 +++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 9a17ed7e57..8f950481b9 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -481,3 +481,26 @@ fn right_to_left_mirrors_docks_their_edges_and_new_docks() { d.settle(); assert_eq!(d.rect("column-collapse", 5).left(), 0.0); } + +#[test] +fn a_column_s_first_tab_dropped_on_its_own_column_edge_anchors_on_another_panel() { + // Two columns, 0..240 and 240..480; the dragged tab is the first panel of the last one. + let wide = |columns: &[&[&[u32]]]| { + let mut layout = docked(Side::Start, columns); + if let Some(Node::Split { size, .. }) = &mut layout.root { + *size = SplitSize::FixedFirst(480.0); + } + layout + }; + let mut d = Driver::new(wide(&[&[&[2]], &[&[3, 4]]])); + let out = d.drag(d.tab(3).center(), pos2(484.0, 300.0)); + assert_eq!(out.actions, vec![Action::Move { panel: 3, anchor: 4, placement: Placement::Column { after: true } }]); + assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![2]], vec![vec![4]], vec![vec![3]]]); + + // Alone in its column, the panel stays where it is. + let layout = wide(&[&[&[2]], &[&[3]]]); + let mut d = Driver::new(layout.clone()); + let out = d.drag(d.tab(3).center(), pos2(484.0, 300.0)); + assert_eq!(out.actions, vec![]); + assert_eq!(d.layout, layout); +} diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 3709d1694a..96936f7af8 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -10,7 +10,8 @@ use egui::{Context, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, p use super::{GroupKind, Renderer}; use crate::docking::{ - Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Profile, Side, Target, + Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Placement, Profile, Side, Target, + dock_model::Unit, targets::{DockDrop, DockTarget, column_edge, horizontal_line, resolve_dock, usable, vertical_line}, }; use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; @@ -471,6 +472,15 @@ impl Renderer<'_, P> { let candidates = self.dock_candidates(); let drop = resolve_dock(pointer, &candidates)?; let action = match drop.target.to() { + // A target named by the dragged panel is its own group or column: another panel + // there names the same one. With none, the drop leaves the panel where it is. + Target::At { anchor, placement } if &anchor == panel => { + let unit = if matches!(placement, Placement::Column { .. }) { Unit::Column } else { Unit::Group }; + match self.layout.members(panel, unit).ok()?.into_iter().find(|p| p != panel) { + Some(anchor) => Action::Move { panel: panel.clone(), anchor, placement }, + None => return Some((None, drop.line)), + } + } Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, to @ Target::NewDock { .. } if self.layout.place(panel).and_then(|place| self.layout.group(&place)).is_some_and(|g| g.panels.len() == 1) => From a55cbe870ed6f4d178ced15a7ad0b1bae7e90780 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:42:52 +0000 Subject: [PATCH 57/94] docking: a huge wheel delta over a tab strip stops at the last tab The step count saturates instead of overflowing the index subtraction. --- crates/ui/src/docking/group_tests.rs | 4 ++++ crates/ui/src/docking/render/group.rs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index cdcfab2494..059634b848 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -687,6 +687,10 @@ fn frame_tabs_follow_the_wheel_and_close_on_a_middle_click() { let out = d.step(vec![wheel(egui::MouseWheelUnit::Point, -30.0)]); assert_eq!(second(&d), tabs(&[2, 3], 1)); assert_eq!(out.focused, Some(3)); + d.step(vec![wheel(egui::MouseWheelUnit::Line, -1e30)]); + assert_eq!(second(&d), tabs(&[2, 3], 1), "a huge delta stops at the last tab"); + d.step(vec![wheel(egui::MouseWheelUnit::Line, 1e30)]); + assert_eq!(second(&d), tabs(&[2, 3], 0), "and at the first"); d.step(vec![middle(over, true)]); let out = d.step(vec![middle(over, false)]); diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 74a33b06da..bb313e1f47 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -235,7 +235,7 @@ impl Renderer<'_, P> { let steps = total.trunc(); ui.ctx().data_mut(|d| d.insert_temp(key, total - steps)); // A wheel turned down scrolls content up: a negative delta selects the next tab. - let to = (active as i64 - steps as i64).clamp(0, panels.len().saturating_sub(1) as i64) as usize; + let to = (active as i64).saturating_sub(steps as i64).clamp(0, panels.len().saturating_sub(1) as i64) as usize; if to != active && let Some(panel) = panels.get(to) { From ae0c19b49bf5f04bfdd42425210e09459b1e5b48 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:44:25 +0000 Subject: [PATCH 58/94] docking: hidden floating windows do not cover dock targets Dock targets check the floating windows drawn this frame instead of every window's last egui area rect. floating_layer says that an undrawn window keeps its last area rect. --- crates/ui/src/docking/floating_tests.rs | 17 +++++++++++++++++ crates/ui/src/docking/hits.rs | 4 +++- crates/ui/src/docking/render/dock.rs | 20 +++++++++----------- crates/ui/src/docking/render/floating.rs | 4 ++-- crates/ui/src/docking/render/preview.rs | 8 ++++---- docs/ui-docking.md | 4 +++- 6 files changed, 38 insertions(+), 19 deletions(-) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 5e3c1ba79b..da5ae98c50 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -592,3 +592,20 @@ fn hidden_panels_leave_their_split_and_resizing_names_the_layout_path() { let Some(Node::Split { size: SplitSize::FixedFirst(200.0), second, .. }) = &d.layout.root else { panic!("{:?}", d.layout) }; assert!(matches!(**second, Node::Split { size, .. } if size != SplitSize::Ratio(0.5))); } + +#[test] +fn a_hidden_floating_window_does_not_cover_dock_targets() { + // Window 5 covers the column's seam at x 150..240 until it is hidden. + let mut layout = workspace(); + layout.floating = vec![Floating::single(vec![5], 0, [150.0, 250.0, 200.0, 150.0]), Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0])]; + let mut d = Driver::new(layout, Profile::Dock); + d.hide = Hide::Keep; + d.content.keep = vec![2, 3, 4, 8]; + d.step(vec![]); + d.step(vec![]); + d.drag(d.title(8).center(), pos2(200.0, 309.0)); + let Some(Node::Split { first, .. }) = &d.layout.root else { panic!("{:?}", d.layout.root) }; + let Node::Dock { columns, .. } = &**first else { panic!("{first:?}") }; + let groups: Vec> = columns[0].groups.iter().map(|g| g.panels.clone()).collect(); + assert_eq!(groups, vec![vec![2, 3], vec![8], vec![4]]); +} diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index 053732bb0f..c2eb05f488 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -112,7 +112,9 @@ impl DockArea<'_, P> { /// The egui layer of a floating window in the area `id`; `None` for an empty window. Of two /// layers, the later in `ctx.memory(|m| m.layer_ids())` is drawn on top, and - /// `ctx.memory(|m| m.area_rect(layer.id))` is the window's rect. + /// `ctx.memory(|m| m.area_rect(layer.id))` is the window's rect. A window the area does not + /// draw (all its panels hidden, or a frame maximized) keeps its last rect there: check + /// `ctx.memory(|m| m.areas().is_visible(&layer))` before treating it as covering anything. pub fn floating_layer(id: Id, window: &Floating

) -> Option { window.panels().next().map(|first| LayerId::new(Order::Middle, id.with(("floating", first)))) } diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 96936f7af8..c5e88e4b26 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -412,15 +412,13 @@ impl Renderer<'_, P> { }); } - /// Whether a floating window (other than the one following the pointer) or a host overlay - /// covers `pointer`. Covered dock targets take nothing. - fn dock_covered(&self, ctx: &Context, pointer: Pos2, moving: Option<&P>) -> bool { + /// Whether a floating window drawn this frame (other than the one following the pointer) + /// or a host overlay covers `pointer`. Covered dock targets take nothing. + fn dock_covered(&self, pointer: Pos2, moving: Option<&P>) -> bool { self.blockers.iter().any(|r| r.contains(pointer)) || self.iconic.covers(pointer) - || self.layout.floating.iter().any(|window| { - let Some(first) = window.panels().next() else { return false }; - !moving.is_some_and(|p| window.contains(p)) - && ctx.memory(|m| m.area_rect(self.id.with(("floating", first)))).is_some_and(|r| r.contains(pointer)) + || self.frame.stacks.iter().any(|window| { + window.window.contains(pointer) && !moving.is_some_and(|p| window.groups.iter().any(|(panels, ..)| panels.contains(p))) }) } @@ -451,9 +449,9 @@ impl Renderer<'_, P> { /// The dock target a whole group or column drag would take at `pointer`, with the action /// and its line. A target that leaves the layout unchanged is a no-op: `None` action. - pub(super) fn dock_group_proposal(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2) -> Option<(Option>, Rect)> { + pub(super) fn dock_group_proposal(&self, drag: &GroupDrag

, pointer: Pos2) -> Option<(Option>, Rect)> { let moving = (drag.gesture == GroupGesture::Window).then_some(&drag.panel); - if self.dock_covered(ctx, pointer, moving) { + if self.dock_covered(pointer, moving) { return None; } let candidates = self.dock_candidates(); @@ -465,8 +463,8 @@ impl Renderer<'_, P> { /// The dock target a single tab drag would take: a new group, column or dock of that panel. /// A panel alone in its group takes the group's state to a new dock; one that shares its /// group leaves the other tabs behind (P6). - pub(super) fn dock_tab_proposal(&self, ctx: &Context, panel: &P, pointer: Pos2) -> Option<(Option>, Rect)> { - if self.dock_covered(ctx, pointer, None) { + pub(super) fn dock_tab_proposal(&self, panel: &P, pointer: Pos2) -> Option<(Option>, Rect)> { + if self.dock_covered(pointer, None) { return None; } let candidates = self.dock_candidates(); diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 1e46077f64..f0045e237d 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -310,8 +310,8 @@ impl Renderer<'_, P> { /// Release of a title bar drag. The window already sits where it was dragged; a dock or /// group target docks or merges every group in it, else hosts get the release in /// `group_drop`. - pub(super) fn drop_window(&mut self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { - if !float_only && let Some((action, _)) = self.dock_group_proposal(ctx, drag, pointer) { + pub(super) fn drop_window(&mut self, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + if !float_only && let Some((action, _)) = self.dock_group_proposal(drag, pointer) { self.output.actions.extend(action); return; } diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index aff38e9571..4feed8b9c8 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -66,7 +66,7 @@ impl Renderer<'_, P> { } let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return }; match drag.gesture { - GroupGesture::Window => self.drop_window(ctx, &drag, pointer, float_only), + GroupGesture::Window => self.drop_window(&drag, pointer, float_only), GroupGesture::Group | GroupGesture::Column => self.drop_group(ctx, &drag, pointer, float_only), } } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { @@ -113,7 +113,7 @@ impl Renderer<'_, P> { if pointer.distance(drag.origin) < 2.0 { return; } - if !float_only && let Some((action, _)) = self.dock_group_proposal(ctx, drag, pointer) { + if !float_only && let Some((action, _)) = self.dock_group_proposal(drag, pointer) { self.output.actions.extend(action); return; } @@ -162,7 +162,7 @@ impl Renderer<'_, P> { if float_only { return; } - if let Some((action, line)) = self.dock_group_proposal(ctx, drag, pointer) { + if let Some((action, line)) = self.dock_group_proposal(drag, pointer) { if action.is_some() { self.paint_dock_line(ctx, line); } @@ -214,7 +214,7 @@ impl Renderer<'_, P> { } return; } - let dock = if float_only || gone { None } else { self.dock_tab_proposal(ctx, &drag.panel, pointer) }; + let dock = if float_only || gone { None } else { self.dock_tab_proposal(&drag.panel, pointer) }; if let Some((action, line)) = dock { if released { cancel_drag::

(ctx, self.id); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 122f0bae86..df9f3f6d09 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -274,7 +274,9 @@ grips, resize edges and dividers. It is always compiled, so an app can return it `DockArea::hit_id(id, &hit)` is the egui widget id of a control, for tests and automation that focus it or read its response. `DockArea::floating_layer(id, &window)` is a floating window's egui layer: compare its place in `memory.layer_ids()` with another layer to tell whether the -window covers it, and read its rect with `memory.area_rect(layer.id)`. +window covers it, and read its rect with `memory.area_rect(layer.id)`. A window the area does not +draw (its panels hidden, or a frame maximized) keeps its last rect there, so check +`memory.areas().is_visible(&layer)` first. The `testing` feature adds `docking::testing::DockDriver`. It runs a `DockArea` in a headless egui context with real pointer and key events, and applies the actions each frame emits. From 815d6480163752340b1c500672dca632d3ab8a09 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:45:18 +0000 Subject: [PATCH 59/94] docking: split divider hits name the layout path while panels are hidden A split's handle id and its Hit::Divider use the layout path that ResizeSplit takes, also when hiding panels collapses a split in the drawn tree. --- crates/ui/src/docking/floating_tests.rs | 5 ++++- crates/ui/src/docking/render/mod.rs | 6 ++++-- crates/ui/src/docking/surface.rs | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index da5ae98c50..76175b2cef 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -586,7 +586,10 @@ fn hidden_panels_leave_their_split_and_resizing_names_the_layout_path() { d.step(vec![]); d.step(vec![]); assert_eq!(d.tab(1).map(|r| r.left()), Some(0.0), "the hidden frame's space goes to the others"); - let divider = d.response(Id::new(AREA).with(("split", &Vec::::new()))).unwrap().center(); + // Hits and widget ids name the split by its layout path, as `ResizeSplit` does. + let hit = Hit::Divider(Divider::Split(vec![true])); + assert!(DockArea::::hit_rects(&d.ctx, Id::new(AREA)).iter().any(|(h, _)| *h == hit), "the hits name the layout path"); + let divider = d.response(DockArea::::hit_id(Id::new(AREA), &hit)).unwrap().center(); let out = d.hold(divider, divider + vec2(0.0, 60.0)); assert!(out.actions.iter().any(|a| matches!(a, Action::ResizeSplit { path, .. } if path == &vec![true])), "{:?}", out.actions); let Some(Node::Split { size: SplitSize::FixedFirst(200.0), second, .. }) = &d.layout.root else { panic!("{:?}", d.layout) }; diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 167f68d908..869c8d0cb4 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -95,8 +95,10 @@ impl Renderer<'_, P> { path.pop(); // The divider's inner-edge hit margin must win over child scrollbars, just // as accordion dividers win over the adjacent panel's content. + // Named by its layout path, which `ResizeSplit` takes and hits report. + let layout_path = self.original_path(path); let response = ResizeHandle::new( - self.id.with(("split", &*path)), + self.id.with(("split", &layout_path)), *axis, split.divider, &self.style.resize_label, @@ -108,7 +110,7 @@ impl Renderer<'_, P> { if response.delta != 0.0 && let Some(size) = split.resized(*size, (split.first_size() + response.delta).clamp(lo, hi) - split.first_size(), 0.0) { - self.output.actions.push(Action::ResizeSplit { path: self.original_path(path), size }); + self.output.actions.push(Action::ResizeSplit { path: layout_path, size }); } } Node::Tabs { panels, active } => self.group(ui, panels, *active, false, rect, GroupKind::Frame), diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 36b037b3f6..234c7c4a98 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -863,7 +863,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { renderer.finish_group_drag(ui); renderer.finish_drag(ui.ctx()); renderer.report_flyout(ui.ctx()); - super::hits::record(ui.ctx(), self.id, &view, &renderer.owned_interactions); + super::hits::record(ui.ctx(), self.id, layout, &renderer.owned_interactions); record_tab_focus(ui.ctx(), self.id, layout, !renderer.output.actions.is_empty()); ui.ctx().data_mut(|d| d.insert_temp(float_space_key(self.id), renderer.float_space)); ui.ctx().data_mut(|d| d.insert_temp(self.id.with("owned-interactions"), renderer.owned_interactions)); From 91e8cf401e92775fc324e3d60c95805b26dd5312 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:46:31 +0000 Subject: [PATCH 60/94] docking: chrome_has_focus recognizes every control a Hit names It checks the same widget ids as hit_rects and hit_id, which adds icons and icon grips. --- crates/ui/src/docking/hits.rs | 10 ++++- crates/ui/src/docking/iconic_tests.rs | 16 ++++++++ crates/ui/src/docking/surface.rs | 59 ++------------------------- docs/ui-docking.md | 4 +- 4 files changed, 29 insertions(+), 60 deletions(-) diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index c2eb05f488..be32efae1c 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -120,8 +120,8 @@ impl DockArea<'_, P> { } } -/// Name the controls the renderer registered this frame and store their rects. -pub(super) fn record(ctx: &Context, area: Id, layout: &Layout

, owned: &[Id]) { +/// Every control the area `area` can draw for `layout`, by widget id. +pub(super) fn named(area: Id, layout: &Layout

) -> HashMap> { let mut names: HashMap> = HashMap::new(); let mut name = |hit: Hit

| { names.insert(DockArea::

::hit_id(area, &hit), hit); @@ -162,6 +162,12 @@ pub(super) fn record(ctx: nodes.push((first, first_path)); } } + names +} + +/// Name the controls the renderer registered this frame and store their rects. +pub(super) fn record(ctx: &Context, area: Id, layout: &Layout

, owned: &[Id]) { + let mut names = named(area, layout); let hits: Vec<(Hit

, Rect)> = owned.iter().filter_map(|id| Some((names.remove(id)?, ctx.read_response(*id)?.rect))).filter(|(_, rect)| rect.is_positive()).collect(); ctx.data_mut(|d| d.insert_temp(key(area), hits)); diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index a90cc2981c..b71ad9049b 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -371,3 +371,19 @@ fn an_icon_painted_in_code_replaces_the_initial_and_others_fall_back() { assert_eq!(initials.len(), 1, "only panel 2 draws its initial: {initials:?}"); assert!(two.contains(initials[0])); } + +#[test] +fn chrome_has_focus_covers_every_drawn_control() { + let mut layout = docked(&[&[1, 2], &[3]], true); + layout.floating.push(Floating::single(vec![5, 6], 0, [400.0, 100.0, 240.0, 200.0])); + let mut d = Driver::new(layout, Content); + d.settle(); + let hits = d.hits(); + assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Icon(_))), "{hits:?}"); + assert!(hits.iter().any(|(h, _)| matches!(h, Hit::IconGrip(_))), "{hits:?}"); + assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Resize(_, ResizeEdge::Left))), "{hits:?}"); + for (hit, _) in hits { + d.ctx.memory_mut(|m| m.request_focus(DockArea::::hit_id(d.id, &hit))); + assert!(DockArea::::new(d.id).chrome_has_focus(&d.ctx, &d.layout), "{hit:?}"); + } +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 234c7c4a98..dc1c2a873d 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -3,8 +3,8 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Color32, Context, FontId, Id, Pos2, Rect, Sense, Stroke, Ui, Vec2}; use super::{ - Action, DockError, DropTarget, Layout, Node, Permissions, - render::{RESIZE_HANDLES, Renderer}, + Action, DockError, DropTarget, Layout, Permissions, + render::Renderer, resize::AnchoredResize, }; @@ -701,60 +701,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { if layout.validate().is_err() || ctx.read_response(focused).is_none() { return false; } - let matches = |id: Id| id == focused; - let group = |panels: &[P]| { - panels.iter().any(|panel| matches(self.id.with(("tab", panel))) || matches(self.id.with(("overflow", panel)))) - || ["move-group", "drag-bar", "drag-border"].iter().any(|name| matches(self.id.with((*name, panels.first())))) - }; - for floating in &layout.floating { - if floating.groups.iter().any(|g| group(&g.panels)) - || floating.panels().next().is_some_and(|first| { - RESIZE_HANDLES.iter().any(|name| matches(self.id.with(("floating", first)).with(*name))) - || matches(self.id.with(("move-group", Some(first))).with("close")) - }) - || floating.groups.iter().any(|g| matches(self.id.with(("group-resize", g.panels.first())))) - { - return true; - } - } - let mut nodes = layout.root.as_ref().map(|root| vec![(root, Vec::::new())]).unwrap_or_default(); - while let Some((node, path)) = nodes.pop() { - match node { - Node::Tabs { panels, .. } if group(panels) => return true, - Node::Dock { columns, .. } - if columns.iter().flat_map(|c| c.groups.iter()).any(|g| { - group(&g.panels) - || ["column-bar", "column-collapse", "column-resize", "group-resize"] - .iter() - .any(|name| matches(self.id.with((*name, g.panels.first())))) - }) => - { - return true; - } - Node::Stack { entries } => { - if entries.iter().any(|entry| { - matches(self.id.with(("tab", &entry.panel))) - || matches(self.id.with(("collapse", &entry.panel))) - || matches(self.id.with(("stack-resize", &entry.panel))) - }) { - return true; - } - } - Node::Split { first, second, .. } => { - if matches(self.id.with(("split", &path))) { - return true; - } - let mut second_path = path.clone(); - second_path.push(true); - let mut first_path = path; - first_path.push(false); - nodes.push((second, second_path)); - nodes.push((first, first_path)); - } - _ => {} - } - } - false + super::hits::named(self.id, layout).contains_key(&focused) } /// Raise a panel's floating window (or open its flyout) on this frame. Apply Activate diff --git a/docs/ui-docking.md b/docs/ui-docking.md index df9f3f6d09..5ceb81fd4e 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -135,8 +135,8 @@ Builder options on `DockArea`: and the floating window ×. They hide controls only: a panel that stays `closable` still closes by the app's own Close items and commands. -`DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome rather than on a -panel body. Focus follows only the user's input: a tab keeps keyboard focus until a command or a +`DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome (any control a +`Hit` names) rather than on a panel body. Focus follows only the user's input: a tab keeps keyboard focus until a command or a workspace reset hides, closes or moves its panel, and then gives it up. A divider or a floating window's resize grip keeps keyboard focus after a pointer drag, so arrow keys resize it right away; its focus highlight shows once a key is pressed. Hovering focuses nothing. `begin_drag` hands a drag that started in the app's own chrome to the area. From 46f2ffd654fe8e99c9a7aa47538e7d5802454124 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:47:12 +0000 Subject: [PATCH 61/94] docking: a press in a group header focuses the shown panel Host widgets in the header, such as a menu button or the host's own tabs, focus the panel the way a press on its tab or body does. --- crates/ui/src/docking/group_tests.rs | 5 ++++- crates/ui/src/docking/render/group.rs | 6 +++++- crates/ui/src/docking/surface.rs | 3 ++- docs/ui-docking.md | 3 ++- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 059634b848..c87ab8f9f7 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -284,7 +284,10 @@ fn top_border_drags_the_group_and_the_menu_button_only_clicks() { assert!(held.group_drag.is_none()); let out = d.step(vec![button(menu + vec2(0.0, 200.0), false)]); assert!(out.actions.iter().all(|a| !matches!(a, Action::MoveGroup { .. } | Action::Move { .. } | Action::Float { .. })), "{:?}", out.actions); - d.click(menu); + // A press in the header focuses the group's shown panel, like a press on its tab. + let pressed = d.step(vec![Event::PointerMoved(menu), button(menu, true)]); + assert_eq!(pressed.focused, Some(3)); + d.step(vec![button(menu, false)]); assert_eq!(d.content.header_clicks, 1); let out = d.drag(over_tab, d.tab(1).center()); diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index bb313e1f47..83c24ea890 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -75,6 +75,10 @@ impl Renderer<'_, P> { let mut child = ui.new_child(UiBuilder::new().id(self.id.with(("header", selected))).max_rect(header)); child.set_clip_rect(header.intersect(ui.clip_rect())); self.content.group_header(&mut child, panels, selected, floating); + // A press in the header focuses the shown panel, as a press on its tab does. + if child.rect_contains_pointer(header) && child.input(|i| i.pointer.any_pressed()) { + self.output.focused = Some(selected.clone()); + } } // The drag bar keeps its reserved width: tabs overflow before it narrows. let bar_width = self.style.drag_bar_width.clamp(0.0, (strip.width() - header_width).max(0.0)); @@ -176,7 +180,7 @@ impl Renderer<'_, P> { } let active = response.has_focus() || response.hovered(); if movable { - // A grip mark at rest, centerd in the bar's reserved width beside the header. + // A grip mark at rest, centered in the bar's reserved width beside the header. let grip = if self.style.right_to_left { Rect::from_min_max(hit.min, pos2((hit.left() + self.style.drag_bar_width).min(hit.right()), hit.bottom())) } else { diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index dc1c2a873d..ff5789a02d 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -218,7 +218,8 @@ pub struct DockOutput

{ pub actions: Vec>, pub error: Option, /// The panel the user focused this frame: a clicked tab or menu entry, a drop, or a press - /// of any pointer button in a panel body, stripless panels included. Only user input sets + /// of any pointer button in a panel body (stripless panels included) or in a group header, + /// which focuses the group's shown panel. Only user input sets /// it; [`DockArea::raise_panel`] and host commands do not. pub focused: Option

, /// Whole-floating-group gesture identity; host may display its own group drop preview. diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 5ceb81fd4e..a7586f9e71 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -112,7 +112,8 @@ survives. `DockOutput` also has: - `focused`: the panel the user focused this frame: a clicked tab, a drop, or a press of any - pointer button in a panel body, bare and protected panels included. Commands, `raise_panel` and + pointer button in a panel body (bare and protected panels included) or in the group header, + which focuses the group's shown panel. Commands, `raise_panel` and workspace resets never set it; a host that tracks the last focused panel clears it when a reset or command hides, closes or moves that panel. - `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (Frame) and From 72a0a4dc78caf00c0b2a9c6811d65193932243d4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:51:13 +0000 Subject: [PATCH 62/94] docking: rustfmt --- crates/ui/src/docking/render/dock.rs | 8 +++++--- crates/ui/src/docking/surface.rs | 6 +----- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index c5e88e4b26..83696661e9 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -417,9 +417,11 @@ impl Renderer<'_, P> { fn dock_covered(&self, pointer: Pos2, moving: Option<&P>) -> bool { self.blockers.iter().any(|r| r.contains(pointer)) || self.iconic.covers(pointer) - || self.frame.stacks.iter().any(|window| { - window.window.contains(pointer) && !moving.is_some_and(|p| window.groups.iter().any(|(panels, ..)| panels.contains(p))) - }) + || self + .frame + .stacks + .iter() + .any(|window| window.window.contains(pointer) && !moving.is_some_and(|p| window.groups.iter().any(|(panels, ..)| panels.contains(p)))) } /// Dock targets, with the new-dock bands along the docked area's left and right edges that diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index ff5789a02d..c8fdd84b24 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -2,11 +2,7 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Color32, Context, FontId, Id, Pos2, Rect, Sense, Stroke, Ui, Vec2}; -use super::{ - Action, DockError, DropTarget, Layout, Permissions, - render::Renderer, - resize::AnchoredResize, -}; +use super::{Action, DockError, DropTarget, Layout, Permissions, render::Renderer, resize::AnchoredResize}; /// Horizontal room around a tab's label, both when measuring its natural width and when cutting it. pub(super) const TAB_PADDING: f32 = 24.0; From 07585888d6db7033099e915f5ad2317eec38c40d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:51:38 +0000 Subject: [PATCH 63/94] docking: floating windows resize from the top edge and corners A resizable FloatingFrame keeps a 4 pt band above its contents for the Top, TopLeft and TopRight handles, so they take no title bar moves or button clicks. They keep the opposite edges in place, respect the size limits and the screen, take arrow keys when focused, and have hit ids. Moves carry the whole frame rect, band included. Ported from #189. Co-authored-by: filipessmedeiros-collab <343926472+filipessmedeiros-collab@users.noreply.github.com> --- crates/ui/src/docking/chrome.rs | 36 ++++++++++++++++-------- crates/ui/src/docking/floating_tests.rs | 33 +++++++++++++++++++--- crates/ui/src/docking/group_tests.rs | 2 +- crates/ui/src/docking/hits.rs | 17 ++++++++++- crates/ui/src/docking/iconic_tests.rs | 2 +- crates/ui/src/docking/render/floating.rs | 24 +++++++++------- crates/ui/src/docking/resize.rs | 30 +++++++++----------- crates/ui/src/docking/tests.rs | 2 +- crates/ui/src/panes/tests.rs | 2 +- docs/ui-docking.md | 4 +++ 10 files changed, 104 insertions(+), 48 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index 3d445e82b0..a29f5afc49 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -15,7 +15,12 @@ use super::{DockStyle, PanelLimits, resize::AnchoredResize}; pub const TITLE_HEIGHT: f32 = 14.0; /// Names of the resize handles, appended to the frame id: `id.with(name)`. -pub const RESIZE_HANDLES: [&str; 5] = ["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left"]; +pub const RESIZE_HANDLES: [&str; 8] = + ["resize", "resize-left", "resize-right", "resize-bottom", "resize-bottom-left", "resize-top", "resize-top-left", "resize-top-right"]; + +/// Height of the top resize band of a resizable frame. The frame's contents start below it, so +/// the band takes no moves or clicks from a title bar. +pub const RESIZE_BAND: f32 = 4.0; /// Colors and font of the frame and title bar. #[derive(Clone, Debug)] @@ -51,9 +56,12 @@ impl ChromeStyle { } } -/// Resize handle hit rects and the edges they move: both sides, the bottom and both bottom -/// corners. The top edge belongs to the title bar. -fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 5] { +/// Resize handle hit rects and the edges they move: every side and corner. The top handles +/// fill the band above the contents; the others lie over the contents' edges. +fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 8] { + let band_bottom = (rect.top() + RESIZE_BAND).min(rect.bottom()); + let left_corner = (rect.left() + 12.0).min(rect.right()); + let right_corner = (rect.right() - 12.0).max(rect.left()); [ ("resize", Rect::from_min_max((rect.max - vec2(12.0, 12.0)).max(rect.min), rect.max), vec2(1.0, 1.0)), ( @@ -73,12 +81,12 @@ fn handles(rect: Rect) -> [(&'static str, Rect, Vec2); 5] { ), ( "resize-bottom-left", - Rect::from_min_max( - pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), - pos2((rect.left() + 12.0).min(rect.right()), rect.bottom()), - ), + Rect::from_min_max(pos2(rect.left(), (rect.bottom() - 12.0).max(rect.top())), pos2(left_corner, rect.bottom())), vec2(-1.0, 1.0), ), + ("resize-top", Rect::from_min_max(pos2(left_corner, rect.top()), pos2(right_corner, band_bottom)), vec2(0.0, -1.0)), + ("resize-top-left", Rect::from_min_max(rect.min, pos2(left_corner, band_bottom)), vec2(-1.0, -1.0)), + ("resize-top-right", Rect::from_min_max(pos2(right_corner, rect.top()), pos2(rect.right(), band_bottom)), vec2(1.0, -1.0)), ] } @@ -118,7 +126,8 @@ impl<'a> FloatingFrame<'a> { self } - /// Size limits of a resize. The frame itself is drawn at the given rect. + /// Size limits of a resize, top resize band included. The frame itself is drawn at the + /// given rect. pub fn limits(mut self, limits: PanelLimits) -> Self { self.limits = limits; self @@ -139,7 +148,8 @@ impl<'a> FloatingFrame<'a> { LayerId::new(Order::Middle, id) } - /// Draw the frame, then `add_contents` with the frame's rect, then the outline and handles. + /// Draw the frame, then `add_contents` with the rect for its contents (the frame's rect below + /// the top resize band when resizable), then the outline and handles. pub fn show(self, ctx: &Context, style: &ChromeStyle, add_contents: impl FnOnce(&mut Ui, Rect) -> R) -> FrameResponse { let bounds = self.bounds.unwrap_or_else(|| ctx.content_rect()); let rect = clamp(self.rect, bounds); @@ -155,7 +165,9 @@ impl<'a> FloatingFrame<'a> { ui.set_min_size(rect.size()); ui.allocate_rect(rect, Sense::hover()); ui.painter().rect_filled(rect, 0.0, style.background); - let inner = add_contents(ui, rect); + let contents = + if self.resizable { Rect::from_min_max(pos2(rect.left(), (rect.top() + RESIZE_BAND).min(rect.bottom())), rect.max) } else { rect }; + let inner = add_contents(ui, contents); ui.painter().rect_stroke(rect, 0.0, style.stroke, StrokeKind::Outside); let (resized, resize_started, handles) = if self.resizable { self.handles(ui, rect, bounds, style) } else { (None, None, Vec::new()) }; FrameResponse { inner, rect, layer: Self::layer(self.id), resized, resize_started, handles } @@ -167,7 +179,7 @@ impl<'a> FloatingFrame<'a> { let mut resized = None; let mut started = None; let mut responses = Vec::new(); - let limits = PanelLimits { min: self.limits.min.max(vec2(40.0, TITLE_HEIGHT + 20.0)).min(self.limits.max), ..self.limits }; + let limits = PanelLimits { min: self.limits.min.max(vec2(40.0, RESIZE_BAND + TITLE_HEIGHT + 20.0)).min(self.limits.max), ..self.limits }; let canceled = ui.input(|input| input.key_pressed(Key::Escape) || !input.focused); for (name, handle, direction) in handles(rect) { if !super::targets::usable(handle) { diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 76175b2cef..1ecdb73026 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -289,7 +289,7 @@ fn floating_stack_seams_and_bands_insert_groups() { let divider = d.response(DockArea::hit_id(Id::new(AREA), &Hit::Divider(Divider::Group(5u32)))).unwrap().center(); d.drag(divider, divider + vec2(0.0, 40.0)); let heights: Vec<_> = window_of(&d.layout, 5).unwrap().groups.iter().map(|g| g.height.unwrap()).collect(); - assert!((heights[0] - 181.5).abs() < 2.0 && (heights[1] - 101.5).abs() < 2.0, "{heights:?}"); + assert!((heights[0] - 179.5).abs() < 2.0 && (heights[1] - 99.5).abs() < 2.0, "{heights:?}"); } #[test] @@ -456,7 +456,7 @@ fn hide_panels_keeps_protected_panels_and_the_except_set() { } // A window keeps its rect with its hidden groups left out. d.step(vec![]); - assert_eq!(d.title(6).min, pos2(300.0, 80.0)); + assert_eq!(d.title(6).min, pos2(300.0, 84.0), "below the resize band"); } #[test] @@ -468,7 +468,7 @@ fn native_window_falls_back_in_window_when_viewports_are_embedded() { assert!(d.ctx.embed_viewports()); let out = d.step(vec![]); assert!(out.actions.is_empty(), "{out:?}"); - assert_eq!(d.title(5).min, pos2(300.0, 80.0)); + assert_eq!(d.title(5).min, pos2(300.0, 84.0)); assert_eq!(d.layout, layout); } @@ -513,7 +513,7 @@ fn native_window_close_returns_the_group_to_its_in_window_rect() { assert_eq!(d.layout.floating[0].rect, [300.0, 80.0, 240.0, 300.0]); d.step(vec![]); d.step(vec![]); - assert_eq!(d.title(5).min, pos2(300.0, 80.0)); + assert_eq!(d.title(5).min, pos2(300.0, 84.0)); } #[test] @@ -612,3 +612,28 @@ fn a_hidden_floating_window_does_not_cover_dock_targets() { let groups: Vec> = columns[0].groups.iter().map(|g| g.panels.clone()).collect(); assert_eq!(groups, vec![vec![2, 3], vec![8], vec![4]]); } + +#[test] +fn top_edges_resize_from_the_band_above_the_title_bar() { + // W2 holds [8] at [560, 300, 200, 200]; each top handle keeps the opposite edges. + let area = Id::new(AREA); + for (edge, by, expected) in [ + (ResizeEdge::Top, vec2(0.0, -40.0), [560.0, 260.0, 200.0, 240.0]), + (ResizeEdge::TopLeft, vec2(-30.0, 20.0), [530.0, 320.0, 230.0, 180.0]), + (ResizeEdge::TopRight, vec2(20.0, -10.0), [560.0, 290.0, 220.0, 210.0]), + ] { + let mut d = Driver::new(workspace(), Profile::Dock); + let handle = d.response(DockArea::hit_id(area, &Hit::Resize(8u32, edge))).unwrap(); + assert_eq!(handle.bottom(), d.title(8).top(), "{edge:?} lies above the title bar"); + d.drag(handle.center(), handle.center() + by); + assert_eq!(window_of(&d.layout, 8).unwrap().rect, expected, "{edge:?}"); + } + // The title bar still moves the window, and arrow keys move the focused top edge. + let mut d = Driver::new(workspace(), Profile::Dock); + let title = d.title(8); + d.drag(pos2(title.center().x, title.top() + 1.0), pos2(title.center().x - 50.0, title.top() + 1.0)); + assert_eq!(window_of(&d.layout, 8).unwrap().rect, [510.0, 300.0, 200.0, 200.0]); + d.ctx.memory_mut(|m| m.request_focus(DockArea::hit_id(area, &Hit::Resize(8u32, ResizeEdge::Top)))); + d.step(vec![Event::Key { key: egui::Key::ArrowUp, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + assert_eq!(window_of(&d.layout, 8).unwrap().rect, [510.0, 292.0, 200.0, 208.0]); +} diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index c87ab8f9f7..bface8f234 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -556,7 +556,7 @@ fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() { let mut d = Driver::new(layout); let from = d.rect("drag-bar", 6).center(); let out = d.drag(from, pos2(700.0, 300.0)); - assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 191.5]) })), "{:?}", out.actions); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 189.5]) })), "{:?}", out.actions); assert_eq!(d.layout.floating.len(), 2); assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![5], 0)]); assert_eq!(d.layout.floating[1].groups, vec![Group::new(vec![6, 7], 1)]); diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index be32efae1c..e3869fe438 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -49,6 +49,9 @@ pub enum ResizeEdge { Bottom, BottomLeft, BottomRight, + Top, + TopLeft, + TopRight, } /// A divider that resizes what is on either side of it. @@ -104,6 +107,9 @@ impl DockArea<'_, P> { ResizeEdge::Right => RESIZE_HANDLES[2], ResizeEdge::Bottom => RESIZE_HANDLES[3], ResizeEdge::BottomLeft => RESIZE_HANDLES[4], + ResizeEdge::Top => RESIZE_HANDLES[5], + ResizeEdge::TopLeft => RESIZE_HANDLES[6], + ResizeEdge::TopRight => RESIZE_HANDLES[7], }; id.with(("floating", p)).with(name) } @@ -146,7 +152,16 @@ pub(super) fn named(area: ] { name(hit); } - for edge in [ResizeEdge::BottomRight, ResizeEdge::Left, ResizeEdge::Right, ResizeEdge::Bottom, ResizeEdge::BottomLeft] { + for edge in [ + ResizeEdge::BottomRight, + ResizeEdge::Left, + ResizeEdge::Right, + ResizeEdge::Bottom, + ResizeEdge::BottomLeft, + ResizeEdge::Top, + ResizeEdge::TopLeft, + ResizeEdge::TopRight, + ] { name(Hit::Resize(p(), edge)); } } diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index b71ad9049b..d1008d3efb 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -312,7 +312,7 @@ fn hit_rects_cover_every_gesture_source() { assert!(kinds(kind) > 0, "{name}: {hits:?}"); } assert!(hits.iter().any(|(h, _)| matches!(h, Hit::Divider(Divider::Stack(10))))); - assert_eq!(hits.iter().filter(|(h, _)| matches!(h, Hit::Resize(..))).count(), 5); + assert_eq!(hits.iter().filter(|(h, _)| matches!(h, Hit::Resize(..))).count(), 8); for (hit, rect) in hits.iter().filter(|(h, _)| !matches!(h, Hit::Overflow(_) | Hit::Collapse(_) | Hit::StackToggle(_) | Hit::Close(_))) { let mut d = DockDriver::new(layout.clone(), Content); let from = rect.center(); diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index f0045e237d..25ab410172 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -3,7 +3,7 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Context, Id, Key, Pos2, Rect, Ui, pos2, vec2}; use super::{GroupKind, Renderer, clamp_float, node_limits}; -use crate::docking::chrome::{ChromeStyle, FloatingFrame, TitleBar}; +use crate::docking::chrome::{ChromeStyle, FloatingFrame, RESIZE_BAND, TitleBar}; use crate::docking::{Action, DropProposal, Floating, Group, GroupDrag, GroupGesture, Node, PanelLimits, Placement, Target}; use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; @@ -43,7 +43,10 @@ impl Renderer<'_, P> { /// Size limits of a floating window: its title bar, each group's strip and the bodies of /// the groups that are not minimized. pub(super) fn window_limits(&self, window: &Floating

) -> PanelLimits { - let mut limits = PanelLimits { min: vec2(0.0, self.style.title_height), max: vec2(1_000_000.0, self.style.title_height) }; + // A movable window is resizable, with a resize band above its title bar. + let band = if window.panels().all(|panel| self.permissions(panel).movable) { RESIZE_BAND } else { 0.0 }; + let chrome = band + self.style.title_height; + let mut limits = PanelLimits { min: vec2(0.0, chrome), max: vec2(1_000_000.0, chrome) }; for (index, group) in window.groups.iter().enumerate() { let policy = node_limits(&Node::Tabs { panels: group.panels.clone(), active: 0 }, self.style, &*self.content); let gap = if index > 0 { GAP } else { 0.0 }; @@ -62,7 +65,7 @@ impl Renderer<'_, P> { let [x, y, width, height] = window.rect; let limits = self.window_limits(window); let size = vec2(width, height).max(limits.min).min(limits.max); - let rect = Rect::from_min_size(pos2(x, y), size); + let rect = crate::docking::chrome::clamp(Rect::from_min_size(pos2(x, y), size), screen); let id = self.id.with(("floating", first)); if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { ctx.move_to_top(FloatingFrame::layer(id)); @@ -73,7 +76,7 @@ impl Renderer<'_, P> { let response = FloatingFrame::new(id, rect).bounds(screen).limits(limits).resizable(movable).resize_label(&resize_label).show( ctx, &style, - |ui, rect| self.window_contents(ui, window, rect, &style), + |ui, contents| self.window_contents(ui, window, contents, rect, &style), ); for handle in &response.handles { self.register_interaction(ctx, handle.id); @@ -94,12 +97,13 @@ impl Renderer<'_, P> { } } - /// The title bar, then the stacked groups below it. - pub(super) fn window_contents(&mut self, ui: &mut Ui, window: &Floating

, rect: Rect, style: &ChromeStyle) { - let title = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + self.style.title_height).min(rect.bottom()))); - self.title_bar(ui, window, title, rect, style); - let body = Rect::from_min_max(pos2(rect.left(), title.bottom()), rect.max); - self.floating_stack(ui, &window.groups, body, rect); + /// The title bar, then the stacked groups below it, in `contents`. Moves carry the whole + /// `frame`, resize band included. + fn window_contents(&mut self, ui: &mut Ui, window: &Floating

, contents: Rect, frame: Rect, style: &ChromeStyle) { + let title = Rect::from_min_max(contents.min, pos2(contents.right(), (contents.top() + self.style.title_height).min(contents.bottom()))); + self.title_bar(ui, window, title, frame, style); + let body = Rect::from_min_max(pos2(contents.left(), title.bottom()), contents.max); + self.floating_stack(ui, &window.groups, body, frame); } /// Drag moves the whole window live, double-click minimizes or expands every group, × diff --git a/crates/ui/src/docking/resize.rs b/crates/ui/src/docking/resize.rs index 48e50f4e52..24d62c2983 100644 --- a/crates/ui/src/docking/resize.rs +++ b/crates/ui/src/docking/resize.rs @@ -81,26 +81,22 @@ mod tests { let start = Rect::from_min_max(pos2(100.0, 80.0), pos2(400.0, 300.0)); let viewport = Rect::from_min_max(Pos2::ZERO, pos2(800.0, 600.0)); let limits = PanelLimits { min: vec2(160.0, 120.0), max: vec2(500.0, 400.0) }; - for direction in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0)] { - let edge = pos2(if direction.x < 0.0 { start.left() } else { start.right() }, start.bottom()); + for direction in + [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(0.0, -1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0)] + { + let edge = + pos2(if direction.x < 0.0 { start.left() } else { start.right() }, if direction.y < 0.0 { start.top() } else { start.bottom() }); let pointer = edge + vec2(2.0, -3.0); let resize = AnchoredResize::new(start, pointer, direction).unwrap(); let rect = resize.rect(pointer + vec2(20.0, 25.0), viewport, limits).unwrap(); - assert_eq!(rect.top(), start.top()); - if direction.x < 0.0 { - assert_eq!(rect.right(), start.right()); - assert_eq!(rect.left(), start.left() + 20.0); - } else { - assert_eq!(rect.left(), start.left()); - } - if direction.x > 0.0 { - assert_eq!(rect.right(), start.right() + 20.0); - } - if direction.y > 0.0 { - assert_eq!(rect.bottom(), start.bottom() + 25.0); - } else { - assert_eq!(rect.bottom(), start.bottom()); - } + // A moving edge follows the pointer; every other edge stays. + let moved = |d: f32, lo: f32, hi: f32, by: f32| match d { + d if d < 0.0 => (lo + by, hi), + d if d > 0.0 => (lo, hi + by), + _ => (lo, hi), + }; + assert_eq!((rect.left(), rect.right()), moved(direction.x, start.left(), start.right(), 20.0), "{direction:?}"); + assert_eq!((rect.top(), rect.bottom()), moved(direction.y, start.top(), start.bottom(), 25.0), "{direction:?}"); } } diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index e752bb5141..2a111b82c3 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1420,7 +1420,7 @@ fn collapsed_floating_height_cap_does_not_disable_keyboard_width_resizing() { } ctx.memory_mut(|memory| memory.request_focus(id)); frame(vec![Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); - assert_eq!(layout.floating[0].rect, [80.0, 70.0, 308.0, 40.0]); + assert_eq!(layout.floating[0].rect, [80.0, 70.0, 308.0, 44.0]); } #[test] diff --git a/crates/ui/src/panes/tests.rs b/crates/ui/src/panes/tests.rs index e8ab8527b3..6d449e66da 100644 --- a/crates/ui/src/panes/tests.rs +++ b/crates/ui/src/panes/tests.rs @@ -189,7 +189,7 @@ fn title_dragged_out_floats_and_a_drop_near_an_edge_docks() { vec![PaneRequest::Place(Pane::Styles, Place::Floating), PaneRequest::FloatRect(Pane::Styles, [360.0, 112.0, 270.0, 480.0])], "floats under the pointer, clamped to the window" ); - assert_eq!(title(&h, Pane::Styles).min, pos2(360.0, 112.0)); + assert_eq!(title(&h, Pane::Styles).min, pos2(360.0, 116.0)); // Dropped within 32 pt of the right edge: docked at End. h.state_mut().log.clear(); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index a7586f9e71..76423b13b6 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -178,6 +178,10 @@ A flyout fits its content the same way, without the title bar. - A tab drags one panel. A group's drag bar (the space beside its tabs) or its top border drags the whole group. A column bar drags a column. A floating window's title bar drags the window. +- A movable floating window resizes from every edge and corner. The top edge and corners are a + 4 pt band above the title bar (`chrome::RESIZE_BAND`), so they take no moves and no clicks on + the title bar's buttons. A resize keeps the opposite edges in place and stays within the size + limits and the screen. A focused resize handle moves its edge 8 pt per arrow key. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. - Double-click a tab or drag bar to minimize a group to its strip. From 95d5cddb5ffeecccdaeaeaeebdfffe3b18507fd9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:07:24 +0000 Subject: [PATCH 64/94] docking: a canvas that accepts splits stays protected Hiding panels and dropping the tab strip tested for exactly Permissions::PROTECTED, so a canvas set up as the docs describe (accepts_splits on) was hidden and got a tab strip. Permissions::is_protected decides from what the panel allows. --- crates/ui/src/docking/floating_tests.rs | 25 +++++++++++++++++++++++-- crates/ui/src/docking/model.rs | 6 ++++++ crates/ui/src/docking/render/frame.rs | 4 ++-- crates/ui/src/docking/render/mod.rs | 2 +- 4 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 1ecdb73026..8501588862 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -48,17 +48,25 @@ fn workspace() -> Layout { struct Content { native: bool, keep: Vec, + /// Canvas 0 accepts side splits, as an app that opens panels beside it does. + beside: bool, + drawn: Vec, } impl DockContent for Content { - fn body(&mut self, ui: &mut egui::Ui, _: &u32) { + fn body(&mut self, ui: &mut egui::Ui, panel: &u32) { + self.drawn.push(*panel); ui.label("Body"); } fn logical_label(&self, panel: &u32) -> String { format!("Panel {panel}") } fn permissions(&self, panel: &u32) -> Permissions { - if *panel == 0 { Permissions::PROTECTED } else { Permissions::default() } + match *panel { + 0 if self.beside => Permissions { accepts_splits: true, ..Permissions::PROTECTED }, + 0 => Permissions::PROTECTED, + _ => Permissions::default(), + } } fn allow_native(&self, _: &u32) -> bool { self.native @@ -459,6 +467,19 @@ fn hide_panels_keeps_protected_panels_and_the_except_set() { assert_eq!(d.title(6).min, pos2(300.0, 84.0), "below the resize band"); } +#[test] +fn a_canvas_that_accepts_splits_is_still_protected() { + let mut d = Driver::new(workspace(), Profile::Dock); + d.content.beside = true; + d.hide = Hide::All; + d.step(vec![]); + d.content.drawn.clear(); + d.step(vec![]); + assert_eq!(d.content.drawn, vec![0], "hiding every panel keeps the canvas"); + assert!(d.tab(0).is_none()); + assert!(d.response(DockArea::::hit_id(Id::new(AREA), &Hit::DragBar(0))).is_none()); +} + #[test] fn native_window_falls_back_in_window_when_viewports_are_embedded() { let mut layout = workspace(); diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 3ca0c100c4..e79bf09680 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -346,6 +346,12 @@ impl Permissions { /// uses `Permissions { accepts_splits: true, ..Permissions::PROTECTED }`. pub const PROTECTED: Self = Self { movable: false, floatable: false, closable: false, accepts_tabs: false, accepts_splits: false }; + /// A canvas: it can neither move, close nor take tabs. `accepts_splits` and `floatable` + /// do not matter, so a canvas that opens panels beside it still counts. + pub fn is_protected(self) -> bool { + !self.movable && !self.closable && !self.accepts_tabs + } + /// Lock Workspace: nothing moves, floats or closes; tab and split drops keep their policy. /// [`super::Workspace::apply`] applies this when the workspace is locked; an application /// with a global lock preference applies it in its own permissions callback. diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index 0296daf6ff..8b90fe9963 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -6,7 +6,7 @@ use egui::{Context, Pos2, Rect, pos2, vec2}; use super::{GroupKind, Renderer, floating::StackHit, group::TabGroup}; use crate::docking::{ - Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Permissions, Profile, Zone, + Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Profile, Zone, dock_model::{Place, node_at}, }; @@ -29,7 +29,7 @@ pub(in crate::docking) fn view<'a, P: Clone + Eq + Hash>( hide: HidePanels<'_, P>, content: &dyn DockContent

, ) -> (Cow<'a, Layout

>, FrameState

) { - let protected = |p: &P| content.permissions(p) == Permissions::PROTECTED; + let protected = |p: &P| content.permissions(p).is_protected(); let hidden = |p: &P| match hide { HidePanels::None => false, HidePanels::All => !protected(p), diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 869c8d0cb4..3d579f671f 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -231,7 +231,7 @@ impl Renderer<'_, P> { /// A lone protected or bare panel draws no tab strip and no drag bar. pub(in crate::docking) fn stripless

(panels: &[P], content: &dyn DockContent

) -> bool { match panels { - [panel] => content.permissions(panel) == Permissions::PROTECTED || content.bare(panel), + [panel] => content.permissions(panel).is_protected() || content.bare(panel), _ => false, } } From 37374d06c0c072348b7d6c63dabdb86458c6be0c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:08:51 +0000 Subject: [PATCH 65/94] docking: a dock wider than its area shrinks its columns to fit A layout saved on a larger screen drew its outer columns 0 wide with no hit rect and resized them to width 0, which the model rejects. Columns shrink in proportion down to their minimum width; resizing one fixes the others at their drawn widths so the divider follows the pointer. --- crates/ui/src/docking/dock_tests.rs | 35 ++++++++++++++++ crates/ui/src/docking/render/dock.rs | 62 ++++++++++++++++++++++++---- crates/ui/src/docking/render/mod.rs | 2 + 3 files changed, 92 insertions(+), 7 deletions(-) diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 8f950481b9..17c673d58f 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -504,3 +504,38 @@ fn a_column_s_first_tab_dropped_on_its_own_column_edge_anchors_on_another_panel( assert_eq!(out.actions, vec![]); assert_eq!(d.layout, layout); } + +#[test] +fn a_dock_wider_than_the_window_shrinks_to_fit_and_resizes() { + let widths = render::fit_widths(&[(600.0, Some(40.0)), (600.0, Some(40.0)), (48.0, None)], 800.0); + assert!((widths.iter().sum::() - 800.0).abs() < 0.01 && widths[2] == 48.0, "{widths:?}"); + assert_eq!(render::fit_widths(&[(600.0, Some(300.0)), (600.0, Some(300.0))], 400.0), vec![300.0, 300.0]); + + // Three 600-wide columns saved on a larger screen, in an 800-wide window. + let mut layout = docked(Side::Start, &[&[&[1]], &[&[2]], &[&[3]]]); + if let Some(Node::Split { first, .. }) = &mut layout.root + && let Node::Dock { columns, .. } = &mut **first + { + for column in columns { + column.width = 600.0; + } + } + let mut d = testing::DockDriver::new(layout, TestContent::default()); + for panel in [1, 2, 3] { + let divider = d.hit(&Hit::Divider(Divider::Column(panel))).unwrap(); + assert!(d.hit(&Hit::Tab(panel)).is_some_and(|tab| tab.width() > 0.0), "{panel}"); + assert!(divider.right() < 800.0, "{panel}: {divider:?}"); + } + let divider = d.hit(&Hit::Divider(Divider::Column(1))).unwrap().center(); + d.press(divider); + d.move_to(divider + vec2(-8.0, 0.0)); + let out = d.move_to(divider + vec2(-30.0, 0.0)); + assert!(out.error.is_none() && !out.actions.is_empty(), "{out:?}"); + for action in &out.actions { + assert!(matches!(action, Action::ResizeColumn { width, .. } if *width > 0.0), "{action:?}"); + } + d.release(divider + vec2(-30.0, 0.0)); + let total: f32 = (0..3).map(|i| column(&d.layout, i).width).sum(); + assert!(total < 800.0, "{total}"); + assert!((d.hit(&Hit::Divider(Divider::Column(1))).unwrap().center().x - (divider.x - 30.0)).abs() < 1.0); +} diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 83696661e9..140cc3d724 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -90,6 +90,32 @@ pub(in crate::docking) fn group_heights(groups: &[(bool, Option, f32)], str heights } +/// Column widths that fit `room`. Each entry is (width, floor); a column with a floor shrinks +/// in proportion, never below its floor, and one without keeps its width. A dock saved on a +/// larger screen still fits, as far as the floors allow. +pub(in crate::docking) fn fit_widths(columns: &[(f32, Option)], room: f32) -> Vec { + let mut widths: Vec = columns.iter().map(|(w, _)| *w).collect(); + for _ in 0..columns.len() { + let total: f32 = widths.iter().sum(); + if total <= room { + break; + } + let flex: f32 = widths.iter().zip(columns).filter(|(w, (_, floor))| floor.is_some_and(|f| **w > f)).map(|(w, _)| *w).sum(); + if flex <= 0.0 { + break; + } + let scale = ((room - (total - flex)) / flex).max(0.0); + for (width, (_, floor)) in widths.iter_mut().zip(columns) { + if let Some(floor) = *floor + && *width > floor + { + *width = (*width * scale).max(floor); + } + } + } + widths +} + impl Renderer<'_, P> { /// A horizontal split with a dock child: the dock takes its columns' width on its physical /// edge, the sibling the rest. False when neither child is a dock. @@ -138,12 +164,21 @@ impl Renderer<'_, P> { if usable(rect) { ui.painter().rect_filled(rect, 0.0, self.style.background); } - let total: f32 = columns.iter().map(|c| column_width(c, self.style)).sum(); + let bounds: Vec<(f32, f32)> = columns + .iter() + .map(|c| if c.iconic { (self.style.iconic_width, self.style.iconic_max_width) } else { self.column_bounds(c) }) + .collect(); + let natural: Vec<(f32, Option)> = + columns.iter().zip(&bounds).map(|(c, (lo, _))| (column_width(c, self.style), (!c.iconic).then_some(lo.max(1.0)))).collect(); + let widths = fit_widths(&natural, rect.width()); + let scaled = widths.iter().zip(&natural).any(|(w, (n, _))| w != n); + let total: f32 = widths.iter().sum(); let mut x = outer; let mut drawn = Vec::new(); for (index, column) in columns.iter().enumerate() { let Some(first) = column.groups.first().and_then(|g| g.panels.first()) else { continue }; - let width = column_width(column, self.style).min((rect.width() - (x - outer).abs()).max(0.0)); + let fitted = widths.get(index).copied().unwrap_or_default(); + let width = fitted.min((rect.width() - (x - outer).abs()).max(0.0)); let inner = x + inward * width; let column_rect = Rect::from_x_y_ranges(x.min(inner)..=x.max(inner), rect.y_range()); self.column(ui, column, first, column_rect, edge); @@ -153,13 +188,16 @@ impl Renderer<'_, P> { } let (band, line) = column_edge(inner, -inward, rect.y_range()); self.dock_targets.push(DockDrop { target: DockTarget::ColumnEdge { anchor: first.clone(), after: true }, band, line }); - drawn.push((column, first, width, inner)); + drawn.push((index, column, first, width, inner)); x = inner; } // Registered after the columns, so the narrow hit areas win at the edges. - for (column, first, width, inner) in drawn { - let others = total - column_width(column, self.style); - let (lo, hi) = if column.iconic { (self.style.iconic_width, self.style.iconic_max_width) } else { self.column_bounds(column) }; + for (index, column, first, width, inner) in drawn { + if width < 1.0 { + continue; + } + let others = total - widths.get(index).copied().unwrap_or_default(); + let (lo, hi) = bounds.get(index).copied().unwrap_or_default(); let hi = hi.min(room - others).max(lo.min(room - others).max(0.0)); let lo = lo.min(hi); let divider = Rect::from_x_y_ranges((inner - 1.0)..=(inner + 1.0), rect.y_range()); @@ -174,12 +212,22 @@ impl Renderer<'_, P> { .show(ui); self.register_interaction(ui.ctx(), response.response.id); let next = (width + inward * response.delta).clamp(lo, hi); - if response.delta != 0.0 && next != width { + if response.delta != 0.0 && next != width && next > 0.0 { self.output.actions.push(if column.iconic { Action::ResizeIconic { panel: first.clone(), width: Some(next) } } else { Action::ResizeColumn { panel: first.clone(), width: next } }); + // A dock shrunk to fit keeps the widths it was drawn at, so the resized column + // follows the pointer instead of being scaled again. + if scaled { + for (other, (column, width)) in columns.iter().zip(&widths).enumerate() { + let first = column.groups.first().and_then(|g| g.panels.first()); + if let Some(first) = first.filter(|_| other != index && !column.iconic && *width > 0.0) { + self.output.actions.push(Action::ResizeColumn { panel: first.clone(), width: *width }); + } + } + } } } } diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 3d579f671f..1f05202904 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -21,6 +21,8 @@ pub(in crate::docking) use iconic::Iconic; pub use iconic::{close_flyout, flyout, open_flyout}; pub(in crate::docking) use floating::RESIZE_HANDLES; +#[cfg(test)] +pub(in crate::docking) use dock::fit_widths; mod group; mod preview; From 4310fc72a141333d09194a71551346ae4fa7e092 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:09:34 +0000 Subject: [PATCH 66/94] docking: window.panel.dock to a side never anchors on what moves On the first panel of the last column, the command picked that panel as its own anchor and failed with InvalidPlacement. The anchor is a panel of the last column outside the moving unit; when the unit already is that column, the command does nothing. --- crates/ui/src/docking/command.rs | 12 ++++++++---- crates/ui/src/docking/command_tests.rs | 10 ++++++++++ docs/ui-docking.md | 3 ++- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index e377f256c2..93151e6e62 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -399,7 +399,11 @@ impl DockCommand

{ } if let Some(side) = side { let to = match last_column(layout, *side) { - Some(anchor) => Target::At { anchor, placement: Placement::Column { after: true } }, + Some(column) => match column.into_iter().find(|p| !members(layout, panel, unit).contains(p)) { + Some(anchor) => Target::At { anchor, placement: Placement::Column { after: true } }, + // What moves already is that dock's last column. + None => return Ok(Vec::new()), + }, None => Target::NewDock { side: *side }, }; let unit = match (unit, &to) { @@ -548,12 +552,12 @@ impl

DockCommand

{ } } -/// The first panel of the last column of the dock on `side`. -fn last_column(layout: &Layout

, side: Side) -> Option

{ +/// The panels of the last column of the dock on `side`, or `None` without such a dock. +fn last_column(layout: &Layout

, side: Side) -> Option> { let path = layout.dock_path(side)?; let node = layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, &path))?; match node { - super::Node::Dock { columns, .. } => columns.last()?.groups.first()?.panels.first().cloned(), + super::Node::Dock { columns, .. } => Some(columns.last()?.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect()), _ => None, } } diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 1f07116999..9397e62aa4 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -409,3 +409,13 @@ fn dock_with_a_side_zone_and_no_anchor_makes_an_outer_edge_frame() { ); rejected(json!({"command": "window.panel.dock", "panel": "color", "zone": "left", "before": null}), DockError::InvalidPlacement); } + +#[test] +fn dock_to_the_side_a_panel_already_leads_the_last_column_of() { + // Layers leads the dock's only column: it moves out to a new column after it. + let (workspace, _) = applied(json!({"command": "window.panel.dock", "panel": "layers", "side": "Start"})); + assert!(matches!(workspace.layout.place(&s("layers")), Some(dock_model::Place::Dock { column: 1, .. }))); + assert!(matches!(workspace.layout.place(&s("channels")), Some(dock_model::Place::Dock { column: 0, .. }))); + // The whole column already is the last one: nothing to do. + assert_eq!(actions(json!({"command": "window.panel.dock", "panel": "layers", "column": true, "side": "Start"})), vec![]); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 76423b13b6..912a37ccbb 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -231,7 +231,8 @@ let closed = command.apply(&mut app.workspace, style.right_to_left, &space, |pan `Placement::for_zone`, so beside a docked panel they make a new column or group. `apply` and `to_actions` take the layout's `right_to_left` for that. - `group` moves the panel's whole group; `column` moves its dock column, or its whole window when - it floats. `side` is `Start` or `End`. + it floats. `side` is `Start` or `End`: what moves becomes a new last column of that dock, or + a new dock; when it already is that dock's last column, the command does nothing. - `window.panel.dock` with `left`, `right`, `top` or `bottom` and no `anchor` or `side` makes a new frame on that outer edge (`Placement::Edge`). A hidden panel is shown first. - `window.panel.float` without a rect floats what it moves at the size a drag floats it at (see From 41a14168ea3d611a30e098e12f581b3b710f60a3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:12:06 +0000 Subject: [PATCH 67/94] docking: reconcile and restore keep a protected canvas shown Restoring beside a sibling subtree needed the exact same set of panels, so a migrated layout without the canvas put the canvas in hidden. Restore splits the anchor alone when the subtree changed. reconcile takes the panels' permissions and never leaves a registered panel that cannot close in hidden: it goes back to its recorded or default place, else to the outer edge of the docked area. --- crates/ui/src/docking/model.rs | 33 +++++++++++++--- crates/ui/src/docking/model_tests.rs | 58 +++++++++++++++++++++++++++- crates/ui/src/docking/workspace.rs | 16 +++++++- docs/ui-docking.md | 2 +- 4 files changed, 100 insertions(+), 9 deletions(-) diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index e79bf09680..e3a0904067 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -675,6 +675,7 @@ impl Layout

{ if !proposed.contains(anchor) { return Err(DockError::MissingTarget); } + let mut around = false; if let Placement::Split(zone @ (Zone::Left | Zone::Right | Zone::Top | Zone::Bottom)) = location.placement && !location.sibling.is_empty() { @@ -685,14 +686,13 @@ impl Layout

{ if members.len() != location.sibling.len() || !members.contains(anchor) { return Err(DockError::InvalidPlacement); } - let inserted = proposed + around = proposed .root .as_mut() .is_some_and(|root| restore_around_subtree(root, &panel, &members, zone, location.size.unwrap_or(SplitSize::Ratio(0.5)))); - if !inserted { - return Err(DockError::MissingTarget); - } - } else { + } + // A subtree that changed since (a migrated or reconciled layout) splits the anchor. + if !around { proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor: anchor.clone(), placement: location.placement.clone() })?; if let Some(size) = location.size && let Some(root) = proposed.root.as_mut() @@ -719,6 +719,29 @@ impl Layout

{ Ok(()) } + /// Open an absent panel as a frame at the outer edge of the docked area, taking most of it: + /// the last resort for a panel that must stay shown, such as a protected canvas. + pub(super) fn open_at_edge(&mut self, panel: P) -> Result<(), DockError> { + let mut proposed = self.clone(); + if self.root.is_none() { + proposed.root = Some(Node::Tabs { panels: vec![panel], active: 0 }); + } else { + let anchor = self + .panels() + .into_iter() + .find(|p| matches!(self.place(p), Some(Place::Dock { .. } | Place::Node(_)))) + .cloned() + .ok_or(DockError::MissingTarget)?; + proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor, placement: Placement::Edge(Zone::Right) })?; + if let Some(root) = proposed.root.as_mut() { + restore_parent_size(root, &panel, SplitSize::Ratio(0.25)); + } + } + proposed.validate()?; + *self = proposed; + Ok(()) + } + /// [`Self::apply_with_permissions`] with default permissions. pub fn apply(&mut self, action: Action

) -> Result, DockError> { self.apply_with_permissions(action, |_| Permissions::default()) diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index 5a6843eb6d..74eab84c5d 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -329,7 +329,7 @@ fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() { let stray = workspace.layout.location(&99).unwrap(); workspace.hidden.push((98, stray)); let registered = |p: &u32| *p < 90; - workspace.reconcile(registered, &default); + workspace.reconcile(registered, |_| Permissions::default(), &default); workspace.validate().unwrap(); // Unregistered panels wait in `hidden` and come back once registered. assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [98, 99]); @@ -341,7 +341,7 @@ fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() { let mut broken = default.clone(); broken.layout.floating[0].rect[2] = -1.0; - broken.reconcile(registered, &default); + broken.reconcile(registered, |_| Permissions::default(), &default); assert_eq!(broken.layout, default.layout); } @@ -469,6 +469,60 @@ mod serde_tests { } } } + + #[test] + fn every_app_fixture_reconciles_with_its_canvas_shown() { + let s = |p: &str| p.to_owned(); + let permissions = |p: &String| if p == "canvas" { Permissions::PROTECTED } else { Permissions::default() }; + // The canvas between a start dock and the properties, which no fixture matches exactly. + let beside = super::Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(240.0), + first: Box::new(Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![s("layers"), s("pages")], 0)], 240.0)] }), + second: Box::new(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::Ratio(0.75), + first: Box::new(Node::Tabs { panels: vec![s("canvas")], active: 0 }), + second: Box::new(Node::Tabs { panels: vec![s("properties"), s("stroke")], active: 0 }), + }), + }), + floating: Vec::new(), + }; + // The canvas with no anchor to go back beside. + let alone = super::Layout { root: Some(Node::Tabs { panels: vec![s("canvas")], active: 0 }), floating: Vec::new() }; + let fixtures = [ + ("designcraft", include_str!("../../tests/fixtures/v1/designcraft.json"), "/docking"), + ("designcraft", include_str!("../../tests/fixtures/v1/designcraft.json"), "/customWorkspaces/0/docking"), + ("vectorcraft", include_str!("../../tests/fixtures/v1/vectorcraft.json"), "/docking"), + ("lightcraft", include_str!("../../tests/fixtures/v1/lightcraft.json"), "/docking/layout"), + ("pdfcraft", include_str!("../../tests/fixtures/v1/pdfcraft.json"), "/docking/layout"), + ("cadcraft", include_str!("../../tests/fixtures/v1/cadcraft.json"), "/workspace/docking/layout"), + ("soundcraft", include_str!("../../tests/fixtures/v1/soundcraft.json"), "/docking/layout"), + ("soundcraft", include_str!("../../tests/fixtures/v1/soundcraft.json"), "/mix_docking/layout"), + ("photocraft", include_str!("../../tests/fixtures/v1/photocraft.json"), "/docking"), + ("photocraft", include_str!("../../tests/fixtures/v1/photocraft.json"), "/panel_layout/docking"), + ]; + for (app, text, pointer) in fixtures { + let file: Value = serde_json::from_str(text).unwrap(); + let mut saved: super::Layout = serde_json::from_value(file.pointer(pointer).unwrap().clone()).unwrap(); + let own = saved.contains(&s("canvas")).then(|| saved.clone()); + saved.take(&s("canvas")); + for default in own.iter().chain([&beside, &alone]) { + let mut workspace = super::Workspace::new(saved.clone()); + // A file written while the canvas could still be lost. + if let Ok(location) = default.location(&s("canvas")) { + workspace.hidden.push((s("canvas"), location)); + } + for mut workspace in [super::Workspace::new(saved.clone()), workspace] { + workspace.reconcile(|_| true, permissions, &super::Workspace::new(default.clone())); + workspace.validate().unwrap_or_else(|e| panic!("{app}{pointer}: {e}")); + assert!(workspace.layout.contains(&s("canvas")), "{app}{pointer}: {:?}", workspace.layout); + assert!(workspace.hidden.iter().all(|(p, _)| p != "canvas"), "{app}{pointer}"); + } + } + } + } } #[test] diff --git a/crates/ui/src/docking/workspace.rs b/crates/ui/src/docking/workspace.rs index 06cc91bc6f..92eb4c06d8 100644 --- a/crates/ui/src/docking/workspace.rs +++ b/crates/ui/src/docking/workspace.rs @@ -157,8 +157,11 @@ impl Workspace

{ /// numbered panels) move to `hidden` with their location, so they come back once registered; /// the saved arrangement drops them. Registered panels in `default` that are neither shown /// nor hidden go to their default place, or to `hidden` when that place cannot be rebuilt. + /// A registered panel that `permissions` says cannot close, such as a protected canvas, is + /// always shown: at its recorded or default place, else at the outer edge of the docked + /// area. Pass the panels' own permissions, not [`Permissions::locked`] ones. /// `hidden` keeps at most [`MAX_PANELS`] entries, dropping the oldest unregistered ones first. - pub fn reconcile(&mut self, registered: impl Fn(&P) -> bool, default: &Workspace

) { + pub fn reconcile(&mut self, registered: impl Fn(&P) -> bool, permissions: impl Fn(&P) -> Permissions, default: &Workspace

) { if self.validate().is_err() { *self = Workspace { locked: self.locked, ..default.clone() }; } @@ -201,6 +204,17 @@ impl Workspace

{ self.hidden.push((panel.clone(), location.clone())); } } + let stuck: Vec

= self.hidden.iter().map(|(p, _)| p).filter(|p| registered(p) && !permissions(p).closable).cloned().collect(); + for panel in stuck { + let mut layout = self.layout.clone(); + let shown = self.restore_into(&mut layout, &panel).is_ok() + || default.layout.location(&panel).is_ok_and(|location| layout.restore(panel.clone(), &location).is_ok()) + || layout.open_at_edge(panel.clone()).is_ok(); + if shown { + self.layout = layout; + self.hidden.retain(|(p, _)| p != &panel); + } + } let mut excess = self.hidden.len().saturating_sub(MAX_PANELS); self.hidden.retain(|(p, _)| { let drop = excess > 0 && !registered(p); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 912a37ccbb..d2b1cad5db 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -89,7 +89,7 @@ an optional saved arrangement for Reset, and `locked`. |---|---| | `apply`, `apply_all` | Apply actions all or none, with the app's permissions. Closed panels are recorded in `hidden`. While `locked`, moving, floating and closing are refused. | | `set_visible(panel, visible, fallback)` | Hide a panel, or show it at its recorded place, else beside `fallback`. | -| `reconcile(registered, default)` | Fit a loaded workspace to the panels the app has now. Unknown panels move to `hidden`, so they come back when registered again. | +| `reconcile(registered, permissions, default)` | Fit a loaded workspace to the panels the app has now. Unknown panels move to `hidden`, so they come back when registered again. A registered panel that cannot close, such as the canvas, is always shown. | | `reset(default)` | Return to the saved arrangement, or to `default` for a built-in workspace. | | `validate` | Check a loaded workspace before use. | From c084db9c78ca5ab6f0bb4adb28001769484b4cd5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:21:46 +0000 Subject: [PATCH 68/94] docking: a pointer drag on a divider or resize grip leaves no focus behind Keeping focus on the handle after a pointer drag broke app shortcuts that defer to a focused widget (egui_wants_keyboard_input), and arrow keys moved both the canvas selection and the divider. A handle focused by the pointer gives the focus up on release; one reached with Tab or F6 keeps it, and arrow keys resize it. --- crates/ui/src/docking/chrome.rs | 5 ++--- crates/ui/src/docking/tests.rs | 2 +- crates/ui/src/layout/mod.rs | 2 +- crates/ui/src/layout/resize.rs | 29 ++++++++++++++--------------- crates/ui/src/layout/tests.rs | 33 +++++++++++++++++++++++---------- docs/ui-docking.md | 5 +++-- 6 files changed, 44 insertions(+), 32 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index a29f5afc49..39f44aef0c 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -197,8 +197,8 @@ impl<'a> FloatingFrame<'a> { let response = ui.interact(handle, self.id.with(name), Sense::drag()).on_hover_cursor(cursor); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.resize_label)); let anchor_id = response.id.with("pointer-anchor"); + crate::layout::drag_focus(ui, &response); if response.drag_started() { - response.request_focus(); if let Some(origin) = ui.input(|i| i.pointer.press_origin()) && let Some(anchor) = AnchoredResize::new(rect, origin, direction) { @@ -206,7 +206,6 @@ impl<'a> FloatingFrame<'a> { started = Some(response.id); } } - let quiet = crate::layout::pointer_focus(ui, &response); let mut delta = Vec2::ZERO; if response.has_focus() { ui.memory_mut(|memory| { @@ -246,7 +245,7 @@ impl<'a> FloatingFrame<'a> { if canceled || !ui.input(|input| input.pointer.primary_down()) { ui.ctx().data_mut(|data| data.remove::(anchor_id)); } - if name == "resize" && (response.hovered() || response.dragged() || (response.has_focus() && !quiet)) { + if name == "resize" && (response.hovered() || response.dragged() || response.has_focus()) { ui.painter().line_segment([handle.left_bottom(), handle.right_top()], Stroke::new(2.0, style.accent)); } responses.push(response); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 2a111b82c3..1f266440b8 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -1478,7 +1478,7 @@ fn pointer_floating_resize_stops_at_edges_and_waits_for_cursor_to_return() { step(&ctx, &mut layout, vec![Event::PointerMoved(start)]); assert_eq!(layout.floating[0].rect, original, "{name}: returning to the original handle restores its geometry"); step(&ctx, &mut layout, vec![pointer_button(start, false)]); - assert!(ctx.memory(|memory| memory.has_focus(id)), "{name}: the grip keeps keyboard focus after the drag"); + assert!(ctx.memory(|memory| memory.focused()).is_none(), "{name}: the grip gives up focus after a pointer drag"); } } diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs index 92cff1989a..a6ffed8488 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -9,7 +9,7 @@ mod resize; mod toolbar; pub use geometry::{SplitAxis, SplitLayout, SplitSize, split_rect}; -pub(crate) use resize::pointer_focus; +pub(crate) use resize::drag_focus; pub use resize::{ResizeHandle, ResizeHandleStyle, ResizeResponse}; pub use toolbar::{ToolbarFit, fit_toolbar}; diff --git a/crates/ui/src/layout/resize.rs b/crates/ui/src/layout/resize.rs index 422c654674..540058819d 100644 --- a/crates/ui/src/layout/resize.rs +++ b/crates/ui/src/layout/resize.rs @@ -25,7 +25,7 @@ pub struct ResizeResponse { /// /// This widget never stores or changes a pane size. IDs and labels are separate, so translated /// labels do not change identity. Pointer drags retain egui's immediate `Sense::drag` behavior -/// and leave keyboard focus on the handle, highlighted once a key is pressed. +/// and hold focus only for the gesture (see [`drag_focus`]). /// Only arrows along the split axis are consumed, while this handle has focus. Tab remains /// available for normal focus traversal. pub struct ResizeHandle<'a> { @@ -83,12 +83,8 @@ impl<'a> ResizeHandle<'a> { let mut response = ui.interact(if valid { hit } else { inert }, self.id, if valid { Sense::drag() } else { Sense::hover() }); let enabled = valid && response.enabled(); let mut delta = 0.0; - let mut quiet = false; if enabled { - if response.drag_started() { - response.request_focus(); - } - quiet = pointer_focus(ui, &response); + drag_focus(ui, &response); if response.dragged() { let drag = response.drag_delta(); delta = match self.axis { @@ -179,7 +175,7 @@ impl<'a> ResizeHandle<'a> { if enabled { let fill = if response.dragged() { Some(self.style.dragged) - } else if response.has_focus() && !quiet { + } else if response.has_focus() { Some(self.style.focused) } else if response.hovered() { Some(self.style.hovered) @@ -200,15 +196,18 @@ impl<'a> ResizeHandle<'a> { } } -/// A pointer drag focuses its handle, and the handle keeps focus after the release so arrow -/// keys resize it right away. That focus draws no highlight until a key is pressed. Call after -/// the handle requests focus; true while its focus came from the pointer. -pub(crate) fn pointer_focus(ui: &Ui, response: &Response) -> bool { +/// A pointer drag focuses its handle for the gesture only and gives the focus up on release, +/// so the app's shortcuts and its canvas arrow keys work again (they defer to a focused +/// widget). A handle focused from the keyboard (Tab, F6) before the drag keeps its focus. +pub(crate) fn drag_focus(ui: &Ui, response: &Response) { let key = response.id.with("pointer-focus"); if response.drag_started() { - ui.ctx().data_mut(|d| d.insert_temp(key, true)); - } else if !response.has_focus() || ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) { - ui.ctx().data_mut(|d| d.remove::(key)); + if !response.has_focus() { + ui.ctx().data_mut(|d| d.insert_temp(key, ())); + } + response.request_focus(); + } + if response.drag_stopped() && ui.ctx().data_mut(|d| d.remove_temp::<()>(key)).is_some() { + response.surrender_focus(); } - ui.ctx().data(|d| d.get_temp::(key)).unwrap_or(false) } diff --git a/crates/ui/src/layout/tests.rs b/crates/ui/src/layout/tests.rs index 72544c5074..0a14f1e2a1 100644 --- a/crates/ui/src/layout/tests.rs +++ b/crates/ui/src/layout/tests.rs @@ -171,19 +171,32 @@ fn resize_handle_preserves_pointer_drag_lifecycle_and_reports_per_frame_delta() let (response, _) = h.frame(vec![pointer(center + vec2(16.0, 0.0), false)]); assert!(response.response.drag_stopped()); assert_eq!(response.delta, 0.0); - assert!(response.response.has_focus(), "a pointer drag leaves keyboard focus on the handle"); - let (_, output) = h.frame(vec![Event::PointerMoved(pos2(300.0, 180.0))]); - let handle = h.rect; - let highlighted = |output: &FullOutput| { - output.shapes.iter().any(|shape| matches!(&shape.shape, egui::epaint::Shape::Rect(rect) if rect.rect == handle && rect.fill == Color32::BLUE)) - }; - assert!(!highlighted(&output), "focus from the pointer draws no highlight"); - let (response, output) = h.frame(vec![key(Key::ArrowRight)]); - assert_eq!(response.delta, 8.0, "arrow keys resize right after the drag"); - assert!(highlighted(&output)); + assert!(!response.response.has_focus()); + let (response, _) = h.frame(vec![key(Key::ArrowRight)]); + assert!(h.ctx.memory(|m| m.focused()).is_none(), "after a pointer drag no widget has focus, so app shortcuts work"); + assert_eq!(response.delta, 0.0, "arrow keys are left to the app"); assert_eq!(h.value, 100.0, "the component never owns pane state"); } +#[test] +fn tab_focused_handle_keeps_focus_through_a_pointer_drag_and_arrow_resizing() { + let mut h = HandleTest::new(); + let center = h.rect.center(); + h.settle(); + h.frame(vec![key(Key::Tab)]); + let (response, _) = h.frame(vec![]); + assert!(response.response.has_focus(), "Tab reaches the handle"); + h.frame(vec![Event::PointerMoved(center), pointer(center, true)]); + h.frame(vec![Event::PointerMoved(center + vec2(12.0, 0.0))]); + h.frame(vec![pointer(center + vec2(12.0, 0.0), false)]); + let (response, _) = h.frame(vec![key(Key::ArrowRight)]); + assert!(response.response.has_focus()); + assert_eq!(response.delta, 8.0); + let (response, _) = h.frame(vec![key(Key::ArrowLeft)]); + assert!(response.response.has_focus()); + assert_eq!(response.delta, -8.0); +} + #[test] fn focused_handle_resizes_with_axis_arrows_and_draws_visible_focus() { for (axis, forward, back) in [(SplitAxis::Horizontal, Key::ArrowRight, Key::ArrowLeft), (SplitAxis::Vertical, Key::ArrowDown, Key::ArrowUp)] { diff --git a/docs/ui-docking.md b/docs/ui-docking.md index d2b1cad5db..2763ab59aa 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -139,8 +139,9 @@ by the app's own Close items and commands. `DockArea::chrome_has_focus` tells whether keyboard focus is on docking chrome (any control a `Hit` names) rather than on a panel body. Focus follows only the user's input: a tab keeps keyboard focus until a command or a workspace reset hides, closes or moves its panel, and then gives it up. A divider or a floating -window's resize grip keeps keyboard focus after a pointer drag, so arrow keys resize it right -away; its focus highlight shows once a key is pressed. Hovering focuses nothing. `begin_drag` hands a drag that started in the app's own chrome to the area. +window's resize grip holds focus only while the pointer drags it, so the app's shortcuts and +canvas arrow keys work right after; one reached with Tab or F6 keeps its focus, and arrow keys +resize it. Hovering focuses nothing. `begin_drag` hands a drag that started in the app's own chrome to the area. `docking::chrome` has the floating frame, the title bar and `drop_preview` (the drop preview docking and `craft_ui::panes` both draw) for apps that draw their own windows. From 0781c48870bc6777c37dfa6fb5e0cc55f12bb9bf Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:21:46 +0000 Subject: [PATCH 69/94] docking: screen-reader resize values follow the column width on either edge On a dock at the right edge the column handle passed accessibility values through the physical axis, so SetValue 300 gave width 180 and Increment shrank the column. ResizeHandle::reversed applies accessibility actions in value space; the pointer and arrow keys stay physical. --- crates/ui/src/docking/dock_tests.rs | 24 ++++++++++++++++++++++++ crates/ui/src/docking/render/dock.rs | 1 + crates/ui/src/layout/resize.rs | 20 ++++++++++++++++---- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 17c673d58f..0e3ea1f070 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -539,3 +539,27 @@ fn a_dock_wider_than_the_window_shrinks_to_fit_and_resizes() { assert!(total < 800.0, "{total}"); assert!((d.hit(&Hit::Divider(Divider::Column(1))).unwrap().center().x - (divider.x - 30.0)).abs() < 1.0); } + +#[test] +fn screen_reader_values_follow_the_column_width_on_either_edge() { + use egui::accesskit::{Action as A, ActionData, ActionRequest, TreeId}; + for (side, right_to_left) in [(Side::End, false), (Side::Start, true), (Side::Start, false)] { + let mut d = testing::DockDriver::new(docked(side, &[&[&[2]]]), TestContent::default()).with_style(move |s| s.right_to_left = right_to_left); + d.ctx.enable_accesskit(); + d.settle(); + let id = DockArea::::hit_id(d.id, &Hit::Divider(Divider::Column(2))); + let request = |action, data| Event::AccessKitActionRequest(ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.accesskit_id(), data }); + let case = format!("{side:?}, right to left {right_to_left}"); + let out = d.frame(vec![request(A::SetValue, Some(ActionData::NumericValue(300.0)))]); + assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width: 300.0 }], "{case}"); + let out = d.frame(vec![request(A::Increment, None)]); + assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width: 248.0 }], "{case}"); + // Arrow keys stay physical: right moves the divider right. + d.ctx.memory_mut(|m| m.request_focus(id)); + d.frame(vec![]); + let out = d.frame(vec![key(egui::Key::ArrowRight)]); + let wider = d.hit(&Hit::Divider(Divider::Column(2))).unwrap().center().x < 400.0; + let width = if wider { 248.0 } else { 232.0 }; + assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width }], "{case}"); + } +} diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 140cc3d724..0544bc4feb 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -209,6 +209,7 @@ impl Renderer<'_, P> { self.handle_style(), ) .value(width, lo..=hi) + .reversed(inward < 0.0) .show(ui); self.register_interaction(ui.ctx(), response.response.id); let next = (width + inward * response.delta).clamp(lo, hi); diff --git a/crates/ui/src/layout/resize.rs b/crates/ui/src/layout/resize.rs index 540058819d..eed86e9365 100644 --- a/crates/ui/src/layout/resize.rs +++ b/crates/ui/src/layout/resize.rs @@ -37,11 +37,12 @@ pub struct ResizeHandle<'a> { hit_margin: f32, step: f32, value: Option<(f32, RangeInclusive)>, + reversed: bool, } impl<'a> ResizeHandle<'a> { pub fn new(id: Id, axis: SplitAxis, rect: Rect, label: &'a str, style: ResizeHandleStyle) -> Self { - Self { id, axis, rect, label, style, hit_margin: 3.0, step: 8.0, value: None } + Self { id, axis, rect, label, style, hit_margin: 3.0, step: 8.0, value: None, reversed: false } } /// Expand the hit rectangle along the movement axis, in logical points. Default: 3. @@ -63,6 +64,14 @@ impl<'a> ResizeHandle<'a> { self } + /// The value grows against the axis, as for a column docked on the right edge that widens + /// as its divider moves left. Accessibility actions then work on the value; the pointer + /// and arrow keys stay physical, and `delta` stays along the axis. + pub fn reversed(mut self, reversed: bool) -> Self { + self.reversed = reversed; + self + } + pub fn show(self, ui: &mut Ui) -> ResizeResponse { let hit = self.rect.expand2(match self.axis { SplitAxis::Horizontal => Vec2::new(self.hit_margin, 0.0), @@ -116,27 +125,30 @@ impl<'a> ResizeHandle<'a> { } }); } + let mut change = 0.0; ui.input_mut(|input| { input.consume_accesskit_action_requests(response.id, |request| match request.action { accesskit::Action::Increment => { - delta += self.step; + change += self.step; true } accesskit::Action::Decrement => { - delta -= self.step; + change -= self.step; true } accesskit::Action::SetValue => { if let (Some((value, range)), Some(accesskit::ActionData::NumericValue(new_value))) = (&self.value, &request.data) && new_value.is_finite() { - delta = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32; + change = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32; + delta = 0.0; } true } _ => false, }); }); + delta += if self.reversed { -change } else { change }; } if !delta.is_finite() { delta = 0.0; From b19b2638a133ac593058da16ba4d1bdbbde37ed7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:21:51 +0000 Subject: [PATCH 70/94] docking: validate rejects empty frames and accordions No action leaves a Tabs or Stack node without panels, and no app fixture has one; a file that does is invalid, as an empty group is. --- crates/ui/src/docking/model.rs | 9 ++++++++- crates/ui/src/docking/tests.rs | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index e3a0904067..e1fc5541be 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -417,7 +417,8 @@ fn valid_active(len: usize, active: usize) -> bool { } impl Layout

{ - /// Check depth, allocation bounds, geometry, selection and globally unique panel ownership. + /// Check depth, allocation bounds, geometry, selection, globally unique panel ownership and + /// that no frame, group, column or window is empty. /// Traversal is iterative, including for an invalid, excessively deep supplied tree. pub fn validate(&self) -> Result<(), DockError> { if self.floating.len() > MAX_PANELS { @@ -468,9 +469,15 @@ impl Layout

{ } } Node::Tabs { panels, active } => { + if panels.is_empty() { + return Err(DockError::InvalidGeometry); + } check_tabs(panels, *active, &mut seen)?; } Node::Stack { entries } => { + if entries.is_empty() { + return Err(DockError::InvalidGeometry); + } if entries.len() > MAX_PANELS { return Err(DockError::LimitExceeded); } diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 1f266440b8..77d197e738 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -225,6 +225,12 @@ fn invalid_saved_layouts_reject_duplicates_selection_depth_and_nonfinite_geometr assert_eq!(deep.apply(Action::Activate { panel: 0 }), Err(DockError::LimitExceeded)); let oversized = Layout { root: Some(Node::Tabs { panels: (0..=MAX_PANELS as u32).collect(), active: 0 }), floating: Vec::new() }; assert_eq!(oversized.validate(), Err(DockError::LimitExceeded)); + for empty in [tabs(&[], 0), Node::Stack { entries: Vec::new() }] { + let root = Layout { root: Some(empty.clone()), floating: Vec::new() }; + assert_eq!(root.validate(), Err(DockError::InvalidGeometry)); + let beside = Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(0.5), first: Box::new(tabs(&[1], 0)), second: Box::new(empty) }; + assert_eq!(Layout { root: Some(beside), floating: Vec::new() }.validate(), Err(DockError::InvalidGeometry)); + } } fn target(anchor: u32, members: &[u32], rect: Rect) -> DropTarget { From bc4addb8d49fbe626c1c1d46d17355a405b6bb4c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:21:51 +0000 Subject: [PATCH 71/94] docking: opening works when locked, and hiding respects closable OpenAt checked the opened panel's movable, so a locked workspace refused OpenAt while Open worked. It checks movable only for a panel already shown. Workspace::set_visible takes the app's permissions, so hiding cannot close a protected canvas. --- crates/ui/src/docking/command.rs | 4 ++-- crates/ui/src/docking/model.rs | 4 +++- crates/ui/src/docking/model_tests.rs | 26 ++++++++++++++++++++------ crates/ui/src/docking/tests.rs | 2 +- crates/ui/src/docking/workspace.rs | 7 ++++--- docs/ui-docking.md | 2 +- 6 files changed, 31 insertions(+), 14 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 93151e6e62..2dd7f67a82 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -517,12 +517,12 @@ impl DockCommand

{ }; if let Some(panel) = show.filter(|p| !workspace.layout.contains(p)) { if self.edge().is_none() { - workspace.set_visible(panel.clone(), true, None)?; + workspace.set_visible(panel.clone(), true, None, &permissions)?; return Ok(Vec::new()); } // Shown, then moved to the edge, all or nothing. let mut shown = workspace.clone(); - shown.set_visible(panel.clone(), true, None)?; + shown.set_visible(panel.clone(), true, None, &permissions)?; let closed = shown.apply_all(self.to_actions(&shown, right_to_left, space)?, permissions)?; *workspace = shown; return Ok(closed); diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index e1fc5541be..641e6373f1 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -762,7 +762,9 @@ impl Layout

{ self.validate()?; match &action { Action::Move { panel, anchor, placement } | Action::OpenAt { panel, anchor, placement } => { - if !permissions(panel).movable { + // Opening an absent panel moves nothing, so it works in a locked workspace too. + let opens = matches!(action, Action::OpenAt { .. }) && !self.contains(panel); + if !opens && !permissions(panel).movable { return Err(DockError::NotAllowed); } if !placement_allowed(placement, permissions(anchor)) { diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index 74eab84c5d..6e70d5aed7 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -170,8 +170,8 @@ fn close_group_and_close_window_record_a_restorable_location_per_member() { assert_eq!(workspace.apply(Action::CloseGroup { panel: 3 }, allow).unwrap(), [2, 3]); assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [2, 3]); assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![4]]); - workspace.set_visible(2, true, None).unwrap(); - workspace.set_visible(3, true, None).unwrap(); + workspace.set_visible(2, true, None, |_| Permissions::default()).unwrap(); + workspace.set_visible(3, true, None, |_| Permissions::default()).unwrap(); assert_eq!(panels_of(&dock(&workspace.layout, Side::End)[0].groups), [vec![2, 3], vec![4]]); assert_eq!(workspace.layout.closed_by(&Action::CloseWindow { panel: 7 }).unwrap(), [6, 7, 8]); @@ -179,7 +179,7 @@ fn close_group_and_close_window_record_a_restorable_location_per_member() { assert!(workspace.layout.floating.is_empty()); assert_eq!(workspace.hidden.len(), 3); for panel in [6, 7, 8] { - workspace.set_visible(panel, true, None).unwrap(); + workspace.set_visible(panel, true, None, |_| Permissions::default()).unwrap(); } assert_eq!(workspace.layout.floating.len(), 1); assert_eq!(panels_of(&workspace.layout.floating[0].groups), [vec![6, 7], vec![8]]); @@ -187,7 +187,7 @@ fn close_group_and_close_window_record_a_restorable_location_per_member() { workspace.apply(Action::CloseOthers { panel: 12 }, allow).unwrap(); assert_eq!(group_state(&workspace.layout, 12).0, [12]); - workspace.set_visible(11, true, None).unwrap(); + workspace.set_visible(11, true, None, |_| Permissions::default()).unwrap(); assert_eq!(group_state(&workspace.layout, 12).0, [11, 12]); assert!(workspace.hidden.is_empty()); assert_eq!(sorted(&workspace.layout), ALL); @@ -299,7 +299,7 @@ fn locked_workspace_rejects_structure_but_allows_activate_open_minimize_and_resi assert_eq!(workspace.apply(action.clone(), allow), Err(DockError::NotAllowed), "{action:?}"); assert_eq!(workspace, before); } - assert_eq!(workspace.set_visible(4, false, None), Err(DockError::NotAllowed)); + assert_eq!(workspace.set_visible(4, false, None, |_| Permissions::default()), Err(DockError::NotAllowed)); let allowed = [ Action::Activate { panel: 2 }, Action::Open { panel: 12, anchor: Some(11) }, @@ -317,6 +317,20 @@ fn locked_workspace_rejects_structure_but_allows_activate_open_minimize_and_resi assert_eq!(workspace.layout.panel_state(&5), PanelState::Open); assert_eq!(workspace.layout.panel_state(&2), PanelState::Front); assert_eq!(workspace.layout.panel_state(&3), PanelState::Open); + // Opening at a chosen place works too; moving a shown panel there does not. + workspace.apply(Action::OpenAt { panel: 13, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow).unwrap(); + assert!(workspace.layout.contains(&13)); + assert_eq!(workspace.apply(Action::OpenAt { panel: 2, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow), Err(DockError::NotAllowed)); +} + +#[test] +fn hiding_a_panel_that_may_not_close_is_refused() { + let mut workspace = Workspace::new(docked()); + let canvas = |p: &u32| if *p == 1 { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }; + assert_eq!(workspace.set_visible(1, false, None, canvas), Err(DockError::NotAllowed)); + assert!(workspace.layout.contains(&1) && workspace.hidden.is_empty()); + workspace.set_visible(2, false, None, canvas).unwrap(); + assert!(!workspace.layout.contains(&2)); } #[test] @@ -334,7 +348,7 @@ fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() { // Unregistered panels wait in `hidden` and come back once registered. assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [98, 99]); assert_eq!(sorted(&workspace.layout), ALL); - workspace.set_visible(99, true, None).unwrap(); + workspace.set_visible(99, true, None, |_| Permissions::default()).unwrap(); assert_eq!(group_state(&workspace.layout, 2).0, [2, 3, 99]); assert_eq!(dock(&workspace.layout, Side::End).len(), 2); assert_eq!(group_state(&workspace.layout, 11).0, [11, 12]); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 77d197e738..7ed5d39256 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -314,7 +314,7 @@ fn long_action_sequence_never_loses_or_duplicates_a_panel() { { let fallback = workspace.layout.panels().first().map(|p| **p); let before = workspace.clone(); - if workspace.set_visible(hidden, true, fallback).is_err() { + if workspace.set_visible(hidden, true, fallback, |_| Permissions::default()).is_err() { assert_eq!(workspace, before); } } diff --git a/crates/ui/src/docking/workspace.rs b/crates/ui/src/docking/workspace.rs index 92eb4c06d8..da414e78f1 100644 --- a/crates/ui/src/docking/workspace.rs +++ b/crates/ui/src/docking/workspace.rs @@ -114,14 +114,15 @@ impl Workspace

{ /// Show or hide one panel. Showing restores its recorded location, following the chain of /// hidden anchors when its own anchor is hidden too; otherwise it opens beside `fallback`. - /// A shown panel becomes the active tab of its group. - pub fn set_visible(&mut self, panel: P, visible: bool, fallback: Option

) -> Result<(), DockError> { + /// A shown panel becomes the active tab of its group. Hiding follows `permissions` and + /// [`Self::locked`], as [`Self::apply`] does, so a protected canvas stays shown. + pub fn set_visible(&mut self, panel: P, visible: bool, fallback: Option

, permissions: impl Fn(&P) -> Permissions) -> Result<(), DockError> { self.validate()?; if !visible { if !self.layout.contains(&panel) { return Ok(()); } - return self.apply(Action::Close { panel }, |_| Permissions::default()).map(drop); + return self.apply(Action::Close { panel }, permissions).map(drop); } if self.layout.contains(&panel) { return self.apply(Action::Activate { panel }, |_| Permissions::default()).map(drop); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 2763ab59aa..40c8b329b8 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -88,7 +88,7 @@ an optional saved arrangement for Reset, and `locked`. | Method | Does | |---|---| | `apply`, `apply_all` | Apply actions all or none, with the app's permissions. Closed panels are recorded in `hidden`. While `locked`, moving, floating and closing are refused. | -| `set_visible(panel, visible, fallback)` | Hide a panel, or show it at its recorded place, else beside `fallback`. | +| `set_visible(panel, visible, fallback, permissions)` | Hide a panel that may close, or show it at its recorded place, else beside `fallback`. | | `reconcile(registered, permissions, default)` | Fit a loaded workspace to the panels the app has now. Unknown panels move to `hidden`, so they come back when registered again. A registered panel that cannot close, such as the canvas, is always shown. | | `reset(default)` | Return to the saved arrangement, or to `default` for a built-in workspace. | | `validate` | Check a loaded workspace before use. | From 0fe98b3be9b249f3464e0e0f64b43c16ef37d057 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:26:57 +0000 Subject: [PATCH 72/94] docking: Target, Side, ResizeEdge, Profile and DockStyle are non_exhaustive New variants and style fields can then be added without breaking apps. DockStyle gains from_visuals and Default for building a style without a Ui. --- crates/ui/src/docking/dock_model.rs | 2 ++ crates/ui/src/docking/hits.rs | 1 + crates/ui/src/docking/surface.rs | 15 ++++++++++++++- docs/ui-docking.md | 2 ++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index ea88d380fb..99eeec7fa5 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -19,6 +19,7 @@ const DEFAULT_FLOAT: [f32; 4] = [48.0, 48.0, 260.0, 320.0]; /// layout); the renderer maps it to a physical edge from the layout direction. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] pub enum Side { Start, End, @@ -74,6 +75,7 @@ impl

Column

{ /// Where a group, column or floating window goes. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] pub enum Target

{ /// Relative to the panel `anchor`, which must not be part of what moves. At { anchor: P, placement: Placement

}, diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index e3869fe438..96e0521d3b 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -43,6 +43,7 @@ pub enum Hit

{ /// The edge or corner a floating window's resize handle moves. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[non_exhaustive] pub enum ResizeEdge { Left, Right, diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index c8fdd84b24..c8d7dc8626 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -9,6 +9,7 @@ pub(super) const TAB_PADDING: f32 = 24.0; /// Application-supplied chrome. Body renderers retain their own UI style and contents. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct DockStyle { pub tab_height: f32, pub gap: f32, @@ -105,15 +106,27 @@ pub struct DockStyle { /// Which arrangement a [`DockStyle`] renders and labels. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] pub enum Profile { #[default] Dock, Frame, } +impl Default for DockStyle { + /// [`Self::from_visuals`] with egui's default visuals. + fn default() -> Self { + Self::from_visuals(&egui::Visuals::default()) + } +} + impl DockStyle { + /// Colors from the `ui`'s visuals; adjust fields afterwards. pub fn from_ui(ui: &Ui) -> Self { - let visuals = ui.visuals(); + Self::from_visuals(ui.visuals()) + } + + pub fn from_visuals(visuals: &egui::Visuals) -> Self { Self { tab_height: 26.0, gap: 4.0, diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 40c8b329b8..b2226fa4a2 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -10,6 +10,8 @@ Office apps that draw their own document with a few task panes beside it use ## Profiles `DockStyle::profile` picks one of two arrangements. Both use the same model and actions. +An app builds its style with `DockStyle::from_ui`, `from_visuals` or `default` and then sets +fields; new fields can be added, so the struct has no literal form outside the crate. | Profile | Arrangement | Apps | |---|---|---| From 5f48f1e1ebf66426ad891a7f5c4b1bb35c8e990d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:32:26 +0000 Subject: [PATCH 73/94] docking: per-frame lookups scale with the panel count The renderer looked up each panel's place with a tree walk, found recorded content heights by linear search and named every possible control of every panel to record hit rects. Places come from one traversal per frame, content heights through an index, and hit rects are named only when hit_rects asks. --- crates/ui/src/docking/dock_model.rs | 53 ++++++++++++++++++++++++- crates/ui/src/docking/hits.rs | 17 +++++--- crates/ui/src/docking/render/dock.rs | 10 ++--- crates/ui/src/docking/render/frame.rs | 8 +--- crates/ui/src/docking/render/group.rs | 2 +- crates/ui/src/docking/render/mod.rs | 22 ++++++++-- crates/ui/src/docking/render/preview.rs | 12 +++--- crates/ui/src/docking/surface.rs | 44 ++++++++++---------- 8 files changed, 115 insertions(+), 53 deletions(-) diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index 99eeec7fa5..435fd2dc64 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -4,7 +4,7 @@ //! A group, column or floating window is named by a panel it contains. Edits run on a proposed //! copy of the layout, so a helper that fails part-way leaves nothing behind. -use std::hash::Hash; +use std::{collections::HashMap, hash::Hash}; use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, Node, Placement, Zone, valid_height, valid_rect, valid_width}; use crate::layout::{SplitAxis, SplitSize}; @@ -253,6 +253,57 @@ impl Layout

{ None } + /// [`Self::place`] of every panel, from one traversal: the renderer looks up many panels a + /// frame. + pub(super) fn places(&self) -> HashMap { + let mut places = HashMap::new(); + for (w, window) in self.floating.iter().enumerate() { + for (g, group) in window.groups.iter().enumerate() { + for panel in &group.panels { + places.entry(panel.clone()).or_insert(Place::Floating { window: w, group: g }); + } + } + } + let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); + let mut visited = 0usize; + while let Some((node, path)) = visit.pop() { + visited = visited.saturating_add(1); + if visited > MAX_NODES { + break; + } + match node { + Node::Split { first, second, .. } => { + let mut second_path = path.clone(); + second_path.push(true); + let mut first_path = path; + first_path.push(false); + visit.push((second, second_path)); + visit.push((first, first_path)); + } + Node::Tabs { panels, .. } => { + for panel in panels { + places.entry(panel.clone()).or_insert_with(|| Place::Node(path.clone())); + } + } + Node::Stack { entries } => { + for entry in entries { + places.entry(entry.panel.clone()).or_insert_with(|| Place::Node(path.clone())); + } + } + Node::Dock { columns, .. } => { + for (c, column) in columns.iter().enumerate() { + for (g, group) in column.groups.iter().enumerate() { + for panel in &group.panels { + places.entry(panel.clone()).or_insert_with(|| Place::Dock { path: path.clone(), column: c, group: g }); + } + } + } + } + } + } + places + } + pub(super) fn dock_path(&self, side: Side) -> Option> { let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); let mut visited = 0usize; diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index 96e0521d3b..0c5faf70fa 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -79,7 +79,9 @@ impl DockArea<'_, P> { /// return these from a `ui.docking` control method beside the layout and `focused`; tests /// drag from their centers. pub fn hit_rects(ctx: &Context, id: Id) -> Vec<(Hit

, Rect)> { - ctx.data(|d| d.get_temp::, Rect)>>(key(id))).unwrap_or_default() + let Some((layout, rects)) = ctx.data(|d| d.get_temp::>(key(id))) else { return Vec::new() }; + let mut names = named(id, &layout); + rects.into_iter().filter_map(|(id, rect)| Some((names.remove(&id)?, rect))).collect() } /// The egui widget id of the control `hit` names in the area `id`, for tests and @@ -181,10 +183,13 @@ pub(super) fn named(area: names } -/// Name the controls the renderer registered this frame and store their rects. +/// The layout of the last frame and the rects of the controls it registered, by widget id. +type Recorded

= (Layout

, Vec<(Id, Rect)>); + +/// Store the rects of the controls the renderer registered this frame. They are named only +/// when [`DockArea::hit_rects`] asks, which tests and automation do, not every frame. pub(super) fn record(ctx: &Context, area: Id, layout: &Layout

, owned: &[Id]) { - let mut names = named(area, layout); - let hits: Vec<(Hit

, Rect)> = - owned.iter().filter_map(|id| Some((names.remove(id)?, ctx.read_response(*id)?.rect))).filter(|(_, rect)| rect.is_positive()).collect(); - ctx.data_mut(|d| d.insert_temp(key(area), hits)); + let rects: Vec<(Id, Rect)> = + owned.iter().filter_map(|id| Some((*id, ctx.read_response(*id)?.rect))).filter(|(_, rect)| rect.is_positive()).collect(); + ctx.data_mut(|d| d.insert_temp::>(key(area), (layout.clone(), rects))); } diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 0544bc4feb..feb9b68ba4 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -164,10 +164,8 @@ impl Renderer<'_, P> { if usable(rect) { ui.painter().rect_filled(rect, 0.0, self.style.background); } - let bounds: Vec<(f32, f32)> = columns - .iter() - .map(|c| if c.iconic { (self.style.iconic_width, self.style.iconic_max_width) } else { self.column_bounds(c) }) - .collect(); + let bounds: Vec<(f32, f32)> = + columns.iter().map(|c| if c.iconic { (self.style.iconic_width, self.style.iconic_max_width) } else { self.column_bounds(c) }).collect(); let natural: Vec<(f32, Option)> = columns.iter().zip(&bounds).map(|(c, (lo, _))| (column_width(c, self.style), (!c.iconic).then_some(lo.max(1.0)))).collect(); let widths = fit_widths(&natural, rect.width()); @@ -531,9 +529,7 @@ impl Renderer<'_, P> { } } Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, - to @ Target::NewDock { .. } - if self.layout.place(panel).and_then(|place| self.layout.group(&place)).is_some_and(|g| g.panels.len() == 1) => - { + to @ Target::NewDock { .. } if self.place(panel).and_then(|place| self.layout.group(place)).is_some_and(|g| g.panels.len() == 1) => { Action::MoveGroup { panel: panel.clone(), to } } to @ Target::NewDock { .. } => Action::MovePanel { panel: panel.clone(), to }, diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index 8b90fe9963..2fc3156b32 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -168,12 +168,8 @@ impl Renderer<'_, P> { if distance > band { return None; } - let anchor = self - .layout - .panels() - .into_iter() - .find(|p| !members.contains(p) && !matches!(self.layout.place(p), Some(Place::Floating { .. }) | None))? - .clone(); + let anchor = + self.layout.panels().into_iter().find(|p| !members.contains(p) && !matches!(self.place(p), Some(Place::Floating { .. }) | None))?.clone(); let size = area.size() * 0.25; let preview = match zone { Zone::Left => Rect::from_min_size(area.min, vec2(size.x, area.height())), diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 83c24ea890..25d873253f 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -332,7 +332,7 @@ impl Renderer<'_, P> { if members.contains(anchor) { continue; } - let Some(place) = self.layout.place(anchor) else { continue }; + let Some(place) = self.place(anchor) else { continue }; if !places.contains(&place) { places.push(place); anchors.push(anchor.clone()); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 1f05202904..b1d24a77c1 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -1,10 +1,10 @@ -use std::{fmt::Debug, hash::Hash}; +use std::{collections::HashMap, fmt::Debug, hash::Hash}; use egui::{Context, Id, Rect, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split_rect}; -use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions}; +use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions, dock_model::Place}; mod dock; mod floating; @@ -20,9 +20,9 @@ pub(in crate::docking) use group::GroupKind; pub(in crate::docking) use iconic::Iconic; pub use iconic::{close_flyout, flyout, open_flyout}; -pub(in crate::docking) use floating::RESIZE_HANDLES; #[cfg(test)] pub(in crate::docking) use dock::fit_widths; +pub(in crate::docking) use floating::RESIZE_HANDLES; mod group; mod preview; @@ -45,9 +45,21 @@ pub(super) struct Renderer<'a, P> { pub(super) iconic: Iconic

, /// What a drag would float from each drawn panel, group and column, for commands. pub(super) float_space: crate::docking::FloatSpace

, + /// Each panel's place in `layout`, and its entry in `float_space.contents`. + pub(super) places: HashMap, + pub(super) contents: HashMap, } impl Renderer<'_, P> { + pub(super) fn place(&self, panel: &P) -> Option<&Place> { + self.places.get(panel) + } + + /// The height `panel`'s content last used: `Some(None)` when it filled its body. + pub(super) fn content_height(&self, panel: &P) -> Option> { + self.contents.get(panel).and_then(|i| self.float_space.contents.get(*i)).map(|(_, height)| *height) + } + pub(super) fn label_of(&self, panel: &P) -> String { self.content.logical_label(panel) } @@ -222,7 +234,9 @@ impl Renderer<'_, P> { ui.new_child(UiBuilder::new().id(self.id.with(("body", panel))).max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); child.set_clip_rect(rect.intersect(ui.clip_rect())); self.content.body(&mut child, panel); - self.float_space.record_content(panel.clone(), child.min_rect().height(), rect.height()); + let at = self.contents.get(panel).copied(); + let at = self.float_space.record_content(at, panel.clone(), child.min_rect().height(), rect.height()); + self.contents.insert(panel.clone(), at); // Any button: a canvas pans with the middle button and opens menus with the secondary. if child.rect_contains_pointer(rect) && child.input(|i| i.pointer.any_pressed()) { self.output.focused = Some(panel.clone()); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 4feed8b9c8..72c5001990 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -117,7 +117,7 @@ impl Renderer<'_, P> { self.output.actions.extend(action); return; } - let floating = matches!(self.layout.place(&drag.panel), Some(Place::Floating { .. })); + let floating = matches!(self.place(&drag.panel), Some(Place::Floating { .. })); let proposal = if float_only { None } else { self.group_proposal(drag, pointer) }; if let Some(proposal) = proposal.as_ref().filter(|p| !p.noop) { let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; @@ -288,10 +288,10 @@ impl Renderer<'_, P> { return vec2(size.x, self.fitted_height(panel, chrome, size.y).unwrap_or(size.y)); } let mut size = self.iconic.float_width(panel).map_or(source, |width| vec2(width, DOCKED_FLOAT_HEIGHT)); - if matches!(self.layout.place(panel), Some(Place::Dock { .. } | Place::Node(_))) { + if matches!(self.place(panel), Some(Place::Dock { .. } | Place::Node(_))) { size.y = match self.fitted_height(panel, chrome, DOCKED_FLOAT_HEIGHT) { Some(height) => height, - None if self.float_space.filled(panel) => DOCKED_FLOAT_HEIGHT, + None if self.content_height(panel) == Some(None) => DOCKED_FLOAT_HEIGHT, None => size.y.min(DOCKED_FLOAT_HEIGHT), }; } @@ -304,7 +304,7 @@ impl Renderer<'_, P> { /// content height the panel last drew, at least [`MIN_FITTED_HEIGHT`] and at most `max`. /// `None` for a panel the area has not drawn. pub(super) fn fitted_height(&self, panel: &P, chrome: f32, max: f32) -> Option { - let content = self.float_space.content(panel)?; + let content = self.content_height(panel).flatten()?; Some((chrome + content).max(MIN_FITTED_HEIGHT).min(max)) } @@ -330,7 +330,7 @@ impl Renderer<'_, P> { /// dock column. A group fits that height to its active panel's content. A group that already /// floats keeps its size. pub(super) fn group_float_size(&self, members: &[P], source: Vec2) -> Vec2 { - let Some(place) = members.first().and_then(|panel| self.layout.place(panel)) else { return source }; + let Some(place) = members.first().and_then(|panel| self.place(panel)) else { return source }; if matches!(place, Place::Floating { .. }) { return source; } @@ -339,7 +339,7 @@ impl Renderer<'_, P> { let docked = matches!(place, Place::Dock { .. }); let chrome = self.style.title_height + self.style.tab_height; let max = host.or(docked.then_some(DOCKED_FLOAT_HEIGHT)); - let fitted = max.and_then(|max| self.group_active(members, &place).and_then(|active| self.fitted_height(active, chrome, max))); + let fitted = max.and_then(|max| self.group_active(members, place).and_then(|active| self.fitted_height(active, chrome, max))); vec2(source.x, fitted.or(host).unwrap_or(if docked { source.y.min(DOCKED_FLOAT_HEIGHT) } else { source.y })) } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index c8d7dc8626..d8812080a8 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -287,16 +287,23 @@ impl FloatSpace

{ impl FloatSpace

{ /// Record the height `panel`'s content used in a body `available` tall. Content that /// reaches the body's bottom filled it and has no height of its own, unless the body was - /// sized to the height recorded before (a fitted window). - pub(super) fn record_content(&mut self, panel: P, used: f32, available: f32) { + /// sized to the height recorded before (a fitted window). `at` is the panel's entry in + /// `contents` if it has one; returns where the entry is. + pub(super) fn record_content(&mut self, at: Option, panel: P, used: f32, available: f32) -> usize { const TOLERANCE: f32 = 1.0; let used = if used.is_finite() { used.max(0.0) } else { 0.0 }; - let recorded = self.contents.iter_mut().find(|(p, _)| *p == panel); + let recorded = at.and_then(|i| self.contents.get_mut(i)).filter(|(p, _)| *p == panel); let fitted = recorded.as_ref().and_then(|(_, height)| *height).is_some_and(|height| height >= available - TOLERANCE); let height = (used < available - TOLERANCE || fitted).then_some(used); - match recorded { - Some((_, recorded)) => *recorded = height, - None => self.contents.push((panel, height)), + match (recorded, at) { + (Some((_, recorded)), Some(at)) => { + *recorded = height; + at + } + _ => { + self.contents.push((panel, height)); + self.contents.len() - 1 + } } } } @@ -316,15 +323,6 @@ impl FloatSpace

{ Self::find(&self.columns, panel) } - /// Whether `panel`'s content filled its body when it was last drawn. - pub(super) fn filled(&self, panel: &P) -> bool { - self.contents.iter().any(|(p, height)| p == panel && height.is_none()) - } - - pub(super) fn content(&self, panel: &P) -> Option { - self.contents.iter().find(|(p, _)| p == panel).and_then(|(_, height)| *height) - } - /// The first record wins: an iconic panel is recorded at its icon before its flyout. fn find(sizes: &[(P, Vec2)], panel: &P) -> Option { sizes.iter().find(|(p, _)| p == panel).map(|(_, size)| *size) @@ -789,6 +787,12 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { } release_moved_tab_focus(ui.ctx(), self.id, layout); let (view, frame) = super::render::view(layout, self.maximized.as_ref(), self.hide, &*content); + let places = layout.places(); + // A panel keeps the content height it last drew while hidden or minimized. + let contents: Vec<(P, Option)> = float_space::

(ui.ctx(), self.id) + .map(|space| space.contents.into_iter().filter(|(panel, _)| places.contains_key(panel)).collect()) + .unwrap_or_default(); + let content_index = contents.iter().enumerate().map(|(i, (panel, _))| (panel.clone(), i)).collect(); let mut renderer = Renderer { id: self.id, style, @@ -803,13 +807,9 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { output: DockOutput::default(), frame, iconic: super::render::Iconic::new(self.auto_collapse), - float_space: FloatSpace { - // A panel keeps the content height it last drew while hidden or minimized. - contents: float_space::

(ui.ctx(), self.id) - .map(|space| space.contents.into_iter().filter(|(panel, _)| layout.contains(panel)).collect()) - .unwrap_or_default(), - ..FloatSpace::new(rect) - }, + float_space: FloatSpace { contents, ..FloatSpace::new(rect) }, + places, + contents: content_index, }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); From 352a8308c5cc53c2ae31326fa38a4a6bcb0ff9eb Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:32:26 +0000 Subject: [PATCH 74/94] docking: rustfmt and clippy --- crates/ui/src/docking/chrome.rs | 13 ++++++------- crates/ui/src/docking/dock_tests.rs | 3 ++- crates/ui/src/docking/model_tests.rs | 10 ++++++++-- crates/ui/src/docking/tests.rs | 3 ++- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index 39f44aef0c..323419b773 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -198,13 +198,12 @@ impl<'a> FloatingFrame<'a> { response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), self.resize_label)); let anchor_id = response.id.with("pointer-anchor"); crate::layout::drag_focus(ui, &response); - if response.drag_started() { - if let Some(origin) = ui.input(|i| i.pointer.press_origin()) - && let Some(anchor) = AnchoredResize::new(rect, origin, direction) - { - ui.ctx().data_mut(|data| data.insert_temp(anchor_id, anchor)); - started = Some(response.id); - } + if response.drag_started() + && let Some(origin) = ui.input(|i| i.pointer.press_origin()) + && let Some(anchor) = AnchoredResize::new(rect, origin, direction) + { + ui.ctx().data_mut(|data| data.insert_temp(anchor_id, anchor)); + started = Some(response.id); } let mut delta = Vec2::ZERO; if response.has_focus() { diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 0e3ea1f070..8ba4387bc8 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -548,7 +548,8 @@ fn screen_reader_values_follow_the_column_width_on_either_edge() { d.ctx.enable_accesskit(); d.settle(); let id = DockArea::::hit_id(d.id, &Hit::Divider(Divider::Column(2))); - let request = |action, data| Event::AccessKitActionRequest(ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.accesskit_id(), data }); + let request = + |action, data| Event::AccessKitActionRequest(ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.accesskit_id(), data }); let case = format!("{side:?}, right to left {right_to_left}"); let out = d.frame(vec![request(A::SetValue, Some(ActionData::NumericValue(300.0)))]); assert_eq!(out.actions, vec![Action::ResizeColumn { panel: 2, width: 300.0 }], "{case}"); diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index 6e70d5aed7..c72119025f 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -320,7 +320,10 @@ fn locked_workspace_rejects_structure_but_allows_activate_open_minimize_and_resi // Opening at a chosen place works too; moving a shown panel there does not. workspace.apply(Action::OpenAt { panel: 13, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow).unwrap(); assert!(workspace.layout.contains(&13)); - assert_eq!(workspace.apply(Action::OpenAt { panel: 2, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow), Err(DockError::NotAllowed)); + assert_eq!( + workspace.apply(Action::OpenAt { panel: 2, anchor: 11, placement: Placement::Split(Zone::Bottom) }, allow), + Err(DockError::NotAllowed) + ); } #[test] @@ -493,7 +496,10 @@ mod serde_tests { root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(240.0), - first: Box::new(Node::Dock { side: Side::Start, columns: vec![Column::new(vec![Group::new(vec![s("layers"), s("pages")], 0)], 240.0)] }), + first: Box::new(Node::Dock { + side: Side::Start, + columns: vec![Column::new(vec![Group::new(vec![s("layers"), s("pages")], 0)], 240.0)], + }), second: Box::new(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(0.75), diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 7ed5d39256..fb3c847f93 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -228,7 +228,8 @@ fn invalid_saved_layouts_reject_duplicates_selection_depth_and_nonfinite_geometr for empty in [tabs(&[], 0), Node::Stack { entries: Vec::new() }] { let root = Layout { root: Some(empty.clone()), floating: Vec::new() }; assert_eq!(root.validate(), Err(DockError::InvalidGeometry)); - let beside = Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(0.5), first: Box::new(tabs(&[1], 0)), second: Box::new(empty) }; + let beside = + Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::Ratio(0.5), first: Box::new(tabs(&[1], 0)), second: Box::new(empty) }; assert_eq!(Layout { root: Some(beside), floating: Vec::new() }.validate(), Err(DockError::InvalidGeometry)); } } From 592cba1ca18e52819479aa0dfc95c7f1d37dd406 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 04:12:09 +0000 Subject: [PATCH 75/94] docking: drag areas draw no grip marks The drag strip beside the tabs, the column bar, the floating title bar and the strip above an icon group stay draggable, with the grab cursor and the hover outline, but paint no grip lines. --- crates/ui/src/docking/chrome.rs | 14 ++++---------- crates/ui/src/docking/render/dock.rs | 5 ----- crates/ui/src/docking/render/group.rs | 14 -------------- crates/ui/src/docking/render/iconic.rs | 8 ++------ crates/ui/src/docking/trial_tests.rs | 10 ++++------ docs/ui-docking.md | 2 +- 6 files changed, 11 insertions(+), 42 deletions(-) diff --git a/crates/ui/src/docking/chrome.rs b/crates/ui/src/docking/chrome.rs index 323419b773..2933ffd0d0 100644 --- a/crates/ui/src/docking/chrome.rs +++ b/crates/ui/src/docking/chrome.rs @@ -1,5 +1,5 @@ -//! Floating window chrome: an opaque frame with anchored resize handles, and a title bar with a -//! grip, an optional ▾ menu button and ×. [`super::DockArea`] draws its floating windows with +//! Floating window chrome: an opaque frame with anchored resize handles, and a title bar with an +//! optional title, ▾ menu button and ×. [`super::DockArea`] draws its floating windows with //! these; other hosts (task panes) use them with their own ids and actions. Nothing here changes //! a layout: the caller turns the responses into its own commands. @@ -282,7 +282,7 @@ pub(super) fn truncated(ui: &Ui, text: WidgetText, width: f32, font: FontId) -> ui.painter().layout_job(job) } -/// A title bar: two grip lines (or a title), an optional ▾ menu button and an optional ×, 10 pt +/// A title bar: an optional title, an optional ▾ menu button and an optional ×, 10 pt /// in from the right edge, mirrored when [`ChromeStyle::right_to_left`] is set. The bar senses /// clicks and drags; double-clicks are the caller's. pub struct TitleBar<'a> { @@ -309,7 +309,7 @@ impl<'a> TitleBar<'a> { Self { id, move_label, title: None, menu: None, close: None, movable: true } } - /// Text at the leading edge instead of the grip lines, cut with '…' to fit. + /// Text at the leading edge, cut with '…' to fit. pub fn title(mut self, title: impl Into) -> Self { self.title = Some(title.into()); self @@ -358,12 +358,6 @@ impl<'a> TitleBar<'a> { let galley = truncated(ui, title, (bar_rect.width() - 12.0).max(0.0), style.font.clone()); let x = if style.right_to_left { bar_rect.right() - 6.0 - galley.size().x } else { bar_rect.left() + 6.0 }; painter.galley(pos2(x, rect.center().y - galley.size().y * 0.5), galley, style.text); - } else { - let grip = Stroke::new(0.6, style.weak_text); - for k in 0..2 { - let y = rect.center().y - 1.5 + k as f32 * 3.0; - painter.line_segment([pos2(rect.center().x - 9.0, y), pos2(rect.center().x + 9.0, y)], grip); - } } if bar.has_focus() { painter.rect_stroke(bar_rect.shrink(1.0), 0.0, Stroke::new(1.0, style.accent), StrokeKind::Inside); diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index feb9b68ba4..73d398439c 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -428,11 +428,6 @@ impl Renderer<'_, P> { if response.double_clicked() { self.output.actions.push(Action::SetIconic { panel: first.clone(), iconic: !column.iconic }); } - for k in 0..2 { - let y = grip.center().y - 1.5 + k as f32 * 3.0; - let x = grip.center().x; - ui.painter().with_clip_rect(grip).line_segment([pos2(x - 9.0, y), pos2(x + 9.0, y)], Stroke::new(1.0, self.style.inactive_text)); - } if response.has_focus() || response.hovered() { ui.painter().with_clip_rect(grip).rect_stroke( grip.shrink(1.0), diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 25d873253f..28061ff52d 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -179,20 +179,6 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetMinimized { panel: owner.selected.clone(), minimized: !owner.minimized }); } let active = response.has_focus() || response.hovered(); - if movable { - // A grip mark at rest, centered in the bar's reserved width beside the header. - let grip = if self.style.right_to_left { - Rect::from_min_max(hit.min, pos2((hit.left() + self.style.drag_bar_width).min(hit.right()), hit.bottom())) - } else { - Rect::from_min_max(pos2((hit.right() - self.style.drag_bar_width).max(hit.left()), hit.top()), hit.max) - }; - let stroke = Stroke::new(1.0, if active { self.style.text } else { self.style.inactive_text }); - let half = (hit.height() * 0.2).min(4.0); - for k in -1..=1 { - let x = grip.center().x + k as f32 * 3.0; - ui.painter().with_clip_rect(hit).line_segment([pos2(x, grip.center().y - half), pos2(x, grip.center().y + half)], stroke); - } - } if active { ui.painter().with_clip_rect(hit).rect_stroke( hit.shrink(1.0), diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 8949e334bc..12d84c76ab 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -15,7 +15,7 @@ use crate::docking::{ targets::{DockDrop, DockTarget, horizontal_line, usable}, }; -/// Height of the grip above each icon group. +/// Height of the drag strip above each icon group. const GRIP: f32 = 6.0; /// Room between two icon groups, with the separator line in its middle. const SEPARATOR: f32 = 7.0; @@ -185,7 +185,7 @@ impl Renderer<'_, P> { } } - /// The grip above an icon group drags the whole group (S8). + /// The strip above an icon group drags the whole group (S8). fn icon_grip(&mut self, ui: &mut Ui, group: &Group

, grip: Rect, width: f32) { let Some(first) = group.panels.first() else { return }; let movable = group.panels.iter().all(|p| self.permissions(p).movable); @@ -196,10 +196,6 @@ impl Renderer<'_, P> { let source = Rect::from_min_size(grip.min, vec2(width.max(self.style.min_pane), height.max(self.style.tab_height))); self.record_float(&group.panels, vec2(grip.width(), self.row_height()), source.size()); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label)); - let color = if response.hovered() || response.dragged() { self.style.text } else { self.style.inactive_text }; - let painter = ui.painter().with_clip_rect(grip.intersect(ui.clip_rect())); - painter.hline((grip.center().x - 8.0)..=(grip.center().x + 8.0), grip.center().y - 1.0, Stroke::new(1.0, color)); - painter.hline((grip.center().x - 8.0)..=(grip.center().x + 8.0), grip.center().y + 1.0, Stroke::new(1.0, color)); if movable && response.drag_started() { let origin = ui.input(|i| i.pointer.press_origin()).or_else(|| ui.ctx().pointer_interact_pos()).unwrap_or(grip.center()); let drag = GroupDrag { diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 15b4535d76..5f6c17e355 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -121,17 +121,15 @@ fn galley_labels_stay_whole_and_only_an_over_wide_active_tab_ends_with_an_ellips } #[test] -fn drag_bar_shows_a_grip_at_rest_and_a_group_drag_paints_a_filled_labeled_ghost() { +fn drag_bar_draws_no_mark_at_rest_and_a_group_drag_paints_a_filled_labeled_ghost() { let mut d = Driver::new(frames()); let visuals = d.ctx.global_style().visuals.clone(); let bar = d.rect("drag-bar", 2); - let grip = flat(&d.shapes).into_iter().any(|(_, shape)| match shape { - egui::Shape::LineSegment { points, stroke } => { - bar.contains(points[0]) && bar.contains(points[1]) && stroke.color == visuals.weak_text_color() - } + let mark = flat(&d.shapes).into_iter().any(|(_, shape)| match shape { + egui::Shape::LineSegment { points, .. } => bar.contains(points[0]) && bar.contains(points[1]), _ => false, }); - assert!(grip, "no grip mark in the drag bar at rest"); + assert!(!mark, "a mark in the drag bar at rest"); d.hold(bar.center(), pos2(150.0, 300.0)); let fill = visuals.selection.stroke.color.gamma_multiply(0.15); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index b2226fa4a2..1686b934eb 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -195,7 +195,7 @@ A flyout fits its content the same way, without the title bar. `middle_click_closes_tabs` turn either on or off in any profile. - A column's »/« button collapses it to icons, one icon per panel with a separator between groups. Widen an iconic column to show panel names. Click an icon to open its group as a flyout on the - canvas side. Drag an icon to move its panel, or the grip above an icon group to move the group. + canvas side. Drag an icon to move its panel, or the strip above an icon group to move the group. ## Commands From a0b923ac1e8d7dba473e4ac8dd9cb572d9e62633 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 04:40:33 +0000 Subject: [PATCH 76/94] docking: icon groups reserve no drag strip An icon group's drag band covers the separator above it and the top 4 pt of its first icon, so icons are spaced only by the separators between groups. --- crates/ui/src/docking/iconic_tests.rs | 7 ++++--- crates/ui/src/docking/render/iconic.rs | 22 +++++++++++++--------- docs/ui-docking.md | 2 +- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index d1008d3efb..1d372ad52a 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -76,9 +76,10 @@ fn collapsed_column_shows_one_icon_per_panel_with_group_separators() { let (one, two, three) = (hit(&d, Hit::Icon(1)), hit(&d, Hit::Icon(2)), hit(&d, Hit::Icon(3))); let (grip1, grip3) = (hit(&d, Hit::IconGrip(1)), hit(&d, Hit::IconGrip(3))); assert_eq!(one.width(), 36.0, "the column takes the style's iconic width"); - assert_eq!((grip1.bottom(), one.bottom()), (one.top(), two.top()), "a group's icons follow its grip and each other"); - assert_eq!(grip3.top() - two.bottom(), 7.0, "groups are apart by the separator"); - assert_eq!(three.top(), grip3.bottom()); + assert_eq!(one.bottom(), two.top(), "a group's icons follow each other"); + assert_eq!(three.top() - two.bottom(), 7.0, "groups are apart by the separator, with no room for a grip"); + assert_eq!((grip1.top(), grip1.bottom()), (one.top(), one.top() + 4.0), "the first group's band is its top edge"); + assert_eq!((grip3.top(), grip3.bottom()), (two.bottom(), three.top() + 4.0), "a later group's band covers the separator"); assert!(d.hit(&Hit::Tab(1)).is_none(), "an iconic column draws no tabs"); } diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 12d84c76ab..2abe22d75b 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -15,8 +15,9 @@ use crate::docking::{ targets::{DockDrop, DockTarget, horizontal_line, usable}, }; -/// Height of the drag strip above each icon group. -const GRIP: f32 = 6.0; +/// How far an icon group's drag band reaches into its first icon. The band also covers the +/// separator room above the group; it reserves no height of its own. +const GROUP_BAND: f32 = 4.0; /// Room between two icon groups, with the separator line in its middle. const SEPARATOR: f32 = 7.0; /// Height of a flyout, or of a panel floated from an icon, when nothing else sizes it. @@ -103,7 +104,7 @@ impl Renderer<'_, P> { } fn icon_group_height(&self, group: &Group

) -> f32 { - GRIP + group.panels.len() as f32 * self.row_height() + group.panels.len() as f32 * self.row_height() } /// The body of an iconic column: icon groups top to bottom, scrolling when they do not fit. @@ -146,21 +147,23 @@ impl Renderer<'_, P> { let mut bands = Vec::new(); for (index, group) in column.groups.iter().enumerate() { let Some(first) = group.panels.first() else { continue }; + let band_top = if index > 0 { top } else { area.top() }; if index > 0 { let y = top + SEPARATOR * 0.5; ui.painter().with_clip_rect(view).hline(area.x_range().shrink(4.0), y, self.style.border); top += SEPARATOR; } let rect = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), self.icon_group_height(group))); - let grip = Rect::from_min_size(rect.min, vec2(rect.width(), GRIP)); - self.icon_grip(ui, group, grip, column.width); let showing = open.as_ref().filter(|p| group.panels.contains(p)); - let mut y = grip.bottom(); + let mut y = rect.top(); for panel in &group.panels { let cell = Rect::from_min_size(pos2(rect.left(), y), vec2(rect.width(), self.row_height())); self.icon(ui, panel, cell, labels, showing); y = cell.bottom(); } + // After the icons, so the band wins the top of the first icon. + let band = Rect::from_min_max(pos2(rect.left(), band_top), pos2(rect.right(), (rect.top() + GROUP_BAND).min(rect.bottom()))); + self.icon_grip(ui, group, band, rect.top(), column.width); // The state again: a click above may have opened or closed this group's flyout. if flyout::

(ui.ctx(), self.id).is_some_and(|p| group.panels.contains(&p)) { self.iconic.request = Some(Request { group: group.clone(), icons: rect.intersect(view), column: view, edge, width: column.width }); @@ -185,15 +188,16 @@ impl Renderer<'_, P> { } } - /// The strip above an icon group drags the whole group (S8). - fn icon_grip(&mut self, ui: &mut Ui, group: &Group

, grip: Rect, width: f32) { + /// The band on an icon group's top edge drags the whole group (S8). `top` is the group's + /// first icon's top, where a floated group's source starts. + fn icon_grip(&mut self, ui: &mut Ui, group: &Group

, grip: Rect, top: f32, width: f32) { let Some(first) = group.panels.first() else { return }; let movable = group.panels.iter().all(|p| self.permissions(p).movable); let response = ui.interact(grip, self.id.with(("icon-grip", Some(first))), Sense::drag()); let response = if movable { response.on_hover_cursor(egui::CursorIcon::Grab) } else { response }; self.register_interaction(ui.ctx(), response.id); let height = group.height.filter(|h| h.is_finite()).unwrap_or(FLYOUT_HEIGHT); - let source = Rect::from_min_size(grip.min, vec2(width.max(self.style.min_pane), height.max(self.style.tab_height))); + let source = Rect::from_min_size(pos2(grip.left(), top), vec2(width.max(self.style.min_pane), height.max(self.style.tab_height))); self.record_float(&group.panels, vec2(grip.width(), self.row_height()), source.size()); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &self.style.move_group_label)); if movable && response.drag_started() { diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 1686b934eb..e2b0607a56 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -195,7 +195,7 @@ A flyout fits its content the same way, without the title bar. `middle_click_closes_tabs` turn either on or off in any profile. - A column's »/« button collapses it to icons, one icon per panel with a separator between groups. Widen an iconic column to show panel names. Click an icon to open its group as a flyout on the - canvas side. Drag an icon to move its panel, or the strip above an icon group to move the group. + canvas side. Drag an icon to move its panel, or an icon group's top edge (the separator line above it) to move the group. ## Commands From 2fa4ad79d7dcde5e6ad671d36083dee367a1b788 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 16:19:25 +0000 Subject: [PATCH 77/94] docking: floating windows stay inside the app's float bounds DockArea::float_bounds sets where floating windows, flyouts and drag ghosts may go; the default is the whole viewport. An app with its own title bar under a transparent macOS title bar passes the viewport below it, so a floating window can't be dropped, dragged or restored where pressing it moves the app window. --- crates/ui/src/docking/iconic_tests.rs | 20 ++++++++++++++++++++ crates/ui/src/docking/render/floating.rs | 4 ++-- crates/ui/src/docking/render/group.rs | 4 ++-- crates/ui/src/docking/render/iconic.rs | 3 +-- crates/ui/src/docking/render/mod.rs | 2 ++ crates/ui/src/docking/render/native.rs | 2 +- crates/ui/src/docking/render/preview.rs | 22 +++++++++++----------- crates/ui/src/docking/surface.rs | 14 +++++++++++++- crates/ui/src/docking/testing.rs | 8 +++++++- docs/ui-docking.md | 1 + 10 files changed, 60 insertions(+), 20 deletions(-) diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index 1d372ad52a..825a2687cc 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -388,3 +388,23 @@ fn chrome_has_focus_covers_every_drawn_control() { assert!(DockArea::::new(d.id).chrome_has_focus(&d.ctx, &d.layout), "{hit:?}"); } } + +#[test] +fn floating_windows_stay_inside_the_float_bounds() { + // The app's title bar strip (top 30 pt) is outside the bounds: a window saved there is + // drawn below it, and a title bar drag towards it stops at its edge. Command keeps the + // drag from docking. + let mut layout = docked(&[&[1]], false); + layout.floating.push(Floating::single(vec![5], 0, [400.0, 0.0, 240.0, 200.0])); + let mut d = DockDriver::new(layout, Content); + d.float_bounds = Some(Rect::from_min_max(pos2(0.0, 30.0), pos2(800.0, 600.0))); + d.settle(); + let title = hit(&d, Hit::Title(5)); + assert!(title.top() >= 30.0, "{title:?}"); + d.modifiers = egui::Modifiers::COMMAND; + d.drag(title.center(), pos2(title.center().x, 2.0)); + d.modifiers = egui::Modifiers::NONE; + d.settle(); + let title = hit(&d, Hit::Title(5)); + assert!(title.top() >= 30.0, "{title:?}"); +} diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 25ab410172..85282ca041 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -23,7 +23,7 @@ pub(in crate::docking) struct StackHit

{ impl Renderer<'_, P> { pub(in crate::docking) fn floating(&mut self, ctx: &Context, windows: &[Floating

]) { - let screen = ctx.content_rect(); + let screen = self.float_bounds; if !crate::docking::targets::usable(screen) { return; } @@ -139,7 +139,7 @@ impl Renderer<'_, P> { && !ui.input(|i| i.key_pressed(Key::Escape) || !i.focused) { // From the press origin, so fractional pointer steps do not accumulate rounding. - let moved = clamp_float(drag.source.translate(pointer - drag.origin), ui.ctx().content_rect()); + let moved = clamp_float(drag.source.translate(pointer - drag.origin), self.float_bounds); self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); } if response.bar.double_clicked() { diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 28061ff52d..b84cde4ab1 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -269,7 +269,7 @@ impl Renderer<'_, P> { } if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.float_group_label()) { let size = self.group_float_size(owner.panels, owner.rect.size()); - let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), ui.ctx().content_rect()); + let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), self.float_bounds); self.output.actions.push(Action::MoveGroup { panel: panel.clone(), to: Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) }, @@ -410,7 +410,7 @@ impl Renderer<'_, P> { response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); if response.clicked() { let size = self.float_size(panel, group.size()); - let rect = clamp_float(Rect::from_min_size(group.min + vec2(24.0, 24.0), size), ui.ctx().content_rect()); + let rect = clamp_float(Rect::from_min_size(group.min + vec2(24.0, 24.0), size), self.float_bounds); self.output.actions.push(Action::Float { panel: panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }); ui.close(); } diff --git a/crates/ui/src/docking/render/iconic.rs b/crates/ui/src/docking/render/iconic.rs index 2abe22d75b..2bb3e23503 100644 --- a/crates/ui/src/docking/render/iconic.rs +++ b/crates/ui/src/docking/render/iconic.rs @@ -296,8 +296,7 @@ impl Renderer<'_, P> { close_flyout::

(ctx, self.id); return; } - let screen = ctx.content_rect(); - let bounds = self.workspace.intersect(screen); + let bounds = self.workspace.intersect(self.float_bounds); let width = request.width.max(self.style.min_pane).min(bounds.width()); let max = self .content diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index b1d24a77c1..badd4678bf 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -35,6 +35,8 @@ pub(super) struct Renderer<'a, P> { pub(super) layout: &'a Layout

, /// The docked area, for host drop requests. pub(super) workspace: Rect, + /// Where floating windows, flyouts and drag ghosts go: [`crate::docking::DockArea::float_bounds`]. + pub(super) float_bounds: Rect, pub(super) targets: Vec>, /// [D] Seams, group bands, column edges and new-dock bands, see [`crate::docking::targets::DockDrop`]. pub(super) dock_targets: Vec>, diff --git a/crates/ui/src/docking/render/native.rs b/crates/ui/src/docking/render/native.rs index 94627bd1a0..349dcbf25b 100644 --- a/crates/ui/src/docking/render/native.rs +++ b/crates/ui/src/docking/render/native.rs @@ -134,7 +134,7 @@ impl Renderer<'_, P> { Some(window) => window.rect, None => { let size = self.float_size(panel, owner.rect.size()); - let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), ctx.content_rect()); + let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), self.float_bounds); [rect.left(), rect.top(), rect.width(), rect.height()] } }; diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 72c5001990..4349e14de7 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -34,7 +34,7 @@ impl Renderer<'_, P> { let (escape, focused, down, released, pointer) = ctx.input(|i| (i.key_pressed(Key::Escape), i.focused, i.pointer.primary_down(), i.pointer.primary_released(), i.pointer.interact_pos())); let pointer = pointer.filter(|p| p.is_finite()); - let ghost = pointer.map(|pointer| self.group_ghost(ctx, &drag, pointer)); + let ghost = pointer.map(|pointer| self.group_ghost(&drag, pointer)); if !escape && focused && (down || released) @@ -67,7 +67,7 @@ impl Renderer<'_, P> { let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return }; match drag.gesture { GroupGesture::Window => self.drop_window(&drag, pointer, float_only), - GroupGesture::Group | GroupGesture::Column => self.drop_group(ctx, &drag, pointer, float_only), + GroupGesture::Group | GroupGesture::Column => self.drop_group(&drag, pointer, float_only), } } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { self.output.group_drag = Some(drag.panel.clone()); @@ -109,7 +109,7 @@ impl Renderer<'_, P> { /// Release of a group drag: join or split at the target, or float at the ghost with the /// group's size. Over its own docked position nothing changes; a floating group released /// over itself moves there. - fn drop_group(&mut self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + fn drop_group(&mut self, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { if pointer.distance(drag.origin) < 2.0 { return; } @@ -129,7 +129,7 @@ impl Renderer<'_, P> { } // No target: hosts that still apply their own policy for a whole-group release get it. self.output.group_drop = Some((drag.panel.clone(), pointer)); - let rect = self.group_ghost(ctx, drag, pointer); + let rect = self.group_ghost(drag, pointer); let action = group_action(drag, Target::Float { rect: Some([rect.left(), rect.top(), rect.width(), rect.height()]) }); if self.layout.clone().apply_with_permissions(action.clone(), |p| self.permissions(p)).is_ok() { self.output.actions.push(action); @@ -142,7 +142,7 @@ impl Renderer<'_, P> { let ctx = ui.ctx(); let painter = self.preview_painter(ctx); if drag.gesture != GroupGesture::Window { - let ghost = self.group_ghost(ctx, drag, pointer); + let ghost = self.group_ghost(drag, pointer); drop_preview(&painter, ghost, self.style.accent, true); let strip = Rect::from_min_size(ghost.min, vec2(ghost.width(), self.style.tab_height.min(ghost.height()))); let labels = painter.with_clip_rect(strip.shrink(2.0)); @@ -207,7 +207,7 @@ impl Renderer<'_, P> { let float_only = float_only(ctx) || drag.undock; let floatable = self.permissions(&drag.panel).floatable && (float_only || gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); - let floating_rect = floatable.then(|| self.tab_float_rect(ctx, &drag, pointer)); + let floating_rect = floatable.then(|| self.tab_float_rect(&drag, pointer)); if self.host_drop(ctx, &drag.panel, pointer, false, released, floating_rect) { if released { cancel_drag::

(ctx, self.id); @@ -357,16 +357,16 @@ impl Renderer<'_, P> { /// Where a group or column drag floats with the pointer at `pointer`, keeping the grab /// offset, inside the window (Z2). - fn group_ghost(&self, ctx: &Context, drag: &GroupDrag

, pointer: Pos2) -> Rect { + fn group_ghost(&self, drag: &GroupDrag

, pointer: Pos2) -> Rect { let size = if drag.gesture == GroupGesture::Window { drag.source.size() } else { self.group_float_size(&drag.members, drag.source.size()) }; let grab = (drag.origin - drag.source.min).clamp(Vec2::ZERO, size); - clamp_float(Rect::from_min_size(pointer - grab, size), ctx.content_rect()) + clamp_float(Rect::from_min_size(pointer - grab, size), self.float_bounds) } - fn tab_float_rect(&self, ctx: &Context, drag: &Drag

, pointer: Pos2) -> Rect { + fn tab_float_rect(&self, drag: &Drag

, pointer: Pos2) -> Rect { let size = self.float_size(&drag.panel, drag.source.size()); let grab = drag.grab.min(vec2(size.x, self.style.tab_height)); - clamp_float(Rect::from_min_size(pointer - grab, size), ctx.content_rect()) + clamp_float(Rect::from_min_size(pointer - grab, size), self.float_bounds) } /// Offer the gesture to [`crate::docking::DockContent::resolve_drag`]. True when the host @@ -388,7 +388,7 @@ impl Renderer<'_, P> { whole_group, released, workspace: self.workspace, - screen: ctx.content_rect(), + screen: self.float_bounds, }; let Some(feedback) = self.content.resolve_drag(ctx, self.style, &request) else { return false }; if !released { diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index d8812080a8..03aae03f74 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -672,11 +672,12 @@ pub struct DockArea<'a, P = ()> { maximized: Option

, hide: HidePanels<'a, P>, auto_collapse: bool, + float_bounds: Option, } impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { pub fn new(id: Id) -> Self { - Self { id, activation: None, blockers: Vec::new(), maximized: None, hide: HidePanels::None, auto_collapse: true } + Self { id, activation: None, blockers: Vec::new(), maximized: None, hide: HidePanels::None, auto_collapse: true, float_bounds: None } } /// [D] Auto-Collapse Iconic Panels (default on): a flyout closes on Escape or a press @@ -720,6 +721,16 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { self } + /// Where floating windows, flyouts and drag ghosts may go (default: the whole viewport). + /// An app whose own title bar sits under a transparent OS title bar (macOS full-size + /// content) passes the viewport below that strip: a window drawn there would take presses + /// that the OS or the app turns into moving the whole app window. Windows outside the + /// bounds, such as ones restored from a saved layout, are drawn moved inside. + pub fn float_bounds(mut self, bounds: Rect) -> Self { + self.float_bounds = Some(bounds); + self + } + /// Host overlays that must reject docking gestures, including floating fallback. pub fn blocked_rects(mut self, rects: &[Rect]) -> Self { self.blockers = rects.to_vec(); @@ -801,6 +812,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { blockers: self.blockers, layout, workspace: rect, + float_bounds: self.float_bounds.map_or(ui.ctx().content_rect(), |bounds| bounds.intersect(ui.ctx().content_rect())), targets: Vec::new(), dock_targets: Vec::new(), owned_interactions: Vec::new(), diff --git a/crates/ui/src/docking/testing.rs b/crates/ui/src/docking/testing.rs index e34cad2f36..868a6c4cc3 100644 --- a/crates/ui/src/docking/testing.rs +++ b/crates/ui/src/docking/testing.rs @@ -42,6 +42,8 @@ pub struct DockDriver { pub maximized: Option

, /// Passed to [`DockArea::raise_panel`] on the next frame only. pub raise: Option

, + /// Passed to [`DockArea::float_bounds`]. + pub float_bounds: Option, style: Option, shapes: Vec, time: f64, @@ -63,6 +65,7 @@ impl> Do auto_collapse: true, maximized: None, raise: None, + float_bounds: None, style: None, shapes: Vec::new(), time: 0.0, @@ -97,7 +100,7 @@ impl> Do ..Default::default() }; let (layout, content, area, id) = (&self.layout, &mut self.content, self.area, self.id); - let (style_fn, maximized, raise, auto) = (&self.style, self.maximized.clone(), self.raise.take(), self.auto_collapse); + let (style_fn, maximized, raise, auto, bounds) = (&self.style, self.maximized.clone(), self.raise.take(), self.auto_collapse, self.float_bounds); let mut full = self.ctx.run_ui(input, |ui| { let mut style = DockStyle::from_ui(ui); if let Some(adjust) = style_fn { @@ -108,6 +111,9 @@ impl> Do if let Some(panel) = raise.clone() { dock = dock.raise_panel(panel); } + if let Some(bounds) = bounds { + dock = dock.float_bounds(bounds); + } output = dock.show_content(ui, layout, &style, content); }); }); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index e2b0607a56..79a0ec711a 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -133,6 +133,7 @@ Builder options on `DockArea`: | `auto_collapse_iconic(on)` | Close a flyout on Escape or a click outside (default on). | | `raise_panel(panel)` | Raise a panel's floating window, or open its flyout, this frame. It moves no keyboard focus and does not set `DockOutput::focused`. | | `blocked_rects(rects)` | App overlays that docking gestures must ignore. | +| `float_bounds(rect)` | Where floating windows, flyouts and drag ghosts may go (default: the whole viewport). Pass the viewport below a title bar drawn under a transparent OS title bar, so no floating window sits where a press moves the app window. | `DockStyle::close_menu_items` and `DockStyle::close_button` hide the built-in Close menu items and the floating window ×. They hide controls only: a panel that stays `closable` still closes From 40c59bb577b225664a1a13e3d13a92df6119ae81 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 16:40:59 +0000 Subject: [PATCH 78/94] docking: narrow frames keep usable side drop zones, and seams split A side zone is a quarter of the frame deep, at least 32 pt and at most half the frame, so a 64 pt tool strip offers its left and right edges past the outer edge band. A pointer in the gap between frames resolves to the nearest frame's edge instead of floating. --- crates/ui/src/docking/frame_tests.rs | 120 ++++++++++++++++++++++++ crates/ui/src/docking/mod.rs | 2 + crates/ui/src/docking/render/preview.rs | 20 +++- crates/ui/src/docking/targets.rs | 22 +++-- docs/ui-docking.md | 4 + 5 files changed, 161 insertions(+), 7 deletions(-) create mode 100644 crates/ui/src/docking/frame_tests.rs diff --git a/crates/ui/src/docking/frame_tests.rs b/crates/ui/src/docking/frame_tests.rs new file mode 100644 index 0000000000..4d8c55f4d6 --- /dev/null +++ b/crates/ui/src/docking/frame_tests.rs @@ -0,0 +1,120 @@ +//! Frame profile in a Premiere-style editing layout, as FilmCraft draws it: a bottom row of +//! Project | Tools | Timeline | Audio Meters, where Tools and the meters are narrow fixed-width +//! frames without a tab strip that a grip on top moves. + +use std::collections::HashMap; + +use super::testing::DockDriver; +use super::*; +use crate::layout::{SplitAxis, SplitSize}; +use egui::{Id, Pos2, Rect, Sense, pos2, vec2}; + +const SOURCE: [u32; 4] = [1, 11, 12, 13]; +const PROGRAM: u32 = 2; +const PROPERTIES: [u32; 3] = [3, 31, 32]; +const PROJECT: [u32; 7] = [4, 41, 42, 43, 44, 45, 46]; +const TOOLS: u32 = 5; +const TIMELINE: u32 = 6; +const METERS: u32 = 7; + +const TOOLS_WIDTH: f32 = 64.0; +const METERS_WIDTH: f32 = 116.0; + +/// Panel bodies by their rects, with a FilmCraft-style 8 pt grip on the bare frames. +#[derive(Default)] +struct Film { + bodies: HashMap, +} + +impl DockContent for Film { + fn body(&mut self, ui: &mut egui::Ui, panel: &u32) { + let frame = ui.max_rect(); + self.bodies.insert(*panel, frame); + if self.bare(panel) { + let grip = Rect::from_min_size(frame.min, vec2(frame.width(), 8.0_f32.min(frame.height()))); + if ui.interact(grip, Id::new(("grip", *panel)), Sense::drag()).drag_started() { + begin_drag(ui.ctx(), Id::new("dock-driver"), *panel, frame); + } + } + ui.allocate_rect(frame, Sense::hover()); + } + fn logical_label(&self, panel: &u32) -> String { + format!("Panel {panel}") + } + fn bare(&self, panel: &u32) -> bool { + matches!(*panel, TOOLS | METERS) + } +} + +type Driver = DockDriver; + +fn tabs(panels: &[u32]) -> Node { + Node::Tabs { panels: panels.to_vec(), active: 0 } +} + +fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node { + Node::Split { axis, size, first: Box::new(first), second: Box::new(second) } +} + +fn hsplit(size: SplitSize, first: Node, second: Node) -> Node { + split(SplitAxis::Horizontal, size, first, second) +} + +/// Tools | Timeline | Audio Meters. +fn tools_row() -> Node { + hsplit(SplitSize::FixedFirst(TOOLS_WIDTH), tabs(&[TOOLS]), hsplit(SplitSize::FixedSecond(METERS_WIDTH), tabs(&[TIMELINE]), tabs(&[METERS]))) +} + +/// FilmCraft's Editing workspace: Source | Program | Properties over Project | Tools | Timeline | Meters. +fn editing() -> Layout { + let top = hsplit(SplitSize::FixedSecond(450.0), hsplit(SplitSize::Ratio(0.5), tabs(&SOURCE), tabs(&[PROGRAM])), tabs(&PROPERTIES)); + let bottom = hsplit(SplitSize::Ratio(0.29), tabs(&PROJECT), tools_row()); + Layout { root: Some(split(SplitAxis::Vertical, SplitSize::Ratio(0.57), top, bottom)), floating: Vec::new() } +} + +fn driver(layout: Layout) -> Driver { + let mut d = DockDriver::new(layout, Film::default()).with_style(|style| style.profile = Profile::Frame); + d.screen = Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 860.0)); + d.area = d.screen; + d.settle(); + d +} + +fn body(d: &Driver, panel: u32) -> Rect { + d.content.bodies.get(&panel).copied().unwrap_or_else(|| panic!("panel {panel} not drawn")) +} + +fn floated_project() -> Driver { + let mut layout = editing(); + layout.apply(Action::MoveGroup { panel: PROJECT[0], to: Target::Float { rect: Some([600.0, 120.0, 400.0, 300.0]) } }).unwrap(); + driver(layout) +} + +fn split_at(anchor: u32, zone: Zone) -> Target { + Target::At { anchor, placement: Placement::Split(zone) } +} + +#[test] +fn a_narrow_frame_offers_both_side_targets_and_a_seam_splits_beside_its_frames() { + let d = floated_project(); + let tools = body(&d, TOOLS); + assert_eq!((tools.left(), tools.width()), (0.0, TOOLS_WIDTH), "Tools starts the bottom row"); + // Left: past the 8 pt outer edge band. + for (at, zone) in [(pos2(20.0, tools.center().y), Zone::Left), (pos2(tools.right() - 12.0, tools.center().y), Zone::Right)] { + let mut d = floated_project(); + let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap(); + let out = d.drag(bar.center(), at); + assert_eq!(out.actions, vec![Action::MoveGroup { panel: PROJECT[0], to: split_at(TOOLS, zone) }], "{zone:?}"); + } + // The gap between Tools and Timeline: a tab dropped there splits instead of floating. + let mut d = floated_project(); + let timeline = body(&d, TIMELINE); + let seam = pos2((tools.right() + timeline.left()) * 0.5, timeline.center().y); + assert!(!tools.contains(seam) && !timeline.contains(seam), "the seam is outside both frames"); + let out = d.drag(d.hit(&Hit::Tab(PROGRAM)).unwrap().center(), seam); + assert!( + matches!(&out.actions[..], [Action::Move { panel: PROGRAM, anchor: TOOLS | TIMELINE, placement: Placement::Split(Zone::Left | Zone::Right) }]), + "{:?}", + out.actions + ); +} diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index b8462ec329..ba6651d223 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -42,6 +42,8 @@ mod dock_tests; #[cfg(test)] mod floating_tests; #[cfg(test)] +mod frame_tests; +#[cfg(test)] mod group_tests; #[cfg(test)] mod iconic_tests; diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 4349e14de7..7fb51f5b41 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -88,6 +88,7 @@ impl Renderer<'_, P> { return valid(proposal); } let own = |t: &crate::docking::DropTarget

| t.tabs.iter().any(|(p, _)| drag.members.contains(p)); + let pointer = self.seam_pointer(pointer); let target = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer) && !(window && own(t)))?; if own(target) { @@ -106,6 +107,22 @@ impl Renderer<'_, P> { valid(proposal) } + /// A pointer in the gap between docked frames, outside every target, moves onto the edge of + /// the nearest frame that takes splits, so a seam splits beside that frame rather than floating. + pub(super) fn seam_pointer(&self, pointer: Pos2) -> Pos2 { + let usable = |rect: Rect| crate::docking::targets::usable(rect); + if self.targets.iter().any(|t| usable(t.rect) && t.rect.contains(pointer)) { + return pointer; + } + self.targets + .iter() + .filter(|t| t.allow_splits && usable(t.rect)) + .map(|t| (t.rect.distance_to_pos(pointer), t.rect)) + .filter(|(distance, _)| *distance <= self.style.gap) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map_or(pointer, |(_, rect)| rect.clamp(pointer)) + } + /// Release of a group drag: join or split at the target, or float at the ghost with the /// group's size. Over its own docked position nothing changes; a floating group released /// over itself moves there. @@ -230,7 +247,8 @@ impl Renderer<'_, P> { let proposal = if float_only { None } else { - self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false).or_else(|| resolve_drop(&drag.panel, pointer, &self.targets)) + self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false) + .or_else(|| resolve_drop(&drag.panel, self.seam_pointer(pointer), &self.targets)) }; if released { cancel_drag::

(ctx, self.id); diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index 3f94615391..ff515ec0e0 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -31,8 +31,13 @@ pub(super) fn usable(rect: Rect) -> bool { rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0 && rect.width() <= 1_000_000.0 && rect.height() <= 1_000_000.0 } -/// Tab header is the center; otherwise the nearest quarter-width/height edge wins. -/// Outside, non-finite, empty and inverted rectangles have no target. +/// Least depth of a side zone, so a narrow frame such as a tool strip keeps side targets wide +/// enough to hit. +const MIN_SIDE_ZONE: f32 = 32.0; + +/// Tab header is the center; otherwise the nearest side zone wins. A side zone is a quarter of +/// the frame deep, at least 32 pt and at most half the frame, so a frame up to 64 pt wide has no +/// center. Outside, non-finite, empty and inverted rectangles have no target. pub fn drop_zone(rect: Rect, tab_height: f32, pointer: Pos2) -> Option { if !usable(rect) || !pointer.is_finite() || !rect.contains(pointer) || !tab_height.is_finite() || tab_height < 0.0 { return None; @@ -40,11 +45,16 @@ pub fn drop_zone(rect: Rect, tab_height: f32, pointer: Pos2) -> Option { if pointer.y < rect.top() + tab_height.min(rect.height()) { return Some(Zone::Center); } - let x = (pointer.x - rect.left()) / rect.width(); - let y = (pointer.y - rect.top()) / rect.height(); - let distances = [(x, Zone::Left), (1.0 - x, Zone::Right), (y, Zone::Top), (1.0 - y, Zone::Bottom)]; + let depth = |extent: f32| (extent * 0.25).max(MIN_SIDE_ZONE).min(extent * 0.5); + let (x, y) = (depth(rect.width()), depth(rect.height())); + let distances = [ + ((pointer.x - rect.left()) / x, Zone::Left), + ((rect.right() - pointer.x) / x, Zone::Right), + ((pointer.y - rect.top()) / y, Zone::Top), + ((rect.bottom() - pointer.y) / y, Zone::Bottom), + ]; let (distance, zone) = distances.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?; - Some(if distance > 0.25 { Zone::Center } else { zone }) + Some(if distance > 1.0 { Zone::Center } else { zone }) } /// Preview of the region occupied after a split or group merge. diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 79a0ec711a..e3f6255f4f 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -186,6 +186,10 @@ A flyout fits its content the same way, without the title bar. 4 pt band above the title bar (`chrome::RESIZE_BAND`), so they take no moves and no clicks on the title bar's buttons. A resize keeps the opposite edges in place and stays within the size limits and the screen. A focused resize handle moves its edge 8 pt per arrow key. +- Over a frame, the tab strip and the middle join its tabs, and the nearest side splits it. A + side zone is a quarter of the frame deep, at least 32 pt and at most half the frame, so a narrow + tool strip keeps both side targets. A drop in the gap between two frames splits beside the + nearer one. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. - Double-click a tab or drag bar to minimize a group to its strip. From 899807ff19c9fc210a9f360b723b1411ba38960a Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 16:44:06 +0000 Subject: [PATCH 79/94] docking: a split beside a fixed-size frame keeps that frame's size A side split replaced the anchor frame in place, so a split beside a fixed-width frame such as a tool strip took the frame's fixed slot: the two frames shared its width, and the parent's divider resized both. The frame now keeps its size: on its outer side the new split wraps the parent, on its inner side it halves the parent's other child. The drop preview shows the half the new frame takes. --- crates/ui/src/docking/dock_model.rs | 41 +++++++++++++++++---- crates/ui/src/docking/frame_tests.rs | 48 +++++++++++++++++++++++++ crates/ui/src/docking/model.rs | 21 +++++------ crates/ui/src/docking/render/mod.rs | 27 ++++++++++++++ crates/ui/src/docking/render/preview.rs | 28 +++++++++++++-- crates/ui/src/docking/surface.rs | 1 + docs/ui-docking.md | 5 +++ 7 files changed, 152 insertions(+), 19 deletions(-) diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index 435fd2dc64..747f5dc346 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -207,6 +207,38 @@ pub(super) fn node_at_mut<'a, P>(mut node: &'a mut Node

, path: &[bool]) -> Op Some(node) } +/// Put `new` on the `zone` side of the frame at `path`, in a new half-size split. A frame that +/// holds the fixed size of its parent split along the same axis keeps that size: on its outer +/// side the new split wraps the parent, on its inner side it halves the parent's other child. +/// So a fixed-width tool strip neither halves nor shares its width with the new frame. +pub(super) fn split_frame

(root: &mut Node

, path: &[bool], new: Node

, zone: Zone) -> bool { + let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; + let before = matches!(zone, Zone::Top | Zone::Left); + let (target, new_first) = match fixed_slot(root, path, axis) { + Some((parent, anchor_first)) if before == anchor_first => (parent.to_vec(), before), + Some((parent, anchor_first)) => ([parent, &[anchor_first]].concat(), !before), + None => (path.to_vec(), before), + }; + let Some(node) = node_at_mut(root, &target) else { return false }; + let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); + let (first, second) = if new_first { (new, old) } else { (old, new) }; + *node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) }; + true +} + +/// The parent path of the frame at `path` and whether the frame is its first child, when the +/// parent splits along `axis` and the frame holds its fixed size. +pub(super) fn fixed_slot<'a, P>(root: &Node

, path: &'a [bool], axis: SplitAxis) -> Option<(&'a [bool], bool)> { + let (second, parent) = path.split_last()?; + let Node::Split { axis: parent_axis, size, .. } = node_at(root, parent)? else { return None }; + let fixed = match size { + SplitSize::FixedFirst(_) => !second, + SplitSize::FixedSecond(_) => *second, + SplitSize::Ratio(_) => false, + }; + (*parent_axis == axis && fixed).then_some((parent, !second)) +} + /// Insert `new` at `index` and select the member at `index + selected`. fn splice

(panels: &mut Vec

, active: &mut usize, index: usize, new: Vec

, selected: usize) { let index = index.min(panels.len()); @@ -578,14 +610,9 @@ impl Layout

{ } Placement::Split(zone) => { let Place::Node(path) = place else { return Err(DockError::InvalidPlacement) }; - let node = self.root.as_mut().and_then(|root| node_at_mut(root, &path)).ok_or(DockError::MissingTarget)?; let (panels, active) = flatten(moving.groups); - let new = Node::Tabs { panels, active }; - let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); - let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; - let (first, second) = if matches!(zone, Zone::Top | Zone::Left) { (new, old) } else { (old, new) }; - *node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) }; - Ok(()) + let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; + if split_frame(root, &path, Node::Tabs { panels, active }, zone) { Ok(()) } else { Err(DockError::MissingTarget) } } Placement::Group { below, height } => { if !valid_height(height) { diff --git a/crates/ui/src/docking/frame_tests.rs b/crates/ui/src/docking/frame_tests.rs index 4d8c55f4d6..6044b5c28d 100644 --- a/crates/ui/src/docking/frame_tests.rs +++ b/crates/ui/src/docking/frame_tests.rs @@ -118,3 +118,51 @@ fn a_narrow_frame_offers_both_side_targets_and_a_seam_splits_beside_its_frames() out.actions ); } + + +fn bottom(layout: &Layout) -> &Node { + let Some(Node::Split { second, .. }) = &layout.root else { panic!("{:?}", layout.root) }; + second +} + +/// Drag a split divider by `dx`, hovering it first as a pointer does. +fn drag_divider(d: &mut Driver, path: &[bool], dx: f32) { + let divider = d.hit(&Hit::Divider(Divider::Split(path.to_vec()))).unwrap_or_else(|| panic!("{path:?} in {:?}", d.hits())); + d.move_to(divider.center()); + d.drag(divider.center(), divider.center() + vec2(dx, 0.0)); + d.settle(); +} + +#[test] +fn a_split_beside_a_fixed_width_frame_keeps_its_width_and_gets_its_own_divider() { + // Left of Tools: the new frame takes half the row, beside Tools at its own width. + let mut d = floated_project(); + let tools = body(&d, TOOLS); + let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap(); + let at = pos2(20.0, tools.center().y); + d.hold(bar.center(), at); + let row = Rect::from_x_y_ranges(0.0..=1440.0, tools.y_range()); + assert!(d.filled(Rect::from_min_max(row.min, pos2(row.center().x, row.bottom())).shrink(1.0)), "the preview shows the new frame"); + d.release(at); + assert_eq!(bottom(&d.layout), &hsplit(SplitSize::Ratio(0.5), tabs(&PROJECT), tools_row())); + d.settle(); + assert_eq!(body(&d, TOOLS).width(), TOOLS_WIDTH); + // Each divider resizes its own two sides; Tools keeps its width. + let project = body(&d, PROJECT[0]).width(); + drag_divider(&mut d, &[true], -200.0); + let widths = |d: &Driver| (body(d, PROJECT[0]).width().round(), body(d, TOOLS).width().round()); + assert_eq!(widths(&d), ((project - 200.0).round(), TOOLS_WIDTH)); + drag_divider(&mut d, &[true, true], 30.0); + assert_eq!(widths(&d), ((project - 200.0).round(), TOOLS_WIDTH + 30.0)); + + // Right of Tools: the new frame takes half of what lies right of Tools. + let mut d = driver(editing()); + let tools = body(&d, TOOLS); + let tab = d.hit(&Hit::Tab(PROGRAM)).unwrap(); + d.drag(tab.center(), pos2(tools.right() - 12.0, tools.center().y)); + let rest = hsplit(SplitSize::FixedSecond(METERS_WIDTH), tabs(&[TIMELINE]), tabs(&[METERS])); + let right = hsplit(SplitSize::FixedFirst(TOOLS_WIDTH), tabs(&[TOOLS]), hsplit(SplitSize::Ratio(0.5), tabs(&[PROGRAM]), rest)); + assert_eq!(bottom(&d.layout), &hsplit(SplitSize::Ratio(0.29), tabs(&PROJECT), right)); + d.settle(); + assert_eq!(body(&d, TOOLS).width(), TOOLS_WIDTH); +} diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 641e6373f1..2fb4649928 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -1,6 +1,6 @@ use std::{collections::HashSet, fmt, hash::Hash}; -use super::dock_model::{Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, valid_column}; +use super::dock_model::{Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, split_frame, valid_column}; use crate::layout::{SplitAxis, SplitSize}; /// Limits are checked before cloning or recursively modifying an application layout. @@ -165,7 +165,9 @@ pub enum Placement

{ /// Insert before this existing destination member, or append. Also reorders a group. Tab { before: Option

}, /// Center inserts after the anchor; sides create a new half-size split. Sides apply to - /// `Tabs` and `Stack` nodes only. + /// `Tabs` and `Stack` nodes only. A frame that holds the fixed size of its parent split + /// along the same axis keeps it: on its outer side the new split wraps the parent, on its + /// inner side it halves the parent's other child. Split(Zone), /// A new group above or below the anchor's group, in a dock column or a floating stack. /// `height` is the inserted group's preferred height ([`super::Group::height`]); `None` @@ -1068,6 +1070,13 @@ impl Layout

{ let group = Group::new(vec![entry.panel], 0); return self.insert_moving(Moving::group(group), Target::At { anchor: anchor.clone(), placement }); } + if let (Placement::Split(zone), Place::Node(path)) = (&placement, &place) + && *zone != Zone::Center + { + let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; + let new = Node::Tabs { panels: vec![entry.panel], active: 0 }; + return if split_frame(root, path, new, *zone) { Ok(()) } else { Err(DockError::MissingTarget) }; + } if let Some(root) = self.root.as_mut() && insert_node(root, &entry, anchor, &placement) { @@ -1213,14 +1222,6 @@ fn insert_node(node: &mut Node

, entry: &StackEntry

, anchor: if !here { return false; } - if let Placement::Split(zone @ (Zone::Left | Zone::Right | Zone::Top | Zone::Bottom)) = placement { - let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); - let new = Node::Tabs { panels: vec![entry.panel.clone()], active: 0 }; - let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; - let (first, second) = if matches!(zone, Zone::Top | Zone::Left) { (new, old) } else { (old, new) }; - *node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) }; - return true; - } match node { Node::Tabs { panels, active } => { let index = match placement { diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index badd4678bf..c74a45c57d 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -50,6 +50,18 @@ pub(super) struct Renderer<'a, P> { /// Each panel's place in `layout`, and its entry in `float_space.contents`. pub(super) places: HashMap, pub(super) contents: HashMap, + /// Frames drawn as the fixed-size side of their parent split, for split previews. + pub(super) fixed_slots: Vec>, +} + +/// A frame that holds the fixed size of its parent split: the parent's and the other child's +/// rects, where a side split of the frame goes (see `dock_model::split_frame`). +pub(super) struct FixedSlot

{ + pub(super) panels: Vec

, + pub(super) axis: SplitAxis, + pub(super) first: bool, + pub(super) parent: Rect, + pub(super) sibling: Rect, } impl Renderer<'_, P> { @@ -103,6 +115,21 @@ impl Renderer<'_, P> { let (lo, hi) = split_bounds(wanted.available(), *axis, self.node_limits(first), self.node_limits(second)); let first_size = wanted.first_size().clamp(lo, hi); let Some(split) = split_rect(rect, *axis, SplitSize::FixedFirst(first_size), self.style.gap, 0.0) else { return }; + let fixed = match size { + SplitSize::FixedFirst(_) => Some((first, true, split.second)), + SplitSize::FixedSecond(_) => Some((second, false, split.first)), + SplitSize::Ratio(_) => None, + }; + let panels = |node: &Node

| match node { + Node::Tabs { panels, .. } => Some(panels.clone()), + Node::Stack { entries } => Some(entries.iter().map(|e| e.panel.clone()).collect()), + Node::Split { .. } | Node::Dock { .. } => None, + }; + if let Some((node, first, sibling)) = fixed + && let Some(panels) = panels(node) + { + self.fixed_slots.push(FixedSlot { panels, axis: *axis, first, parent: rect, sibling }); + } path.push(false); self.node(ui, first, split.first, path); path.pop(); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 7fb51f5b41..c18971594d 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -9,7 +9,9 @@ use crate::docking::{ dock_model::{Place, node_at}, resolve_drop, surface::TAB_PADDING, + zone_rect, }; +use crate::layout::SplitAxis; /// Ctrl (Windows, Linux) or Cmd (macOS) held: the drop floats and no target is offered. fn float_only(ctx: &Context) -> bool { @@ -104,7 +106,29 @@ impl Renderer<'_, P> { if window && matches!(proposal.placement, Placement::Split(_)) { return None; } - valid(proposal) + valid(self.split_preview(proposal)) + } + + /// The preview of a side split beside a frame that holds its parent's fixed size: the half + /// of the parent or of the other child that the new frame takes. + fn split_preview(&self, mut proposal: DropProposal

) -> DropProposal

{ + let Placement::Split(zone) = proposal.placement else { return proposal }; + let axis = match zone { + Zone::Center => return proposal, + Zone::Left | Zone::Right => SplitAxis::Horizontal, + Zone::Top | Zone::Bottom => SplitAxis::Vertical, + }; + let Some(slot) = self.fixed_slots.iter().find(|slot| slot.axis == axis && slot.panels.contains(&proposal.anchor)) else { return proposal }; + let opposite = match zone { + Zone::Left => Zone::Right, + Zone::Right => Zone::Left, + Zone::Top => Zone::Bottom, + _ => Zone::Top, + }; + let before = matches!(zone, Zone::Left | Zone::Top); + let preview = if before == slot.first { zone_rect(slot.parent, zone) } else { zone_rect(slot.sibling, opposite) }; + proposal.preview = preview.unwrap_or(proposal.preview); + proposal } /// A pointer in the gap between docked frames, outside every target, moves onto the edge of @@ -248,7 +272,7 @@ impl Renderer<'_, P> { None } else { self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false) - .or_else(|| resolve_drop(&drag.panel, self.seam_pointer(pointer), &self.targets)) + .or_else(|| resolve_drop(&drag.panel, self.seam_pointer(pointer), &self.targets).map(|p| self.split_preview(p))) }; if released { cancel_drag::

(ctx, self.id); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 03aae03f74..0c93281570 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -822,6 +822,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { float_space: FloatSpace { contents, ..FloatSpace::new(rect) }, places, contents: content_index, + fixed_slots: Vec::new(), }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index e3f6255f4f..e3cd49e613 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -68,6 +68,11 @@ layout.apply(Action::Move { `Placement::for_zone(layout, anchor, zone, right_to_left)` maps a left, right, top, bottom or center zone onto what the anchor's container takes: a split in the frame tree, a new column on that side or a new group above or below in a dock, a group above or below in a floating window. +- A side split zone puts what moves in a new half-size split of the anchor's frame. A frame + that holds the fixed size of its parent split along the same axis, such as a tool strip, keeps + that size: on its outer side the new split wraps the parent, on its inner side it halves the + parent's other child. The new split has its own divider, and the drop preview shows the half + the new frame takes. - Other actions select, minimize, collapse to icons, resize splits, columns and groups, and move a floating window to its own OS window (`SetNative`, feature `native-windows`). From 7d786e510868ac66c6c6ccf9dbeb4dfbab317c93 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 16:45:20 +0000 Subject: [PATCH 80/94] docking: the Frame profile drop preview says which key floats MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While a drag offers a docking target, a hint under the pointer reads "Hold Ctrl to float" ("Hold ⌘ to float" on macOS), from the localizable float_hint_label (key dock.floatHint). --- crates/ui/src/docking/frame_tests.rs | 45 ++++++++++++++++++++++++- crates/ui/src/docking/labels.rs | 4 ++- crates/ui/src/docking/render/frame.rs | 18 ++++++++++ crates/ui/src/docking/render/preview.rs | 8 +++++ crates/ui/src/docking/surface.rs | 4 +++ crates/ui/src/docking/trial_tests.rs | 2 +- docs/ui-docking.md | 5 ++- 7 files changed, 82 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/docking/frame_tests.rs b/crates/ui/src/docking/frame_tests.rs index 6044b5c28d..c27ce707b5 100644 --- a/crates/ui/src/docking/frame_tests.rs +++ b/crates/ui/src/docking/frame_tests.rs @@ -7,7 +7,7 @@ use std::collections::HashMap; use super::testing::DockDriver; use super::*; use crate::layout::{SplitAxis, SplitSize}; -use egui::{Id, Pos2, Rect, Sense, pos2, vec2}; +use egui::{Id, Modifiers, Pos2, Rect, Sense, pos2, vec2}; const SOURCE: [u32; 4] = [1, 11, 12, 13]; const PROGRAM: u32 = 2; @@ -166,3 +166,46 @@ fn a_split_beside_a_fixed_width_frame_keeps_its_width_and_gets_its_own_divider() d.settle(); assert_eq!(body(&d, TOOLS).width(), TOOLS_WIDTH); } + +fn texts(d: &Driver) -> Vec { + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let mut out = Vec::new(); + d.shapes().iter().for_each(|clipped| walk(&clipped.shape, &mut out)); + out +} + +#[test] +fn ctrl_or_cmd_floats_from_a_tab_a_drag_bar_or_a_grip_and_the_preview_says_so() { + const HINT: &str = "Hold Ctrl to float"; + let floated = |actions: &[Action], panel: u32| match actions { + [Action::Float { panel: p, .. }] => *p == panel, + [Action::MoveGroup { panel: p, to: Target::Float { .. } }] => *p == panel, + _ => false, + }; + let d = driver(editing()); + let over = body(&d, TIMELINE).center(); + let tab = d.hit(&Hit::Tab(PROJECT[0])).unwrap().center(); + let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); + let grip = pos2(body(&d, TOOLS).center().x, body(&d, TOOLS).top() + 4.0); + for (from, panel) in [(tab, PROJECT[0]), (bar, PROJECT[0]), (grip, TOOLS)] { + // Without the modifier, a release over a frame docks there; the preview names the modifier. + let mut d = driver(editing()); + d.hold(from, over); + assert!(texts(&d).iter().any(|t| t == HINT), "{from:?}: {:?}", texts(&d)); + let out = d.release(over); + assert!(!out.actions.is_empty() && !floated(&out.actions, panel), "{from:?}: {:?}", out.actions); + // Held, it floats, and the hint is gone. + let mut d = driver(editing()); + d.modifiers = Modifiers::COMMAND; + d.hold(from, over); + assert!(!texts(&d).iter().any(|t| t == HINT), "{from:?}"); + let out = d.release(over); + assert!(floated(&out.actions, panel), "{from:?}: {:?}", out.actions); + } +} diff --git a/crates/ui/src/docking/labels.rs b/crates/ui/src/docking/labels.rs index 4a4799c598..16934febb3 100644 --- a/crates/ui/src/docking/labels.rs +++ b/crates/ui/src/docking/labels.rs @@ -46,6 +46,7 @@ impl DockStyle { /// | `dock.restoreFrame` | `restore_frame_label` | Restore Frame Size | /// | `dock.newWindow` | `new_window_label` | Move Panel to New Window | /// | `dock.autoCollapse` | `auto_collapse_label` | Auto-Collapse Iconic Panels | + /// | `dock.floatHint` | `float_hint_label` | Hold {key} to float | #[must_use] pub fn localized(mut self, translate: impl Fn(&str) -> Option) -> Self { for (key, label) in self.labels_mut() { @@ -56,7 +57,7 @@ impl DockStyle { self } - fn labels_mut(&mut self) -> [(&'static str, &mut String); 27] { + fn labels_mut(&mut self) -> [(&'static str, &mut String); 28] { [ ("dock.float", &mut self.float_label), ("dock.close", &mut self.close_label), @@ -85,6 +86,7 @@ impl DockStyle { ("dock.restoreFrame", &mut self.restore_frame_label), ("dock.newWindow", &mut self.new_window_label), ("dock.autoCollapse", &mut self.auto_collapse_label), + ("dock.floatHint", &mut self.float_hint_label), ] } } diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index 2fc3156b32..1470b96df3 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -10,6 +10,9 @@ use crate::docking::{ dock_model::{Place, node_at}, }; +/// How far below the pointer the float hint sits, clear of the cursor. +const HINT_OFFSET: f32 = 28.0; + /// What the renderer draws when it is not the layout itself, and the targets that depend on it. pub(in crate::docking) struct FrameState

{ /// View path to layout path of each split, when the view is not the layout. @@ -180,6 +183,21 @@ impl Renderer<'_, P> { Some((anchor, zone, preview)) } + /// Under the pointer while a drag offers a docking target (frame profile): which modifier + /// floats the drop instead. + pub(super) fn paint_float_hint(&self, ctx: &Context, pointer: Pos2) { + if self.style.profile != Profile::Frame || self.style.float_hint_label.is_empty() { + return; + } + let key = if ctx.os() == egui::os::OperatingSystem::Mac { "⌘" } else { "Ctrl" }; + let painter = self.preview_painter(ctx); + let galley = painter.layout_no_wrap(self.style.float_hint_label.replace("{key}", key), self.style.font.clone(), self.style.text); + let rect = Rect::from_center_size(pointer + vec2(0.0, HINT_OFFSET), galley.size() + vec2(12.0, 6.0)); + let rect = crate::docking::chrome::clamp(rect, self.float_bounds); + painter.rect(rect, 4.0, self.style.floating_background, egui::Stroke::new(1.0, self.style.accent), egui::StrokeKind::Inside); + painter.galley(rect.center() - galley.size() * 0.5, galley, self.style.text); + } + pub(super) fn float_label(&self) -> String { if self.style.profile == Profile::Frame { self.style.undock_label.clone() } else { self.style.float_label.clone() } } diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index c18971594d..d3e043e641 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -206,6 +206,7 @@ impl Renderer<'_, P> { if let Some((action, line)) = self.dock_group_proposal(drag, pointer) { if action.is_some() { self.paint_dock_line(ctx, line); + self.paint_float_hint(ctx, pointer); } return; } @@ -217,6 +218,9 @@ impl Renderer<'_, P> { if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); } + if drag.gesture != GroupGesture::Window { + self.paint_float_hint(ctx, pointer); + } } } @@ -265,6 +269,7 @@ impl Renderer<'_, P> { } } else if action.is_some() { self.paint_dock_line(ctx, line); + self.paint_float_hint(ctx, pointer); } return; } @@ -308,6 +313,9 @@ impl Renderer<'_, P> { if let Some(marker) = proposal.insertion { painter.rect_filled(marker, 0.0, self.style.accent); } + if !proposal.noop { + self.paint_float_hint(ctx, pointer); + } } else if let Some(rect) = floating_rect { drop_preview(&painter, rect, self.style.accent, false); } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 0c93281570..7b60f7f834 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -90,6 +90,9 @@ pub struct DockStyle { pub restore_frame_label: String, /// Shown where native windows are available (feature `native-windows`). pub new_window_label: String, + /// Frame profile: shown under the pointer while a drag offers a docking target. `{key}` + /// stands for the modifier that floats the drop instead: ⌘ on macOS, Ctrl elsewhere. + pub float_hint_label: String, /// Show the built-in Close items in tab and group menus (Close Panel, Close Tab Group, /// Close Other Panels in Group) for closable panels. A host that draws its own Close items /// turns this off and keeps [`Permissions::closable`], so its close actions still apply. @@ -180,6 +183,7 @@ impl DockStyle { maximize_label: "Maximize Frame".into(), restore_frame_label: "Restore Frame Size".into(), new_window_label: "Move Panel to New Window".into(), + float_hint_label: "Hold {key} to float".into(), close_menu_items: true, close_button: true, wheel_selects_tabs: None, diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 5f6c17e355..0383012334 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -195,7 +195,7 @@ fn localized_covers_every_label_and_contains_takes_a_borrowed_panel() { }); full.textures_delta.clear(); let values: Vec<&str> = debug.split("_label: \"").skip(1).filter_map(|rest| rest.split('"').next()).collect(); - assert_eq!(values.len(), 27, "{debug}"); + assert_eq!(values.len(), 28, "{debug}"); assert!(values.iter().all(|v| v.starts_with("dock.")), "a label without a key: {values:?}"); let unique: std::collections::HashSet<_> = values.iter().collect(); assert_eq!(unique.len(), values.len()); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index e3cd49e613..2da9736b08 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -16,7 +16,7 @@ fields; new fields can be added, so the struct has no literal form outside the c | Profile | Arrangement | Apps | |---|---|---| | `Profile::Dock` (default) | Docks on the window's start and end edges. A dock has columns; a column has stacked groups and can collapse to icons. Frames (tab groups and splits) fill the space between the docks. | Creative apps with a canvas and panel docks | -| `Profile::Frame` | A split tree of tab frames. Frame menus offer Maximize Frame, Undock and Close Other Panels. Ctrl/Cmd + tab drag undocks. Drops on all four outer edges split at the root. | Apps whose whole window is frames | +| `Profile::Frame` | A split tree of tab frames. Frame menus offer Maximize Frame, Undock and Close Other Panels. Ctrl/Cmd + drag undocks, and a hint under the pointer says so. Drops on all four outer edges split at the root. | Apps whose whole window is frames | Sides are logical: `Side::Start` is the left edge, or the right edge when `DockStyle::right_to_left` is set. egui has no app-wide direction, so the app sets it from its @@ -197,6 +197,9 @@ A flyout fits its content the same way, without the title bar. nearer one. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. +- In the Frame profile, Ctrl (⌘ on macOS) held while dragging a tab, a drag bar or a grip that + calls `begin_drag` floats the drop wherever it lands. While a drag offers a docking target, a + hint under the pointer names the modifier: `float_hint_label`, where `{key}` becomes ⌘ or Ctrl. - Double-click a tab or drag bar to minimize a group to its strip. - Right-click a tab for its menu, or a drag bar for the group menu; Enter or Space on a focused drag bar opens it too. A left click on the drag bar only focuses it. From 958c5ada58269ceb84a763021ad31524c0ee7a76 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 16:46:50 +0000 Subject: [PATCH 81/94] docking: the Frame profile's drop hint says undock, as its menus do --- crates/ui/src/docking/frame_tests.rs | 2 +- crates/ui/src/docking/labels.rs | 2 +- crates/ui/src/docking/surface.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/frame_tests.rs b/crates/ui/src/docking/frame_tests.rs index c27ce707b5..febd375053 100644 --- a/crates/ui/src/docking/frame_tests.rs +++ b/crates/ui/src/docking/frame_tests.rs @@ -182,7 +182,7 @@ fn texts(d: &Driver) -> Vec { #[test] fn ctrl_or_cmd_floats_from_a_tab_a_drag_bar_or_a_grip_and_the_preview_says_so() { - const HINT: &str = "Hold Ctrl to float"; + const HINT: &str = "Hold Ctrl to undock"; let floated = |actions: &[Action], panel: u32| match actions { [Action::Float { panel: p, .. }] => *p == panel, [Action::MoveGroup { panel: p, to: Target::Float { .. } }] => *p == panel, diff --git a/crates/ui/src/docking/labels.rs b/crates/ui/src/docking/labels.rs index 16934febb3..76324dffd8 100644 --- a/crates/ui/src/docking/labels.rs +++ b/crates/ui/src/docking/labels.rs @@ -46,7 +46,7 @@ impl DockStyle { /// | `dock.restoreFrame` | `restore_frame_label` | Restore Frame Size | /// | `dock.newWindow` | `new_window_label` | Move Panel to New Window | /// | `dock.autoCollapse` | `auto_collapse_label` | Auto-Collapse Iconic Panels | - /// | `dock.floatHint` | `float_hint_label` | Hold {key} to float | + /// | `dock.floatHint` | `float_hint_label` | Hold {key} to undock | #[must_use] pub fn localized(mut self, translate: impl Fn(&str) -> Option) -> Self { for (key, label) in self.labels_mut() { diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 7b60f7f834..389589dd7e 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -183,7 +183,7 @@ impl DockStyle { maximize_label: "Maximize Frame".into(), restore_frame_label: "Restore Frame Size".into(), new_window_label: "Move Panel to New Window".into(), - float_hint_label: "Hold {key} to float".into(), + float_hint_label: "Hold {key} to undock".into(), close_menu_items: true, close_button: true, wheel_selects_tabs: None, From d30c207c8d9dae04ffa02a7bb38f268bc8e30723 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 20:01:31 +0000 Subject: [PATCH 82/94] docking: one model; profile differences are style data Remove `Profile`. What it switched is now a `DockStyle` setting with the dock-and-canvas behaviour as the default: `side_edge_zones`, `new_dock_zones`, `maximize_item`, `close_others_item`, `command_press_floats`, `float_hint`, and plain bools for `wheel_selects_tabs` and `middle_click_closes_tabs`. The undock and Close Panel Group labels go; an app sets `float_label`, `float_group_label` and `close_group_label` instead. Remove the size machinery that made frames stick: `DockContent::bare`, `FixedSlot` and the split that took a parent's or sibling's half beside a fixed-size frame, and the gap snapping to the nearest frame. A tab group takes the largest maximum of its panels, so a panel without one lifts the cap of the group it joins. A dragged divider stores a ratio whatever mode it was saved with. Sizes follow the reference rules: a divider resizes only the groups that touch it and stops at their minimums; a four-way handle where a divider ends on another moves both (`Divider::Intersection`); a split or outer-edge drop that would leave a group without `min_pane` is not offered, and a group too small to halve takes the drop as a tab. Tests: one per rule, the stuck cases from the FilmCraft map, and a property test over random drops checking minimums and divider travel. --- crates/ui/src/docking/dock_model.rs | 28 +- crates/ui/src/docking/dock_tests.rs | 2 +- crates/ui/src/docking/floating_tests.rs | 83 +++-- crates/ui/src/docking/frame_tests.rs | 211 ----------- crates/ui/src/docking/group_tests.rs | 10 +- crates/ui/src/docking/hits.rs | 9 + crates/ui/src/docking/labels.rs | 8 +- crates/ui/src/docking/mod.rs | 8 +- crates/ui/src/docking/render/dock.rs | 45 ++- crates/ui/src/docking/render/floating.rs | 8 + crates/ui/src/docking/render/frame.rs | 66 ++-- crates/ui/src/docking/render/group.rs | 10 +- crates/ui/src/docking/render/mod.rs | 122 ++++--- crates/ui/src/docking/render/preview.rs | 100 ++--- crates/ui/src/docking/render/sizes.rs | 172 +++++++++ crates/ui/src/docking/split_tests.rs | 445 +++++++++++++++++++++++ crates/ui/src/docking/surface.rs | 83 ++--- crates/ui/src/docking/tests.rs | 6 +- crates/ui/src/docking/trial_tests.rs | 2 +- docs/ui-docking.md | 67 ++-- 20 files changed, 974 insertions(+), 511 deletions(-) delete mode 100644 crates/ui/src/docking/frame_tests.rs create mode 100644 crates/ui/src/docking/render/sizes.rs create mode 100644 crates/ui/src/docking/split_tests.rs diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index 747f5dc346..a42bb56fc8 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -207,38 +207,18 @@ pub(super) fn node_at_mut<'a, P>(mut node: &'a mut Node

, path: &[bool]) -> Op Some(node) } -/// Put `new` on the `zone` side of the frame at `path`, in a new half-size split. A frame that -/// holds the fixed size of its parent split along the same axis keeps that size: on its outer -/// side the new split wraps the parent, on its inner side it halves the parent's other child. -/// So a fixed-width tool strip neither halves nor shares its width with the new frame. +/// Put `new` on the `zone` side of the frame at `path`: the frame splits into two halves and +/// every other frame keeps its size. pub(super) fn split_frame

(root: &mut Node

, path: &[bool], new: Node

, zone: Zone) -> bool { let axis = if matches!(zone, Zone::Top | Zone::Bottom) { SplitAxis::Vertical } else { SplitAxis::Horizontal }; - let before = matches!(zone, Zone::Top | Zone::Left); - let (target, new_first) = match fixed_slot(root, path, axis) { - Some((parent, anchor_first)) if before == anchor_first => (parent.to_vec(), before), - Some((parent, anchor_first)) => ([parent, &[anchor_first]].concat(), !before), - None => (path.to_vec(), before), - }; - let Some(node) = node_at_mut(root, &target) else { return false }; + let new_first = matches!(zone, Zone::Top | Zone::Left); + let Some(node) = node_at_mut(root, path) else { return false }; let old = std::mem::replace(node, Node::Tabs { panels: Vec::new(), active: 0 }); let (first, second) = if new_first { (new, old) } else { (old, new) }; *node = Node::Split { axis, size: SplitSize::Ratio(0.5), first: Box::new(first), second: Box::new(second) }; true } -/// The parent path of the frame at `path` and whether the frame is its first child, when the -/// parent splits along `axis` and the frame holds its fixed size. -pub(super) fn fixed_slot<'a, P>(root: &Node

, path: &'a [bool], axis: SplitAxis) -> Option<(&'a [bool], bool)> { - let (second, parent) = path.split_last()?; - let Node::Split { axis: parent_axis, size, .. } = node_at(root, parent)? else { return None }; - let fixed = match size { - SplitSize::FixedFirst(_) => !second, - SplitSize::FixedSecond(_) => *second, - SplitSize::Ratio(_) => false, - }; - (*parent_axis == axis && fixed).then_some((parent, !second)) -} - /// Insert `new` at `index` and select the member at `index + selected`. fn splice

(panels: &mut Vec

, active: &mut usize, index: usize, new: Vec

, selected: usize) { let index = index.min(panels.len()); diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 8ba4387bc8..87e1c4a0bc 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -1,4 +1,4 @@ -//! [D] Dock profile: columns, stacked groups, seams, column bars and their drops. +//! [D] Docks: columns, stacked groups, seams, column bars and their drops. use super::*; use crate::layout::{SplitAxis, SplitSize}; diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 8501588862..c05271c5b7 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -1,4 +1,4 @@ -//! Floating windows (title bar, stacks, close), the frame profile (outer edge, Maximize, +//! Floating windows (title bar, stacks, close), the split-tree settings (outer edge, Maximize, //! Ctrl/Cmd undock, frame menu items), hidden panels, native windows and the public chrome. use super::*; @@ -80,11 +80,26 @@ enum Hide { Keep, } +/// The style of an editor whose layout is one split tree of tab groups, as FilmCraft sets it. +pub(super) fn frame_style(style: &mut DockStyle) { + style.side_edge_zones = true; + style.new_dock_zones = false; + style.close_others_item = true; + style.maximize_item = true; + style.command_press_floats = true; + style.float_hint = true; + style.wheel_selects_tabs = true; + style.middle_click_closes_tabs = true; + style.float_label = "Undock Panel".into(); + style.float_group_label = "Undock Panel Group".into(); + style.close_group_label = "Close Panel Group".into(); +} + struct Driver { ctx: Context, layout: Layout, content: Content, - profile: Profile, + split_tree: bool, maximized: Option, hide: Hide, modifiers: Modifiers, @@ -92,12 +107,12 @@ struct Driver { } impl Driver { - fn new(layout: Layout, profile: Profile) -> Self { + fn new(layout: Layout, split_tree: bool) -> Self { let mut driver = Self { ctx: Context::default(), layout, content: Content::default(), - profile, + split_tree, maximized: None, hide: Hide::None, modifiers: Modifiers::NONE, @@ -119,12 +134,14 @@ impl Driver { time: Some(self.time), ..Default::default() }; - let (layout, content, profile, maximized, hide) = (&self.layout, &mut self.content, self.profile, self.maximized, self.hide); + let (layout, content, split_tree, maximized, hide) = (&self.layout, &mut self.content, self.split_tree, self.maximized, self.hide); let keep: Vec = content.keep.clone(); let keep = move |p: &u32| keep.contains(p); let full = self.ctx.run_ui(input, |ui| { let mut style = DockStyle::from_ui(ui); - style.profile = profile; + if split_tree { + frame_style(&mut style); + } let hide = match hide { Hide::None => HidePanels::None, Hide::All => HidePanels::All, @@ -200,7 +217,7 @@ fn groups_of(window: &Floating) -> Vec> { #[test] fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_groups() { // The window follows the pointer with every group; Escape puts it back. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(5).center(); d.hold(title, title + vec2(40.0, 30.0)); assert_eq!(d.layout.floating[0].rect, [340.0, 110.0, 240.0, 300.0]); @@ -221,7 +238,7 @@ fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_gro assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![8], vec![5], vec![6, 7]]); // Released over a docked group's strip: every panel joins it as tabs. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(5).center(); let strip = d.tab(4).unwrap().center(); let out = d.drag(title, strip); @@ -230,7 +247,7 @@ fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_gro assert_eq!(d.layout.place(&4), d.layout.place(&6)); // Released over the canvas: the window stays where it was moved and hosts get the release. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(5).center(); let out = d.drag(title, pos2(500.0, 300.0)); assert!(!out.actions.iter().any(|a| matches!(a, Action::MoveWindow { .. })), "{:?}", out.actions); @@ -241,7 +258,7 @@ fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_gro #[test] fn title_bar_drag_onto_dock_targets_docks_the_window() { // Released on the seam between two docked groups: the window's group stacks between them. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(8).center(); let seam = pos2(120.0, d.tab(4).unwrap().top()); let out = d.drag(title, seam); @@ -258,7 +275,7 @@ fn title_bar_drag_onto_dock_targets_docks_the_window() { assert_eq!(stacked, vec![vec![2, 3], vec![8], vec![4]]); // Released on the new-dock band along the right edge: the window becomes an end dock. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(5).center(); let out = d.drag(title, pos2(796.0, 300.0)); assert!(out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::NewDock { side: Side::End } }), "{:?}", out.actions); @@ -268,7 +285,7 @@ fn title_bar_drag_onto_dock_targets_docks_the_window() { #[test] fn floating_stack_seams_and_bands_insert_groups() { // A group dragged by its bar to another window's top band stacks above that group. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let bar = d.response(Id::new(AREA).with(("drag-bar", Some(&6u32)))).unwrap().center(); let out = d.drag(bar, pos2(660.0, 360.0)); assert!( @@ -281,7 +298,7 @@ fn floating_stack_seams_and_bands_insert_groups() { assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5]]); // A tab dropped on the seam between two stacked groups becomes a group between them. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let tab = d.tab(8).unwrap().center(); let seam = pos2(420.0, 237.0); let out = d.drag(tab, seam); @@ -293,7 +310,7 @@ fn floating_stack_seams_and_bands_insert_groups() { assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![8], vec![6, 7]]); // The divider between two open groups resizes both. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let divider = d.response(DockArea::hit_id(Id::new(AREA), &Hit::Divider(Divider::Group(5u32)))).unwrap().center(); d.drag(divider, divider + vec2(0.0, 40.0)); let heights: Vec<_> = window_of(&d.layout, 5).unwrap().groups.iter().map(|g| g.height.unwrap()).collect(); @@ -302,7 +319,7 @@ fn floating_stack_seams_and_bands_insert_groups() { #[test] fn title_bar_double_click_minimizes_every_group_and_close_box_closes_the_window() { - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(5).center(); d.click(title); d.click(title); @@ -334,7 +351,7 @@ fn closed_floating_window_reopens_each_panel_at_its_last_rect() { #[test] fn ctrl_drag_from_a_frame_strip_undocks_to_a_floating_window() { - let mut d = Driver::new(frames(), Profile::Frame); + let mut d = Driver::new(frames(), true); let tab = d.tab(3).unwrap().center(); let other = d.tab(1).unwrap().center(); d.modifiers = Modifiers::COMMAND; @@ -345,23 +362,23 @@ fn ctrl_drag_from_a_frame_strip_undocks_to_a_floating_window() { assert!(window_of(&d.layout, 3).is_some()); // Without the modifier the same drag joins the other frame. - let mut d = Driver::new(frames(), Profile::Frame); + let mut d = Driver::new(frames(), true); let out = d.drag(tab, other); assert!(matches!(out.actions.as_slice(), [Action::Move { panel: 3, anchor: 1, .. }]), "{:?}", out.actions); } #[test] fn outer_edge_band_splits_at_the_root() { - // Frame profile: all four edges. - let mut d = Driver::new(frames(), Profile::Frame); + // With side edge zones: all four edges. + let mut d = Driver::new(frames(), true); let tab = d.tab(3).unwrap().center(); let out = d.drag(tab, pos2(3.0, 300.0)); assert!(out.actions.contains(&Action::Move { panel: 3, anchor: 1, placement: Placement::Edge(Zone::Left) }), "{:?}", out.actions); let Some(Node::Split { axis: SplitAxis::Horizontal, first, .. }) = &d.layout.root else { panic!("{:?}", d.layout) }; assert_eq!(**first, tabs(&[3], 0)); - // Dock profile: the bottom edge of the part between the docks, for a Timeline. - let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, Profile::Dock); + // The defaults: the bottom edge of the part between the docks, for a Timeline. + let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, false); let tab = d.tab(2).unwrap().center(); let out = d.drag(tab, pos2(500.0, 597.0)); assert!(out.actions.iter().any(|a| matches!(a, Action::Move { panel: 2, placement: Placement::Edge(Zone::Bottom), .. })), "{:?}", out.actions); @@ -370,7 +387,7 @@ fn outer_edge_band_splits_at_the_root() { assert!(matches!(&**second, Node::Split { axis: SplitAxis::Vertical, second, .. } if **second == tabs(&[2], 0))); // Its left and right edges are the docks' (new columns and docks), not root splits. - let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, Profile::Dock); + let mut d = Driver::new(Layout { floating: Vec::new(), ..workspace() }, false); let tab = d.tab(4).unwrap().center(); let out = d.drag(tab, pos2(246.0, 300.0)); assert!(!out.actions.iter().any(|a| matches!(a, Action::Move { placement: Placement::Edge(_), .. })), "{:?}", out.actions); @@ -380,7 +397,7 @@ fn outer_edge_band_splits_at_the_root() { fn maximized_frame_fills_the_area_and_other_frames_do_not_render_or_take_input() { let mut layout = frames(); layout.floating.push(Floating::single(vec![5], 0, [400.0, 300.0, 200.0, 150.0])); - let mut d = Driver::new(layout.clone(), Profile::Frame); + let mut d = Driver::new(layout.clone(), true); let window_title = d.title(5).center(); d.maximized = Some(2); d.step(vec![]); @@ -392,7 +409,7 @@ fn maximized_frame_fills_the_area_and_other_frames_do_not_render_or_take_input() assert!(out.actions.iter().all(|a| !matches!(a, Action::MoveFloating { .. } | Action::MoveWindow { .. })), "{:?}", out.actions); // A floating panel does not maximize. - let mut d = Driver::new(layout, Profile::Frame); + let mut d = Driver::new(layout, true); d.maximized = Some(5); d.step(vec![]); d.step(vec![]); @@ -406,7 +423,7 @@ fn close_other_panels_keeps_only_the_chosen_tab() { let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( |ui, (content, actions, events): &mut State| { let mut style = DockStyle::from_ui(ui); - style.profile = Profile::Frame; + frame_style(&mut style); let out = DockArea::new(Id::new(AREA)).show_content(ui, &frames(), &style, content); actions.extend(out.actions); events.extend(out.events); @@ -444,7 +461,7 @@ fn close_other_panels_keeps_only_the_chosen_tab() { #[test] fn hide_panels_keeps_protected_panels_and_the_except_set() { - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); d.hide = Hide::All; d.step(vec![]); d.step(vec![]); @@ -469,7 +486,7 @@ fn hide_panels_keeps_protected_panels_and_the_except_set() { #[test] fn a_canvas_that_accepts_splits_is_still_protected() { - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); d.content.beside = true; d.hide = Hide::All; d.step(vec![]); @@ -484,7 +501,7 @@ fn a_canvas_that_accepts_splits_is_still_protected() { fn native_window_falls_back_in_window_when_viewports_are_embedded() { let mut layout = workspace(); layout.floating[0].native = Some([1200.0, 900.0, 240.0, 300.0]); - let mut d = Driver::new(layout.clone(), Profile::Dock); + let mut d = Driver::new(layout.clone(), false); d.content.native = true; assert!(d.ctx.embed_viewports()); let out = d.step(vec![]); @@ -519,7 +536,7 @@ fn native_window_close_returns_the_group_to_its_in_window_rect() { }); let mut layout = workspace(); layout.floating[0].native = Some([1200.0, 900.0, 240.0, 300.0]); - let mut d = Driver::new(Layout::default(), Profile::Dock); + let mut d = Driver::new(Layout::default(), false); d.ctx.set_embed_viewports(false); d.content.native = true; d.layout = layout; @@ -601,7 +618,7 @@ fn hidden_panels_leave_their_split_and_resizing_names_the_layout_path() { }), floating: Vec::new(), }; - let mut d = Driver::new(layout, Profile::Frame); + let mut d = Driver::new(layout, true); d.hide = Hide::Keep; d.content.keep = vec![1, 2]; d.step(vec![]); @@ -622,7 +639,7 @@ fn a_hidden_floating_window_does_not_cover_dock_targets() { // Window 5 covers the column's seam at x 150..240 until it is hidden. let mut layout = workspace(); layout.floating = vec![Floating::single(vec![5], 0, [150.0, 250.0, 200.0, 150.0]), Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0])]; - let mut d = Driver::new(layout, Profile::Dock); + let mut d = Driver::new(layout, false); d.hide = Hide::Keep; d.content.keep = vec![2, 3, 4, 8]; d.step(vec![]); @@ -643,14 +660,14 @@ fn top_edges_resize_from_the_band_above_the_title_bar() { (ResizeEdge::TopLeft, vec2(-30.0, 20.0), [530.0, 320.0, 230.0, 180.0]), (ResizeEdge::TopRight, vec2(20.0, -10.0), [560.0, 290.0, 220.0, 210.0]), ] { - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let handle = d.response(DockArea::hit_id(area, &Hit::Resize(8u32, edge))).unwrap(); assert_eq!(handle.bottom(), d.title(8).top(), "{edge:?} lies above the title bar"); d.drag(handle.center(), handle.center() + by); assert_eq!(window_of(&d.layout, 8).unwrap().rect, expected, "{edge:?}"); } // The title bar still moves the window, and arrow keys move the focused top edge. - let mut d = Driver::new(workspace(), Profile::Dock); + let mut d = Driver::new(workspace(), false); let title = d.title(8); d.drag(pos2(title.center().x, title.top() + 1.0), pos2(title.center().x - 50.0, title.top() + 1.0)); assert_eq!(window_of(&d.layout, 8).unwrap().rect, [510.0, 300.0, 200.0, 200.0]); diff --git a/crates/ui/src/docking/frame_tests.rs b/crates/ui/src/docking/frame_tests.rs deleted file mode 100644 index febd375053..0000000000 --- a/crates/ui/src/docking/frame_tests.rs +++ /dev/null @@ -1,211 +0,0 @@ -//! Frame profile in a Premiere-style editing layout, as FilmCraft draws it: a bottom row of -//! Project | Tools | Timeline | Audio Meters, where Tools and the meters are narrow fixed-width -//! frames without a tab strip that a grip on top moves. - -use std::collections::HashMap; - -use super::testing::DockDriver; -use super::*; -use crate::layout::{SplitAxis, SplitSize}; -use egui::{Id, Modifiers, Pos2, Rect, Sense, pos2, vec2}; - -const SOURCE: [u32; 4] = [1, 11, 12, 13]; -const PROGRAM: u32 = 2; -const PROPERTIES: [u32; 3] = [3, 31, 32]; -const PROJECT: [u32; 7] = [4, 41, 42, 43, 44, 45, 46]; -const TOOLS: u32 = 5; -const TIMELINE: u32 = 6; -const METERS: u32 = 7; - -const TOOLS_WIDTH: f32 = 64.0; -const METERS_WIDTH: f32 = 116.0; - -/// Panel bodies by their rects, with a FilmCraft-style 8 pt grip on the bare frames. -#[derive(Default)] -struct Film { - bodies: HashMap, -} - -impl DockContent for Film { - fn body(&mut self, ui: &mut egui::Ui, panel: &u32) { - let frame = ui.max_rect(); - self.bodies.insert(*panel, frame); - if self.bare(panel) { - let grip = Rect::from_min_size(frame.min, vec2(frame.width(), 8.0_f32.min(frame.height()))); - if ui.interact(grip, Id::new(("grip", *panel)), Sense::drag()).drag_started() { - begin_drag(ui.ctx(), Id::new("dock-driver"), *panel, frame); - } - } - ui.allocate_rect(frame, Sense::hover()); - } - fn logical_label(&self, panel: &u32) -> String { - format!("Panel {panel}") - } - fn bare(&self, panel: &u32) -> bool { - matches!(*panel, TOOLS | METERS) - } -} - -type Driver = DockDriver; - -fn tabs(panels: &[u32]) -> Node { - Node::Tabs { panels: panels.to_vec(), active: 0 } -} - -fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node { - Node::Split { axis, size, first: Box::new(first), second: Box::new(second) } -} - -fn hsplit(size: SplitSize, first: Node, second: Node) -> Node { - split(SplitAxis::Horizontal, size, first, second) -} - -/// Tools | Timeline | Audio Meters. -fn tools_row() -> Node { - hsplit(SplitSize::FixedFirst(TOOLS_WIDTH), tabs(&[TOOLS]), hsplit(SplitSize::FixedSecond(METERS_WIDTH), tabs(&[TIMELINE]), tabs(&[METERS]))) -} - -/// FilmCraft's Editing workspace: Source | Program | Properties over Project | Tools | Timeline | Meters. -fn editing() -> Layout { - let top = hsplit(SplitSize::FixedSecond(450.0), hsplit(SplitSize::Ratio(0.5), tabs(&SOURCE), tabs(&[PROGRAM])), tabs(&PROPERTIES)); - let bottom = hsplit(SplitSize::Ratio(0.29), tabs(&PROJECT), tools_row()); - Layout { root: Some(split(SplitAxis::Vertical, SplitSize::Ratio(0.57), top, bottom)), floating: Vec::new() } -} - -fn driver(layout: Layout) -> Driver { - let mut d = DockDriver::new(layout, Film::default()).with_style(|style| style.profile = Profile::Frame); - d.screen = Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 860.0)); - d.area = d.screen; - d.settle(); - d -} - -fn body(d: &Driver, panel: u32) -> Rect { - d.content.bodies.get(&panel).copied().unwrap_or_else(|| panic!("panel {panel} not drawn")) -} - -fn floated_project() -> Driver { - let mut layout = editing(); - layout.apply(Action::MoveGroup { panel: PROJECT[0], to: Target::Float { rect: Some([600.0, 120.0, 400.0, 300.0]) } }).unwrap(); - driver(layout) -} - -fn split_at(anchor: u32, zone: Zone) -> Target { - Target::At { anchor, placement: Placement::Split(zone) } -} - -#[test] -fn a_narrow_frame_offers_both_side_targets_and_a_seam_splits_beside_its_frames() { - let d = floated_project(); - let tools = body(&d, TOOLS); - assert_eq!((tools.left(), tools.width()), (0.0, TOOLS_WIDTH), "Tools starts the bottom row"); - // Left: past the 8 pt outer edge band. - for (at, zone) in [(pos2(20.0, tools.center().y), Zone::Left), (pos2(tools.right() - 12.0, tools.center().y), Zone::Right)] { - let mut d = floated_project(); - let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap(); - let out = d.drag(bar.center(), at); - assert_eq!(out.actions, vec![Action::MoveGroup { panel: PROJECT[0], to: split_at(TOOLS, zone) }], "{zone:?}"); - } - // The gap between Tools and Timeline: a tab dropped there splits instead of floating. - let mut d = floated_project(); - let timeline = body(&d, TIMELINE); - let seam = pos2((tools.right() + timeline.left()) * 0.5, timeline.center().y); - assert!(!tools.contains(seam) && !timeline.contains(seam), "the seam is outside both frames"); - let out = d.drag(d.hit(&Hit::Tab(PROGRAM)).unwrap().center(), seam); - assert!( - matches!(&out.actions[..], [Action::Move { panel: PROGRAM, anchor: TOOLS | TIMELINE, placement: Placement::Split(Zone::Left | Zone::Right) }]), - "{:?}", - out.actions - ); -} - - -fn bottom(layout: &Layout) -> &Node { - let Some(Node::Split { second, .. }) = &layout.root else { panic!("{:?}", layout.root) }; - second -} - -/// Drag a split divider by `dx`, hovering it first as a pointer does. -fn drag_divider(d: &mut Driver, path: &[bool], dx: f32) { - let divider = d.hit(&Hit::Divider(Divider::Split(path.to_vec()))).unwrap_or_else(|| panic!("{path:?} in {:?}", d.hits())); - d.move_to(divider.center()); - d.drag(divider.center(), divider.center() + vec2(dx, 0.0)); - d.settle(); -} - -#[test] -fn a_split_beside_a_fixed_width_frame_keeps_its_width_and_gets_its_own_divider() { - // Left of Tools: the new frame takes half the row, beside Tools at its own width. - let mut d = floated_project(); - let tools = body(&d, TOOLS); - let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap(); - let at = pos2(20.0, tools.center().y); - d.hold(bar.center(), at); - let row = Rect::from_x_y_ranges(0.0..=1440.0, tools.y_range()); - assert!(d.filled(Rect::from_min_max(row.min, pos2(row.center().x, row.bottom())).shrink(1.0)), "the preview shows the new frame"); - d.release(at); - assert_eq!(bottom(&d.layout), &hsplit(SplitSize::Ratio(0.5), tabs(&PROJECT), tools_row())); - d.settle(); - assert_eq!(body(&d, TOOLS).width(), TOOLS_WIDTH); - // Each divider resizes its own two sides; Tools keeps its width. - let project = body(&d, PROJECT[0]).width(); - drag_divider(&mut d, &[true], -200.0); - let widths = |d: &Driver| (body(d, PROJECT[0]).width().round(), body(d, TOOLS).width().round()); - assert_eq!(widths(&d), ((project - 200.0).round(), TOOLS_WIDTH)); - drag_divider(&mut d, &[true, true], 30.0); - assert_eq!(widths(&d), ((project - 200.0).round(), TOOLS_WIDTH + 30.0)); - - // Right of Tools: the new frame takes half of what lies right of Tools. - let mut d = driver(editing()); - let tools = body(&d, TOOLS); - let tab = d.hit(&Hit::Tab(PROGRAM)).unwrap(); - d.drag(tab.center(), pos2(tools.right() - 12.0, tools.center().y)); - let rest = hsplit(SplitSize::FixedSecond(METERS_WIDTH), tabs(&[TIMELINE]), tabs(&[METERS])); - let right = hsplit(SplitSize::FixedFirst(TOOLS_WIDTH), tabs(&[TOOLS]), hsplit(SplitSize::Ratio(0.5), tabs(&[PROGRAM]), rest)); - assert_eq!(bottom(&d.layout), &hsplit(SplitSize::Ratio(0.29), tabs(&PROJECT), right)); - d.settle(); - assert_eq!(body(&d, TOOLS).width(), TOOLS_WIDTH); -} - -fn texts(d: &Driver) -> Vec { - fn walk(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)), - egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), - _ => {} - } - } - let mut out = Vec::new(); - d.shapes().iter().for_each(|clipped| walk(&clipped.shape, &mut out)); - out -} - -#[test] -fn ctrl_or_cmd_floats_from_a_tab_a_drag_bar_or_a_grip_and_the_preview_says_so() { - const HINT: &str = "Hold Ctrl to undock"; - let floated = |actions: &[Action], panel: u32| match actions { - [Action::Float { panel: p, .. }] => *p == panel, - [Action::MoveGroup { panel: p, to: Target::Float { .. } }] => *p == panel, - _ => false, - }; - let d = driver(editing()); - let over = body(&d, TIMELINE).center(); - let tab = d.hit(&Hit::Tab(PROJECT[0])).unwrap().center(); - let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); - let grip = pos2(body(&d, TOOLS).center().x, body(&d, TOOLS).top() + 4.0); - for (from, panel) in [(tab, PROJECT[0]), (bar, PROJECT[0]), (grip, TOOLS)] { - // Without the modifier, a release over a frame docks there; the preview names the modifier. - let mut d = driver(editing()); - d.hold(from, over); - assert!(texts(&d).iter().any(|t| t == HINT), "{from:?}: {:?}", texts(&d)); - let out = d.release(over); - assert!(!out.actions.is_empty() && !floated(&out.actions, panel), "{from:?}: {:?}", out.actions); - // Held, it floats, and the hint is gone. - let mut d = driver(editing()); - d.modifiers = Modifiers::COMMAND; - d.hold(from, over); - assert!(!texts(&d).iter().any(|t| t == HINT), "{from:?}"); - let out = d.release(over); - assert!(floated(&out.actions, panel), "{from:?}: {:?}", out.actions); - } -} diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index bface8f234..9d81bb9abb 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -493,12 +493,12 @@ fn docked_header_drag_reaches_the_host_hook_and_preserves_the_group() { } #[test] -fn lone_bare_or_protected_panels_draw_no_strip_and_no_bar() { +fn a_lone_protected_panel_draws_no_strip_and_no_bar() { struct Bare; impl DockContent for Bare { fn body(&mut self, _: &mut egui::Ui, _: &u32) {} - fn bare(&self, panel: &u32) -> bool { - *panel == 1 + fn permissions(&self, panel: &u32) -> Permissions { + if *panel == 1 { Permissions::PROTECTED } else { Permissions::default() } } } let ctx = Context::default(); @@ -669,7 +669,7 @@ fn frame_tabs_follow_the_wheel_and_close_on_a_middle_click() { let wheel = |unit, y| Event::MouseWheel { unit, delta: vec2(0.0, y), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE }; let middle = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Middle, pressed, modifiers: Modifiers::NONE }; - // Off by default in the Dock profile. + // Off by default. let mut d = Driver::new(frames()); let over = d.tab(2).center(); d.step(vec![Event::PointerMoved(over), wheel(egui::MouseWheelUnit::Line, 1.0)]); @@ -678,7 +678,7 @@ fn frame_tabs_follow_the_wheel_and_close_on_a_middle_click() { assert_eq!(second(&d), tabs(&[2, 3], 1)); let mut d = Driver::new(frames()); - d.tweak = |style| style.profile = Profile::Frame; + d.tweak = super::floating_tests::frame_style; d.step(vec![]); let over = d.tab(2).center(); d.step(vec![Event::PointerMoved(over), wheel(egui::MouseWheelUnit::Line, 1.0)]); diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index 0c5faf70fa..17b37149d5 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -68,6 +68,9 @@ pub enum Divider

{ Column(P), /// Below the dock or floating group holding this panel first. Group(P), + /// Where the divider of a split inside another split ends on the outer split's divider, + /// by the outer and the inner split's paths. Dragging it moves both dividers. + Intersection(Vec, Vec), } fn key(area: Id) -> Id { @@ -101,6 +104,7 @@ impl DockArea<'_, P> { Hit::Divider(Divider::Column(p)) => id.with(("column-resize", Some(p))), Hit::Divider(Divider::Group(p)) => id.with(("group-resize", Some(p))), Hit::Divider(Divider::Split(path)) => id.with(("split", path)), + Hit::Divider(Divider::Intersection(outer, inner)) => id.with(("intersection", outer, inner)), Hit::Title(p) => id.with(("move-group", Some(p))), Hit::Close(p) => id.with(("move-group", Some(p))).with("close"), Hit::Resize(p, edge) => { @@ -169,9 +173,14 @@ pub(super) fn named(area: } } let mut nodes = layout.root.as_ref().map(|root| vec![(root, Vec::::new())]).unwrap_or_default(); + let mut splits: Vec> = Vec::new(); while let Some((node, path)) = nodes.pop() { if let Node::Split { first, second, .. } = node { name(Hit::Divider(Divider::Split(path.clone()))); + for outer in splits.iter().filter(|outer| path.starts_with(outer)) { + name(Hit::Divider(Divider::Intersection(outer.clone(), path.clone()))); + } + splits.push(path.clone()); let mut second_path = path.clone(); second_path.push(true); let mut first_path = path; diff --git a/crates/ui/src/docking/labels.rs b/crates/ui/src/docking/labels.rs index 76324dffd8..e900e6fca4 100644 --- a/crates/ui/src/docking/labels.rs +++ b/crates/ui/src/docking/labels.rs @@ -38,9 +38,6 @@ impl DockStyle { /// | `dock.expandColumn` | `expand_column_label` | Expand column | /// | `dock.moveWindow` | `move_window_label` | Move panel window | /// | `dock.closeWindow` | `close_window_label` | Close panel window | - /// | `dock.undock` | `undock_label` | Undock Panel | - /// | `dock.undockGroup` | `undock_group_label` | Undock Panel Group | - /// | `dock.closePanelGroup` | `close_panel_group_label` | Close Panel Group | /// | `dock.closeOthers` | `close_others_label` | Close Other Panels in Group | /// | `dock.maximize` | `maximize_label` | Maximize Frame | /// | `dock.restoreFrame` | `restore_frame_label` | Restore Frame Size | @@ -57,7 +54,7 @@ impl DockStyle { self } - fn labels_mut(&mut self) -> [(&'static str, &mut String); 28] { + fn labels_mut(&mut self) -> [(&'static str, &mut String); 25] { [ ("dock.float", &mut self.float_label), ("dock.close", &mut self.close_label), @@ -78,9 +75,6 @@ impl DockStyle { ("dock.expandColumn", &mut self.expand_column_label), ("dock.moveWindow", &mut self.move_window_label), ("dock.closeWindow", &mut self.close_window_label), - ("dock.undock", &mut self.undock_label), - ("dock.undockGroup", &mut self.undock_group_label), - ("dock.closePanelGroup", &mut self.close_panel_group_label), ("dock.closeOthers", &mut self.close_others_label), ("dock.maximize", &mut self.maximize_label), ("dock.restoreFrame", &mut self.restore_frame_label), diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index ba6651d223..2587dca034 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -27,8 +27,8 @@ pub use hits::{Divider, Hit, ResizeEdge}; pub use model::{Action, DockError, Floating, Layout, Location, MAX_DEPTH, MAX_PANELS, Node, Permissions, Placement, StackEntry, Zone}; pub use render::{close_flyout, flyout, open_flyout}; pub use surface::{ - DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, FloatSpace, HidePanels, PanelLimits, Profile, begin_drag, - cancel_drag, float_space, is_dragging, + DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, FloatSpace, HidePanels, PanelLimits, begin_drag, cancel_drag, + float_space, is_dragging, }; pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect}; pub use workspace::Workspace; @@ -42,12 +42,12 @@ mod dock_tests; #[cfg(test)] mod floating_tests; #[cfg(test)] -mod frame_tests; -#[cfg(test)] mod group_tests; #[cfg(test)] mod iconic_tests; #[cfg(test)] mod model_tests; #[cfg(test)] +mod split_tests; +#[cfg(test)] mod tests; diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 73d398439c..16932bf8c9 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -1,4 +1,4 @@ -//! [D] The dock profile: side docks of columns, each a column bar above stacked groups. +//! [D] Docks: side docks of columns, each a column bar above stacked groups. //! //! Columns run from the window edge inwards. Every column's inner edge resizes it; the last //! column's inner edge is the dock's inner edge. Behavior follows VectorCraft `floating.rs` @@ -10,7 +10,7 @@ use egui::{Context, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, p use super::{GroupKind, Renderer}; use crate::docking::{ - Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Placement, Profile, Side, Target, + Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Placement, Side, Target, dock_model::Unit, targets::{DockDrop, DockTarget, column_edge, horizontal_line, resolve_dock, usable, vertical_line}, }; @@ -41,6 +41,31 @@ fn side_at(edge: Edge, right_to_left: bool) -> Side { } } +/// The rects of a dock beside `other` in `rect`, and the widest the dock may get. +pub(in crate::docking) fn dock_rects

( + side: Side, + columns: &[Column

], + other: &Node

, + rect: Rect, + style: &DockStyle, + content: &dyn crate::docking::DockContent

, +) -> (Rect, Rect, f32) { + let gap = style.gap; + let room = (rect.width() - gap - super::node_limits(other, style, content).min.x).clamp(0.0, rect.width()); + let width = columns.iter().map(|c| column_width(c, style)).sum::().clamp(0.0, room); + let (dock, rest) = match edge_of(side, style.right_to_left) { + Edge::Left => ( + Rect::from_min_max(rect.min, pos2(rect.left() + width, rect.bottom())), + Rect::from_min_max(pos2((rect.left() + width + gap).min(rect.right()), rect.top()), rect.max), + ), + Edge::Right => ( + Rect::from_min_max(pos2(rect.right() - width, rect.top()), rect.max), + Rect::from_min_max(rect.min, pos2((rect.right() - width - gap).max(rect.left()), rect.bottom())), + ), + }; + (dock, rest, room) +} + pub(in crate::docking) fn column_width

(column: &Column

, style: &DockStyle) -> f32 { if column.iconic { column.iconic_width.unwrap_or(style.iconic_width).clamp(style.iconic_width, style.iconic_max_width) } else { column.width } } @@ -125,19 +150,7 @@ impl Renderer<'_, P> { (other, Node::Dock { side, columns }) => (false, *side, columns, other), _ => return false, }; - let gap = self.style.gap; - let room = (rect.width() - gap - self.node_limits(other).min.x).clamp(0.0, rect.width()); - let width = columns.iter().map(|c| column_width(c, self.style)).sum::().clamp(0.0, room); - let (dock, rest) = match edge_of(side, self.style.right_to_left) { - Edge::Left => ( - Rect::from_min_max(rect.min, pos2(rect.left() + width, rect.bottom())), - Rect::from_min_max(pos2((rect.left() + width + gap).min(rect.right()), rect.top()), rect.max), - ), - Edge::Right => ( - Rect::from_min_max(pos2(rect.right() - width, rect.top()), rect.max), - Rect::from_min_max(rect.min, pos2((rect.right() - width - gap).max(rect.left()), rect.bottom())), - ), - }; + let (dock, rest, room) = dock_rects(side, columns, other, rect, self.style, &*self.content); self.dock(ui, side, columns, dock, room); path.push(dock_first); self.node(ui, other, rest, path); @@ -470,7 +483,7 @@ impl Renderer<'_, P> { /// have no dock yet. fn dock_candidates(&self) -> Vec> { let mut candidates = self.dock_targets.clone(); - if self.style.profile != Profile::Dock || !usable(self.workspace) { + if !self.style.new_dock_zones || !usable(self.workspace) { return candidates; } let rtl = self.style.right_to_left; diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 85282ca041..f8bc435a36 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -240,6 +240,14 @@ impl Renderer<'_, P> { return self.stack_proposal(window, members, pointer); } let (anchor, zone, preview) = self.edge_proposal(members, pointer)?; + let lead = members.first()?.clone(); + let action = match members { + [_] => Action::Move { panel: lead, anchor: anchor.clone(), placement: Placement::Edge(zone) }, + _ => Action::MoveGroup { panel: lead, to: Target::At { anchor: anchor.clone(), placement: Placement::Edge(zone) } }, + }; + if !self.leaves_room(action) { + return None; + } Some(DropProposal { anchor, placement: Placement::Edge(zone), preview, insertion: None, noop: false }) } diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index 1470b96df3..f7fa795328 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -1,4 +1,5 @@ -//! Frame profile: Maximize Frame, the outer edge band, hidden panels and the frame menu items. +//! What the split tree adds around the groups: Maximize Frame, the outer edge band, hidden +//! panels, the float hint and the group menu tail. use std::{borrow::Cow, collections::HashMap, fmt::Debug, hash::Hash}; @@ -6,7 +7,7 @@ use egui::{Context, Pos2, Rect, pos2, vec2}; use super::{GroupKind, Renderer, floating::StackHit, group::TabGroup}; use crate::docking::{ - Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Profile, Zone, + Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Zone, dock_model::{Place, node_at}, }; @@ -157,14 +158,14 @@ impl Renderer<'_, P> { self.frame.paths.as_ref().and_then(|paths| paths.get(path).cloned()).unwrap_or_else(|| path.to_vec()) } - /// The outer edge band under the pointer (P8): top and bottom in both profiles, left and - /// right in the frame profile. Returns a docked anchor that is not moving, the zone and - /// the preview of the new frame. + /// The outer edge band under the pointer (P8): top and bottom, and left and right with + /// [`crate::docking::DockStyle::side_edge_zones`]. Returns a docked anchor that is not + /// moving, the zone and the preview of the new frame. pub(super) fn edge_proposal(&self, members: &[P], pointer: Pos2) -> Option<(P, Zone, Rect)> { let area = self.frame.edge.filter(|area| area.contains(pointer))?; let band = self.style.edge_band.min(area.width() / 4.0).min(area.height() / 4.0); let mut edges = vec![(pointer.y - area.top(), Zone::Top), (area.bottom() - pointer.y, Zone::Bottom)]; - if self.style.profile == Profile::Frame { + if self.style.side_edge_zones { edges.extend([(pointer.x - area.left(), Zone::Left), (area.right() - pointer.x, Zone::Right)]); } let (distance, zone) = edges.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?; @@ -183,10 +184,10 @@ impl Renderer<'_, P> { Some((anchor, zone, preview)) } - /// Under the pointer while a drag offers a docking target (frame profile): which modifier - /// floats the drop instead. + /// Under the pointer while a drag offers a docking target: which modifier floats the drop + /// instead. pub(super) fn paint_float_hint(&self, ctx: &Context, pointer: Pos2) { - if self.style.profile != Profile::Frame || self.style.float_hint_label.is_empty() { + if !self.style.float_hint || self.style.float_hint_label.is_empty() { return; } let key = if ctx.os() == egui::os::OperatingSystem::Mac { "⌘" } else { "Ctrl" }; @@ -198,22 +199,10 @@ impl Renderer<'_, P> { painter.galley(rect.center() - galley.size() * 0.5, galley, self.style.text); } - pub(super) fn float_label(&self) -> String { - if self.style.profile == Profile::Frame { self.style.undock_label.clone() } else { self.style.float_label.clone() } - } - - pub(super) fn float_group_label(&self) -> String { - if self.style.profile == Profile::Frame { self.style.undock_group_label.clone() } else { self.style.float_group_label.clone() } - } - - pub(super) fn close_group_label(&self) -> String { - if self.style.profile == Profile::Frame { self.style.close_panel_group_label.clone() } else { self.style.close_group_label.clone() } - } - - /// Ctrl/Cmd held when a frame-profile tab drag starts: the drop floats (S9). + /// Ctrl/Cmd held when a split-tree tab drag starts: the drop floats (S9). pub(super) fn latch_undock(&self, ctx: &Context, kind: Option) { let command = ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.mac_cmd); - if self.style.profile == Profile::Frame && kind == Some(GroupKind::Frame) && command { + if self.style.command_press_floats && kind == Some(GroupKind::Frame) && command { ctx.data_mut(|d| { if let Some(drag) = d.get_temp::>(self.id.with("drag")) { d.insert_temp(self.id.with("drag"), crate::docking::Drag { undock: true, ..drag }); @@ -222,21 +211,24 @@ impl Renderer<'_, P> { } } - /// Frame items of the menu tail: Close Other Panels in Group and Maximize Frame (frame - /// profile), and Move Panel to New Window where native windows are available. + /// The menu tail: Close Other Panels in Group and Maximize Frame when the style shows + /// them, and Move Panel to New Window where native windows are available. pub(super) fn frame_items(&mut self, ui: &mut egui::Ui, owner: &TabGroup<'_, P>, panel: &P) { - if self.style.profile == Profile::Frame { - let others = owner.panels.iter().filter(|p| *p != panel).all(|p| self.permissions(p).closable); - if owner.panels.len() > 1 && others && self.style.close_menu_items && self.menu_action(ui, &self.style.close_others_label.clone()) { - self.output.actions.push(Action::CloseOthers { panel: panel.clone() }); - } - if owner.kind == GroupKind::Frame { - let restore = self.frame.maximized.as_ref().is_some_and(|m| owner.panels.contains(m)); - let label = if restore { self.style.restore_frame_label.clone() } else { self.style.maximize_label.clone() }; - if self.menu_action(ui, &label) { - let panel = if restore { self.frame.maximized.clone().unwrap_or_else(|| panel.clone()) } else { panel.clone() }; - self.output.events.push(DockEvent::ToggleMaximize { panel }); - } + let others = owner.panels.iter().filter(|p| *p != panel).all(|p| self.permissions(p).closable); + if self.style.close_others_item + && owner.panels.len() > 1 + && others + && self.style.close_menu_items + && self.menu_action(ui, &self.style.close_others_label.clone()) + { + self.output.actions.push(Action::CloseOthers { panel: panel.clone() }); + } + if self.style.maximize_item && owner.kind == GroupKind::Frame { + let restore = self.frame.maximized.as_ref().is_some_and(|m| owner.panels.contains(m)); + let label = if restore { self.style.restore_frame_label.clone() } else { self.style.maximize_label.clone() }; + if self.menu_action(ui, &label) { + let panel = if restore { self.frame.maximized.clone().unwrap_or_else(|| panel.clone()) } else { panel.clone() }; + self.output.events.push(DockEvent::ToggleMaximize { panel }); } } #[cfg(feature = "native-windows")] diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index b84cde4ab1..8ce1ecb9d0 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -134,7 +134,7 @@ impl Renderer<'_, P> { // Registered last, so the band wins over the tabs below it. let border = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, (strip.top() + BORDER_BAND).min(strip.bottom())))); self.group_handle(ui, "drag-border", border, &owner, movable); - if self.style.wheel_selects_tabs() { + if self.style.wheel_selects_tabs { let tabs_area = mirror(Rect::from_min_max(strip.min, pos2(strip.right() - header_width, strip.bottom()))); self.wheel_tabs(ui, tabs_area, panels, active); } @@ -255,7 +255,7 @@ impl Renderer<'_, P> { let closable = self.style.close_menu_items && all(&|p| p.closable); let movable = all(&|p| p.movable); let floatable = movable && all(&|p| p.floatable); - if closable && self.menu_action(ui, &self.close_group_label()) { + if closable && self.menu_action(ui, &self.style.close_group_label.clone()) { self.output.actions.push(Action::CloseGroup { panel: panel.clone() }); } if owner.kind != GroupKind::Frame { @@ -267,7 +267,7 @@ impl Renderer<'_, P> { if owner.kind == GroupKind::Dock && self.menu_action(ui, &self.style.collapse_to_icons_label.clone()) { self.output.actions.push(Action::SetIconic { panel: panel.clone(), iconic: true }); } - if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.float_group_label()) { + if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.style.float_group_label.clone()) { let size = self.group_float_size(owner.panels, owner.rect.size()); let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), self.float_bounds); self.output.actions.push(Action::MoveGroup { @@ -395,7 +395,7 @@ impl Renderer<'_, P> { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !minimized }); } } - if self.style.middle_click_closes_tabs() && policy.closable && response.clicked_by(egui::PointerButton::Middle) { + if self.style.middle_click_closes_tabs && policy.closable && response.clicked_by(egui::PointerButton::Middle) { self.output.actions.push(Action::Close { panel: panel.clone() }); } if policy.movable && response.drag_started() && begin_drag(ui.ctx(), self.id, panel.clone(), group) { @@ -404,7 +404,7 @@ impl Renderer<'_, P> { response.context_menu(|ui| { self.content.panel_menu(ui, panel); if policy.movable && policy.floatable { - let logical = self.float_label(); + let logical = self.style.float_label.clone(); let text = self.content.action_label(ui, &logical, &self.style.font, self.style.text); let response = ui.button(text); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &logical)); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index c74a45c57d..742839a7ad 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -1,8 +1,8 @@ use std::{collections::HashMap, fmt::Debug, hash::Hash}; -use egui::{Context, Id, Rect, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; +use egui::{Context, CursorIcon, Id, Rect, Sense, Ui, UiBuilder, Vec2, pos2, vec2}; -use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize, split_rect}; +use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; use super::{Action, DockContent, DockOutput, DockStyle, DropTarget, Layout, Node, PanelLimits, Permissions, dock_model::Place}; @@ -25,6 +25,9 @@ pub(in crate::docking) use dock::fit_widths; pub(in crate::docking) use floating::RESIZE_HANDLES; mod group; mod preview; +mod sizes; + +pub(in crate::docking) use sizes::{DROP_MARGIN, Drawn, Sizer}; pub(super) struct Renderer<'a, P> { pub(super) id: Id, @@ -50,18 +53,16 @@ pub(super) struct Renderer<'a, P> { /// Each panel's place in `layout`, and its entry in `float_space.contents`. pub(super) places: HashMap, pub(super) contents: HashMap, - /// Frames drawn as the fixed-size side of their parent split, for split previews. - pub(super) fixed_slots: Vec>, + /// Split dividers drawn so far, by view path, for the intersections of their ancestors. + pub(super) dividers: Vec, } -/// A frame that holds the fixed size of its parent split: the parent's and the other child's -/// rects, where a side split of the frame goes (see `dock_model::split_frame`). -pub(super) struct FixedSlot

{ - pub(super) panels: Vec

, - pub(super) axis: SplitAxis, - pub(super) first: bool, - pub(super) parent: Rect, - pub(super) sibling: Rect, +pub(super) struct DrawnDivider { + path: Vec, + axis: SplitAxis, + /// The whole split's rect. + rect: Rect, + divider: Rect, } impl Renderer<'_, P> { @@ -111,25 +112,10 @@ impl Renderer<'_, P> { match node { Node::Split { axis: SplitAxis::Horizontal, first, second, .. } if self.dock_split(ui, first, second, rect, path) => {} Node::Split { axis, size, first, second } => { - let Some(wanted) = split_rect(rect, *axis, *size, self.style.gap, 0.0) else { return }; - let (lo, hi) = split_bounds(wanted.available(), *axis, self.node_limits(first), self.node_limits(second)); - let first_size = wanted.first_size().clamp(lo, hi); - let Some(split) = split_rect(rect, *axis, SplitSize::FixedFirst(first_size), self.style.gap, 0.0) else { return }; - let fixed = match size { - SplitSize::FixedFirst(_) => Some((first, true, split.second)), - SplitSize::FixedSecond(_) => Some((second, false, split.first)), - SplitSize::Ratio(_) => None, - }; - let panels = |node: &Node

| match node { - Node::Tabs { panels, .. } => Some(panels.clone()), - Node::Stack { entries } => Some(entries.iter().map(|e| e.panel.clone()).collect()), - Node::Split { .. } | Node::Dock { .. } => None, - }; - if let Some((node, first, sibling)) = fixed - && let Some(panels) = panels(node) - { - self.fixed_slots.push(FixedSlot { panels, axis: *axis, first, parent: rect, sibling }); - } + let sizer = self.sizer(); + let Some(split) = sizer.split(*axis, *size, first, second, rect) else { return }; + let (lo, hi) = sizer.range(node, rect); + let mark = self.dividers.len(); path.push(false); self.node(ui, first, split.first, path); path.pop(); @@ -147,13 +133,16 @@ impl Renderer<'_, P> { &self.style.resize_label, ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, ) - .value(split.first_size(), lo..=hi) + .value(split.first_size(), (split.first_size() + lo)..=(split.first_size() + hi)) .show(ui); self.register_interaction(ui.ctx(), response.response.id); - if response.delta != 0.0 - && let Some(size) = split.resized(*size, (split.first_size() + response.delta).clamp(lo, hi) - split.first_size(), 0.0) - { - self.output.actions.push(Action::ResizeSplit { path: layout_path, size }); + if response.delta != 0.0 { + let actions = self.divider_actions(node, rect, path, response.delta); + self.output.actions.extend(actions); + } + self.intersections(ui, node, rect, path, split.divider, mark); + if self.dividers.len() < crate::docking::model::MAX_NODES { + self.dividers.push(DrawnDivider { path: path.clone(), axis: *axis, rect, divider: split.divider }); } } Node::Tabs { panels, active } => self.group(ui, panels, *active, false, rect, GroupKind::Frame), @@ -250,8 +239,50 @@ impl Renderer<'_, P> { } } - pub(super) fn node_limits(&self, node: &Node

) -> PanelLimits { - node_limits(node, self.style, &*self.content) + pub(super) fn sizer(&self) -> Sizer<'_, P> { + Sizer { style: self.style, content: &*self.content } + } + + /// `ResizeSplit` actions that move the divider of the split `node`, drawn at view path + /// `path` in `rect`, by `delta` points. + fn divider_actions(&self, node: &Node

, rect: Rect, path: &[bool], delta: f32) -> Vec> { + let sizes = self.sizer().drag(node, rect, delta, &mut path.to_vec()); + sizes.into_iter().map(|(path, size)| Action::ResizeSplit { path: self.original_path(&path), size }).collect() + } + + /// Four-way handles where a divider drawn inside the split `node` (since `mark`) ends on + /// the split's own divider: dragging one moves both dividers. + fn intersections(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &[bool], divider: Rect, mark: usize) { + let Node::Split { axis, .. } = node else { return }; + let side = (self.style.gap * 3.0).max(12.0); + let mut found = Vec::new(); + for inner in self.dividers.get(mark..).unwrap_or_default() { + if inner.axis == *axis || !inner.divider.expand(1.0).intersects(divider) { + continue; + } + let center = match axis { + SplitAxis::Horizontal => pos2(divider.center().x, inner.divider.center().y), + SplitAxis::Vertical => pos2(inner.divider.center().x, divider.center().y), + }; + found.push((inner.path.clone(), inner.rect, Rect::from_center_size(center, Vec2::splat(side)).intersect(rect))); + } + for (inner_path, inner_rect, hit) in found { + let Some(inner) = inner_path.get(path.len()..).and_then(|rest| crate::docking::dock_model::node_at(node, rest)) else { continue }; + let id = self.id.with(("intersection", self.original_path(path), self.original_path(&inner_path))); + let response = ui.interact(hit, id, Sense::drag()); + self.register_interaction(ui.ctx(), id); + if response.hovered() || response.dragged() { + ui.ctx().set_cursor_icon(CursorIcon::Move); + } + let delta = response.drag_delta(); + if delta != Vec2::ZERO && delta.is_finite() { + let along = |axis: SplitAxis| if axis == SplitAxis::Horizontal { delta.x } else { delta.y }; + let Node::Split { axis: inner_axis, .. } = inner else { continue }; + let mut actions = self.divider_actions(node, rect, path, along(*axis)); + actions.extend(self.divider_actions(inner, inner_rect, &inner_path, along(*inner_axis))); + self.output.actions.extend(actions); + } + } } pub(super) fn contents(&mut self, ui: &mut Ui, panel: &P, rect: Rect) { @@ -273,10 +304,10 @@ impl Renderer<'_, P> { } } -/// A lone protected or bare panel draws no tab strip and no drag bar. +/// A lone protected panel draws no tab strip and no drag bar. pub(in crate::docking) fn stripless

(panels: &[P], content: &dyn DockContent

) -> bool { match panels { - [panel] => content.permissions(panel).is_protected() || content.bare(panel), + [panel] => content.permissions(panel).is_protected(), _ => false, } } @@ -288,12 +319,14 @@ pub(in crate::docking) fn node_limits

(node: &Node

, style: &DockStyle, cont let width: f32 = columns.iter().map(|c| dock::column_width(c, style)).sum(); PanelLimits { min: vec2(width.clamp(style.min_pane, 1_000_000.0), style.min_pane), ..PanelLimits::default() } } + // A group is as large as its largest panel allows: a panel without a maximum lifts the + // maximum of the panels it joins. Node::Tabs { panels, .. } => { - let mut limits = PanelLimits::default(); + let mut limits = PanelLimits { min: Vec2::ZERO, max: if panels.is_empty() { PanelLimits::default().max } else { Vec2::ZERO } }; for panel in panels { let policy = content.limits(panel); limits.min = limits.min.max(policy.min).max(Vec2::splat(style.min_pane)); - limits.max = limits.max.min(policy.max); + limits.max = limits.max.max(policy.max); } limits.max = limits.max.max(limits.min); if !stripless(panels, content) { @@ -304,11 +337,14 @@ pub(in crate::docking) fn node_limits

(node: &Node

, style: &DockStyle, cont } Node::Stack { entries } => { let mut limits = PanelLimits::default(); + if !entries.is_empty() { + limits.max.x = 0.0; + } for entry in entries { let policy = content.limits(&entry.panel); limits.min.x = limits.min.x.max(policy.min.x).max(style.min_pane); limits.min.y += if entry.open { policy.min.y.max(style.min_pane) } else { 0.0 } + style.tab_height; - limits.max.x = limits.max.x.min(policy.max.x); + limits.max.x = limits.max.x.max(policy.max.x); } limits.min = limits.min.min(Vec2::splat(1_000_000.0)); limits.max = limits.max.max(limits.min); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index d3e043e641..9de57d9753 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -1,17 +1,15 @@ -use std::{fmt::Debug, hash::Hash}; +use std::{collections::HashMap, fmt::Debug, hash::Hash}; use egui::{Context, Key, Pos2, Rect, Ui, Vec2, pos2, vec2}; -use super::{Renderer, clamp_float, dock::group_action}; +use super::{DROP_MARGIN, Drawn, Renderer, clamp_float, dock::group_action}; use crate::docking::chrome::drop_preview; use crate::docking::{ - Action, Drag, DropProposal, DropRequest, GroupDrag, GroupGesture, Node, Placement, Target, Zone, cancel_drag, + Action, Drag, DropProposal, DropRequest, DropTarget, GroupDrag, GroupGesture, Layout, Node, Placement, Target, Zone, cancel_drag, dock_model::{Place, node_at}, resolve_drop, surface::TAB_PADDING, - zone_rect, }; -use crate::layout::SplitAxis; /// Ctrl (Windows, Linux) or Cmd (macOS) held: the drop floats and no target is offered. fn float_only(ctx: &Context) -> bool { @@ -90,7 +88,6 @@ impl Renderer<'_, P> { return valid(proposal); } let own = |t: &crate::docking::DropTarget

| t.tabs.iter().any(|(p, _)| drag.members.contains(p)); - let pointer = self.seam_pointer(pointer); let target = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer) && !(window && own(t)))?; if own(target) { @@ -102,49 +99,48 @@ impl Renderer<'_, P> { noop: true, }); } - let proposal = resolve_drop(&drag.panel, pointer, std::slice::from_ref(target))?; + let proposal = self.resolve_roomy(&drag.panel, pointer, std::slice::from_ref(target), |to| group_action(drag, to))?; if window && matches!(proposal.placement, Placement::Split(_)) { return None; } - valid(self.split_preview(proposal)) + valid(proposal) } - /// The preview of a side split beside a frame that holds its parent's fixed size: the half - /// of the parent or of the other child that the new frame takes. - fn split_preview(&self, mut proposal: DropProposal

) -> DropProposal

{ - let Placement::Split(zone) = proposal.placement else { return proposal }; - let axis = match zone { - Zone::Center => return proposal, - Zone::Left | Zone::Right => SplitAxis::Horizontal, - Zone::Top | Zone::Bottom => SplitAxis::Vertical, - }; - let Some(slot) = self.fixed_slots.iter().find(|slot| slot.axis == axis && slot.panels.contains(&proposal.anchor)) else { return proposal }; - let opposite = match zone { - Zone::Left => Zone::Right, - Zone::Right => Zone::Left, - Zone::Top => Zone::Bottom, - _ => Zone::Top, - }; - let before = matches!(zone, Zone::Left | Zone::Top); - let preview = if before == slot.first { zone_rect(slot.parent, zone) } else { zone_rect(slot.sibling, opposite) }; - proposal.preview = preview.unwrap_or(proposal.preview); - proposal - } - - /// A pointer in the gap between docked frames, outside every target, moves onto the edge of - /// the nearest frame that takes splits, so a seam splits beside that frame rather than floating. - pub(super) fn seam_pointer(&self, pointer: Pos2) -> Pos2 { - let usable = |rect: Rect| crate::docking::targets::usable(rect); - if self.targets.iter().any(|t| usable(t.rect) && t.rect.contains(pointer)) { - return pointer; + /// [`resolve_drop`], where a split that would leave a group without room becomes a join + /// of the target group. + fn resolve_roomy(&self, panel: &P, pointer: Pos2, targets: &[DropTarget

], action: impl Fn(Target

) -> Action

) -> Option> { + let proposal = resolve_drop(panel, pointer, targets)?; + if !matches!(proposal.placement, Placement::Split(zone) if zone != Zone::Center) { + return Some(proposal); } - self.targets - .iter() - .filter(|t| t.allow_splits && usable(t.rect)) - .map(|t| (t.rect.distance_to_pos(pointer), t.rect)) - .filter(|(distance, _)| *distance <= self.style.gap) - .min_by(|a, b| a.0.total_cmp(&b.0)) - .map_or(pointer, |(_, rect)| rect.clamp(pointer)) + if self.leaves_room(action(Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() })) { + return Some(proposal); + } + let target = targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer))?; + resolve_drop(panel, pointer, std::slice::from_ref(&DropTarget { allow_splits: false, ..target.clone() })) + } + + /// Whether `action`, a drop that splits a group or the outer edge, leaves room: every group + /// it makes smaller stays [`DROP_MARGIN`] above its minimum, so each divider can still + /// travel both ways. An action the model rejects is left to the model's check. + pub(super) fn leaves_room(&self, action: Action

) -> bool { + let mut candidate = self.layout.clone(); + if candidate.apply_with_permissions(action, |p| self.permissions(p)).is_err() { + return true; + } + let sizer = self.sizer(); + let drawn = |layout: &Layout

| { + let mut out: Vec> = Vec::new(); + if let Some(root) = &layout.root { + sizer.groups(root, self.workspace, &mut out); + } + out.into_iter().filter_map(|d| Some((lead(d.node)?.clone(), d.rect.size(), d.limits.min))).collect::>() + }; + let before: HashMap = drawn(self.layout).into_iter().map(|(panel, size, _)| (panel, size)).collect(); + drawn(&candidate).into_iter().all(|(panel, size, min)| { + let room = size - min; + (room.x >= DROP_MARGIN && room.y >= DROP_MARGIN) || before.get(&panel).is_some_and(|old| size.x >= old.x - 0.5 && size.y >= old.y - 0.5) + }) } /// Release of a group drag: join or split at the target, or float at the ghost with the @@ -276,8 +272,13 @@ impl Renderer<'_, P> { let proposal = if float_only { None } else { - self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false) - .or_else(|| resolve_drop(&drag.panel, self.seam_pointer(pointer), &self.targets).map(|p| self.split_preview(p))) + self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false).or_else(|| { + let panel = &drag.panel; + self.resolve_roomy(panel, pointer, &self.targets, |to| match to { + Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, + to => Action::MovePanel { panel: panel.clone(), to }, + }) + }) }; if released { cancel_drag::

(ctx, self.id); @@ -453,3 +454,12 @@ impl Renderer<'_, P> { true } } + +/// The panel that names a drawn group: its first panel; none for a dock or a split. +fn lead

(node: &Node

) -> Option<&P> { + match node { + Node::Tabs { panels, .. } => panels.first(), + Node::Stack { entries } => entries.first().map(|e| &e.panel), + Node::Split { .. } | Node::Dock { .. } => None, + } +} diff --git a/crates/ui/src/docking/render/sizes.rs b/crates/ui/src/docking/render/sizes.rs new file mode 100644 index 0000000000..bf7fd3dc53 --- /dev/null +++ b/crates/ui/src/docking/render/sizes.rs @@ -0,0 +1,172 @@ +//! Split-tree geometry: where each split draws its children, how far a divider can travel, +//! and the sizes that move a divider while every group away from it keeps its size. + +use egui::Rect; + +use super::{dock::dock_rects, node_limits, split_bounds}; +use crate::docking::{DockContent, DockStyle, Node, PanelLimits}; +use crate::layout::{SplitAxis, SplitLayout, SplitSize, split_rect}; + +/// Room a group keeps above its minimum after a drop, so each of its dividers can still +/// travel both ways. +pub(in crate::docking) const DROP_MARGIN: f32 = 1.0; + +pub(in crate::docking) struct Sizer<'a, P> { + pub(in crate::docking) style: &'a DockStyle, + pub(in crate::docking) content: &'a dyn DockContent

, +} + +/// One group as drawn: its node, rect and limits. +pub(in crate::docking) struct Drawn<'a, P> { + pub(in crate::docking) node: &'a Node

, + pub(in crate::docking) rect: Rect, + pub(in crate::docking) limits: PanelLimits, +} + +fn extent(rect: Rect, axis: SplitAxis) -> f32 { + match axis { + SplitAxis::Horizontal => rect.width(), + SplitAxis::Vertical => rect.height(), + } +} + +fn along(v: egui::Vec2, axis: SplitAxis) -> f32 { + match axis { + SplitAxis::Horizontal => v.x, + SplitAxis::Vertical => v.y, + } +} + +impl

Sizer<'_, P> { + fn limits(&self, node: &Node

) -> PanelLimits { + node_limits(node, self.style, self.content) + } + + /// The split as drawn: its stored size, clamped so both children fit their limits. + pub(in crate::docking) fn split(&self, axis: SplitAxis, size: SplitSize, first: &Node

, second: &Node

, rect: Rect) -> Option { + let wanted = split_rect(rect, axis, size, self.style.gap, 0.0)?; + let (lo, hi) = split_bounds(wanted.available(), axis, self.limits(first), self.limits(second)); + split_rect(rect, axis, SplitSize::FixedFirst(wanted.first_size().clamp(lo, hi)), self.style.gap, 0.0) + } + + /// The children of a split drawn in `rect`, with their rects; a dock beside its neighbour + /// is drawn by the dock renderer. + pub(in crate::docking) fn children<'n>(&self, node: &'n Node

, rect: Rect) -> Option<[(&'n Node

, Rect); 2]> { + let Node::Split { axis, size, first, second } = node else { return None }; + match (&**first, &**second) { + (Node::Dock { side, columns }, other) if *axis == SplitAxis::Horizontal => { + let (dock, rest, _) = dock_rects(*side, columns, other, rect, self.style, self.content); + Some([(first, dock), (second, rest)]) + } + (other, Node::Dock { side, columns }) if *axis == SplitAxis::Horizontal => { + let (dock, rest, _) = dock_rects(*side, columns, other, rect, self.style, self.content); + Some([(first, rest), (second, dock)]) + } + _ => { + let split = self.split(*axis, *size, first, second, rect)?; + Some([(first, split.first), (second, split.second)]) + } + } + } + + /// Every group of `node` drawn in `rect`; a dock counts as one. + pub(in crate::docking) fn groups<'n>(&self, node: &'n Node

, rect: Rect, out: &mut Vec>) { + match self.children(node, rect) { + Some(children) => children.into_iter().for_each(|(child, rect)| self.groups(child, rect, out)), + None => out.push(Drawn { node, rect, limits: self.limits(node) }), + } + } + + /// How far the end edge (`end`) or start edge of `node` drawn in `rect` can move along + /// `axis`: inward while the groups touching it stay at their minimums, and outward up to + /// their maximums. + pub(in crate::docking) fn travel(&self, node: &Node

, rect: Rect, axis: SplitAxis, end: bool) -> (f32, f32) { + let docked = + matches!(node, Node::Split { first, second, .. } if matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. })); + match (node, self.children(node, rect)) { + (Node::Split { first, .. }, Some([a, b])) if docked => { + let (other, rect) = if matches!(**first, Node::Dock { .. }) { b } else { a }; + self.travel(other, rect, axis, end) + } + (Node::Split { axis: split_axis, .. }, Some([a, b])) if *split_axis == axis => { + let (child, rect) = if end { b } else { a }; + self.travel(child, rect, axis, end) + } + (_, Some([a, b])) => { + let (a, b) = (self.travel(a.0, a.1, axis, end), self.travel(b.0, b.1, axis, end)); + (a.0.min(b.0), a.1.min(b.1)) + } + (_, None) => { + let limits = self.limits(node); + let size = extent(rect, axis); + ((size - along(limits.min, axis)).max(0.0), (along(limits.max, axis) - size).max(0.0)) + } + } + } + + /// The sizes that move the end (`end`) or start edge of `node` drawn in `rect` outward by + /// `grow` points: only the groups touching that edge change. Paths are relative to `path`. + pub(in crate::docking) fn follow( + &self, + (node, rect): (&Node

, Rect), + axis: SplitAxis, + end: bool, + grow: f32, + path: &mut Vec, + out: &mut Vec<(Vec, SplitSize)>, + ) { + let Some([a, b]) = self.children(node, rect) else { return }; + let Node::Split { axis: split_axis, first, second, .. } = node else { return }; + let docked = matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. }); + let visit = |child: (&Node

, Rect), second_child: bool, path: &mut Vec, out: &mut Vec<(Vec, SplitSize)>| { + path.push(second_child); + self.follow(child, axis, end, grow, path, out); + path.pop(); + }; + if docked { + let dock_first = matches!(**first, Node::Dock { .. }); + visit(if dock_first { b } else { a }, dock_first, path, out); + } else if *split_axis == axis { + let available = extent(a.1, axis) + extent(b.1, axis) + grow; + let first_size = extent(a.1, axis) + if end { 0.0 } else { grow }; + if available > 0.0 { + out.push((path.clone(), SplitSize::Ratio((first_size / available).clamp(0.0, 1.0)))); + } + visit(if end { b } else { a }, end, path, out); + } else { + visit(a, false, path, out); + visit(b, true, path, out); + } + } + + /// The divider of the split `node` drawn in `rect` moved by `delta` points, clamped to its + /// travel: the split's own size and those of the splits that keep the groups away from the + /// divider at their sizes. Paths are relative to `path`, the split's own. + pub(in crate::docking) fn drag(&self, node: &Node

, rect: Rect, delta: f32, path: &mut Vec) -> Vec<(Vec, SplitSize)> { + let Node::Split { axis, size, first, second } = node else { return Vec::new() }; + let Some(split) = self.split(*axis, *size, first, second, rect) else { return Vec::new() }; + let (lo, hi) = self.range(node, rect); + let delta = delta.clamp(lo, hi); + if delta == 0.0 || !delta.is_finite() || split.available() <= 0.0 { + return Vec::new(); + } + let mut out = vec![(path.clone(), SplitSize::Ratio(((split.first_size() + delta) / split.available()).clamp(0.0, 1.0)))]; + path.push(false); + self.follow((first, split.first), *axis, true, delta, path, &mut out); + path.pop(); + path.push(true); + self.follow((second, split.second), *axis, false, -delta, path, &mut out); + path.pop(); + out + } + + /// How far the divider of the split `node` drawn in `rect` can move: `(lo, hi)`, with + /// `lo <= 0 <= hi`. + pub(in crate::docking) fn range(&self, node: &Node

, rect: Rect) -> (f32, f32) { + let Node::Split { axis, size, first, second } = node else { return (0.0, 0.0) }; + let Some(split) = self.split(*axis, *size, first, second, rect) else { return (0.0, 0.0) }; + let (first_in, first_out) = self.travel(first, split.first, *axis, true); + let (second_in, second_out) = self.travel(second, split.second, *axis, false); + (-first_in.min(second_out), first_out.min(second_in)) + } +} diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs new file mode 100644 index 0000000000..89a94dc94f --- /dev/null +++ b/crates/ui/src/docking/split_tests.rs @@ -0,0 +1,445 @@ +//! A split tree of tab groups in an editing layout like FilmCraft's: Source | Program | +//! Properties over Project | Tools | Timeline | Audio Meters, every group an ordinary +//! resizable one. One test per docking rule, the stuck cases of the FilmCraft map, and a +//! property test over random drops. + +use std::collections::HashMap; + +use super::floating_tests::frame_style; +use super::render::{Drawn, Sizer}; +use super::testing::DockDriver; +use super::*; +use crate::layout::{SplitAxis, SplitSize}; +use egui::{Modifiers, Pos2, Rect, Vec2, pos2, vec2}; + +const SOURCE: [u32; 4] = [1, 11, 12, 13]; +const PROGRAM: u32 = 2; +const PROPERTIES: [u32; 3] = [3, 31, 32]; +const PROJECT: [u32; 7] = [4, 41, 42, 43, 44, 45, 46]; +const TOOLS: u32 = 5; +const TIMELINE: u32 = 6; +const METERS: u32 = 7; +const INFO: u32 = 9; + +const SCREEN: Vec2 = Vec2::new(1440.0, 860.0); + +/// Panel bodies by their rects; `caps` are maximum widths a host asks for. +#[derive(Default)] +struct Film { + bodies: HashMap, + caps: HashMap, +} + +impl DockContent for Film { + fn body(&mut self, ui: &mut egui::Ui, panel: &u32) { + self.bodies.insert(*panel, ui.max_rect()); + } + fn logical_label(&self, panel: &u32) -> String { + format!("Panel {panel}") + } + fn limits(&self, panel: &u32) -> PanelLimits { + match self.caps.get(panel) { + Some(width) => PanelLimits { min: Vec2::ZERO, max: vec2(*width, 1_000_000.0) }, + None => PanelLimits::default(), + } + } +} + +type Driver = DockDriver; + +fn tabs(panels: &[u32]) -> Node { + Node::Tabs { panels: panels.to_vec(), active: 0 } +} + +fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) -> Node { + Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) } +} + +fn hsplit(ratio: f32, first: Node, second: Node) -> Node { + split(SplitAxis::Horizontal, ratio, first, second) +} + +/// The Editing workspace, with Info floating over Properties. +fn editing() -> Layout { + let top = hsplit(0.69, hsplit(0.5, tabs(&SOURCE), tabs(&[PROGRAM])), tabs(&PROPERTIES)); + let row = hsplit(0.06, tabs(&[TOOLS]), hsplit(0.88, tabs(&[TIMELINE]), tabs(&[METERS]))); + let bottom = hsplit(0.29, tabs(&PROJECT), row); + Layout { + root: Some(split(SplitAxis::Vertical, 0.57, top, bottom)), + floating: vec![Floating::single(vec![INFO], 0, [1120.0, 60.0, 280.0, 200.0])], + } +} + +fn driver(layout: Layout, content: Film) -> Driver { + let mut d = DockDriver::new(layout, content).with_style(frame_style); + d.screen = Rect::from_min_size(Pos2::ZERO, SCREEN); + d.area = d.screen; + d.settle(); + d +} + +fn film() -> Driver { + driver(editing(), Film::default()) +} + +/// A group's rect: its active body and its tab strip. +fn group(d: &Driver, panel: u32) -> Rect { + let body = d.content.bodies.get(&panel).copied().unwrap_or_else(|| panic!("panel {panel} not drawn")); + Rect::from_min_max(pos2(body.left(), body.top() - 26.0), body.max) +} + +fn tab(d: &Driver, panel: u32) -> Pos2 { + d.hit(&Hit::Tab(panel)).unwrap_or_else(|| panic!("tab {panel}")).center() +} + +/// Drag a divider by `delta`, hovering it first as a pointer does. +fn drag_hit(d: &mut Driver, hit: Hit, delta: Vec2) { + let at = d.hit(&hit).unwrap_or_else(|| panic!("{hit:?} in {:?}", d.hits())).center(); + d.move_to(at); + d.drag(at, at + delta); + d.settle(); +} + +fn divider(path: &[bool]) -> Hit { + Hit::Divider(Divider::Split(path.to_vec())) +} + +fn sizes(d: &Driver, panels: &[u32]) -> Vec { + panels.iter().map(|p| group(d, *p).size()).collect() +} + +fn close(a: Rect, b: Rect) -> bool { + (a.min - b.min).length() < 1.0 && (a.max - b.max).length() < 1.0 +} + +#[test] +fn a_group_is_a_picture_frame_whose_edges_split_it_in_half_and_whose_middle_joins_it() { + let base = film(); + let timeline = group(&base, TIMELINE); + let others = [PROJECT[0], TOOLS, METERS, SOURCE[0], PROGRAM, PROPERTIES[0]]; + let inset = |zone| { + let (w, h) = (timeline.width() * 0.08, (timeline.height() - 26.0) * 0.08); + match zone { + Zone::Left => pos2(timeline.left() + w, timeline.center().y + 13.0), + Zone::Right => pos2(timeline.right() - w, timeline.center().y + 13.0), + Zone::Top => pos2(timeline.center().x, timeline.top() + 26.0 + h), + Zone::Bottom => pos2(timeline.center().x, timeline.bottom() - h), + Zone::Center => pos2(timeline.center().x, timeline.center().y + 13.0), + } + }; + for zone in [Zone::Left, Zone::Right, Zone::Top, Zone::Bottom] { + let mut d = film(); + let before = sizes(&d, &others); + let at = inset(zone); + d.hold(tab(&d, INFO), at); + let half = zone_rect(timeline, zone).unwrap(); + assert!(d.filled(half.shrink(1.0)), "{zone:?}: the preview is that half of the group"); + let out = d.release(at); + assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TIMELINE, placement: Placement::Split(zone) }], "{zone:?}"); + d.settle(); + let (info, rest) = (group(&d, INFO), group(&d, TIMELINE)); + assert!(close(info.union(rest), timeline), "{zone:?}: the two halves fill the group: {info:?} {rest:?} in {timeline:?}"); + assert!((info.area() - rest.area()).abs() < info.area() * 0.05, "{zone:?}: about halves"); + assert_eq!(sizes(&d, &others), before, "{zone:?}: no other group changes"); + } + // The middle and the tab row join the group. + let mut d = film(); + let out = d.drag(tab(&d, INFO), inset(Zone::Center)); + assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TIMELINE, placement: Placement::Split(Zone::Center) }]); + let mut d = film(); + let out = d.drag(tab(&d, INFO), pos2(timeline.center().x, timeline.top() + 10.0)); + assert!(matches!(&out.actions[..], [Action::Move { panel: INFO, placement: Placement::Tab { .. }, .. }]), "{:?}", out.actions); + // The gap between two groups belongs to neither: the tab floats. + let mut d = film(); + let tools = group(&d, TOOLS); + let gap = pos2(tools.right() + 2.0, tools.center().y); + let out = d.drag(tab(&d, INFO), gap); + assert!(matches!(&out.actions[..], [Action::Float { panel: INFO, .. }]), "{:?}", out.actions); +} + +#[test] +fn window_edges_add_a_full_column_or_row_without_taking_the_groups_edges() { + let mut d = film(); + let project = group(&d, PROJECT[0]); + let out = d.drag(tab(&d, INFO), pos2(3.0, project.center().y)); + assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: SOURCE[0], placement: Placement::Edge(Zone::Left) }]); + d.settle(); + let info = group(&d, INFO); + assert_eq!((info.top(), info.bottom(), info.left()), (0.0, SCREEN.y, 0.0), "a full-height column at the left"); + assert!((info.width() - SCREEN.x * 0.25).abs() < 4.0, "{info:?}"); + + for (at, zone) in [(pos2(SCREEN.x - 3.0, 300.0), Zone::Right), (pos2(700.0, 3.0), Zone::Top), (pos2(700.0, SCREEN.y - 3.0), Zone::Bottom)] { + let mut d = film(); + let out = d.drag(tab(&d, INFO), at); + assert!(matches!(&out.actions[..], [Action::Move { placement: Placement::Edge(z), .. }] if *z == zone), "{zone:?}: {:?}", out.actions); + } + // Past the window band, the group's own edge band splits that group. + let mut d = film(); + let out = d.drag(tab(&d, INFO), pos2(project.left() + 20.0, project.center().y + 13.0)); + assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: PROJECT[0], placement: Placement::Split(Zone::Left) }]); +} + +#[test] +fn groups_have_one_small_minimum_and_no_maximum() { + let mut d = film(); + let tools = group(&d, TOOLS).width(); + drag_hit(&mut d, divider(&[true, true]), vec2(400.0, 0.0)); + assert!((group(&d, TOOLS).width() - (tools + 400.0)).abs() < 1.0, "Tools grows as wide as it is dragged"); + drag_hit(&mut d, divider(&[true, true]), vec2(-2000.0, 0.0)); + assert_eq!(group(&d, TOOLS).width(), 40.0, "and shrinks to the minimum, no further"); + + // A group too narrow for two halves takes a drop on its edge as a tab. + let tools = group(&d, TOOLS); + let out = d.drag(tab(&d, INFO), pos2(tools.right() - 4.0, tools.center().y + 30.0)); + assert!( + matches!(&out.actions[..], [Action::Move { panel: INFO, anchor: TOOLS, placement: Placement::Split(Zone::Center) | Placement::Tab { .. } }]), + "{:?}", + out.actions + ); +} + +#[test] +fn a_divider_resizes_only_the_groups_that_share_it() { + // Timeline | Meters: Project and Tools keep their widths. + let mut d = film(); + let (project, tools, timeline, meters) = (group(&d, PROJECT[0]), group(&d, TOOLS), group(&d, TIMELINE), group(&d, METERS)); + drag_hit(&mut d, divider(&[true, true, true]), vec2(-100.0, 0.0)); + assert_eq!((group(&d, PROJECT[0]), group(&d, TOOLS)), (project, tools)); + assert!((group(&d, TIMELINE).width() - (timeline.width() - 100.0)).abs() < 1.0); + assert!((group(&d, METERS).width() - (meters.width() + 100.0)).abs() < 1.0); + + // Project | the rest: only Tools, on the other side, gives way; Timeline and Meters stay. + let mut d = film(); + drag_hit(&mut d, divider(&[true]), vec2(15.0, 0.0)); + assert!((group(&d, PROJECT[0]).width() - (project.width() + 15.0)).abs() < 1.0); + assert!((group(&d, TOOLS).width() - (tools.width() - 15.0)).abs() < 1.0); + assert!(close(group(&d, TIMELINE), timeline) && close(group(&d, METERS), meters), "{:?}", d.layout); + + // Top row: Source | Program leaves Properties alone. + let mut d = film(); + let properties = group(&d, PROPERTIES[0]); + drag_hit(&mut d, divider(&[false, false]), vec2(80.0, 0.0)); + assert_eq!(group(&d, PROPERTIES[0]), properties); +} + +#[test] +fn an_intersection_moves_both_dividers() { + let mut d = film(); + let (project, tools, source) = (group(&d, PROJECT[0]), group(&d, TOOLS), group(&d, SOURCE[0])); + let hit = Hit::Divider(Divider::Intersection(vec![], vec![true])); + let at = d.hit(&hit).unwrap_or_else(|| panic!("{:?}", d.hits())); + assert!(at.contains(pos2(project.right() + 2.0, project.top() - 2.0)), "{at:?} at Project's top right corner"); + drag_hit(&mut d, hit, vec2(15.0, -60.0)); + assert!((group(&d, PROJECT[0]).width() - (project.width() + 15.0)).abs() < 1.0); + assert!((group(&d, PROJECT[0]).height() - (project.height() + 60.0)).abs() < 1.0); + assert!((group(&d, TOOLS).width() - (tools.width() - 15.0)).abs() < 1.0); + assert!((group(&d, SOURCE[0]).height() - (source.height() - 60.0)).abs() < 1.0); + assert_eq!(group(&d, SOURCE[0]).width(), source.width()); +} + +#[test] +fn closing_a_group_gives_its_space_to_its_neighbours() { + let mut d = film(); + let (tools, meters) = (group(&d, TOOLS), group(&d, METERS)); + d.layout.apply(Action::CloseGroup { panel: TIMELINE }).unwrap(); + d.settle(); + let meters_now = group(&d, METERS); + assert_eq!(group(&d, TOOLS), tools); + assert_eq!((meters_now.right(), meters_now.top(), meters_now.bottom()), (meters.right(), meters.top(), meters.bottom())); + assert!((meters_now.left() - (tools.right() + 4.0)).abs() < 1.0, "the row has no hole: {meters_now:?}"); +} + +// The stuck cases of the FilmCraft map (map.md section 3). + +#[test] +fn info_dropped_onto_a_capped_group_lifts_the_cap() { + let content = Film { caps: HashMap::from([(METERS, 116.0)]), ..Film::default() }; + let mut d = driver(editing(), content); + let meters = group(&d, METERS); + d.drag(tab(&d, INFO), pos2(meters.center().x, meters.center().y + 13.0)); + d.settle(); + assert!(d.layout.location(&INFO).is_ok_and(|l| l.anchor == Some(METERS)), "{:?}", d.layout); + // Info is the group's shown panel. + let width = group(&d, INFO).width(); + drag_hit(&mut d, divider(&[true, true, true]), vec2(-200.0, 0.0)); + assert!((group(&d, INFO).width() - (width + 200.0)).abs() < 1.0, "the group grows past the cap of one of its panels"); + drag_hit(&mut d, divider(&[true, true, true]), vec2(150.0, 0.0)); + assert!((group(&d, INFO).width() - (width + 50.0)).abs() < 1.0, "and shrinks again"); +} + +#[test] +fn a_drop_beside_a_narrow_group_splits_that_group_only() { + let mut d = film(); + drag_hit(&mut d, divider(&[true, true]), vec2(80.0, 0.0)); + let (tools, project, timeline, meters) = (group(&d, TOOLS), group(&d, PROJECT[0]), group(&d, TIMELINE), group(&d, METERS)); + assert!(tools.width() > 120.0, "{tools:?}"); + let at = pos2(tools.right() - 8.0, tools.center().y + 13.0); + d.hold(tab(&d, INFO), at); + assert!(d.filled(zone_rect(tools, Zone::Right).unwrap().shrink(1.0)), "the preview is Tools' right half"); + let out = d.release(at); + assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TOOLS, placement: Placement::Split(Zone::Right) }]); + d.settle(); + assert!(close(group(&d, TOOLS).union(group(&d, INFO)), tools)); + assert_eq!((group(&d, PROJECT[0]), group(&d, TIMELINE), group(&d, METERS)), (project, timeline, meters)); +} + +#[test] +fn every_divider_travels_after_drops() { + let mut d = film(); + let tools = group(&d, TOOLS); + d.drag(tab(&d, INFO), pos2(tools.right() - 8.0, tools.center().y + 13.0)); + d.settle(); + let meters = group(&d, METERS); + d.drag(tab(&d, PROGRAM), pos2(meters.center().x, meters.center().y + 13.0)); + d.settle(); + let timeline = group(&d, TIMELINE); + d.drag(tab(&d, PROPERTIES[0]), pos2(timeline.center().x, timeline.bottom() - 10.0)); + d.settle(); + assert_dividers_travel(&mut d); +} + +/// Each split divider moves both ways when dragged, from the layout as it is. +fn assert_dividers_travel(d: &mut Driver) { + let start = d.layout.clone(); + let paths: Vec> = d + .hits() + .into_iter() + .filter_map(|(hit, _)| match hit { + Hit::Divider(Divider::Split(path)) => Some(path), + _ => None, + }) + .collect(); + assert!(!paths.is_empty()); + for path in paths { + for step in [12.0, -24.0] { + let Some(rect) = d.hit(÷r(&path)) else { continue }; + let delta = if rect.width() < rect.height() { vec2(step, 0.0) } else { vec2(0.0, step) }; + let before = d.layout.clone(); + drag_hit(d, divider(&path), delta); + assert_ne!(d.layout, before, "divider {path:?} does not move by {step}"); + } + d.layout = start.clone(); + d.settle(); + } +} + +/// Every group at or above its minimum, and every divider with room both ways. +fn assert_sizes(d: &Driver, context: &str) { + let mut style = DockStyle::default(); + frame_style(&mut style); + let Some(root) = &d.layout.root else { return }; + let sizer = Sizer { style: &style, content: &d.content }; + let mut groups: Vec> = Vec::new(); + sizer.groups(root, d.area, &mut groups); + for g in &groups { + let room = g.rect.size() - g.limits.min; + assert!(room.x >= -0.01 && room.y >= -0.01, "{context}: {:?} is below its minimum {:?}", g.rect, g.limits.min); + } + let mut nodes = vec![(root, d.area)]; + while let Some((node, rect)) = nodes.pop() { + let Some(children) = sizer.children(node, rect) else { continue }; + let (lo, hi) = sizer.range(node, rect); + assert!(lo < -0.5 && hi > 0.5, "{context}: a divider is stuck ({lo}, {hi}) at {rect:?} in {:?}", d.layout); + nodes.extend(children); + } +} + +/// A small deterministic generator, so a failing sequence repeats. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + self.0 >> 33 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + fn unit(&mut self) -> f32 { + (self.next() % 1000) as f32 / 1000.0 + } +} + +#[test] +fn random_drops_leave_every_group_its_minimum_and_every_divider_travel() { + for seed in 1..=6u64 { + let mut rng = Lcg(seed); + let mut d = film(); + for step in 0..14 { + // Only the bodies drawn now. + d.content.bodies.clear(); + d.settle(); + let panels: Vec = d.layout.panels().into_iter().copied().collect(); + let panel = panels[rng.below(panels.len())]; + let Some(from) = d.hit(&Hit::Tab(panel)).map(|r| r.center()) else { continue }; + let target = panels[rng.below(panels.len())]; + let Some(rect) = d.content.bodies.get(&target).copied() else { continue }; + let to = match rng.below(8) { + // A window edge. + 0 => { + let edges = [ + pos2(3.0, rect.center().y), + pos2(SCREEN.x - 3.0, rect.center().y), + pos2(rect.center().x, 3.0), + pos2(rect.center().x, SCREEN.y - 3.0), + ]; + edges[rng.below(4)] + } + // The tab row. + 1 => pos2(rect.center().x, rect.top() - 13.0), + // Anywhere in the body: an edge band or the middle. + _ => rect.lerp_inside(vec2(0.02 + rng.unit() * 0.96, 0.02 + rng.unit() * 0.96)), + }; + d.drag(from, to); + d.settle(); + if d.layout.floating.iter().any(|w| w.contains(&panel)) && panel != INFO { + // Back into the tree: this test is about the docked layout. + d.layout.apply(Action::Move { panel, anchor: target, placement: Placement::Split(Zone::Center) }).ok(); + d.settle(); + } + assert_sizes(&d, &format!("seed {seed}, step {step}")); + } + assert_dividers_travel(&mut d); + } +} + +#[test] +fn ctrl_or_cmd_floats_from_a_tab_or_a_drag_bar_and_the_preview_says_so() { + const HINT: &str = "Hold Ctrl to undock"; + let floated = |actions: &[Action], panel: u32| match actions { + [Action::Float { panel: p, .. }] => *p == panel, + [Action::MoveGroup { panel: p, to: Target::Float { .. } }] => *p == panel, + _ => false, + }; + fn texts(d: &Driver) -> Vec { + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let mut out = Vec::new(); + d.shapes().iter().for_each(|clipped| walk(&clipped.shape, &mut out)); + out + } + let d = film(); + let over = group(&d, TIMELINE).center() + vec2(0.0, 13.0); + let from_tab = tab(&d, PROJECT[0]); + let from_bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); + for from in [from_tab, from_bar] { + // Without the modifier, a release over a group docks there; the preview names the modifier. + let mut d = film(); + d.hold(from, over); + assert!(texts(&d).iter().any(|t| t == HINT), "{from:?}: {:?}", texts(&d)); + let out = d.release(over); + assert!(!out.actions.is_empty() && !floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); + // Held, it floats, and the hint is gone. + let mut d = film(); + d.modifiers = Modifiers::COMMAND; + d.hold(from, over); + assert!(!texts(&d).iter().any(|t| t == HINT), "{from:?}"); + let out = d.release(over); + assert!(floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); + } +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 389589dd7e..e4a82b3449 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -44,13 +44,16 @@ pub struct DockStyle { /// Painted under every floating window, so it stays opaque when the panel colors are not. pub floating_background: Color32, pub floating_stroke: Stroke, - /// Dock: docks, columns and stacked groups. Frame: a split tree of tab frames, with - /// Maximize, Ctrl/Cmd-drag undock, splits on all four outer edges and frame menu labels. - pub profile: Profile, /// Height of a floating window's title bar. pub title_height: f32, /// Width of the band along the layout's outer edge that splits at the root. pub edge_band: f32, + /// The outer edge band also runs along the left and right edges, where a drop adds a + /// full-height column. Off: only the top and bottom edges add a full-width row. + pub side_edge_zones: bool, + /// [D] The docked area's left and right edges, where no dock is yet, take a drop as a new + /// dock (see [`Self::new_dock_band`]). + pub new_dock_zones: bool, /// [D] Height of the bar above each dock column. It drags the column and holds its »/« button. pub column_bar_height: f32, /// [D] Height of the band around the seam between two stacked groups, in docks and @@ -69,7 +72,7 @@ pub struct DockStyle { /// [D] Column menu item that toggles Auto-Collapse Iconic Panels. pub auto_collapse_label: String, /// [D] Lay docks out right to left: `Side::Start` is the right edge. egui has no app-wide - /// layout direction, so the host sets this from its locale. Frame splits keep their sides. + /// layout direction, so the host sets this from its locale. Splits keep their sides. pub right_to_left: bool, /// [D] Accessibility label of a column bar. pub move_column_label: String, @@ -81,18 +84,23 @@ pub struct DockStyle { pub expand_column_label: String, pub move_window_label: String, pub close_window_label: String, - /// Frame profile menu labels. - pub undock_label: String, - pub undock_group_label: String, - pub close_panel_group_label: String, + /// Group menu items Close Other Panels in Group, and Maximize Frame / Restore Frame Size + /// for groups of the split tree, each shown when its flag is on. pub close_others_label: String, + pub close_others_item: bool, pub maximize_label: String, pub restore_frame_label: String, + pub maximize_item: bool, /// Shown where native windows are available (feature `native-windows`). pub new_window_label: String, - /// Frame profile: shown under the pointer while a drag offers a docking target. `{key}` - /// stands for the modifier that floats the drop instead: ⌘ on macOS, Ctrl elsewhere. + /// Shown under the pointer while a drag offers a docking target, when [`Self::float_hint`] + /// is on. `{key}` stands for the modifier that floats the drop instead: ⌘ on macOS, Ctrl + /// elsewhere. pub float_hint_label: String, + pub float_hint: bool, + /// Ctrl/Cmd held when a tab drag of a split-tree group starts makes its drop float, even + /// when the key is let go during the drag. Off: only the key held at the drop counts. + pub command_press_floats: bool, /// Show the built-in Close items in tab and group menus (Close Panel, Close Tab Group, /// Close Other Panels in Group) for closable panels. A host that draws its own Close items /// turns this off and keeps [`Permissions::closable`], so its close actions still apply. @@ -100,20 +108,9 @@ pub struct DockStyle { /// Show × on the title bar of a floating window whose panels are all closable. pub close_button: bool, /// The mouse wheel over a tab strip selects the next or previous tab, one per notch. - /// `None`: on in [`Profile::Frame`], off in [`Profile::Dock`]. - pub wheel_selects_tabs: Option, - /// A middle click on a tab closes its panel when the panel is closable. `None`: on in - /// [`Profile::Frame`], off in [`Profile::Dock`]. - pub middle_click_closes_tabs: Option, -} - -/// Which arrangement a [`DockStyle`] renders and labels. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -#[non_exhaustive] -pub enum Profile { - #[default] - Dock, - Frame, + pub wheel_selects_tabs: bool, + /// A middle click on a tab closes its panel when the panel is closable. + pub middle_click_closes_tabs: bool, } impl Default for DockStyle { @@ -157,9 +154,10 @@ impl DockStyle { drag_bar_width: 40.0, floating_background: visuals.window_fill, floating_stroke: visuals.window_stroke, - profile: Profile::Dock, title_height: super::chrome::TITLE_HEIGHT, edge_band: 8.0, + side_edge_zones: false, + new_dock_zones: true, column_bar_height: 14.0, seam_band: 8.0, new_dock_band: 12.0, @@ -176,29 +174,22 @@ impl DockStyle { expand_column_label: "Expand column".into(), move_window_label: "Move panel window".into(), close_window_label: "Close panel window".into(), - undock_label: "Undock Panel".into(), - undock_group_label: "Undock Panel Group".into(), - close_panel_group_label: "Close Panel Group".into(), close_others_label: "Close Other Panels in Group".into(), + close_others_item: false, maximize_label: "Maximize Frame".into(), restore_frame_label: "Restore Frame Size".into(), + maximize_item: false, new_window_label: "Move Panel to New Window".into(), float_hint_label: "Hold {key} to undock".into(), + float_hint: false, + command_press_floats: false, close_menu_items: true, close_button: true, - wheel_selects_tabs: None, - middle_click_closes_tabs: None, + wheel_selects_tabs: false, + middle_click_closes_tabs: false, } } - pub(super) fn wheel_selects_tabs(&self) -> bool { - self.wheel_selects_tabs.unwrap_or(self.profile == Profile::Frame) - } - - pub(super) fn middle_click_closes_tabs(&self) -> bool { - self.middle_click_closes_tabs.unwrap_or(self.profile == Profile::Frame) - } - pub(super) fn valid(&self) -> bool { [ self.tab_height, @@ -415,7 +406,9 @@ impl

Clone for HidePanels<'_, P> { impl

Copy for HidePanels<'_, P> {} /// Preferred body bounds. Tiny viewports relax minima proportionally rather than producing -/// inverted rectangles. Maximums constrain a pane when its sibling can occupy the remainder. +/// inverted rectangles. Maximums constrain a pane when its sibling can occupy the remainder. A +/// tab group takes the largest minimum and the largest maximum of its panels, so a panel without +/// a maximum lifts the maximum of the panels it joins. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PanelLimits { pub min: Vec2, @@ -447,7 +440,7 @@ pub(super) struct Drag

{ pub(super) origin: Pos2, pub(super) source: Rect, pub(super) grab: Vec2, - /// Ctrl/Cmd held at the press of a frame-profile tab drag: the drop always floats. + /// Ctrl/Cmd held at the press, with [`DockStyle::command_press_floats`]: the drop floats. pub(super) undock: bool, } @@ -557,11 +550,6 @@ pub trait DockContent

{ fn allow_native(&self, _panel: &P) -> bool { false } - /// A lone bare panel draws no tab strip and no drag bar, like a lone protected panel. It - /// still moves by command and menu. - fn bare(&self, _panel: &P) -> bool { - false - } /// Host-owned drop resolution for targets the renderer cannot know about. Returning /// feedback consumes the gesture, including no-op targets; the renderer then emits no move. fn resolve_drag(&mut self, _ctx: &Context, _style: &DockStyle, _request: &DropRequest<'_, P>) -> Option { @@ -644,9 +632,6 @@ impl + ?Sized> DockContent

for Overrides<'_, P, C> { fn allow_native(&self, panel: &P) -> bool { self.inner.allow_native(panel) } - fn bare(&self, panel: &P) -> bool { - self.inner.bare(panel) - } fn resolve_drag(&mut self, ctx: &Context, style: &DockStyle, request: &DropRequest<'_, P>) -> Option { self.inner.resolve_drag(ctx, style, request) } @@ -826,7 +811,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { float_space: FloatSpace { contents, ..FloatSpace::new(rect) }, places, contents: content_index, - fixed_slots: Vec::new(), + dividers: Vec::new(), }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index fb3c847f93..87b2cb0ab8 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -651,8 +651,10 @@ fn split_inner_edge_remains_draggable_beside_a_scrollbar() { frame(&mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); frame(&mut layout, vec![Event::PointerMoved(start + vec2(40.0, 0.0))]); frame(&mut layout, vec![pointer_button(start + vec2(40.0, 0.0), false)]); - let Node::Split { size: SplitSize::FixedFirst(width), .. } = layout.root.unwrap() else { panic!() }; - assert!((width - 260.0).abs() < 0.001, "sidebar width after inner-edge drag: {width}"); + // A dragged divider keeps a ratio of the space, whatever mode it was saved with. + let Node::Split { size: SplitSize::Ratio(ratio), .. } = layout.root.unwrap() else { panic!() }; + // 800 points less the 4 point divider. + assert!((ratio * 796.0 - 260.0).abs() < 0.01, "sidebar width after inner-edge drag: {}", ratio * 796.0); } #[test] diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index 0383012334..b7f2e4329c 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -195,7 +195,7 @@ fn localized_covers_every_label_and_contains_takes_a_borrowed_panel() { }); full.textures_delta.clear(); let values: Vec<&str> = debug.split("_label: \"").skip(1).filter_map(|rest| rest.split('"').next()).collect(); - assert_eq!(values.len(), 28, "{debug}"); + assert_eq!(values.len(), 25, "{debug}"); assert!(values.iter().all(|v| v.starts_with("dock.")), "a label without a key: {values:?}"); let unique: std::collections::HashSet<_> = values.iter().collect(); assert_eq!(unique.len(), values.len()); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 2da9736b08..51cfd297ae 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -7,16 +7,17 @@ gestures. The app owns panel contents, commands, document state and where layout Office apps that draw their own document with a few task panes beside it use [`craft_ui::panes`](ui-panes.md) instead. -## Profiles +## Arrangements -`DockStyle::profile` picks one of two arrangements. Both use the same model and actions. -An app builds its style with `DockStyle::from_ui`, `from_visuals` or `default` and then sets -fields; new fields can be added, so the struct has no literal form outside the crate. +One model serves every app. What differs between apps is the default layout and a few +`DockStyle` settings. An app builds its style with `DockStyle::from_ui`, `from_visuals` or +`default` and then sets fields; new fields can be added, so the struct has no literal form +outside the crate. -| Profile | Arrangement | Apps | -|---|---|---| -| `Profile::Dock` (default) | Docks on the window's start and end edges. A dock has columns; a column has stacked groups and can collapse to icons. Frames (tab groups and splits) fill the space between the docks. | Creative apps with a canvas and panel docks | -| `Profile::Frame` | A split tree of tab frames. Frame menus offer Maximize Frame, Undock and Close Other Panels. Ctrl/Cmd + drag undocks, and a hint under the pointer says so. Drops on all four outer edges split at the root. | Apps whose whole window is frames | +| Arrangement | Layout | Style settings | Apps | +|---|---|---|---| +| Docks beside a canvas (the defaults) | `Node::Dock`s on the window's start and end edges. A dock has columns; a column has stacked groups and can collapse to icons. Frames (tab groups and splits) fill the space between the docks. | `new_dock_zones` on | Creative apps with a canvas and panel docks | +| A split tree of tab groups | `Split`s and `Tabs` only. | `side_edge_zones`, `maximize_item`, `close_others_item`, `command_press_floats`, `float_hint`, `wheel_selects_tabs`, `middle_click_closes_tabs` on, `new_dock_zones` off; menu labels such as "Undock Panel" set on `float_label`, `float_group_label` and `close_group_label` | Apps whose whole window is frames | Sides are logical: `Side::Start` is the left edge, or the right edge when `DockStyle::right_to_left` is set. egui has no app-wide direction, so the app sets it from its @@ -32,7 +33,7 @@ their sides. | Node | Holds | |---|---| | `Tabs` | A tab group: panels and the active index. | -| `Split` | Two children, horizontal or vertical, with a ratio or a fixed first or second size. | +| `Split` | Two children, horizontal or vertical, with a ratio. A fixed first or second size from a saved layout is drawn at that size until the divider moves; a moved divider stores a ratio. | | `Stack` | Accordion entries, each open or closed, with an optional height. | | `Dock` | A side and its columns. A `Column` has `Group`s, a width, and `iconic`. | @@ -68,11 +69,9 @@ layout.apply(Action::Move { `Placement::for_zone(layout, anchor, zone, right_to_left)` maps a left, right, top, bottom or center zone onto what the anchor's container takes: a split in the frame tree, a new column on that side or a new group above or below in a dock, a group above or below in a floating window. -- A side split zone puts what moves in a new half-size split of the anchor's frame. A frame - that holds the fixed size of its parent split along the same axis, such as a tool strip, keeps - that size: on its outer side the new split wraps the parent, on its inner side it halves the - parent's other child. The new split has its own divider, and the drop preview shows the half - the new frame takes. +- A side split zone puts what moves in a new half-size split of the anchor's frame, and no + other frame changes size. The new split has its own divider, and the drop preview shows the + half the new frame takes. - Other actions select, minimize, collapse to icons, resize splits, columns and groups, and move a floating window to its own OS window (`SetNative`, feature `native-windows`). @@ -112,19 +111,19 @@ its own command path, so pointer, keyboard and control commands share one path. `DockContent

` is the app's adapter. It draws each panel body and gives its label, icon, permissions, size limits, preferred floating size, panel menu and group header. The group header sits at the end of the tab strip; `group_header_width` gets the strip width, so a header that -draws its own tabs can size them to the room left. `bare` hides the tab strip of a lone panel. An icon is an image (`icon`), or drawn in code by `paint_icon`, which +draws its own tabs can size them to the room left. An icon is an image (`icon`), or drawn in code by `paint_icon`, which gets a painter, the icon rect and the tint color and returns true when it painted. Panel bodies keep a stable egui id when they move, so widget memory survives. `DockOutput` also has: - `focused`: the panel the user focused this frame: a clicked tab, a drop, or a press of any - pointer button in a panel body (bare and protected panels included) or in the group header, + pointer button in a panel body (protected panels included) or in the group header, which focuses the group's shown panel. Commands, `raise_panel` and workspace resets never set it; a host that tracks the last focused panel clears it when a reset or command hides, closes or moves that panel. -- `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (Frame) and - `DockEvent::ToggleAutoCollapse` (Dock), and `DockEvent::FlyoutChanged { panel }` (Dock): the +- `events`: requests outside the layout, such as `DockEvent::ToggleMaximize` (`maximize_item`) and + `DockEvent::ToggleAutoCollapse` and `DockEvent::FlyoutChanged { panel }` (docks): the flyout opened, switched or closed (`None`). It comes once per change, whatever made it: an icon, Escape, a press outside, a raised panel, `open_flyout` or `close_flyout`. - `error`: a rejected gesture. @@ -191,21 +190,33 @@ A flyout fits its content the same way, without the title bar. 4 pt band above the title bar (`chrome::RESIZE_BAND`), so they take no moves and no clicks on the title bar's buttons. A resize keeps the opposite edges in place and stays within the size limits and the screen. A focused resize handle moves its edge 8 pt per arrow key. -- Over a frame, the tab strip and the middle join its tabs, and the nearest side splits it. A - side zone is a quarter of the frame deep, at least 32 pt and at most half the frame, so a narrow - tool strip keeps both side targets. A drop in the gap between two frames splits beside the - nearer one. +- Over a frame, the tab strip and the middle join its tabs, and the nearest side splits it. The + side zones are trapezoids along the four edges, like a picture frame: a quarter of the frame + deep, at least 32 pt and at most half the frame. A split that would leave either half without + `DockStyle::min_pane` joins the frame's tabs instead. The gap between two frames is no target. +- The outer edge band (`DockStyle::edge_band`) takes a drop as a new frame across the whole + window side: top and bottom, and left and right with `side_edge_zones`. It takes a quarter of + the window and is offered only when every frame keeps its minimum. Past the band, a frame's own + side zones apply. +- A divider resizes only the frames that touch it; every other frame keeps its size. It stops + when a frame touching it reaches its minimum. Where a divider ends on another divider, a + four-way handle (`Divider::Intersection`) moves both. +- Every frame has the same minimum, `DockStyle::min_pane` (plus its tab strip), unless its panels + ask for more through `PanelLimits::min`. Frames have no maximum unless every panel in them asks + for one through `PanelLimits::max`: a panel without a maximum lifts the maximum of the panels it + joins. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. -- In the Frame profile, Ctrl (⌘ on macOS) held while dragging a tab, a drag bar or a grip that - calls `begin_drag` floats the drop wherever it lands. While a drag offers a docking target, a - hint under the pointer names the modifier: `float_hint_label`, where `{key}` becomes ⌘ or Ctrl. +- Ctrl (⌘ on macOS) held at the drop floats it wherever it lands. With `command_press_floats`, + the key held when a tab drag of a frame starts is enough. With `float_hint`, a hint under the + pointer names the modifier while a drag offers a docking target: `float_hint_label`, where + `{key}` becomes ⌘ or Ctrl. - Double-click a tab or drag bar to minimize a group to its strip. - Right-click a tab for its menu, or a drag bar for the group menu; Enter or Space on a focused drag bar opens it too. A left click on the drag bar only focuses it. -- In the Frame profile, the mouse wheel over a tab strip selects the next or previous tab, and a - middle click on a closable panel's tab closes it. `DockStyle::wheel_selects_tabs` and - `middle_click_closes_tabs` turn either on or off in any profile. +- With `DockStyle::wheel_selects_tabs`, the mouse wheel over a tab strip selects the next or + previous tab. With `middle_click_closes_tabs`, a middle click on a closable panel's tab closes + it. - A column's »/« button collapses it to icons, one icon per panel with a separator between groups. Widen an iconic column to show panel names. Click an icon to open its group as a flyout on the canvas side. Drag an icon to move its panel, or an icon group's top edge (the separator line above it) to move the group. From 5abc37e45446d5cad2175d6464fad94e6526e91c Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 20:08:18 +0000 Subject: [PATCH 83/94] docking: a release over no target cancels; the title bar only moves a window Two DockStyle settings, on by default so the dock-and-canvas arrangement keeps its behaviour. Without float_on_empty_drop, a tab or group released over no target inside the app window (the gap between groups, a menu bar, a status bar) cancels the drag; Ctrl/Cmd or a release outside the window floats it. Without title_bar_docks, dragging a floating window's title bar only moves the window. --- crates/ui/src/docking/floating_tests.rs | 2 + crates/ui/src/docking/render/floating.rs | 1 + crates/ui/src/docking/render/preview.rs | 27 ++++++---- crates/ui/src/docking/split_tests.rs | 67 +++++++++++++++++++++++- crates/ui/src/docking/surface.rs | 9 ++++ docs/ui-docking.md | 10 +++- 6 files changed, 103 insertions(+), 13 deletions(-) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index c05271c5b7..021b85708f 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -87,6 +87,8 @@ pub(super) fn frame_style(style: &mut DockStyle) { style.close_others_item = true; style.maximize_item = true; style.command_press_floats = true; + style.float_on_empty_drop = false; + style.title_bar_docks = false; style.float_hint = true; style.wheel_selects_tabs = true; style.middle_click_closes_tabs = true; diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index f8bc435a36..a321f3aa1e 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -323,6 +323,7 @@ impl Renderer<'_, P> { /// group target docks or merges every group in it, else hosts get the release in /// `group_drop`. pub(super) fn drop_window(&mut self, drag: &GroupDrag

, pointer: Pos2, float_only: bool) { + let float_only = float_only || !self.style.title_bar_docks; if !float_only && let Some((action, _)) = self.dock_group_proposal(drag, pointer) { self.output.actions.extend(action); return; diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 9de57d9753..a767750a3a 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -60,14 +60,18 @@ impl Renderer<'_, P> { } return; } - // Leaving the window ends a group drag where it is, with no drop. - if !released || !(has_pointer || touch_ended) { + // Leaving the window ends a group drag where it is, with no drop, unless only a + // release outside the window floats. + let gone = !has_pointer && !touch_ended; + let floats_outside = !self.style.float_on_empty_drop && drag.gesture != GroupGesture::Window; + if !(released && !gone) && !(gone && floats_outside) { return; } let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) else { return }; + let outside = gone || !ctx.content_rect().contains(pointer); match drag.gesture { GroupGesture::Window => self.drop_window(&drag, pointer, float_only), - GroupGesture::Group | GroupGesture::Column => self.drop_group(&drag, pointer, float_only), + GroupGesture::Group | GroupGesture::Column => self.drop_group(&drag, pointer, float_only || outside), } } else if let Some(pointer) = pointer.filter(|p| !self.blockers.iter().any(|r| r.contains(*p))) { self.output.group_drag = Some(drag.panel.clone()); @@ -164,6 +168,9 @@ impl Renderer<'_, P> { if proposal.is_some() && !floating { return; } + if !float_only && !self.style.float_on_empty_drop { + return; + } // No target: hosts that still apply their own policy for a whole-group release get it. self.output.group_drop = Some((drag.panel.clone(), pointer)); let rect = self.group_ghost(drag, pointer); @@ -196,7 +203,7 @@ impl Renderer<'_, P> { x += advance; } } - if float_only { + if float_only || (drag.gesture == GroupGesture::Window && !self.style.title_bar_docks) { return; } if let Some((action, line)) = self.dock_group_proposal(drag, pointer) { @@ -246,8 +253,10 @@ impl Renderer<'_, P> { return; } let float_only = float_only(ctx) || drag.undock; - let floatable = self.permissions(&drag.panel).floatable - && (float_only || gone || !drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); + let outside = gone || !ctx.content_rect().contains(pointer); + let empty_drop = self.style.float_on_empty_drop + && (!drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); + let floatable = self.permissions(&drag.panel).floatable && (float_only || outside || empty_drop); let floating_rect = floatable.then(|| self.tab_float_rect(&drag, pointer)); if self.host_drop(ctx, &drag.panel, pointer, false, released, floating_rect) { if released { @@ -255,7 +264,7 @@ impl Renderer<'_, P> { } return; } - let dock = if float_only || gone { None } else { self.dock_tab_proposal(&drag.panel, pointer) }; + let dock = if float_only || outside { None } else { self.dock_tab_proposal(&drag.panel, pointer) }; if let Some((action, line)) = dock { if released { cancel_drag::

(ctx, self.id); @@ -282,10 +291,10 @@ impl Renderer<'_, P> { }; if released { cancel_drag::

(ctx, self.id); - if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !gone) { + if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !outside) { return; } - let action = if let Some(proposal) = proposal.filter(|_| !gone) { + let action = if let Some(proposal) = proposal.filter(|_| !outside) { Some(Action::Move { panel: drag.panel.clone(), anchor: proposal.anchor, placement: proposal.placement }) } else if let Some(rect) = floating_rect { Some(Action::Float { panel: drag.panel.clone(), rect: [rect.left(), rect.top(), rect.width(), rect.height()] }) diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 89a94dc94f..3354d9f03c 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -149,12 +149,12 @@ fn a_group_is_a_picture_frame_whose_edges_split_it_in_half_and_whose_middle_join let mut d = film(); let out = d.drag(tab(&d, INFO), pos2(timeline.center().x, timeline.top() + 10.0)); assert!(matches!(&out.actions[..], [Action::Move { panel: INFO, placement: Placement::Tab { .. }, .. }]), "{:?}", out.actions); - // The gap between two groups belongs to neither: the tab floats. + // The gap between two groups belongs to neither: the drag cancels. let mut d = film(); let tools = group(&d, TOOLS); let gap = pos2(tools.right() + 2.0, tools.center().y); let out = d.drag(tab(&d, INFO), gap); - assert!(matches!(&out.actions[..], [Action::Float { panel: INFO, .. }]), "{:?}", out.actions); + assert!(out.actions.is_empty(), "{:?}", out.actions); } #[test] @@ -443,3 +443,66 @@ fn ctrl_or_cmd_floats_from_a_tab_or_a_drag_bar_and_the_preview_says_so() { assert!(floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); } } + +/// The Editing workspace under a 24 pt menu bar and above a 20 pt status bar. +fn film_in_window() -> Driver { + let mut d = DockDriver::new(editing(), Film::default()).with_style(frame_style); + d.screen = Rect::from_min_size(Pos2::ZERO, SCREEN); + d.area = Rect::from_min_max(pos2(0.0, 24.0), pos2(SCREEN.x, SCREEN.y - 20.0)); + d.settle(); + d +} + +#[test] +fn a_release_over_no_target_inside_the_window_cancels_the_drag() { + let d = film_in_window(); + let (source, program) = (group(&d, SOURCE[0]), group(&d, PROGRAM)); + let gap = pos2((source.right() + program.left()) * 0.5, source.center().y); + let from_tab = tab(&d, PROJECT[0]); + let from_bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); + for from in [from_tab, from_bar] { + for to in [pos2(600.0, 10.0), pos2(600.0, SCREEN.y - 8.0), gap] { + let mut d = film_in_window(); + let before = d.layout.clone(); + let out = d.drag(from, to); + d.settle(); + assert!(out.actions.is_empty(), "{from:?} to {to:?}: {:?}", out.actions); + assert_eq!(d.layout, before, "{from:?} to {to:?}"); + } + // Ctrl/Cmd held floats it there. + let mut d = film_in_window(); + d.modifiers = Modifiers::COMMAND; + d.drag(from, pos2(600.0, 10.0)); + d.settle(); + assert!(d.layout.floating.iter().any(|w| w.contains(&PROJECT[0])), "{from:?}: {:?}", d.layout.floating); + } +} + +#[test] +fn a_release_outside_the_window_floats() { + let d = film_in_window(); + let from_tab = tab(&d, PROJECT[0]); + let from_bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); + for from in [from_tab, from_bar] { + let mut d = film_in_window(); + d.hold(from, pos2(600.0, 10.0)); + d.leave(); + d.settle(); + let window = d.layout.floating.iter().find(|w| w.contains(&PROJECT[0])); + assert!(window.is_some(), "{from:?}: {:?}", d.layout); + // A tab takes one panel; a drag bar takes the group. + assert_eq!(window.unwrap().contains(&PROJECT[1]), from == from_bar, "{from:?}"); + } +} + +#[test] +fn the_title_bar_moves_a_floating_window_without_docking() { + let mut d = film(); + let title = d.hit(&Hit::Title(INFO)).unwrap().center(); + let timeline = group(&d, TIMELINE); + d.drag(title, timeline.center()); + d.settle(); + let window = d.layout.floating.iter().find(|w| w.contains(&INFO)).expect("still floating"); + assert!(window.rect[0] < 1000.0 && window.rect[1] > 400.0, "moved towards the drop: {:?}", window.rect); + assert_eq!(d.layout.root, editing().root); +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index e4a82b3449..1595ef3e5f 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -101,6 +101,13 @@ pub struct DockStyle { /// Ctrl/Cmd held when a tab drag of a split-tree group starts makes its drop float, even /// when the key is let go during the drag. Off: only the key held at the drop counts. pub command_press_floats: bool, + /// A drag released over no drop target inside the window floats what it carries, such as + /// a panel dropped on a protected canvas. Off: that release cancels the drag; only + /// Ctrl/Cmd or a release outside the window floats. + pub float_on_empty_drop: bool, + /// Dragging a floating window's title bar onto a drop target docks the whole window there. + /// Off: the title bar only moves the window; tabs and drag bars dock. + pub title_bar_docks: bool, /// Show the built-in Close items in tab and group menus (Close Panel, Close Tab Group, /// Close Other Panels in Group) for closable panels. A host that draws its own Close items /// turns this off and keeps [`Permissions::closable`], so its close actions still apply. @@ -183,6 +190,8 @@ impl DockStyle { float_hint_label: "Hold {key} to undock".into(), float_hint: false, command_press_floats: false, + float_on_empty_drop: true, + title_bar_docks: true, close_menu_items: true, close_button: true, wheel_selects_tabs: false, diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 51cfd297ae..f92d1aa958 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -17,7 +17,7 @@ outside the crate. | Arrangement | Layout | Style settings | Apps | |---|---|---|---| | Docks beside a canvas (the defaults) | `Node::Dock`s on the window's start and end edges. A dock has columns; a column has stacked groups and can collapse to icons. Frames (tab groups and splits) fill the space between the docks. | `new_dock_zones` on | Creative apps with a canvas and panel docks | -| A split tree of tab groups | `Split`s and `Tabs` only. | `side_edge_zones`, `maximize_item`, `close_others_item`, `command_press_floats`, `float_hint`, `wheel_selects_tabs`, `middle_click_closes_tabs` on, `new_dock_zones` off; menu labels such as "Undock Panel" set on `float_label`, `float_group_label` and `close_group_label` | Apps whose whole window is frames | +| A split tree of tab groups | `Split`s and `Tabs` only. | `side_edge_zones`, `maximize_item`, `close_others_item`, `command_press_floats`, `float_hint`, `wheel_selects_tabs`, `middle_click_closes_tabs` on, `new_dock_zones`, `float_on_empty_drop` and `title_bar_docks` off; menu labels such as "Undock Panel" set on `float_label`, `float_group_label` and `close_group_label` | Apps whose whole window is frames | Sides are logical: `Side::Start` is the left edge, or the right edge when `DockStyle::right_to_left` is set. egui has no app-wide direction, so the app sets it from its @@ -185,7 +185,9 @@ A flyout fits its content the same way, without the title bar. ## Gestures - A tab drags one panel. A group's drag bar (the space beside its tabs) or its top border drags - the whole group. A column bar drags a column. A floating window's title bar drags the window. + the whole group. A column bar drags a column. A floating window's title bar drags the window; + with `title_bar_docks` a release over a target docks the whole window there, else it only + moves. - A movable floating window resizes from every edge and corner. The top edge and corners are a 4 pt band above the title bar (`chrome::RESIZE_BAND`), so they take no moves and no clicks on the title bar's buttons. A resize keeps the opposite edges in place and stays within the size @@ -207,6 +209,10 @@ A flyout fits its content the same way, without the title bar. joins. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, a filled half for a split. Escape or losing window focus cancels a drag. +- With `float_on_empty_drop`, a release over no target floats what moves at the pointer, such + as a panel dropped on a protected canvas. Without it, that release cancels the drag and + nothing moves: the gap between two groups, a menu bar or a status bar is no target. A release + outside the app window floats in both cases. - Ctrl (⌘ on macOS) held at the drop floats it wherever it lands. With `command_press_floats`, the key held when a tab drag of a frame starts is enough. With `float_hint`, a hint under the pointer names the modifier while a drag offers a docking target: `float_hint_label`, where From 809bf909365fb213a06706531b4548418a452ad1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 20:19:09 +0000 Subject: [PATCH 84/94] docking: a floating window holds a tree like the docked layout Floating::root replaces the stack of groups. A floating window takes splits in any direction, tab groups and accordions; its groups split, join and resize like frames, with the Sizer, four-way handles (Divider::WindowSplit, Divider::WindowIntersection, Action::ResizeWindowSplit) and the room check. Tabs and drag bars inside it show the targets of every window and dock; Undock Panel Group floats one group of a window that has several. Floating::minimized replaces per-group minimizing in a window. Saved layouts keep loading: a stored stack of groups becomes a vertical split sized by the groups' heights. Placement::Group on a floating anchor splits its group above or below. A window moved onto a dock keeps its groups as stacked groups. --- crates/ui/src/docking/command.rs | 7 +- crates/ui/src/docking/command_tests.rs | 5 +- crates/ui/src/docking/dock_model.rs | 352 ++++++++++++++++------- crates/ui/src/docking/dock_tests.rs | 2 +- crates/ui/src/docking/floating_tests.rs | 86 ++++-- crates/ui/src/docking/group_tests.rs | 18 +- crates/ui/src/docking/hits.rs | 34 ++- crates/ui/src/docking/iconic_tests.rs | 3 +- crates/ui/src/docking/model.rs | 313 ++++++++++++-------- crates/ui/src/docking/model_tests.rs | 58 ++-- crates/ui/src/docking/render/dock.rs | 4 +- crates/ui/src/docking/render/floating.rs | 247 +++++----------- crates/ui/src/docking/render/frame.rs | 40 +-- crates/ui/src/docking/render/group.rs | 13 +- crates/ui/src/docking/render/mod.rs | 34 ++- crates/ui/src/docking/render/native.rs | 8 +- crates/ui/src/docking/render/preview.rs | 11 +- crates/ui/src/docking/split_tests.rs | 104 +++++++ crates/ui/src/docking/surface.rs | 1 + crates/ui/src/docking/tests.rs | 28 +- crates/ui/src/docking/trial_tests.rs | 8 +- docs/ui-docking.md | 26 +- 22 files changed, 884 insertions(+), 518 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 2dd7f67a82..132d8539a7 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -369,7 +369,7 @@ impl DockCommand

{ let any = given.iter().any(Option::is_some); let unit = Unit::of(*group, *column); let lone = layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1); - let whole = layout.floating.iter().any(|w| w.contains(panel) && w.groups.len() == 1); + let whole = layout.floating.iter().any(|w| w.contains(panel) && matches!(w.root, super::Node::Tabs { .. } | super::Node::Stack { .. })); // The rect a drag would float the unit at, inside the area. let placed = || { let docked = layout.location(panel).ok().and_then(|l| l.group).and_then(|g| g.column).map(|c| c.width); @@ -450,6 +450,7 @@ impl DockCommand

{ Some(super::Node::Stack { entries }) => entries.iter().any(|e| &e.panel == panel && !e.open), _ => false, }, + Place::Floating { window, .. } => layout.floating.get(*window).is_some_and(|w| w.minimized), place => layout.group(place).is_some_and(|g| g.minimized), }; one(Action::SetMinimized { panel: panel.clone(), minimized: minimized.unwrap_or(!current) }) @@ -563,14 +564,14 @@ fn last_column(layout: &Layout

, side: Side) -> Option(layout: &Layout

, panel: &P) -> Option { - layout.place(panel).and_then(|place| layout.group(&place)).map(|g| g.panels.len()) + layout.members(panel, super::dock_model::Unit::Group).ok().map(|members| members.len()) } /// The panels that move with `panel`. fn members(layout: &Layout

, panel: &P, unit: Unit) -> Vec

{ match unit { Unit::Panel => vec![panel.clone()], - Unit::Group => layout.place(panel).and_then(|place| layout.group(&place)).map(|g| g.panels.clone()).unwrap_or_default(), + Unit::Group => layout.members(panel, super::dock_model::Unit::Group).unwrap_or_default(), Unit::Column => match layout.place(panel) { Some(Place::Dock { path, column, .. }) => match layout.root.as_ref().and_then(|root| super::dock_model::node_at(root, &path)) { Some(super::Node::Dock { columns, .. }) => { diff --git a/crates/ui/src/docking/command_tests.rs b/crates/ui/src/docking/command_tests.rs index 9397e62aa4..913cb35daa 100644 --- a/crates/ui/src/docking/command_tests.rs +++ b/crates/ui/src/docking/command_tests.rs @@ -306,8 +306,9 @@ fn side_zones_map_to_the_placement_the_anchor_container_takes_in_either_directio assert_eq!(placed("right", "layers", true), Ok(Placement::Column { after: false })); assert_eq!(placed("left", "layers", true), Ok(Placement::Column { after: true })); assert_eq!(placed("top", "layers", false), Ok(Placement::Group { below: false, height: None })); - assert_eq!(placed("bottom", "color", false), Ok(Placement::Group { below: true, height: None })); - assert_eq!(placed("left", "color", false), Err(DockError::InvalidPlacement)); + // A floating window is a tree like the docked layout's. + assert_eq!(placed("bottom", "color", false), Ok(Placement::Split(Zone::Bottom))); + assert_eq!(placed("left", "color", false), Ok(Placement::Split(Zone::Left))); assert_eq!(placed("left", "canvas", true), Ok(Placement::Split(Zone::Left))); let (workspace, _) = applied(json!({"command": "window.panel.move", "panel": "history", "anchor": "layers", "zone": "right"})); diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index a42bb56fc8..9226bb4f4b 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -1,4 +1,4 @@ -//! Docks, columns, groups and floating stacks: their types and the structural edits behind +//! Docks, columns, groups and floating windows: their types and the structural edits behind //! group, column and window moves. //! //! A group, column or floating window is named by a panel it contains. Edits run on a proposed @@ -6,7 +6,7 @@ use std::{collections::HashMap, hash::Hash}; -use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, Node, Placement, Zone, valid_height, valid_rect, valid_width}; +use super::model::{DockError, Floating, Layout, MAX_DEPTH, MAX_NODES, MAX_PANELS, Node, Placement, Zone, valid_height, valid_rect, valid_width}; use crate::layout::{SplitAxis, SplitSize}; /// Width of a new column when nothing better is known. @@ -25,7 +25,7 @@ pub enum Side { End, } -/// Tabs that move, minimize and size together, in a dock column or a floating stack. +/// Tabs that move, minimize and size together in a dock column. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(bound(deserialize = "P: serde::Deserialize<'de>")))] @@ -92,9 +92,8 @@ impl Placement

{ /// /// | Anchor in | `Center` | `Top`, `Bottom` | `Left`, `Right` | /// |---|---|---|---| - /// | the split tree | [`Placement::Split`] | `Split` | `Split` | + /// | the split tree or a floating window | [`Placement::Split`] | `Split` | `Split` | /// | a dock column | `Split(Center)` (join as tabs) | [`Placement::Group`] above or below | [`Placement::Column`] on that side | - /// | a floating window | `Split(Center)` | `Group` above or below | [`DockError::InvalidPlacement`] | /// /// A dock's `Column { after }` counts from its window edge, which depends on the dock's /// side and `right_to_left` (see [`Side`]); this picks `after` so the new column lands on @@ -102,9 +101,8 @@ impl Placement

{ pub fn for_zone(layout: &Layout

, anchor: &P, zone: Zone, right_to_left: bool) -> Result { let place = layout.place(anchor).ok_or(DockError::MissingTarget)?; Ok(match (place, zone) { - (Place::Node(_), zone) | (_, zone @ Zone::Center) => Placement::Split(zone), - (Place::Dock { .. } | Place::Floating { .. }, Zone::Top | Zone::Bottom) => Placement::Group { below: zone == Zone::Bottom, height: None }, - (Place::Floating { .. }, _) => return Err(DockError::InvalidPlacement), + (Place::Node(_) | Place::Floating { .. }, zone) | (_, zone @ Zone::Center) => Placement::Split(zone), + (Place::Dock { .. }, Zone::Top | Zone::Bottom) => Placement::Group { below: zone == Zone::Bottom, height: None }, (Place::Dock { path, .. }, _) => { let side = match layout.root.as_ref().and_then(|root| node_at(root, &path)) { Some(Node::Dock { side, .. }) => *side, @@ -128,7 +126,7 @@ pub enum PanelState { Front, } -/// The group a closed panel was in, when that group was in a dock or a floating stack. +/// The group a closed panel was in, when that group was in a dock. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct GroupLocation { @@ -157,12 +155,25 @@ pub(super) enum Place { column: usize, group: usize, }, + /// A `Tabs` or `Stack` node of a floating window's tree. Floating { window: usize, - group: usize, + path: Vec, }, } +impl Place { + /// The tree (`None` for the docked layout, else a floating window) and the path of a + /// `Tabs` or `Stack` node. + pub(super) fn tree_path(&self) -> Option<(Option, &[bool])> { + match self { + Place::Node(path) => Some((None, path)), + Place::Floating { window, path } => Some((Some(*window), path)), + Place::Dock { .. } => None, + } + } +} + /// Which container a whole-container action names. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Unit { @@ -174,6 +185,10 @@ pub(super) enum Unit { /// Groups in transit, with the size and state of the container they came from. pub(super) struct Moving

{ pub groups: Vec>, + /// A floating window's whole tree, whose leaves are `groups`. A split or a new window + /// takes the tree; docks take the groups. + pub node: Option>, + pub minimized: bool, pub width: Option, pub iconic: bool, pub iconic_width: Option, @@ -183,7 +198,7 @@ pub(super) struct Moving

{ impl

Moving

{ pub fn group(group: Group

) -> Self { - Self { groups: vec![group], width: None, iconic: false, iconic_width: None, rect: None, native: None } + Self { groups: vec![group], node: None, minimized: false, width: None, iconic: false, iconic_width: None, rect: None, native: None } } fn into_column(self, width: f32) -> Column

{ @@ -207,6 +222,93 @@ pub(super) fn node_at_mut<'a, P>(mut node: &'a mut Node

, path: &[bool]) -> Op Some(node) } +/// Every `Tabs`, `Stack` and `Dock` node of a tree with its path, first to last. Stops at +/// [`MAX_NODES`] for an invalid tree. +pub(super) fn leaves

(root: &Node

) -> Vec<(&Node

, Vec)> { + let mut out = Vec::new(); + let mut visit = vec![(root, Vec::new())]; + let mut visited = 0usize; + while let Some((node, path)) = visit.pop() { + visited = visited.saturating_add(1); + if visited > MAX_NODES { + break; + } + match node { + Node::Split { first, second, .. } => { + let mut second_path = path.clone(); + second_path.push(true); + let mut first_path = path; + first_path.push(false); + visit.push((second, second_path)); + visit.push((first, first_path)); + } + leaf => out.push((leaf, path)), + } + } + out +} + +/// The panels of a tree in order, without recursion; at most [`MAX_PANELS`]. +pub(super) fn tree_panels

(root: &Node

) -> Vec<&P> { + let mut panels = Vec::new(); + for (leaf, _) in leaves(root) { + let room = MAX_PANELS.saturating_sub(panels.len()); + match leaf { + Node::Tabs { panels: group, .. } => panels.extend(group.iter().take(room)), + Node::Stack { entries } => panels.extend(entries.iter().map(|e| &e.panel).take(room)), + Node::Dock { columns, .. } => panels.extend(columns.iter().flat_map(|c| &c.groups).flat_map(|g| &g.panels).take(room)), + Node::Split { .. } => {} + } + } + panels +} + +/// The shown panel of a tree's first group. +pub(super) fn first_active

(root: &Node

) -> Option<&P> { + match leaves(root).into_iter().next()?.0 { + Node::Tabs { panels, active } => panels.get(*active), + Node::Stack { entries } => entries.first().map(|e| &e.panel), + Node::Split { .. } | Node::Dock { .. } => None, + } +} + +/// The groups of a tree, first to last: what a dock column takes from a floating window. +pub(super) fn tree_groups(root: &Node

) -> Vec> { + let mut groups = Vec::new(); + for (leaf, _) in leaves(root) { + match leaf { + Node::Tabs { panels, active } => groups.push(Group::new(panels.clone(), *active)), + Node::Stack { entries } => groups.push(Group::new(entries.iter().map(|e| e.panel.clone()).collect(), 0)), + Node::Dock { columns, .. } => groups.extend(columns.iter().flat_map(|c| c.groups.iter().cloned())), + Node::Split { .. } => {} + } + } + groups +} + +/// Groups stacked top to bottom as a tree: each group over a vertical split of the ones below +/// it, sized by their heights, with an equal share where a group has none. +pub(super) fn stack_tree

(groups: Vec>) -> Option> { + let height = |g: &Group

| g.height.filter(|h| h.is_finite() && *h > 0.0); + let known: Vec = groups.iter().filter_map(height).collect(); + let share = if known.is_empty() { 1.0 } else { known.iter().sum::() / known.len() as f32 }; + let weights: Vec = groups.iter().map(|g| height(g).unwrap_or(share)).collect(); + let mut node = None; + let mut below = 0.0; + for (group, weight) in groups.into_iter().zip(weights).rev() { + let tabs = Node::Tabs { panels: group.panels, active: group.active }; + node = Some(match node { + None => tabs, + Some(rest) => { + let ratio = (weight / (weight + below)).clamp(0.0, 1.0); + Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(ratio), first: Box::new(tabs), second: Box::new(rest) } + } + }); + below += weight; + } + node +} + /// Put `new` on the `zone` side of the frame at `path`: the frame splits into two halves and /// every other frame keeps its size. pub(super) fn split_frame

(root: &mut Node

, path: &[bool], new: Node

, zone: Zone) -> bool { @@ -230,28 +332,14 @@ fn splice

(panels: &mut Vec

, active: &mut usize, index: usize, new: Vec

, impl Layout

{ pub(super) fn place(&self, panel: &P) -> Option { for (w, window) in self.floating.iter().enumerate() { - if let Some(g) = window.groups.iter().position(|group| group.panels.contains(panel)) { - return Some(Place::Floating { window: w, group: g }); + for (leaf, path) in leaves(&window.root) { + if leaf_holds(leaf, panel) { + return Some(Place::Floating { window: w, path }); + } } } - let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); - let mut visited = 0usize; - while let Some((node, path)) = visit.pop() { - visited = visited.saturating_add(1); - if visited > MAX_NODES { - return None; - } - match node { - Node::Split { first, second, .. } => { - let mut second_path = path.clone(); - second_path.push(true); - let mut first_path = path; - first_path.push(false); - visit.push((second, second_path)); - visit.push((first, first_path)); - } - Node::Tabs { panels, .. } if panels.contains(panel) => return Some(Place::Node(path)), - Node::Stack { entries } if entries.iter().any(|e| &e.panel == panel) => return Some(Place::Node(path)), + for (leaf, path) in self.root.as_ref().map(leaves).unwrap_or_default() { + match leaf { Node::Dock { columns, .. } => { for (c, column) in columns.iter().enumerate() { if let Some(g) = column.groups.iter().position(|group| group.panels.contains(panel)) { @@ -259,7 +347,8 @@ impl Layout

{ } } } - Node::Tabs { .. } | Node::Stack { .. } => {} + leaf if leaf_holds(leaf, panel) => return Some(Place::Node(path)), + _ => {} } } None @@ -268,54 +357,74 @@ impl Layout

{ /// [`Self::place`] of every panel, from one traversal: the renderer looks up many panels a /// frame. pub(super) fn places(&self) -> HashMap { - let mut places = HashMap::new(); - for (w, window) in self.floating.iter().enumerate() { - for (g, group) in window.groups.iter().enumerate() { - for panel in &group.panels { - places.entry(panel.clone()).or_insert(Place::Floating { window: w, group: g }); - } - } - } - let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); - let mut visited = 0usize; - while let Some((node, path)) = visit.pop() { - visited = visited.saturating_add(1); - if visited > MAX_NODES { - break; - } - match node { - Node::Split { first, second, .. } => { - let mut second_path = path.clone(); - second_path.push(true); - let mut first_path = path; - first_path.push(false); - visit.push((second, second_path)); - visit.push((first, first_path)); - } + fn note(places: &mut HashMap, leaf: &Node

, place: &dyn Fn() -> Place) { + match leaf { Node::Tabs { panels, .. } => { for panel in panels { - places.entry(panel.clone()).or_insert_with(|| Place::Node(path.clone())); + places.entry(panel.clone()).or_insert_with(place); } } Node::Stack { entries } => { for entry in entries { - places.entry(entry.panel.clone()).or_insert_with(|| Place::Node(path.clone())); + places.entry(entry.panel.clone()).or_insert_with(place); } } - Node::Dock { columns, .. } => { - for (c, column) in columns.iter().enumerate() { - for (g, group) in column.groups.iter().enumerate() { - for panel in &group.panels { - places.entry(panel.clone()).or_insert_with(|| Place::Dock { path: path.clone(), column: c, group: g }); - } + _ => {} + } + } + let mut places = HashMap::new(); + for (w, window) in self.floating.iter().enumerate() { + for (leaf, path) in leaves(&window.root) { + note(&mut places, leaf, &|| Place::Floating { window: w, path: path.clone() }); + } + } + for (leaf, path) in self.root.as_ref().map(leaves).unwrap_or_default() { + if let Node::Dock { columns, .. } = leaf { + for (c, column) in columns.iter().enumerate() { + for (g, group) in column.groups.iter().enumerate() { + for panel in &group.panels { + places.entry(panel.clone()).or_insert_with(|| Place::Dock { path: path.clone(), column: c, group: g }); } } } + } else { + note(&mut places, leaf, &|| Place::Node(path.clone())); } } places } + /// The docked layout (`None`) or a floating window's tree. + pub(super) fn tree(&self, window: Option) -> Option<&Node

> { + match window { + None => self.root.as_ref(), + Some(window) => self.floating.get(window).map(|w| &w.root), + } + } + + pub(super) fn tree_mut(&mut self, window: Option) -> Option<&mut Node

> { + match window { + None => self.root.as_mut(), + Some(window) => self.floating.get_mut(window).map(|w| &mut w.root), + } + } + + /// The docked layout's tree, then each floating window's. + pub(super) fn trees_mut(&mut self) -> impl Iterator> { + self.root.iter_mut().chain(self.floating.iter_mut().map(|w| &mut w.root)) + } + + /// The `Tabs` or `Stack` node at a tree place. + pub(super) fn node_of(&self, place: &Place) -> Option<&Node

> { + let (window, path) = place.tree_path()?; + node_at(self.tree(window)?, path) + } + + fn node_of_mut(&mut self, place: &Place) -> Option<&mut Node

> { + let (window, path) = place.tree_path()?; + node_at_mut(self.tree_mut(window)?, path) + } + pub(super) fn dock_path(&self, side: Side) -> Option> { let mut visit: Vec<(&Node

, Vec)> = self.root.iter().map(|node| (node, Vec::new())).collect(); let mut visited = 0usize; @@ -379,27 +488,37 @@ impl Layout

{ self.columns_mut(path)?.get_mut(*column) } - /// The dock or floating group at `place`; `None` for a `Tabs` or `Stack` node. + /// The dock group at `place`; `None` for a `Tabs` or `Stack` node. pub(super) fn group(&self, place: &Place) -> Option<&Group

> { match place { - Place::Node(_) => None, Place::Dock { group, .. } => self.column(place)?.groups.get(*group), - Place::Floating { window, group } => self.floating.get(*window)?.groups.get(*group), + Place::Node(_) | Place::Floating { .. } => None, } } pub(super) fn group_mut(&mut self, place: &Place) -> Option<&mut Group

> { match place { - Place::Node(_) => None, Place::Dock { group, .. } => self.column_mut(place)?.groups.get_mut(*group), - Place::Floating { window, group } => self.floating.get_mut(*window)?.groups.get_mut(*group), + Place::Node(_) | Place::Floating { .. } => None, } } - /// Remove the node at `path`; its parent split collapses into the sibling. + /// Remove the node at `path` of the docked layout; its parent split collapses into the + /// sibling. pub(super) fn take_node(&mut self, path: &[bool]) -> Option> { - let Some((second_child, parent_path)) = path.split_last() else { return self.root.take() }; - let parent = self.root.as_mut().and_then(|root| node_at_mut(root, parent_path))?; + self.take_node_in(None, path) + } + + /// [`Self::take_node`] in the docked layout (`None`) or a floating window, which closes + /// when its root goes. + fn take_node_in(&mut self, window: Option, path: &[bool]) -> Option> { + let Some((second_child, parent_path)) = path.split_last() else { + return match window { + None => self.root.take(), + Some(window) => (window < self.floating.len()).then(|| self.floating.remove(window).root), + }; + }; + let parent = self.tree_mut(window).and_then(|root| node_at_mut(root, parent_path))?; if !matches!(parent, Node::Split { .. }) { return None; } @@ -421,7 +540,7 @@ impl Layout

{ pub(super) fn members(&self, panel: &P, unit: Unit) -> Result, DockError> { let place = self.place(panel).ok_or(DockError::MissingPanel)?; match (unit, &place) { - (Unit::Group, Place::Node(path)) => match self.root.as_ref().and_then(|root| node_at(root, path)) { + (Unit::Group, Place::Node(_) | Place::Floating { .. }) => match self.node_of(&place) { Some(Node::Tabs { panels, .. }) => Ok(panels.clone()), Some(Node::Stack { .. }) => Ok(vec![panel.clone()]), _ => Err(DockError::MissingPanel), @@ -450,20 +569,32 @@ impl Layout

{ fn take_group(&mut self, panel: &P) -> Result, DockError> { let place = self.place(panel).ok_or(DockError::MissingPanel)?; match place { - Place::Node(path) => { - if let Some(Node::Stack { entries }) = self.root.as_mut().and_then(|root| node_at_mut(root, &path)) + Place::Node(_) | Place::Floating { .. } => { + let (window, path) = place.tree_path().map(|(w, p)| (w, p.to_vec())).ok_or(DockError::MissingPanel)?; + // A group leaving a floating window keeps its width; the window's only group + // takes the window's rect along. + let source = window.and_then(|w| self.floating.get(w)).map(|w| (w.rect, w.native, w.minimized)); + let whole = |moving: Moving

| match source { + Some((rect, native, minimized)) if path.is_empty() => { + Moving { width: rect.get(2).copied(), rect: Some(rect), native, minimized, ..moving } + } + Some((rect, ..)) => Moving { width: rect.get(2).copied(), ..moving }, + None => moving, + }; + if let Some(Node::Stack { entries }) = self.node_of_mut(&place) && entries.len() > 1 && let Some(index) = entries.iter().position(|e| &e.panel == panel) { let entry = entries.remove(index); let group = Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height }; - return Ok(Moving::group(group)); + let moving = whole(Moving::group(group)); + return Ok(Moving { rect: None, native: None, ..moving }); } - match self.take_node(&path) { - Some(Node::Tabs { panels, active }) => Ok(Moving::group(Group::new(panels, active))), + match self.take_node_in(window, &path) { + Some(Node::Tabs { panels, active }) => Ok(whole(Moving::group(Group::new(panels, active)))), Some(Node::Stack { mut entries }) if entries.len() == 1 => { let entry = entries.remove(0); - Ok(Moving::group(Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height })) + Ok(whole(Moving::group(Group { panels: vec![entry.panel], active: 0, minimized: !entry.open, height: entry.height }))) } _ => Err(DockError::MissingPanel), } @@ -484,21 +615,6 @@ impl Layout

{ } Ok(Moving { width: Some(width), ..Moving::group(taken) }) } - Place::Floating { window, group } => { - let source = self.floating.get_mut(window).ok_or(DockError::MissingPanel)?; - if group >= source.groups.len() { - return Err(DockError::MissingPanel); - } - let taken = source.groups.remove(group); - let rect = source.rect; - let native = source.native; - let whole = source.groups.is_empty(); - if whole { - self.floating.remove(window); - } - let width = rect.get(2).copied(); - Ok(Moving { width, rect: whole.then_some(rect), native: native.filter(|_| whole), ..Moving::group(taken) }) - } } } @@ -514,6 +630,8 @@ impl Layout

{ } Ok(Moving { groups: taken.groups, + node: None, + minimized: false, width: Some(taken.width), iconic: taken.iconic, iconic_width: taken.iconic_width, @@ -529,7 +647,9 @@ impl Layout

{ } let taken = self.floating.remove(window); Ok(Moving { - groups: taken.groups, + groups: tree_groups(&taken.root), + node: Some(taken.root), + minimized: taken.minimized, width: taken.rect.get(2).copied(), iconic: false, iconic_width: None, @@ -553,7 +673,11 @@ impl Layout

{ if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } - self.floating.push(Floating { groups: moving.groups, rect, native }); + let root = match moving.node { + Some(node) => node, + None => stack_tree(moving.groups).ok_or(DockError::MissingPanel)?, + }; + self.floating.push(Floating { root, rect, native, minimized: moving.minimized }); Ok(()) } Target::NewDock { side } => { @@ -589,10 +713,21 @@ impl Layout

{ self.merge(&place, index, moving) } Placement::Split(zone) => { - let Place::Node(path) = place else { return Err(DockError::InvalidPlacement) }; - let (panels, active) = flatten(moving.groups); - let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; - if split_frame(root, &path, Node::Tabs { panels, active }, zone) { Ok(()) } else { Err(DockError::MissingTarget) } + let (window, path) = place.tree_path().ok_or(DockError::InvalidPlacement)?; + let new = match moving.node { + Some(node) => node, + None => { + let (panels, active) = flatten(moving.groups); + Node::Tabs { panels, active } + } + }; + let root = self.tree_mut(window).ok_or(DockError::MissingTarget)?; + if split_frame(root, path, new, zone) { Ok(()) } else { Err(DockError::MissingTarget) } + } + // A floating window is a tree: a group above or below splits the anchor's group. + Placement::Group { below, .. } if matches!(place, Place::Floating { .. }) => { + let zone = if below { Zone::Bottom } else { Zone::Top }; + self.insert_moving(moving, Target::At { anchor, placement: Placement::Split(zone) }) } Placement::Group { below, height } => { if !valid_height(height) { @@ -604,10 +739,7 @@ impl Layout

{ } let (groups, index) = match &place { Place::Dock { group, .. } => (&mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups, *group), - Place::Floating { window, group } => { - (&mut self.floating.get_mut(*window).ok_or(DockError::MissingTarget)?.groups, *group) - } - Place::Node(_) => return Err(DockError::InvalidPlacement), + Place::Node(_) | Place::Floating { .. } => return Err(DockError::InvalidPlacement), }; let index = (index + usize::from(below)).min(groups.len()); groups.splice(index..index, moving.groups); @@ -662,7 +794,7 @@ impl Layout

{ fn index_in(&self, place: &Place, panel: &P) -> Option { match place { - Place::Node(path) => match self.root.as_ref().and_then(|root| node_at(root, path))? { + Place::Node(_) | Place::Floating { .. } => match self.node_of(place)? { Node::Tabs { panels, .. } => panels.iter().position(|p| p == panel), Node::Stack { entries } => entries.iter().position(|e| &e.panel == panel), _ => None, @@ -676,7 +808,7 @@ impl Layout

{ fn merge(&mut self, place: &Place, index: Option, moving: Moving

) -> Result<(), DockError> { let (panels, selected) = flatten(moving.groups); match place { - Place::Node(path) => match self.root.as_mut().and_then(|root| node_at_mut(root, path)) { + Place::Node(_) | Place::Floating { .. } => match self.node_of_mut(place) { Some(Node::Tabs { panels: target, active }) => { splice(target, active, index.unwrap_or(target.len()), panels, selected); Ok(()) @@ -698,6 +830,14 @@ impl Layout

{ } } +fn leaf_holds(leaf: &Node

, panel: &P) -> bool { + match leaf { + Node::Tabs { panels, .. } => panels.contains(panel), + Node::Stack { entries } => entries.iter().any(|e| &e.panel == panel), + Node::Split { .. } | Node::Dock { .. } => false, + } +} + /// All panels in order, and the index of the first group's active panel among them. fn flatten

(groups: Vec>) -> (Vec

, usize) { let selected = groups.first().map_or(0, |g| g.active.min(g.panels.len().saturating_sub(1))); diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 87e1c4a0bc..654b637f5d 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -360,7 +360,7 @@ fn column_bar_drag_moves_the_column_and_away_from_a_dock_floats_its_groups() { let out = d.step(vec![button(pos2(560.0, 300.0), false)]); assert!(matches!(moved(&out.actions), Some((2, Target::Float { .. }))), "{:?}", out.actions); assert_eq!(columns(&d.layout, Side::Start), vec![vec![vec![5]]]); - assert_eq!(d.layout.floating[0].groups, vec![group(&[2]), group(&[3])]); + assert_eq!(d.layout.floating[0].groups(), vec![group(&[2]), group(&[3])]); } #[test] diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 021b85708f..824809483c 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -38,7 +38,7 @@ fn workspace() -> Layout { second: Box::new(tabs(&[0], 0)), }), floating: vec![ - Floating { groups: vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], rect: [300.0, 80.0, 240.0, 300.0], native: None }, + Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [300.0, 80.0, 240.0, 300.0]), Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0]), ], } @@ -213,7 +213,7 @@ fn window_of(layout: &Layout, panel: u32) -> Option<&Floating> { } fn groups_of(window: &Floating) -> Vec> { - window.groups.iter().map(|g| g.panels.clone()).collect() + window.groups().iter().map(|g| g.panels.clone()).collect() } #[test] @@ -228,16 +228,16 @@ fn title_bar_drag_moves_every_stacked_group_and_drops_into_a_dock_as_stacked_gro d.step(vec![button(title + vec2(40.0, 30.0), false)]); assert_eq!(d.layout, workspace()); - // Released over another window's lower band: its groups stack below that window's. + // Released over another window's lower band: its tree goes below that window's group, + // unless that leaves a group without room; then its panels join that group. let out = d.drag(title, pos2(660.0, 480.0)); assert!( - out.actions - .contains(&Action::MoveWindow { panel: 5, to: Target::At { anchor: 8, placement: Placement::Group { below: true, height: None } } }), + out.actions.contains(&Action::MoveWindow { panel: 5, to: Target::At { anchor: 8, placement: Placement::Split(Zone::Center) } }), "{:?}", out.actions ); assert_eq!(d.layout.floating.len(), 1); - assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![8], vec![5], vec![6, 7]]); + assert_eq!(groups_of(&d.layout.floating[0]), vec![vec![8, 5, 6, 7]]); // Released over a docked group's strip: every panel joins it as tabs. let mut d = Driver::new(workspace(), false); @@ -285,38 +285,32 @@ fn title_bar_drag_onto_dock_targets_docks_the_window() { } #[test] -fn floating_stack_seams_and_bands_insert_groups() { - // A group dragged by its bar to another window's top band stacks above that group. +fn a_floating_window_is_a_tree_whose_groups_split_and_resize_like_frames() { + // A group dragged by its bar to another window's top band splits that window's group. let mut d = Driver::new(workspace(), false); let bar = d.response(Id::new(AREA).with(("drag-bar", Some(&6u32)))).unwrap().center(); let out = d.drag(bar, pos2(660.0, 360.0)); assert!( - out.actions - .contains(&Action::MoveGroup { panel: 6, to: Target::At { anchor: 8, placement: Placement::Group { below: false, height: None } } }), + out.actions.contains(&Action::MoveGroup { panel: 6, to: Target::At { anchor: 8, placement: Placement::Split(Zone::Top) } }), "{:?}", out.actions ); assert_eq!(groups_of(window_of(&d.layout, 8).unwrap()), vec![vec![6, 7], vec![8]]); assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5]]); - // A tab dropped on the seam between two stacked groups becomes a group between them. + // The gap between two groups of a window is no target. let mut d = Driver::new(workspace(), false); let tab = d.tab(8).unwrap().center(); - let seam = pos2(420.0, 237.0); - let out = d.drag(tab, seam); - assert!( - out.actions.contains(&Action::Move { panel: 8, anchor: 5, placement: Placement::Group { below: true, height: None } }), - "{:?}", - out.actions - ); - assert_eq!(groups_of(window_of(&d.layout, 5).unwrap()), vec![vec![5], vec![8], vec![6, 7]]); + let gap = pos2(420.0, d.tab(6).unwrap().top() - 2.0); + d.drag(tab, gap); + assert_eq!(d.layout, workspace()); - // The divider between two open groups resizes both. + // The divider between them resizes both. let mut d = Driver::new(workspace(), false); - let divider = d.response(DockArea::hit_id(Id::new(AREA), &Hit::Divider(Divider::Group(5u32)))).unwrap().center(); + let divider = d.response(DockArea::hit_id(Id::new(AREA), &Hit::Divider(Divider::WindowSplit(5u32, Vec::new())))).unwrap().center(); d.drag(divider, divider + vec2(0.0, 40.0)); - let heights: Vec<_> = window_of(&d.layout, 5).unwrap().groups.iter().map(|g| g.height.unwrap()).collect(); - assert!((heights[0] - 179.5).abs() < 2.0 && (heights[1] - 99.5).abs() < 2.0, "{heights:?}"); + let Node::Split { size: SplitSize::Ratio(ratio), .. } = window_of(&d.layout, 5).unwrap().root else { panic!("{:?}", d.layout) }; + assert!(ratio > 0.6, "{ratio}"); } #[test] @@ -325,15 +319,16 @@ fn title_bar_double_click_minimizes_every_group_and_close_box_closes_the_window( let title = d.title(5).center(); d.click(title); d.click(title); - assert!(window_of(&d.layout, 5).unwrap().groups.iter().all(|g| g.minimized)); + assert!(window_of(&d.layout, 5).unwrap().minimized); d.wait(); d.click(title); d.click(title); - assert!(window_of(&d.layout, 5).unwrap().groups.iter().all(|g| !g.minimized)); + assert!(!window_of(&d.layout, 5).unwrap().minimized); let close = d.response(Id::new(AREA).with(("move-group", Some(&5u32))).with("close")).unwrap(); assert_eq!(close.center().x, 530.0, "× sits 10 pt in from the right edge"); let before = d.layout.clone(); + d.wait(); let out = d.click(close.center()); assert_eq!(out.actions, vec![Action::CloseWindow { panel: 5 }]); assert_eq!(before.closed_by(&Action::CloseWindow { panel: 5 }), Ok(vec![5, 6, 7])); @@ -677,3 +672,44 @@ fn top_edges_resize_from_the_band_above_the_title_bar() { d.step(vec![Event::Key { key: egui::Key::ArrowUp, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); assert_eq!(window_of(&d.layout, 8).unwrap().rect, [510.0, 292.0, 200.0, 208.0]); } + +#[test] +fn undock_panel_group_floats_one_group_of_a_floating_window() { + use egui_kittest::{Harness, kittest::Queryable}; + let stacked = || Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 0)], [300.0, 80.0, 300.0, 400.0])] }; + type State = (Content, Layout, Vec>); + let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, (content, layout, actions): &mut State| { + let mut style = DockStyle::from_ui(ui); + frame_style(&mut style); + let out = DockArea::new(Id::new(AREA)).show_content(ui, layout, &style, content); + actions.extend(out.actions); + }, + (Content::default(), stacked(), Vec::new()), + ); + h.run_steps(2); + let menu = |h: &mut Harness<'_, State>, panel: u32| { + let at = h.ctx.read_response(Id::new(AREA).with(("tab", &panel))).unwrap().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); + }; + menu(&mut h, 6); + h.get_by_label("Undock Panel Group").click(); + h.run_steps(2); + let actions = std::mem::take(&mut h.state_mut().2); + assert!(matches!(&actions[..], [Action::MoveGroup { panel: 6, to: Target::Float { rect: Some(_) } }]), "{actions:?}"); + let mut layout = stacked(); + layout.apply_all(actions, |_| Permissions::default()).unwrap(); + assert_eq!(layout.floating.iter().map(groups_of).collect::>(), vec![vec![vec![5]], vec![vec![6, 7]]]); + + // A window's only group has nothing to undock from. + h.state_mut().1 = layout; + h.run_steps(2); + menu(&mut h, 5); + assert_eq!(h.query_all_by_label("Undock Panel Group").count(), 0); +} diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index 9d81bb9abb..a11e279608 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -240,7 +240,7 @@ fn docked_two_tab_group_drags_by_its_bar_and_keeps_order_and_active_tab() { assert_eq!((*width, *height), (border.width(), 600.0)); assert_eq!(out.group_drop, Some((2, pos2(700.0, 200.0)))); assert_eq!(d.layout.root, Some(tabs(&[1], 0))); - assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![2, 3], 1)]); + assert_eq!(d.layout.floating[0].groups(), vec![Group::new(vec![2, 3], 1)]); // The same group in a dock column joins the group below it. let mut d = Driver::new(docked()); @@ -266,7 +266,7 @@ fn drag_bar_survives_a_strip_full_of_tabs() { assert!(d.ctx.read_response(Id::new(AREA).with(("overflow", &1u32))).is_some(), "tabs overflow before the bar narrows"); let out = d.drag(bar.center(), pos2(500.0, 300.0)); assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{:?}", out.actions); - assert_eq!(d.layout.floating[0].groups[0].panels.len(), 8); + assert_eq!(d.layout.floating[0].groups()[0].panels.len(), 8); } #[test] @@ -412,7 +412,7 @@ fn floating_window_is_opaque_with_a_transparent_host_background() { fn double_click_on_a_floating_tab_or_bar_minimizes_and_another_tab_expands() { let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; let mut d = Driver::new(layout); - let minimized = |d: &Driver| d.layout.floating[0].groups[0].minimized; + let minimized = |d: &Driver| d.layout.floating[0].minimized; let tab = d.tab(6).center(); d.click(tab); let out = d.click(tab); @@ -424,7 +424,7 @@ fn double_click_on_a_floating_tab_or_bar_minimizes_and_another_tab_expands() { let other = d.tab(5).center(); d.click(other); assert!(!minimized(&d)); - assert_eq!(d.layout.floating[0].groups[0].active_panel(), Some(&5)); + assert_eq!(d.layout.floating[0].groups()[0].active_panel(), Some(&5)); d.wait(); let bar = d.rect("drag-bar", 5).center(); @@ -462,7 +462,7 @@ fn floating_border_and_drag_bar_move_and_cancel_as_a_group() { assert!(matches!(moved_group(&out.actions), Some(Target::Float { .. })), "{name}: {:?}", out.actions); let [x, y, w, h] = d.layout.floating[0].rect; assert_eq!([x, y, w, h], [130.0, 110.0, 300.0, 220.0], "{name}"); - assert_eq!(d.layout.floating[0].groups[0], Group::new(vec![5, 6], 1)); + assert_eq!(d.layout.floating[0].groups()[0], Group::new(vec![5, 6], 1)); } } @@ -551,15 +551,15 @@ fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() { #[test] fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() { - let stack = Floating { groups: vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], rect: [80.0, 70.0, 300.0, 400.0], native: None }; + let stack = Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [80.0, 70.0, 300.0, 400.0]); let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![stack] }; let mut d = Driver::new(layout); let from = d.rect("drag-bar", 6).center(); let out = d.drag(from, pos2(700.0, 300.0)); - assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 189.5]) })), "{:?}", out.actions); + assert!(matches!(moved_group(&out.actions), Some(Target::Float { rect: Some([_, _, 300.0, 189.0]) })), "{:?}", out.actions); assert_eq!(d.layout.floating.len(), 2); - assert_eq!(d.layout.floating[0].groups, vec![Group::new(vec![5], 0)]); - assert_eq!(d.layout.floating[1].groups, vec![Group::new(vec![6, 7], 1)]); + assert_eq!(d.layout.floating[0].groups(), vec![Group::new(vec![5], 0)]); + assert_eq!(d.layout.floating[1].groups(), vec![Group::new(vec![6, 7], 1)]); } #[test] diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index 17b37149d5..28bcf65d18 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -71,6 +71,9 @@ pub enum Divider

{ /// Where the divider of a split inside another split ends on the outer split's divider, /// by the outer and the inner split's paths. Dragging it moves both dividers. Intersection(Vec, Vec), + /// A divider in the floating window holding the panel, by its path from the window's root. + WindowSplit(P, Vec), + WindowIntersection(P, Vec, Vec), } fn key(area: Id) -> Id { @@ -105,6 +108,8 @@ impl DockArea<'_, P> { Hit::Divider(Divider::Group(p)) => id.with(("group-resize", Some(p))), Hit::Divider(Divider::Split(path)) => id.with(("split", path)), Hit::Divider(Divider::Intersection(outer, inner)) => id.with(("intersection", outer, inner)), + Hit::Divider(Divider::WindowSplit(p, path)) => id.with(("window-split", p, path)), + Hit::Divider(Divider::WindowIntersection(p, outer, inner)) => id.with(("window-intersection", p, outer, inner)), Hit::Title(p) => id.with(("move-group", Some(p))), Hit::Close(p) => id.with(("move-group", Some(p))).with("close"), Hit::Resize(p, edge) => { @@ -172,13 +177,35 @@ pub(super) fn named(area: name(Hit::Resize(p(), edge)); } } - let mut nodes = layout.root.as_ref().map(|root| vec![(root, Vec::::new())]).unwrap_or_default(); + if let Some(root) = &layout.root { + name_splits(root, &mut |path, outer| match outer { + None => name(Hit::Divider(Divider::Split(path))), + Some(outer) => name(Hit::Divider(Divider::Intersection(outer, path))), + }); + } + for window in &layout.floating { + let Some(key) = window.panels().next() else { continue }; + name_splits(&window.root, &mut |path, outer| match outer { + None => name(Hit::Divider(Divider::WindowSplit(key.clone(), path))), + Some(outer) => name(Hit::Divider(Divider::WindowIntersection(key.clone(), outer, path))), + }); + } + names +} + +/// Every split of a tree by its path (`None`), and every pair of a split and a split inside it +/// (`Some(outer)`), whose dividers may meet. +fn name_splits

(root: &Node

, name: &mut dyn FnMut(Vec, Option>)) { + let mut nodes = vec![(root, Vec::::new())]; let mut splits: Vec> = Vec::new(); while let Some((node, path)) = nodes.pop() { + if splits.len() > super::model::MAX_NODES { + break; + } if let Node::Split { first, second, .. } = node { - name(Hit::Divider(Divider::Split(path.clone()))); + name(path.clone(), None); for outer in splits.iter().filter(|outer| path.starts_with(outer)) { - name(Hit::Divider(Divider::Intersection(outer.clone(), path.clone()))); + name(path.clone(), Some(outer.clone())); } splits.push(path.clone()); let mut second_path = path.clone(); @@ -189,7 +216,6 @@ pub(super) fn named(area: nodes.push((first, first_path)); } } - names } /// The layout of the last frame and the rects of the controls it registered, by widget id. diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index 825a2687cc..bc946daf9e 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -283,8 +283,7 @@ fn hit_rects_cover_every_gesture_source() { first: Box::new(Node::Tabs { panels: vec![0], active: 0 }), second: Box::new(stack), }; - let mut window = Floating::single(vec![12], 0, [500.0, 60.0, 220.0, 300.0]); - window.groups.push(Group::new(vec![13], 0)); + let window = Floating::stack(vec![Group::new(vec![12], 0), Group::new(vec![13], 0)], [500.0, 60.0, 220.0, 300.0]); let layout = Layout { root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(200.0), first: Box::new(dock), second: Box::new(frames) }), floating: vec![window], diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 2fb4649928..0a88dc73b0 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -1,6 +1,8 @@ use std::{collections::HashSet, fmt, hash::Hash}; -use super::dock_model::{Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, split_frame, valid_column}; +use super::dock_model::{ + Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, split_frame, stack_tree, tree_panels, valid_column, +}; use crate::layout::{SplitAxis, SplitSize}; /// Limits are checked before cloning or recursively modifying an application layout. @@ -54,27 +56,50 @@ pub struct StackEntry

{ pub height: Option, } -/// A floating window: a stack of groups, top to bottom. +/// A floating window: a tree of groups like the docked layout's, without docks. /// -/// Serde reads the v1 shape `{panels, active, rect}` as one group. A window with one plain group -/// (not minimized, no height, no native rect) writes that shape, so older builds can read files +/// Serde reads the v1 shape `{panels, active, rect}` as one group, and a stack of groups +/// `{groups, rect}` as a vertical split of them, sized by their heights. A window with one +/// group (not minimized, no native rect) writes the v1 shape, so older builds can read files /// that use no newer feature. #[derive(Clone, Debug, PartialEq)] pub struct Floating

{ - pub groups: Vec>, + /// `Split`, `Tabs` and `Stack` nodes; a `Dock` is invalid here. + pub root: Node

, /// `[x, y, width, height]` in logical points, in the application's egui viewport. pub rect: [f32; 4], /// Desktop rect while the window is in its own OS window. pub native: Option<[f32; 4]>, + /// Only the title bar shows. + pub minimized: bool, } impl

Floating

{ + pub fn new(root: Node

, rect: [f32; 4]) -> Self { + Self { root, rect, native: None, minimized: false } + } + pub fn single(panels: Vec

, active: usize, rect: [f32; 4]) -> Self { - Self { groups: vec![Group::new(panels, active)], rect, native: None } + Self::new(Node::Tabs { panels, active }, rect) } pub fn panels(&self) -> impl Iterator { - self.groups.iter().flat_map(|group| group.panels.iter()) + tree_panels(&self.root).into_iter() + } + + /// Groups stacked top to bottom, as a v1 layout stored them. + #[cfg(test)] + pub(crate) fn stack(groups: Vec>, rect: [f32; 4]) -> Self { + Self::new(stack_tree(groups).expect("a group"), rect) + } + + /// The window's groups, first to last. + #[cfg(test)] + pub(crate) fn groups(&self) -> Vec> + where + P: Clone, + { + super::dock_model::tree_groups(&self.root) } /// True when a group of this window holds `panel`. Takes any borrowed form of `P`, such @@ -91,7 +116,7 @@ impl

Floating

{ mod floating_serde { use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use super::{Floating, Group}; + use super::{Floating, Group, Node, stack_tree}; #[derive(Serialize)] struct V1<'a, P> { @@ -101,20 +126,22 @@ mod floating_serde { } #[derive(Serialize)] - struct V2<'a, P> { - groups: &'a [Group

], + struct Tree<'a, P> { + root: &'a Node

, rect: [f32; 4], #[serde(skip_serializing_if = "Option::is_none")] native: Option<[f32; 4]>, + #[serde(skip_serializing_if = "std::ops::Not::not")] + minimized: bool, } impl Serialize for Floating

{ fn serialize(&self, serializer: S) -> Result { - match self.groups.as_slice() { - [only] if !only.minimized && only.height.is_none() && self.native.is_none() => { - V1 { panels: &only.panels, active: only.active, rect: self.rect }.serialize(serializer) + match &self.root { + Node::Tabs { panels, active } if !self.minimized && self.native.is_none() => { + V1 { panels, active: *active, rect: self.rect }.serialize(serializer) } - groups => V2 { groups, rect: self.rect, native: self.native }.serialize(serializer), + root => Tree { root, rect: self.rect, native: self.native, minimized: self.minimized }.serialize(serializer), } } } @@ -122,6 +149,7 @@ mod floating_serde { #[derive(Deserialize)] #[serde(bound(deserialize = "P: Deserialize<'de>"))] struct Repr

{ + root: Option>, groups: Option>>, panels: Option>, #[serde(default)] @@ -129,18 +157,25 @@ mod floating_serde { rect: [f32; 4], #[serde(default)] native: Option<[f32; 4]>, + #[serde(default)] + minimized: bool, } impl<'de, P: Deserialize<'de>> Deserialize<'de> for Floating

{ fn deserialize>(deserializer: D) -> Result { let repr = Repr::

::deserialize(deserializer)?; - let groups = match (repr.groups, repr.panels) { - (Some(groups), None) => groups, - (None, Some(panels)) => vec![Group::new(panels, repr.active)], - (None, None) => return Err(serde::de::Error::missing_field("groups")), - (Some(_), Some(_)) => return Err(serde::de::Error::duplicate_field("panels")), + let mut minimized = repr.minimized; + let root = match (repr.root, repr.groups, repr.panels) { + (Some(root), None, None) => root, + (None, Some(groups), None) => { + minimized |= !groups.is_empty() && groups.iter().all(|g| g.minimized); + stack_tree(groups).ok_or_else(|| serde::de::Error::invalid_length(0, &"at least one group"))? + } + (None, None, Some(panels)) => Node::Tabs { panels, active: repr.active }, + (None, None, None) => return Err(serde::de::Error::missing_field("root")), + _ => return Err(serde::de::Error::duplicate_field("root")), }; - Ok(Floating { groups, rect: repr.rect, native: repr.native }) + Ok(Floating { root, rect: repr.rect, native: repr.native, minimized }) } } } @@ -248,6 +283,13 @@ pub enum Action

{ path: Vec, size: SplitSize, }, + /// [`Action::ResizeSplit`] in the floating window holding `panel`, with a path from its + /// root. + ResizeWindowSplit { + panel: P, + path: Vec, + size: SplitSize, + }, SetStackOpen { panel: P, open: bool, @@ -470,38 +512,30 @@ impl Layout

{ } } } - Node::Tabs { panels, active } => { - if panels.is_empty() { - return Err(DockError::InvalidGeometry); - } - check_tabs(panels, *active, &mut seen)?; - } - Node::Stack { entries } => { - if entries.is_empty() { - return Err(DockError::InvalidGeometry); - } - if entries.len() > MAX_PANELS { - return Err(DockError::LimitExceeded); - } - for entry in entries { - if !valid_height(entry.height) { - return Err(DockError::InvalidGeometry); - } - check_panel(&entry.panel, &mut seen)?; - } - } + Node::Tabs { .. } | Node::Stack { .. } => check_leaf(node, &mut seen)?, } } for floating in &self.floating { - if !valid_rect(floating.rect) || floating.groups.is_empty() || floating.native.is_some_and(|r| !valid_rect(r)) { + if !valid_rect(floating.rect) || floating.native.is_some_and(|r| !valid_rect(r)) { return Err(DockError::InvalidGeometry); } - count = count.saturating_add(floating.groups.len()); - if count > MAX_NODES { - return Err(DockError::LimitExceeded); - } - for group in &floating.groups { - check_group(group, &mut seen)?; + let mut visit = vec![(&floating.root, 1usize)]; + while let Some((node, depth)) = visit.pop() { + count = count.saturating_add(1); + if depth > MAX_DEPTH || count > MAX_NODES { + return Err(DockError::LimitExceeded); + } + match node { + Node::Split { size, first, second, .. } => { + if !valid_size(*size) { + return Err(DockError::InvalidGeometry); + } + visit.push((second, depth + 1)); + visit.push((first, depth + 1)); + } + Node::Dock { .. } => return Err(DockError::InvalidPlacement), + Node::Tabs { .. } | Node::Stack { .. } => check_leaf(node, &mut seen)?, + } } } Ok(()) @@ -555,11 +589,13 @@ impl Layout

{ pub fn location(&self, panel: &P) -> Result, DockError> { self.validate()?; let place = self.place(panel).ok_or(DockError::MissingPanel)?; - let (groups, group, floating, column) = match &place { + let (groups, group, column) = match &place { Place::Node(_) => return self.root.as_ref().and_then(|node| node_location(node, panel)).ok_or(DockError::MissingPanel), - Place::Floating { window, group } => { + Place::Floating { window, .. } => { let window = self.floating.get(*window).ok_or(DockError::MissingPanel)?; - (&window.groups, *group, Some(window.rect), None) + let mut location = node_location(&window.root, panel).ok_or(DockError::MissingPanel)?; + location.floating = Some(window.rect); + return Ok(location); } Place::Dock { path, group, .. } => { let side = match self.root.as_ref().and_then(|root| node_at(root, path)) { @@ -568,12 +604,11 @@ impl Layout

{ }; let column = self.column(&place).ok_or(DockError::MissingPanel)?; let state = ColumnLocation { side, width: column.width, iconic: column.iconic, iconic_width: column.iconic_width }; - (&column.groups, *group, None, Some(state)) + (&column.groups, *group, Some(state)) } }; let own = groups.get(group).ok_or(DockError::MissingPanel)?; let mut location = group_location(&own.panels, panel).ok_or(DockError::MissingPanel)?; - location.floating = floating; location.group = Some(GroupLocation { minimized: own.minimized, height: own.height, column }); if location.anchor.is_some() { return Ok(location); @@ -606,11 +641,15 @@ impl Layout

{ pub fn panel_state(&self, panel: &P) -> PanelState { let showing = match self.place(panel) { None => return PanelState::Hidden, - Some(Place::Node(path)) => match self.root.as_ref().and_then(|root| node_at(root, &path)) { - Some(Node::Tabs { panels, active }) => panels.get(*active) == Some(panel), - Some(Node::Stack { entries }) => entries.iter().any(|e| &e.panel == panel && e.open), - _ => false, - }, + Some(place @ (Place::Node(_) | Place::Floating { .. })) => { + let minimized = matches!(place, Place::Floating { window, .. } if self.floating.get(window).is_some_and(|w| w.minimized)); + !minimized + && match self.node_of(&place) { + Some(Node::Tabs { panels, active }) => panels.get(*active) == Some(panel), + Some(Node::Stack { entries }) => entries.iter().any(|e| &e.panel == panel && e.open), + _ => false, + } + } Some(place) => { let iconic = self.column(&place).is_some_and(|c| c.iconic); self.group(&place).is_some_and(|g| !g.minimized && g.active_panel() == Some(panel)) && !iconic @@ -649,20 +688,13 @@ impl Layout

{ } }; let mut proposed = self.clone(); - if let Some(rect) = location.floating { - if !valid_rect(rect) { - return Err(DockError::InvalidGeometry); - } + if location.floating.is_some_and(|rect| !valid_rect(rect)) { + return Err(DockError::InvalidGeometry); + } + let window_open = location.anchor.as_ref().is_some_and(|anchor| proposed.floating.iter().any(|w| w.contains(anchor))); + if let Some(rect) = location.floating.filter(|_| !window_open) { // A window that closed as a whole reopens at its last rect. - if let Some(anchor) = location.anchor.as_ref().filter(|anchor| proposed.floating.iter().any(|g| g.contains(anchor))) { - if let Placement::Group { .. } = location.placement { - proposed.insert_moving(moving(), Target::At { anchor: anchor.clone(), placement: location.placement.clone() })?; - } else { - proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor: anchor.clone(), placement: location.placement.clone() })?; - } - } else { - proposed.insert_moving(moving(), Target::Float { rect: Some(rect) })?; - } + proposed.insert_moving(moving(), Target::Float { rect: Some(rect) })?; } else if let Some(anchor) = &location.anchor && matches!(location.placement, Placement::Group { .. } | Placement::Column { .. }) { @@ -695,18 +727,14 @@ impl Layout

{ if members.len() != location.sibling.len() || !members.contains(anchor) { return Err(DockError::InvalidPlacement); } - around = proposed - .root - .as_mut() - .is_some_and(|root| restore_around_subtree(root, &panel, &members, zone, location.size.unwrap_or(SplitSize::Ratio(0.5)))); + let size = location.size.unwrap_or(SplitSize::Ratio(0.5)); + around = proposed.trees_mut().any(|root| restore_around_subtree(root, &panel, &members, zone, size)); } // A subtree that changed since (a migrated or reconciled layout) splits the anchor. if !around { proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor: anchor.clone(), placement: location.placement.clone() })?; - if let Some(size) = location.size - && let Some(root) = proposed.root.as_mut() - { - restore_parent_size(root, &panel, size); + if let Some(size) = location.size { + proposed.trees_mut().any(|root| restore_parent_size(root, &panel, size)); } } } else if proposed.root.is_none() { @@ -714,13 +742,13 @@ impl Layout

{ } else { return Err(DockError::MissingTarget); } - if let Some((open, height)) = location.stack - && let Some(root) = proposed.root.as_mut() - { - restore_stack_kind(root, &panel); - if let Some(entry) = stack_entry_mut(root, &panel) { - entry.open = open; - entry.height = height; + if let Some((open, height)) = location.stack { + for root in proposed.trees_mut() { + restore_stack_kind(root, &panel); + if let Some(entry) = stack_entry_mut(root, &panel) { + entry.open = open; + entry.height = height; + } } } proposed.validate()?; @@ -884,7 +912,12 @@ impl Layout

{ group.minimized = false; return Ok(()); } - if self.root.as_mut().is_some_and(|node| activate(node, &panel)) { + if let Place::Floating { window, .. } = place + && let Some(window) = self.floating.get_mut(window) + { + window.minimized = false; + } + if self.trees_mut().any(|node| activate(node, &panel)) { return Ok(()); } Err(DockError::MissingPanel) @@ -929,17 +962,20 @@ impl Layout

{ if !valid_size(size) { return Err(DockError::InvalidGeometry); } - let mut node = self.root.as_mut().ok_or(DockError::MissingTarget)?; - for second_child in path { - let Node::Split { first, second, .. } = node else { return Err(DockError::MissingTarget) }; - node = if second_child { second } else { first }; + resize_split(self.root.as_mut().ok_or(DockError::MissingTarget)?, &path, size) + } + Action::ResizeWindowSplit { panel, path, size } => { + if path.len() >= MAX_DEPTH { + return Err(DockError::LimitExceeded); } - let Node::Split { size: old, .. } = node else { return Err(DockError::MissingTarget) }; - *old = size; - Ok(()) + if !valid_size(size) { + return Err(DockError::InvalidGeometry); + } + let window = self.floating.iter_mut().find(|w| w.contains(&panel)).ok_or(DockError::MissingPanel)?; + resize_split(&mut window.root, &path, size) } Action::SetStackOpen { panel, open } => { - let entry = self.root.as_mut().and_then(|n| stack_entry_mut(n, &panel)).ok_or(DockError::MissingPanel)?; + let entry = self.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::MissingPanel)?; entry.open = open; Ok(()) } @@ -947,7 +983,7 @@ impl Layout

{ if !valid_height(height) { return Err(DockError::InvalidGeometry); } - let entry = self.root.as_mut().and_then(|n| stack_entry_mut(n, &panel)).ok_or(DockError::MissingPanel)?; + let entry = self.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::MissingPanel)?; entry.height = height; Ok(()) } @@ -984,7 +1020,11 @@ impl Layout

{ group.minimized = minimized; return Ok(()); } - let entry = self.root.as_mut().and_then(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; + if let Place::Floating { window, .. } = place { + self.floating.get_mut(window).ok_or(DockError::MissingPanel)?.minimized = minimized; + return Ok(()); + } + let entry = self.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; entry.open = !minimized; Ok(()) } @@ -997,7 +1037,7 @@ impl Layout

{ group.height = height; return Ok(()); } - let entry = self.root.as_mut().and_then(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; + let entry = self.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; entry.height = height; Ok(()) } @@ -1046,43 +1086,36 @@ impl Layout

{ if removed.is_some() { return removed; } - for window in &mut self.floating { - for group in &mut window.groups { - if let Some(p) = remove_tab(&mut group.panels, &mut group.active, panel) { - removed = Some(StackEntry { panel: p, open: true, height: None }); - break; + if let Some(index) = self.floating.iter().position(|w| w.contains(panel)) + && let Some(window) = self.floating.get_mut(index) + { + let root = std::mem::replace(&mut window.root, Node::Tabs { panels: Vec::new(), active: 0 }); + match remove_node(root, panel, &mut removed) { + Some(root) => window.root = root, + None => { + self.floating.remove(index); } } - if removed.is_some() { - window.groups.retain(|g| !g.panels.is_empty()); - break; - } } - self.floating.retain(|g| !g.groups.is_empty()); removed } fn insert(&mut self, entry: StackEntry

, anchor: &P, placement: Placement

) -> Result<(), DockError> { let place = self.place(anchor).ok_or(DockError::MissingTarget)?; - if matches!(place, Place::Dock { .. } | Place::Floating { .. }) - || matches!(placement, Placement::Group { .. } | Placement::Column { .. } | Placement::Edge(_)) - { + let tree = place.tree_path().map(|(window, path)| (window, path.to_vec())); + let Some((window, path)) = tree.filter(|_| !matches!(placement, Placement::Group { .. } | Placement::Column { .. } | Placement::Edge(_))) + else { let group = Group::new(vec![entry.panel], 0); return self.insert_moving(Moving::group(group), Target::At { anchor: anchor.clone(), placement }); - } - if let (Placement::Split(zone), Place::Node(path)) = (&placement, &place) - && *zone != Zone::Center + }; + let root = self.tree_mut(window).ok_or(DockError::MissingTarget)?; + if let Placement::Split(zone) = placement + && zone != Zone::Center { - let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; let new = Node::Tabs { panels: vec![entry.panel], active: 0 }; - return if split_frame(root, path, new, *zone) { Ok(()) } else { Err(DockError::MissingTarget) }; + return if split_frame(root, &path, new, zone) { Ok(()) } else { Err(DockError::MissingTarget) }; } - if let Some(root) = self.root.as_mut() - && insert_node(root, &entry, anchor, &placement) - { - return Ok(()); - } - Err(DockError::MissingTarget) + if insert_node(root, &entry, anchor, &placement) { Ok(()) } else { Err(DockError::MissingTarget) } } } @@ -1114,6 +1147,34 @@ fn check_panel<'a, P: Eq + Hash>(panel: &'a P, seen: &mut HashSet<&'a P>) -> Res Ok(()) } +/// A `Tabs` or `Stack` node: not empty, a valid selection and heights, panels not seen before. +fn check_leaf<'a, P: Eq + Hash>(node: &'a Node

, seen: &mut HashSet<&'a P>) -> Result<(), DockError> { + match node { + Node::Tabs { panels, active } => { + if panels.is_empty() { + return Err(DockError::InvalidGeometry); + } + check_tabs(panels, *active, seen) + } + Node::Stack { entries } => { + if entries.is_empty() { + return Err(DockError::InvalidGeometry); + } + if entries.len() > MAX_PANELS { + return Err(DockError::LimitExceeded); + } + for entry in entries { + if !valid_height(entry.height) { + return Err(DockError::InvalidGeometry); + } + check_panel(&entry.panel, seen)?; + } + Ok(()) + } + Node::Split { .. } | Node::Dock { .. } => Ok(()), + } +} + fn check_group<'a, P: Eq + Hash>(group: &'a Group

, seen: &mut HashSet<&'a P>) -> Result<(), DockError> { if group.panels.is_empty() || !valid_height(group.height) { return Err(DockError::InvalidGeometry); @@ -1181,6 +1242,16 @@ fn remove_node(node: Node

, panel: &P, removed: &mut Option(mut node: &mut Node

, path: &[bool], size: SplitSize) -> Result<(), DockError> { + for second_child in path { + let Node::Split { first, second, .. } = node else { return Err(DockError::MissingTarget) }; + node = if *second_child { second } else { first }; + } + let Node::Split { size: old, .. } = node else { return Err(DockError::MissingTarget) }; + *old = size; + Ok(()) +} + fn activate(node: &mut Node

, panel: &P) -> bool { match node { Node::Tabs { panels, active } => { diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index c72119025f..583a2dd98a 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -23,7 +23,7 @@ pub(super) fn docked() -> Layout { Node::Dock { side: Side::End, columns: vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)], 180.0), Column::new(vec![g(&[5], 0)], 120.0)] }; Layout { root: Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), - floating: vec![Floating { groups: vec![g(&[6, 7], 1), g(&[8], 0)], rect: [100.0, 100.0, 300.0, 400.0], native: None }], + floating: vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], [100.0, 100.0, 300.0, 400.0])], } } @@ -38,7 +38,7 @@ fn sorted(layout: &Layout) -> Vec { /// Members, active panel and minimized state of the group holding `panel`. fn group_state(layout: &Layout, panel: u32) -> (Vec, u32, bool) { match layout.place(&panel).unwrap() { - Place::Node(path) => match node_at(layout.root.as_ref().unwrap(), &path).unwrap() { + place @ (Place::Node(_) | Place::Floating { .. }) => match layout.node_of(&place).unwrap() { Node::Tabs { panels, active } => (panels.clone(), panels[*active], false), other => panic!("{other:?}"), }, @@ -78,7 +78,13 @@ fn group_moves_keep_order_active_tab_and_minimized_state() { } let before = group_state(&layout, source); layout.apply(Action::MoveGroup { panel: source, to: to.clone() }).unwrap_or_else(|e| panic!("{source} {to:?}: {e}")); - assert_eq!(group_state(&layout, source), before, "{source} {to:?}"); + let after = group_state(&layout, source); + assert_eq!((&after.0, after.1), (&before.0, before.1), "{source} {to:?}"); + // A group keeps its minimized state from dock to dock; a floating window's tree + // has no minimized groups. + if matches!((source, layout.place(&source)), (2, Some(Place::Dock { .. }))) { + assert_eq!(after.2, before.2, "{source} {to:?}"); + } assert_eq!(sorted(&layout), ALL); } } @@ -86,7 +92,7 @@ fn group_moves_keep_order_active_tab_and_minimized_state() { let mut layout = docked(); layout.apply(Action::MoveGroup { panel: 6, to: Target::At { anchor: 1, placement: Placement::Split(Zone::Left) } }).unwrap(); assert_eq!(group_state(&layout, 6), (vec![6, 7], 7, false)); - assert_eq!(layout.floating[0].groups.len(), 1); + assert_eq!(layout.floating[0].groups().len(), 1); } #[test] @@ -94,7 +100,7 @@ fn group_merge_into_tabs_inserts_every_member_before_the_anchor_tab() { let mut layout = docked(); layout.apply(Action::MoveGroup { panel: 6, to: Target::At { anchor: 2, placement: Placement::Tab { before: Some(3) } } }).unwrap(); assert_eq!(group_state(&layout, 2), (vec![2, 6, 7, 3], 7, false)); - assert_eq!(panels_of(&layout.floating[0].groups), [vec![8]]); + assert_eq!(panels_of(&layout.floating[0].groups()), [vec![8]]); let mut layout = docked(); layout.apply(Action::MoveGroup { panel: 2, to: Target::At { anchor: 11, placement: Placement::Tab { before: Some(12) } } }).unwrap(); @@ -134,7 +140,7 @@ fn column_moves_and_floats_keep_every_group() { layout.apply(Action::MoveColumn { panel: 3, to: Target::Float { rect: None } }).unwrap(); let window = layout.floating.last().unwrap(); - assert_eq!(panels_of(&window.groups), [vec![2, 3], vec![4]]); + assert_eq!(panels_of(&window.groups()), [vec![2, 3], vec![4]]); assert_eq!(window.rect[2], 180.0); assert_eq!(sorted(&layout), ALL); assert_eq!(layout.apply(Action::MoveColumn { panel: 11, to: Target::Float { rect: None } }), Err(DockError::InvalidPlacement)); @@ -182,7 +188,7 @@ fn close_group_and_close_window_record_a_restorable_location_per_member() { workspace.set_visible(panel, true, None, |_| Permissions::default()).unwrap(); } assert_eq!(workspace.layout.floating.len(), 1); - assert_eq!(panels_of(&workspace.layout.floating[0].groups), [vec![6, 7], vec![8]]); + assert_eq!(panels_of(&workspace.layout.floating[0].groups()), [vec![6, 7], vec![8]]); assert_eq!(workspace.layout.floating[0].rect, [100.0, 100.0, 300.0, 400.0]); workspace.apply(Action::CloseOthers { panel: 12 }, allow).unwrap(); @@ -207,11 +213,7 @@ fn restore_into_a_column_group_seam_and_new_column_round_trips() { let start = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![g(&[10], 0)], 200.0)] }; let original = Layout { root: Some(hsplit(SplitSize::FixedFirst(200.0), start, hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end))), - floating: vec![Floating { - groups: vec![g(&[6], 0), Group { height: Some(90.0), ..g(&[7], 0) }], - rect: [10.0, 10.0, 200.0, 300.0], - native: None, - }], + floating: vec![Floating::stack(vec![g(&[6], 0), Group { height: Some(90.0), ..g(&[7], 0) }], [10.0, 10.0, 200.0, 300.0])], }; original.validate().unwrap(); // 4: the seam between [2, 3] and [9]; 9: below [4]; 5: a new column after A; 10: alone in @@ -262,11 +264,14 @@ fn dock_validation_rejects_two_docks_per_side_nested_docks_empty_columns_and_bad } let mut duplicate = docked(); - duplicate.floating[0].groups[1].panels.push(2); + duplicate.floating[0].root = Node::Tabs { panels: vec![6, 7, 2], active: 0 }; assert_eq!(duplicate.validate(), Err(DockError::DuplicatePanel)); let mut empty_window = docked(); - empty_window.floating[0].groups.clear(); + empty_window.floating[0].root = Node::Tabs { panels: Vec::new(), active: 0 }; assert_eq!(empty_window.validate(), Err(DockError::InvalidGeometry)); + let mut docked_window = docked(); + docked_window.floating[0].root = Node::Dock { side: Side::End, columns: vec![Column::new(vec![g(&[6, 7], 0)], 100.0)] }; + assert_eq!(docked_window.validate(), Err(DockError::InvalidPlacement)); let mut native = docked(); native.floating[0].native = Some([0.0, 0.0, -1.0, 10.0]); assert_eq!(native.validate(), Err(DockError::InvalidGeometry)); @@ -385,17 +390,36 @@ mod serde_tests { use super::*; use serde_json::{Value, json}; + #[test] + fn a_saved_stack_of_groups_loads_as_a_vertical_split_by_their_heights() { + let saved = json!({ + "groups": [{"panels": [4], "active": 0, "height": 100.0}, {"panels": [5, 6], "active": 1, "height": 300.0}], + "rect": [1.0, 2.0, 300.0, 400.0], + }); + let window: Floating = serde_json::from_value(saved).unwrap(); + let expected = Node::Split { + axis: SplitAxis::Vertical, + size: SplitSize::Ratio(0.25), + first: Box::new(Node::Tabs { panels: vec![4], active: 0 }), + second: Box::new(Node::Tabs { panels: vec![5, 6], active: 1 }), + }; + assert_eq!((window.root, window.minimized), (expected, false)); + let all_minimized = json!({"groups": [{"panels": [4], "active": 0, "minimized": true}], "rect": [1.0, 2.0, 300.0, 400.0]}); + let window: Floating = serde_json::from_value(all_minimized).unwrap(); + assert_eq!((window.root, window.minimized), (Node::Tabs { panels: vec![4], active: 0 }, true)); + } + #[test] fn single_plain_floating_window_writes_the_v1_shape() { let rect = [1.0, 2.0, 300.0, 200.0]; let plain = Floating::single(vec![4u32, 5], 1, rect); assert_eq!(serde_json::to_value(&plain).unwrap(), json!({"panels": [4, 5], "active": 1, "rect": rect})); - let minimized = Floating { groups: vec![Group { minimized: true, ..g(&[4], 0) }], rect, native: None }; - let stacked = Floating { groups: vec![g(&[4], 0), g(&[5], 0)], rect, native: None }; + let minimized = Floating { minimized: true, ..Floating::single(vec![4u32], 0, rect) }; + let stacked = Floating::stack(vec![g(&[4], 0), g(&[5], 0)], rect); let native = Floating { native: Some(rect), ..Floating::single(vec![4u32], 0, rect) }; for window in [minimized, stacked, native] { let value = serde_json::to_value(&window).unwrap(); - assert!(value.get("groups").is_some() && value.get("panels").is_none(), "{value}"); + assert!(value.get("root").is_some() && value.get("panels").is_none(), "{value}"); assert_eq!(serde_json::from_value::>(value).unwrap(), window); } assert!(serde_json::from_value::>(json!({"rect": rect})).is_err()); diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 16932bf8c9..eb4e4934a9 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -474,9 +474,9 @@ impl Renderer<'_, P> { || self.iconic.covers(pointer) || self .frame - .stacks + .windows .iter() - .any(|window| window.window.contains(pointer) && !moving.is_some_and(|p| window.groups.iter().any(|(panels, ..)| panels.contains(p)))) + .any(|window| window.window.contains(pointer) && !moving.is_some_and(|p| window.members.contains(p))) } /// Dock targets, with the new-dock bands along the docked area's left and right edges that diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index a321f3aa1e..72ec389c35 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -4,21 +4,14 @@ use egui::{Context, Id, Key, Pos2, Rect, Ui, pos2, vec2}; use super::{GroupKind, Renderer, clamp_float, node_limits}; use crate::docking::chrome::{ChromeStyle, FloatingFrame, RESIZE_BAND, TitleBar}; -use crate::docking::{Action, DropProposal, Floating, Group, GroupDrag, GroupGesture, Node, PanelLimits, Placement, Target}; -use crate::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis}; +use crate::docking::{Action, DropProposal, Floating, GroupDrag, GroupGesture, Node, PanelLimits, Placement, Target}; pub(in crate::docking) use crate::docking::chrome::RESIZE_HANDLES; -/// Height of the bar between two stacked groups of a floating window. -const GAP: f32 = 3.0; - -/// A floating stack as drawn, for its band and seam targets. -pub(in crate::docking) struct StackHit

{ +/// A floating window as drawn: what covers the layout behind it. +pub(in crate::docking) struct WindowHit

{ pub(super) window: Rect, - /// Each group's members, rect and tab strip, top to bottom. - pub(super) groups: Vec<(Vec

, Rect, Rect)>, - /// The upper group's index and the band of each seam. - pub(super) seams: Vec<(usize, Rect)>, + pub(super) members: Vec

, } impl Renderer<'_, P> { @@ -40,24 +33,32 @@ impl Renderer<'_, P> { } } - /// Size limits of a floating window: its title bar, each group's strip and the bodies of - /// the groups that are not minimized. + /// Size limits of a floating window: its title bar and, unless it is minimized, its tree. pub(super) fn window_limits(&self, window: &Floating

) -> PanelLimits { - // A movable window is resizable, with a resize band above its title bar. + let chrome = self.window_chrome(window); + let tree = node_limits(&window.root, self.style, &*self.content); + let body = match (&window.root, window.minimized) { + (Node::Tabs { .. }, true) => (self.style.tab_height, self.style.tab_height), + (_, true) => (0.0, 0.0), + (_, false) => (tree.min.y, tree.max.y), + }; + let min = vec2(tree.min.x, chrome + body.0).min(vec2(1_000_000.0, 1_000_000.0)); + PanelLimits { min, max: vec2(tree.max.x, chrome + body.1).max(min).min(vec2(1_000_000.0, 1_000_000.0)) } + } + + /// The title bar and, for a movable (resizable) window, the resize band above it. + fn window_chrome(&self, window: &Floating

) -> f32 { let band = if window.panels().all(|panel| self.permissions(panel).movable) { RESIZE_BAND } else { 0.0 }; - let chrome = band + self.style.title_height; - let mut limits = PanelLimits { min: vec2(0.0, chrome), max: vec2(1_000_000.0, chrome) }; - for (index, group) in window.groups.iter().enumerate() { - let policy = node_limits(&Node::Tabs { panels: group.panels.clone(), active: 0 }, self.style, &*self.content); - let gap = if index > 0 { GAP } else { 0.0 }; - limits.min.x = limits.min.x.max(policy.min.x); - limits.max.x = limits.max.x.min(policy.max.x); - let (min, max) = if group.minimized { (self.style.tab_height, self.style.tab_height) } else { (policy.min.y, policy.max.y) }; - limits.min.y += min + gap; - limits.max.y += max + gap; - } - let min = limits.min.min(vec2(1_000_000.0, 1_000_000.0)); - PanelLimits { min, max: limits.max.max(min).min(vec2(1_000_000.0, 1_000_000.0)) } + band + self.style.title_height + } + + /// Where a floating window draws its tree, as [`Self::floating_window`] places it. + pub(super) fn window_body(&self, window: &Floating

) -> Rect { + let [x, y, width, height] = window.rect; + let limits = self.window_limits(window); + let size = vec2(width, height).max(limits.min).min(limits.max); + let rect = crate::docking::chrome::clamp(Rect::from_min_size(pos2(x, y), size), self.float_bounds); + Rect::from_min_max(pos2(rect.left(), (rect.top() + self.window_chrome(window)).min(rect.bottom())), rect.max) } fn floating_window(&mut self, ctx: &Context, window: &Floating

, screen: Rect) { @@ -97,17 +98,33 @@ impl Renderer<'_, P> { } } - /// The title bar, then the stacked groups below it, in `contents`. Moves carry the whole + /// The title bar, then the window's tree below it, in `contents`. Moves carry the whole /// `frame`, resize band included. fn window_contents(&mut self, ui: &mut Ui, window: &Floating

, contents: Rect, frame: Rect, style: &ChromeStyle) { let title = Rect::from_min_max(contents.min, pos2(contents.right(), (contents.top() + self.style.title_height).min(contents.bottom()))); self.title_bar(ui, window, title, frame, style); let body = Rect::from_min_max(pos2(contents.left(), title.bottom()), contents.max); - self.floating_stack(ui, &window.groups, body, frame); + self.floating_body(ui, window, body, frame); } - /// Drag moves the whole window live, double-click minimizes or expands every group, × - /// closes every panel in it. + /// A floating window's tree in `body`, like the docked layout's: splits, groups, dividers + /// and intersections. A minimized window shows the tab strip of its only group, or nothing. + pub(super) fn floating_body(&mut self, ui: &mut Ui, window: &Floating

, body: Rect, frame: Rect) { + let Some(key) = window.panels().next().cloned() else { return }; + match (&window.root, window.minimized) { + (Node::Tabs { panels, active }, true) => self.group(ui, panels, *active, true, body, GroupKind::Floating { window: frame }), + (_, true) => {} + (root, false) => { + let outer = self.tree.replace((key, frame)); + self.node(ui, root, body, &mut Vec::new()); + self.tree = outer; + } + } + self.frame.windows.push(WindowHit { window: frame, members: window.panels().cloned().collect() }); + } + + /// Drag moves the whole window live, double-click minimizes or expands it, × closes every + /// panel in it. fn title_bar(&mut self, ui: &mut Ui, window: &Floating

, title: Rect, rect: Rect, style: &ChromeStyle) { let Some(first) = window.panels().next() else { return }; let movable = window.panels().all(|p| self.permissions(p).movable); @@ -143,12 +160,7 @@ impl Renderer<'_, P> { self.output.actions.push(Action::MoveFloating { panel: first.clone(), rect: [moved.left(), moved.top(), moved.width(), moved.height()] }); } if response.bar.double_clicked() { - let minimized = !window.groups.iter().all(|g| g.minimized); - for group in window.groups.iter().filter(|g| g.minimized != minimized) { - if let Some(panel) = group.active_panel() { - self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized }); - } - } + self.output.actions.push(Action::SetMinimized { panel: first.clone(), minimized: !window.minimized }); } if let Some(close) = response.close { self.register_interaction(ui.ctx(), close.id); @@ -158,86 +170,19 @@ impl Renderer<'_, P> { } } - /// Groups top to bottom with a bar between them. Minimized groups take their strip; the - /// others share the rest by their preferred heights, equally when none is set. - pub(super) fn floating_stack(&mut self, ui: &mut Ui, groups: &[Group

], body: Rect, window: Rect) { - let strip = self.style.tab_height; - let open = groups.iter().filter(|g| !g.minimized).count(); - let fixed = groups.len().saturating_sub(open) as f32 * strip + groups.len().saturating_sub(1) as f32 * GAP; - let available = (body.height() - fixed).max(0.0); - let equal = if open > 0 { available / open as f32 } else { 0.0 }; - let wanted = |g: &Group

| g.height.filter(|h| h.is_finite() && *h > 0.0).unwrap_or(equal).max(1.0); - let total: f32 = groups.iter().filter(|g| !g.minimized).map(wanted).sum(); - let scale = if total > 0.0 { available / total } else { 0.0 }; - let mut hit = StackHit { window, groups: Vec::new(), seams: Vec::new() }; - let mut top = body.top(); - let mut rects = Vec::new(); - for (index, group) in groups.iter().enumerate() { - if index > 0 { - let gap = Rect::from_min_max(pos2(body.left(), top), pos2(body.right(), (top + GAP).min(body.bottom()))); - ui.painter().rect_filled(gap, 0.0, self.style.tab_background); - hit.seams.push((index - 1, Rect::from_center_size(gap.center(), vec2(gap.width(), self.style.seam_band)))); - top = gap.bottom(); - } - let height = if group.minimized { strip } else { wanted(group) * scale }; - let rect = Rect::from_min_max(pos2(body.left(), top), pos2(body.right(), (top + height).min(body.bottom()))); - self.group(ui, &group.panels, group.active, group.minimized, rect, GroupKind::Floating { window }); - let strip_rect = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + strip).min(rect.bottom()))); - hit.groups.push((group.panels.clone(), rect, strip_rect)); - rects.push(rect); - top = rect.bottom(); - } - // Dividers between two open groups resize both; registered after the strips, so their - // hit region wins at the shared edge. - for (index, pair) in groups.windows(2).enumerate() { - let ([upper, lower], Some(a), Some(b)) = (pair, rects.get(index), rects.get(index + 1)) else { continue }; - if upper.minimized || lower.minimized || scale <= 0.0 { - continue; - } - let (Some(upper_panel), Some(lower_panel)) = (upper.active_panel(), lower.active_panel()) else { continue }; - let divider = Rect::from_min_max(pos2(body.left(), a.bottom()), pos2(body.right(), b.top())); - let least = strip + self.style.min_pane; - let pair_size = a.height() + b.height(); - let (lo, hi) = if pair_size >= 2.0 * least { (least, pair_size - least) } else { (a.height(), a.height()) }; - let response = ResizeHandle::new( - self.id.with(("group-resize", upper.panels.first())), - SplitAxis::Vertical, - divider, - &self.style.resize_label, - ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, - ) - .value(a.height(), lo..=hi) - .show(ui); - self.register_interaction(ui.ctx(), response.response.id); - if response.delta != 0.0 { - let next = (a.height() + response.delta).clamp(lo, hi); - self.output.actions.push(Action::ResizeGroup { panel: upper_panel.clone(), height: Some(next / scale) }); - self.output.actions.push(Action::ResizeGroup { panel: lower_panel.clone(), height: Some((pair_size - next) / scale) }); - } - } - self.frame.stacks.push(hit); - } - - /// Targets the group targets do not cover: the bands and seams of a floating stack (P3, - /// P4), then the layout's outer edge (P8). None leaves the pointer to the group targets. - /// `skip_own` looks through the window holding `members` (a window moving live). + /// The title bar of a floating window occludes what lies behind it: a no-op proposal. Then + /// the layout's outer edge (P8). None leaves the pointer to the group targets. `skip_own` + /// looks through the window holding `members` (a window moving live). pub(super) fn extra_proposal(&self, members: &[P], pointer: Pos2, skip_own: bool) -> Option> { let own = |panels: &[P]| panels.iter().any(|p| members.contains(p)); - let window = self.frame.stacks.iter().rev().find(|w| w.window.contains(pointer) && !(skip_own && w.groups.iter().any(|(g, ..)| own(g)))); + let window = self.frame.windows.iter().rev().find(|w| w.window.contains(pointer) && !(skip_own && own(&w.members))); if let Some(window) = window { - let in_group = window.groups.iter().any(|(_, rect, _)| rect.contains(pointer)) || window.seams.iter().any(|(_, b)| b.contains(pointer)); - if !in_group { - // The title bar occludes what lies behind the window. - let anchor = members.first()?.clone(); - return Some(DropProposal { - anchor, - placement: Placement::Tab { before: None }, - preview: Rect::NOTHING, - insertion: None, - noop: true, - }); + let in_group = self.targets.iter().any(|t| t.rect.contains(pointer) && t.tabs.iter().any(|(p, _)| window.members.contains(p))); + if in_group { + return None; } - return self.stack_proposal(window, members, pointer); + let anchor = members.first()?.clone(); + return Some(DropProposal { anchor, placement: Placement::Tab { before: None }, preview: Rect::NOTHING, insertion: None, noop: true }); } let (anchor, zone, preview) = self.edge_proposal(members, pointer)?; let lead = members.first()?.clone(); @@ -251,74 +196,30 @@ impl Renderer<'_, P> { Some(DropProposal { anchor, placement: Placement::Edge(zone), preview, insertion: None, noop: false }) } - fn stack_proposal(&self, hit: &StackHit

, members: &[P], pointer: Pos2) -> Option> { - let line = |y: f32| Rect::from_min_max(pos2(hit.window.left(), y - 1.0), pos2(hit.window.right(), y + 1.0)); - let same = |panels: &[P]| panels == members; - // An anchor in the group that is not itself moving. - let anchor = |panels: &[P]| panels.iter().find(|p| !members.contains(p)).cloned(); - for (upper, band) in &hit.seams { - if !band.contains(pointer) { - continue; - } - let (Some((a, rect, _)), Some((b, ..))) = (hit.groups.get(*upper), hit.groups.get(upper + 1)) else { return None }; - let line = line(rect.bottom() + GAP * 0.5); - if same(a) || same(b) { - let anchor = members.first()?.clone(); - return Some(DropProposal { - anchor, - placement: Placement::Group { below: true, height: None }, - preview: Rect::NOTHING, - insertion: None, - noop: true, - }); - } - let (anchor, below) = match anchor(a) { - Some(panel) => (panel, true), - None => (anchor(b)?, false), - }; - return Some(DropProposal { - anchor, - placement: Placement::Group { below, height: None }, - preview: Rect::NOTHING, - insertion: Some(line), - noop: false, - }); - } - let (panels, rect, strip) = hit.groups.iter().find(|(_, rect, _)| rect.contains(pointer))?; - if strip.contains(pointer) || same(panels) { - return None; - } - let band = rect.height() * 0.25; - let below = if pointer.y < rect.top() + band { - false - } else if pointer.y > rect.bottom() - band { - true - } else { - return None; - }; - let insertion = Some(line(if below { rect.bottom() } else { rect.top() })); - Some(DropProposal { - anchor: anchor(panels)?, - placement: Placement::Group { below, height: None }, - preview: Rect::NOTHING, - insertion, - noop: false, - }) - } - /// What a group drag carries: the whole window rect for the only group of a floating /// window, so floating it again keeps the window's size; else the group's rect. pub(super) fn drag_source(&self, owner: &super::group::TabGroup<'_, P>) -> Rect { match owner.kind { - GroupKind::Floating { window } - if owner.panels.first().is_some_and(|p| self.layout.floating.iter().any(|w| w.groups.len() == 1 && w.contains(p))) => - { - window - } + GroupKind::Floating { window } if owner.panels.first().is_some_and(|p| self.whole_window(p)) => window, _ => owner.rect, } } + /// Whether a double-click or the group menu minimizes `owner`: a dock group, or the only + /// group of a floating window, which minimizes the window to that group's strip. + pub(super) fn minimizes(&self, owner: &super::group::TabGroup<'_, P>) -> bool { + match owner.kind { + GroupKind::Dock => true, + GroupKind::Floating { .. } => self.whole_window(owner.selected), + GroupKind::Frame => false, + } + } + + /// Whether `panel`'s group is the whole tree of a floating window. + pub(super) fn whole_window(&self, panel: &P) -> bool { + matches!(self.place(panel), Some(crate::docking::dock_model::Place::Floating { path, .. }) if path.is_empty()) + } + /// Release of a title bar drag. The window already sits where it was dragged; a dock or /// group target docks or merges every group in it, else hosts get the release in /// `group_drop`. diff --git a/crates/ui/src/docking/render/frame.rs b/crates/ui/src/docking/render/frame.rs index f7fa795328..e86f1b7cf5 100644 --- a/crates/ui/src/docking/render/frame.rs +++ b/crates/ui/src/docking/render/frame.rs @@ -5,7 +5,7 @@ use std::{borrow::Cow, collections::HashMap, fmt::Debug, hash::Hash}; use egui::{Context, Pos2, Rect, pos2, vec2}; -use super::{GroupKind, Renderer, floating::StackHit, group::TabGroup}; +use super::{GroupKind, Renderer, floating::WindowHit, group::TabGroup}; use crate::docking::{ Action, Column, DockContent, DockEvent, Floating, Group, HidePanels, Layout, Node, Zone, dock_model::{Place, node_at}, @@ -18,12 +18,14 @@ const HINT_OFFSET: f32 = 28.0; pub(in crate::docking) struct FrameState

{ /// View path to layout path of each split, when the view is not the layout. paths: Option, Vec>>, + /// The same for each floating window's splits, by the window's first shown panel. + window_paths: HashMap, Vec>>, /// The view node whose rect is the outer edge area; none while a frame is maximized. edge_path: Option>, pub(super) edge: Option, pub(super) maximized: Option

, - /// Floating stacks as drawn, back to front. - pub(super) stacks: Vec>, + /// Floating windows as drawn, back to front. + pub(super) windows: Vec>, } /// The layout as shown: a maximized frame alone, and hidden panels left out. @@ -48,7 +50,7 @@ pub(in crate::docking) fn view<'a, P: Clone + Eq + Hash>( } Place::Floating { .. } => None, }); - let mut state = FrameState { paths: None, edge_path: None, edge: None, maximized: None, stacks: Vec::new() }; + let mut state = FrameState { paths: None, window_paths: HashMap::new(), edge_path: None, edge: None, maximized: None, windows: Vec::new() }; if maximized.is_none() && matches!(hide, HidePanels::None) { state.edge_path = Some(layout.edge_path()); return (Cow::Borrowed(layout), state); @@ -61,14 +63,16 @@ pub(in crate::docking) fn view<'a, P: Clone + Eq + Hash>( } None => { let root = layout.root.as_ref().and_then(|root| prune(root, Vec::new(), Vec::new(), &hidden, &mut paths)); - let floating = layout - .floating - .iter() - .filter_map(|window| { - let groups: Vec<_> = window.groups.iter().filter_map(|g| prune_group(g, &hidden)).collect(); - (!groups.is_empty()).then(|| Floating { groups, rect: window.rect, native: window.native }) - }) - .collect(); + let mut floating = Vec::new(); + for window in &layout.floating { + let mut paths = HashMap::new(); + let Some(root) = prune(&window.root, Vec::new(), Vec::new(), &hidden, &mut paths) else { continue }; + let shown = Floating { root, ..window.clone() }; + if let Some(key) = shown.panels().next() { + state.window_paths.insert(key.clone(), paths); + } + floating.push(shown); + } Layout { root, floating } } }; @@ -148,14 +152,18 @@ fn prune_group(group: &Group

, hidden: &dyn Fn(&P) -> bo impl Renderer<'_, P> { pub(super) fn note_edge(&mut self, path: &[bool], rect: Rect) { - if self.frame.edge_path.as_deref() == Some(path) { + if self.tree.is_none() && self.frame.edge_path.as_deref() == Some(path) { self.frame.edge = Some(rect); } } - /// The layout path of a split drawn at view path `path`. + /// The layout path of a split drawn at view path `path`, in the tree being drawn. pub(super) fn original_path(&self, path: &[bool]) -> Vec { - self.frame.paths.as_ref().and_then(|paths| paths.get(path).cloned()).unwrap_or_else(|| path.to_vec()) + let paths = match &self.tree { + None => self.frame.paths.as_ref(), + Some((key, _)) => self.frame.window_paths.get(key), + }; + paths.and_then(|paths| paths.get(path).cloned()).unwrap_or_else(|| path.to_vec()) } /// The outer edge band under the pointer (P8): top and bottom, and left and right with @@ -202,7 +210,7 @@ impl Renderer<'_, P> { /// Ctrl/Cmd held when a split-tree tab drag starts: the drop floats (S9). pub(super) fn latch_undock(&self, ctx: &Context, kind: Option) { let command = ctx.input(|i| i.modifiers.command || i.modifiers.ctrl || i.modifiers.mac_cmd); - if self.style.command_press_floats && kind == Some(GroupKind::Frame) && command { + if self.style.command_press_floats && matches!(kind, Some(GroupKind::Frame | GroupKind::Floating { .. })) && command { ctx.data_mut(|d| { if let Some(drag) = d.get_temp::>(self.id.with("drag")) { d.insert_temp(self.id.with("drag"), crate::docking::Drag { undock: true, ..drag }); diff --git a/crates/ui/src/docking/render/group.rs b/crates/ui/src/docking/render/group.rs index 8ce1ecb9d0..ec7d98bdc9 100644 --- a/crates/ui/src/docking/render/group.rs +++ b/crates/ui/src/docking/render/group.rs @@ -13,7 +13,7 @@ pub(in crate::docking) enum GroupKind { Frame, /// A group in a dock column. Dock, - /// A group in the floating window drawn at `window`. + /// A `Tabs` node of the floating window drawn at `window`: side drops split it. Floating { window: Rect }, } @@ -40,7 +40,7 @@ impl Renderer<'_, P> { let Some(selected) = panels.get(active) else { return }; self.record_float(panels, rect.size(), rect.size()); let policy = self.permissions(selected); - let splits = kind == GroupKind::Frame && policy.accepts_splits; + let splits = matches!(kind, GroupKind::Frame | GroupKind::Floating { .. }) && policy.accepts_splits; let rtl = self.style.right_to_left; if stripless(panels, &*self.content) { self.contents(ui, selected, rect); @@ -175,7 +175,7 @@ impl Renderer<'_, P> { if !bar { return; } - if owner.kind != GroupKind::Frame && response.double_clicked() { + if self.minimizes(owner) && response.double_clicked() { self.output.actions.push(Action::SetMinimized { panel: owner.selected.clone(), minimized: !owner.minimized }); } let active = response.has_focus() || response.hovered(); @@ -258,7 +258,7 @@ impl Renderer<'_, P> { if closable && self.menu_action(ui, &self.style.close_group_label.clone()) { self.output.actions.push(Action::CloseGroup { panel: panel.clone() }); } - if owner.kind != GroupKind::Frame { + if self.minimizes(owner) { let label = if owner.minimized { self.style.expand_label.clone() } else { self.style.minimize_label.clone() }; if self.menu_action(ui, &label) { self.output.actions.push(Action::SetMinimized { panel: panel.clone(), minimized: !owner.minimized }); @@ -267,7 +267,8 @@ impl Renderer<'_, P> { if owner.kind == GroupKind::Dock && self.menu_action(ui, &self.style.collapse_to_icons_label.clone()) { self.output.actions.push(Action::SetIconic { panel: panel.clone(), iconic: true }); } - if floatable && !matches!(owner.kind, GroupKind::Floating { .. }) && self.menu_action(ui, &self.style.float_group_label.clone()) { + let whole_window = matches!(owner.kind, GroupKind::Floating { .. }) && self.whole_window(panel); + if floatable && !whole_window && self.menu_action(ui, &self.style.float_group_label.clone()) { let size = self.group_float_size(owner.panels, owner.rect.size()); let rect = clamp_float(Rect::from_min_size(owner.rect.min + vec2(24.0, 24.0), size), self.float_bounds); self.output.actions.push(Action::MoveGroup { @@ -353,7 +354,7 @@ impl Renderer<'_, P> { } pub(super) fn tab(&mut self, ui: &mut Ui, panel: &P, rect: Rect, active: bool, group: Rect, owner: Option<&TabGroup<'_, P>>) { - let minimized = owner.filter(|owner| owner.kind != GroupKind::Frame).map(|owner| owner.minimized); + let minimized = owner.filter(|owner| self.minimizes(owner)).map(|owner| owner.minimized); let policy = self.permissions(panel); let label = self.label_of(panel); let color = if active { self.style.text } else { self.style.inactive_text }; diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 742839a7ad..fc8fd3d448 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -55,6 +55,9 @@ pub(super) struct Renderer<'a, P> { pub(super) contents: HashMap, /// Split dividers drawn so far, by view path, for the intersections of their ancestors. pub(super) dividers: Vec, + /// The floating window whose tree is being drawn: its first panel, which names it in + /// ids and actions, and its rect. `None` while the docked layout draws. + pub(super) tree: Option<(P, Rect)>, } pub(super) struct DrawnDivider { @@ -127,7 +130,7 @@ impl Renderer<'_, P> { // Named by its layout path, which `ResizeSplit` takes and hits report. let layout_path = self.original_path(path); let response = ResizeHandle::new( - self.id.with(("split", &layout_path)), + self.split_id(&layout_path), *axis, split.divider, &self.style.resize_label, @@ -145,7 +148,13 @@ impl Renderer<'_, P> { self.dividers.push(DrawnDivider { path: path.clone(), axis: *axis, rect, divider: split.divider }); } } - Node::Tabs { panels, active } => self.group(ui, panels, *active, false, rect, GroupKind::Frame), + Node::Tabs { panels, active } => { + let kind = match &self.tree { + None => GroupKind::Frame, + Some((_, window)) => GroupKind::Floating { window: *window }, + }; + self.group(ui, panels, *active, false, rect, kind); + } Node::Dock { side, columns } => self.dock(ui, *side, columns, rect, rect.width()), Node::Stack { entries } => { let total_header = (entries.len() as f32 * self.style.tab_height).min(rect.height()); @@ -247,7 +256,20 @@ impl Renderer<'_, P> { /// `path` in `rect`, by `delta` points. fn divider_actions(&self, node: &Node

, rect: Rect, path: &[bool], delta: f32) -> Vec> { let sizes = self.sizer().drag(node, rect, delta, &mut path.to_vec()); - sizes.into_iter().map(|(path, size)| Action::ResizeSplit { path: self.original_path(&path), size }).collect() + let resize = |path: Vec, size| match &self.tree { + None => Action::ResizeSplit { path, size }, + Some((panel, _)) => Action::ResizeWindowSplit { panel: panel.clone(), path, size }, + }; + sizes.into_iter().map(|(path, size)| resize(self.original_path(&path), size)).collect() + } + + /// The id of the divider of the split at `path` in the tree being drawn, as + /// [`crate::docking::DockArea::hit_id`] names it. + fn split_id(&self, path: &[bool]) -> Id { + match &self.tree { + None => self.id.with(("split", path)), + Some((panel, _)) => self.id.with(("window-split", panel, path)), + } } /// Four-way handles where a divider drawn inside the split `node` (since `mark`) ends on @@ -268,7 +290,11 @@ impl Renderer<'_, P> { } for (inner_path, inner_rect, hit) in found { let Some(inner) = inner_path.get(path.len()..).and_then(|rest| crate::docking::dock_model::node_at(node, rest)) else { continue }; - let id = self.id.with(("intersection", self.original_path(path), self.original_path(&inner_path))); + let (outer, inner_layout) = (self.original_path(path), self.original_path(&inner_path)); + let id = match &self.tree { + None => self.id.with(("intersection", outer, inner_layout)), + Some((panel, _)) => self.id.with(("window-intersection", panel, outer, inner_layout)), + }; let response = ui.interact(hit, id, Sense::drag()); self.register_interaction(ui.ctx(), id); if response.hovered() || response.dragged() { diff --git a/crates/ui/src/docking/render/native.rs b/crates/ui/src/docking/render/native.rs index 349dcbf25b..911ae2251f 100644 --- a/crates/ui/src/docking/render/native.rs +++ b/crates/ui/src/docking/render/native.rs @@ -71,7 +71,7 @@ impl Renderer<'_, P> { // and size, which are read back below. let spawn_key = self.id.with(("native-spawn", &first)); let spawn = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(spawn_key, || sanitized(rect))); - let title = window.groups.first().and_then(|g| g.active_panel()).map(|p| self.label_of(p)).unwrap_or_default(); + let title = crate::docking::dock_model::first_active(&window.root).map(|p| self.label_of(p)).unwrap_or_default(); let builder = ViewportBuilder::default() .with_title(title) .with_position([spawn[0], spawn[1]]) @@ -80,11 +80,11 @@ impl Renderer<'_, P> { if self.activation.as_ref().is_some_and(|panel| window.contains(panel)) { ctx.send_viewport_cmd_to(viewport, ViewportCommand::Focus); } - let (targets, stacks) = (self.targets.len(), self.frame.stacks.len()); + let (targets, windows) = (self.targets.len(), self.frame.windows.len()); let (closed, placed) = ctx.show_viewport_immediate(viewport, builder, |ui, class| { let rect = ui.max_rect(); ui.painter().rect_filled(rect, 0.0, self.style.floating_background); - self.floating_stack(ui, &window.groups, rect, rect); + self.floating_body(ui, window, rect, rect); // An embedded fallback reads the main window's input: its close request and place // are not this window's. if matches!(class, ViewportClass::Immediate | ViewportClass::Deferred) { @@ -95,7 +95,7 @@ impl Renderer<'_, P> { }); // Targets in another OS window are in its coordinates, and no drag crosses windows. self.targets.truncate(targets); - self.frame.stacks.truncate(stacks); + self.frame.windows.truncate(windows); ctx.data_mut(|d| { if d.get_temp::>(self.id.with("drag")).is_some_and(|drag| window.contains(&drag.panel)) { d.remove::>(self.id.with("drag")); diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index a767750a3a..0189f81015 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -6,7 +6,7 @@ use super::{DROP_MARGIN, Drawn, Renderer, clamp_float, dock::group_action}; use crate::docking::chrome::drop_preview; use crate::docking::{ Action, Drag, DropProposal, DropRequest, DropTarget, GroupDrag, GroupGesture, Layout, Node, Placement, Target, Zone, cancel_drag, - dock_model::{Place, node_at}, + dock_model::Place, resolve_drop, surface::TAB_PADDING, }; @@ -104,7 +104,9 @@ impl Renderer<'_, P> { }); } let proposal = self.resolve_roomy(&drag.panel, pointer, std::slice::from_ref(target), |to| group_action(drag, to))?; - if window && matches!(proposal.placement, Placement::Split(_)) { + // A window moving live splits only groups of other floating windows. + let into_window = matches!(self.place(&proposal.anchor), Some(Place::Floating { .. })); + if window && !into_window && matches!(proposal.placement, Placement::Split(_)) { return None; } valid(proposal) @@ -138,6 +140,9 @@ impl Renderer<'_, P> { if let Some(root) = &layout.root { sizer.groups(root, self.workspace, &mut out); } + for window in layout.floating.iter().filter(|w| !w.minimized) { + sizer.groups(&window.root, self.window_body(window), &mut out); + } out.into_iter().filter_map(|d| Some((lead(d.node)?.clone(), d.rect.size(), d.limits.min))).collect::>() }; let before: HashMap = drawn(self.layout).into_iter().map(|(panel, size, _)| (panel, size)).collect(); @@ -406,7 +411,7 @@ impl Renderer<'_, P> { /// The active panel of the group at `place` when `members` are that whole group. fn group_active<'a>(&'a self, members: &[P], place: &Place) -> Option<&'a P> { let (panels, active) = match place { - Place::Node(path) => match self.layout.root.as_ref().and_then(|root| node_at(root, path)) { + Place::Node(_) | Place::Floating { .. } => match self.layout.node_of(place) { Some(Node::Tabs { panels, active }) => (panels, *active), _ => return None, }, diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 3354d9f03c..69e1313db5 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -506,3 +506,107 @@ fn the_title_bar_moves_a_floating_window_without_docking() { assert!(window.rect[0] < 1000.0 && window.rect[1] > 400.0, "moved towards the drop: {:?}", window.rect); assert_eq!(d.layout.root, editing().root); } + +fn panel_set(layout: &Layout) -> Vec { + let mut panels: Vec = layout.panels().into_iter().copied().collect(); + panels.sort_unstable(); + panels +} + +fn window_of(layout: &Layout, panel: u32) -> &Floating { + layout.floating.iter().find(|w| w.contains(&panel)).unwrap_or_else(|| panic!("{panel} does not float: {layout:?}")) +} + +#[test] +fn tabs_and_drag_bars_dock_into_a_floating_window_and_out_of_it() { + let mut d = film(); + let all = panel_set(&d.layout); + let info = group(&d, INFO); + let out = d.drag(tab(&d, PROGRAM), pos2(info.left() + 10.0, info.center().y + 13.0)); + assert_eq!(out.actions, vec![Action::Move { panel: PROGRAM, anchor: INFO, placement: Placement::Split(Zone::Left) }]); + d.settle(); + assert!(matches!(window_of(&d.layout, INFO).root, Node::Split { axis: SplitAxis::Horizontal, .. }), "{:?}", d.layout.floating); + let (program, info) = (group(&d, PROGRAM), group(&d, INFO)); + assert!(program.right() < info.left() && (program.width() - info.width()).abs() < 2.0, "{program:?} {info:?}"); + + // A drag bar inside the window moves its group to a group of the main area. + let timeline = group(&d, TIMELINE); + let bar = d.hit(&Hit::DragBar(INFO)).unwrap().center(); + let out = d.drag(bar, timeline.center() + vec2(0.0, 13.0)); + assert_eq!(out.actions, vec![Action::MoveGroup { panel: INFO, to: Target::At { anchor: TIMELINE, placement: Placement::Split(Zone::Center) } }]); + d.settle(); + assert_eq!(window_of(&d.layout, PROGRAM).root, tabs(&[PROGRAM])); + assert_eq!(panel_set(&d.layout), all); +} + +#[test] +fn a_floating_window_tree_resizes_by_its_dividers_and_intersections() { + let mut layout = editing(); + let tree = hsplit(0.5, tabs(&[INFO]), split(SplitAxis::Vertical, 0.5, tabs(&[50]), tabs(&[51]))); + layout.floating = vec![Floating::new(tree, [700.0, 100.0, 600.0, 500.0])]; + let mut d = driver(layout, Film::default()); + let ratios = |d: &Driver| match &d.layout.floating[0].root { + Node::Split { size: SplitSize::Ratio(outer), second, .. } => match &**second { + Node::Split { size: SplitSize::Ratio(inner), .. } => (*outer, *inner), + other => panic!("{other:?}"), + }, + other => panic!("{other:?}"), + }; + let outer = Hit::Divider(Divider::WindowSplit(INFO, Vec::new())); + let inner = Hit::Divider(Divider::WindowSplit(INFO, vec![true])); + for (hit, delta) in [(&outer, vec2(30.0, 0.0)), (&outer, vec2(-60.0, 0.0)), (&inner, vec2(0.0, 30.0)), (&inner, vec2(0.0, -60.0))] { + let before = ratios(&d); + drag_hit(&mut d, hit.clone(), delta); + let after = ratios(&d); + let moved = if hit == &outer { (after.0 - before.0) * delta.x } else { (after.1 - before.1) * delta.y }; + assert!(moved > 0.0, "{hit:?} by {delta:?}: {before:?} to {after:?}"); + assert_eq!(d.layout.root, editing().root, "the main area keeps its sizes"); + } + // The four-way handle where the inner divider meets the outer one moves both. + let before = ratios(&d); + drag_hit(&mut d, Hit::Divider(Divider::WindowIntersection(INFO, Vec::new(), vec![true])), vec2(25.0, 25.0)); + let after = ratios(&d); + assert!(after.0 > before.0 && after.1 > before.1, "{before:?} to {after:?}"); +} + +#[test] +fn moves_between_windows_are_one_action_and_lose_no_panel() { + let mut layout = editing(); + layout.floating.push(Floating::single(vec![50, 51], 0, [200.0, 520.0, 320.0, 260.0])); + let mut d = driver(layout, Film::default()); + let all = panel_set(&d.layout); + // Floating to floating: a whole group, by its drag bar, beside Info. + let info = group(&d, INFO); + let bar = d.hit(&Hit::DragBar(50)).unwrap().center(); + let out = d.drag(bar, pos2(info.right() - 10.0, info.center().y + 13.0)); + assert_eq!(out.actions, vec![Action::MoveGroup { panel: 50, to: Target::At { anchor: INFO, placement: Placement::Split(Zone::Right) } }]); + d.settle(); + assert_eq!(d.layout.floating.len(), 1); + assert_eq!(panel_set(&d.layout), all); + // Main to floating: a tab joins the window's group. + let fifty = group(&d, 50); + let out = d.drag(tab(&d, SOURCE[1]), fifty.center() + vec2(0.0, 13.0)); + assert_eq!(out.actions, vec![Action::Move { panel: SOURCE[1], anchor: 50, placement: Placement::Split(Zone::Center) }]); + d.settle(); + assert!(window_of(&d.layout, 50).contains(&SOURCE[1])); + assert_eq!(panel_set(&d.layout), all); + assert_eq!(d.layout.validate(), Ok(())); +} + +#[test] +fn a_closed_floating_window_closes_its_panels_and_each_reopens_where_it_was() { + let mut layout = editing(); + let tree = hsplit(0.4, tabs(&[INFO]), tabs(&[50])); + layout.floating = vec![Floating::new(tree.clone(), [700.0, 100.0, 600.0, 400.0])]; + let mut d = driver(layout, Film::default()); + let locations: Vec<_> = [INFO, 50].into_iter().map(|p| (p, d.layout.location(&p).unwrap())).collect(); + let close = d.hit(&Hit::Close(INFO)).unwrap().center(); + let out = d.click(close); + assert_eq!(out.actions, vec![Action::CloseWindow { panel: INFO }]); + assert!(d.layout.floating.is_empty() && !d.layout.contains(&50)); + for (panel, location) in &locations { + d.layout.restore(*panel, location).unwrap(); + } + let window = &d.layout.floating[0]; + assert_eq!((&window.root, window.rect), (&tree, [700.0, 100.0, 600.0, 400.0])); +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 1595ef3e5f..0de4119a0c 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -821,6 +821,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { places, contents: content_index, dividers: Vec::new(), + tree: None, }; if let Some(root) = &view.root { renderer.node(ui, root, rect, &mut Vec::new()); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 87b2cb0ab8..61c45051ef 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -29,8 +29,8 @@ fn floating_brush_panel_joins_main_tabs_without_losing_other_panels() { let Node::Split { size, second, .. } = layout.root.as_ref().unwrap() else { panic!() }; assert_eq!(*size, SplitSize::FixedSecond(240.0)); assert_eq!(**second, tabs(&[2, 3, 5, 4], 2)); - assert_eq!(layout.floating[0].groups[0].panels, vec![6]); - assert_eq!(layout.floating[0].groups[0].active, 0); + assert_eq!(layout.floating[0].groups()[0].panels, vec![6]); + assert_eq!(layout.floating[0].groups()[0].active, 0); layout.validate().unwrap(); assert_eq!(layout.panels().len(), 6); } @@ -43,8 +43,8 @@ fn detach_redock_merge_and_collapse_empty_source_containers() { layout.apply(move_to(1, 2, Zone::Left)).unwrap(); assert_eq!(layout.floating.len(), 1); layout.apply(move_to(5, 6, Zone::Center)).unwrap(); - assert_eq!(layout.floating[0].groups[0].panels, vec![6, 5]); - assert_eq!(layout.floating[0].groups[0].active, 1); + assert_eq!(layout.floating[0].groups()[0].panels, vec![6, 5]); + assert_eq!(layout.floating[0].groups()[0].active, 1); layout.apply(move_to(6, 3, Zone::Center)).unwrap(); layout.apply(move_to(5, 3, Zone::Center)).unwrap(); assert!(layout.floating.is_empty()); @@ -82,7 +82,7 @@ fn invalid_moves_are_atomic_including_after_a_source_would_have_been_removed() { for action in [ move_to(5, 99, Zone::Center), move_to(99, 2, Zone::Center), - move_to(5, 6, Zone::Left), + Action::Move { panel: 5, anchor: 6, placement: Placement::Column { after: true } }, move_to(5, 5, Zone::Center), Action::Move { panel: 5, anchor: 2, placement: Placement::Tab { before: Some(6) } }, Action::Float { panel: 3, rect: [f32::NAN, 0.0, 100.0, 100.0] }, @@ -208,12 +208,18 @@ fn closing_and_reopening_an_entire_accordion_restores_its_kind_and_heights() { #[test] fn invalid_saved_layouts_reject_duplicates_selection_depth_and_nonfinite_geometry() { let mut duplicate = sample(); - duplicate.floating[0].groups[0].panels.push(1); + if let Node::Tabs { panels, .. } = &mut duplicate.floating[0].root { + panels.push(1); + } assert_eq!(duplicate.validate(), Err(DockError::DuplicatePanel)); let mut invalid = sample(); - invalid.floating[0].groups[0].active = usize::MAX; + if let Node::Tabs { active, .. } = &mut invalid.floating[0].root { + *active = usize::MAX; + } assert_eq!(invalid.validate(), Err(DockError::InvalidSelection)); - invalid.floating[0].groups[0].active = 0; + if let Node::Tabs { active, .. } = &mut invalid.floating[0].root { + *active = 0; + } invalid.floating[0].rect[3] = f32::INFINITY; assert_eq!(invalid.validate(), Err(DockError::InvalidGeometry)); let mut deep = tabs(&[0], 0); @@ -715,8 +721,8 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() { step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); let actions = step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(50.0, 40.0))]); assert!(actions.iter().any(|a| matches!(a, Action::MoveFloating { .. }))); - assert_eq!(layout.floating[0].groups[0].panels, original.groups[0].panels); - assert_eq!(layout.floating[0].groups[0].active, original.groups[0].active); + assert_eq!(layout.floating[0].groups()[0].panels, original.groups()[0].panels); + assert_eq!(layout.floating[0].groups()[0].active, original.groups()[0].active); assert_ne!(layout.floating[0].rect, original.rect); step(&ctx, &mut layout, vec![pointer_button(start + vec2(50.0, 40.0), false)]); for _ in 0..2 { @@ -731,7 +737,7 @@ fn floating_group_grip_moves_every_member_while_tab_drag_detaches_one() { let detached = step(&ctx, &mut layout, vec![pointer_button(outside, false)]); assert!(detached.iter().any(|a| matches!(a, Action::Float { panel: 5, .. }))); assert_eq!(layout.floating.len(), 2); - assert_eq!(layout.floating[0].groups[0].panels, vec![6]); + assert_eq!(layout.floating[0].groups()[0].panels, vec![6]); } #[test] diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index b7f2e4329c..d16cf98d44 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -146,7 +146,7 @@ fn drag_bar_draws_no_mark_at_rest_and_a_group_drag_paints_a_filled_labeled_ghost fn double_click_on_a_tab_of_a_minimized_group_ends_expanded() { let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::single(vec![5, 6], 1, [80.0, 70.0, 300.0, 220.0])] }; let mut d = Driver::new(layout); - let minimized = |d: &Driver| d.layout.floating[0].groups[0].minimized; + let minimized = |d: &Driver| d.layout.floating[0].minimized; let active = d.tab(6).center(); d.click(active); d.click(active); @@ -157,7 +157,7 @@ fn double_click_on_a_tab_of_a_minimized_group_ends_expanded() { d.click(other); d.click(other); assert!(!minimized(&d)); - assert_eq!(d.layout.floating[0].groups[0].active_panel(), Some(&5)); + assert_eq!(d.layout.floating[0].groups()[0].active_panel(), Some(&5)); } #[test] @@ -364,8 +364,8 @@ fn for_zone_maps_side_zones_onto_columns_groups_and_splits() { assert_eq!(zone(2, Zone::Right, true), Ok(Placement::Column { after: false })); assert_eq!(zone(4, Zone::Bottom, false), Ok(Placement::Group { below: true, height: None })); assert_eq!(zone(2, Zone::Center, false), Ok(Placement::Split(Zone::Center))); - assert_eq!(zone(5, Zone::Top, false), Ok(Placement::Group { below: false, height: None })); - assert_eq!(zone(5, Zone::Left, false), Err(DockError::InvalidPlacement)); + assert_eq!(zone(5, Zone::Top, false), Ok(Placement::Split(Zone::Top))); + assert_eq!(zone(5, Zone::Left, false), Ok(Placement::Split(Zone::Left))); assert_eq!(zone(0, Zone::Left, true), Ok(Placement::Split(Zone::Left))); assert_eq!(zone(9, Zone::Left, false), Err(DockError::MissingTarget)); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index f92d1aa958..26b58eae6f 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -37,8 +37,12 @@ their sides. | `Stack` | Accordion entries, each open or closed, with an optional height. | | `Dock` | A side and its columns. A `Column` has `Group`s, a width, and `iconic`. | -A `Floating` window has one or more stacked groups, a rect, and an optional native-window rect. -`Floating::single` makes a window with one group; `panels()` and `contains()` read it. +A `Floating` window holds a tree like the docked layout's (`root`: splits, tab groups and +accordions, no docks), a rect, an optional native-window rect and `minimized`. +`Floating::single` makes a window with one group and `Floating::new` one with a tree; `panels()` +and `contains()` read it. Saved layouts keep loading: a window stored as one group (v1) or as a +stack of groups loads as that group or as a vertical split of the stacked groups, sized by their +heights. `P` is the app's panel id: stable, not localized, `Clone + Eq + Hash`. The renderer also needs `Debug + Send + Sync + 'static`. A panel occurs at most once in a layout. @@ -68,12 +72,16 @@ layout.apply(Action::Move { - Containers take different placements: a dock column takes groups and columns, not splits. `Placement::for_zone(layout, anchor, zone, right_to_left)` maps a left, right, top, bottom or center zone onto what the anchor's container takes: a split in the frame tree, a new column on - that side or a new group above or below in a dock, a group above or below in a floating window. + that side or a new group above or below in a dock. A floating window takes splits as the + docked layout does; `Placement::Group` on a floating anchor splits its group above or below. - A side split zone puts what moves in a new half-size split of the anchor's frame, and no other frame changes size. The new split has its own divider, and the drop preview shows the half the new frame takes. -- Other actions select, minimize, collapse to icons, resize splits, columns and groups, and move - a floating window to its own OS window (`SetNative`, feature `native-windows`). +- Other actions select, minimize, collapse to icons, resize splits (`ResizeSplit` in the docked + layout, `ResizeWindowSplit` in the floating window holding a panel), columns and groups, and + move a floating window to its own OS window (`SetNative`, feature `native-windows`). +- A move between windows (docked to floating, floating to floating) is one action, checked as a + whole like any other. Every action checks the whole result before it commits. A bad target, a duplicate id, a stale split path or invalid geometry returns a `DockError` and leaves the layout unchanged. The source @@ -188,6 +196,14 @@ A flyout fits its content the same way, without the title bar. the whole group. A column bar drags a column. A floating window's title bar drags the window; with `title_bar_docks` a release over a target docks the whole window there, else it only moves. +- Inside a floating window, tabs and drag bars drag and dock as they do in the docked layout, + into any window. Its groups split, join and resize like frames, with dividers and four-way + handles (`Divider::WindowSplit` and `Divider::WindowIntersection`, named by the window's first + panel). Double-clicking the title bar minimizes the window to its title bar, or to the tab strip + of its only group; so does double-clicking that group's strip. The group menu's float item + floats one group of a window that has several. Closing the window closes its panels; each + reopens where it was while the window or its neighbour in it is open, else in a window at the + window's last rect. - A movable floating window resizes from every edge and corner. The top edge and corners are a 4 pt band above the title bar (`chrome::RESIZE_BAND`), so they take no moves and no clicks on the title bar's buttons. A resize keeps the opposite edges in place and stays within the size From 281ea71f5b55258bcd3b768eb5b3b6cbcd20ab24 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 20:20:26 +0000 Subject: [PATCH 85/94] docking: the drop preview shows the zone under the pointer With side_edge_zones, a drop on a group fills the zone the pointer is in (a side's trapezoid, or the center rectangle with the tab strip) and outlines the rect the drop gives what moves. zone_shape gives a zone's outline; DockDriver::filled_polygon checks it. The dock-and-canvas arrangement keeps its filled half and insertion lines. --- crates/ui/src/docking/mod.rs | 2 +- crates/ui/src/docking/render/preview.rs | 27 +++++++++++++-- crates/ui/src/docking/split_tests.rs | 46 +++++++++++++++++++++++-- crates/ui/src/docking/targets.rs | 29 ++++++++++++++-- crates/ui/src/docking/testing.rs | 12 +++++++ docs/ui-docking.md | 5 ++- 6 files changed, 112 insertions(+), 9 deletions(-) diff --git a/crates/ui/src/docking/mod.rs b/crates/ui/src/docking/mod.rs index 2587dca034..dd4b50bc77 100644 --- a/crates/ui/src/docking/mod.rs +++ b/crates/ui/src/docking/mod.rs @@ -30,7 +30,7 @@ pub use surface::{ DockArea, DockContent, DockEvent, DockOutput, DockStyle, DropFeedback, DropRequest, FloatSpace, HidePanels, PanelLimits, begin_drag, cancel_drag, float_space, is_dragging, }; -pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect}; +pub use targets::{DropProposal, DropTarget, drop_zone, resolve_drop, tab_insertion_marker, zone_rect, zone_shape}; pub use workspace::Workspace; use surface::{Drag, GroupDrag, GroupGesture}; diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 0189f81015..cabb8cdcc9 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -220,7 +220,7 @@ impl Renderer<'_, P> { } if let Some(proposal) = self.group_proposal(drag, pointer).filter(|p| !p.noop) { let split = matches!(proposal.placement, Placement::Split(zone) | Placement::Edge(zone) if zone != Zone::Center); - if crate::docking::targets::usable(proposal.preview) { + if crate::docking::targets::usable(proposal.preview) && !self.paint_zone(&painter, &proposal, pointer) { drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, split); } if let Some(marker) = proposal.insertion { @@ -322,7 +322,7 @@ impl Renderer<'_, P> { // Reordering inside the source strip shows only the insertion line. let same_group = proposal.insertion.is_some() && self.targets.iter().any(|target| target.rect == proposal.preview && target.tabs.iter().any(|(panel, _)| panel == &drag.panel)); - if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) { + if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) && !self.paint_zone(&painter, &proposal, pointer) { drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, true); } if let Some(marker) = proposal.insertion { @@ -336,6 +336,29 @@ impl Renderer<'_, P> { } } + /// With [`crate::docking::DockStyle::side_edge_zones`], a drop on a group shows the zone + /// under the pointer (a side's trapezoid, or the center rectangle with the tab strip) + /// filled, and the rect the drop gives what moves outlined. False when it painted nothing. + fn paint_zone(&self, painter: &egui::Painter, proposal: &DropProposal

, pointer: Pos2) -> bool { + let zone = match proposal.placement { + Placement::Split(zone) => zone, + Placement::Tab { .. } => Zone::Center, + _ => return false, + }; + let target = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer)); + let (Some(target), true) = (target, self.style.side_edge_zones) else { return false }; + let Some(points) = crate::docking::targets::zone_shape(target.rect, zone) else { return false }; + let fill = self.style.accent.gamma_multiply(0.25); + painter.add(egui::Shape::convex_polygon(points, fill, egui::Stroke::NONE)); + if zone == Zone::Center + && let Some(strip) = target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|r| crate::docking::targets::usable(*r)) + { + painter.rect_filled(strip, 0.0, fill); + } + drop_preview(painter, proposal.preview.shrink(1.0), self.style.accent, false); + true + } + /// The single drop preview layer, above every floating window. pub(super) fn preview_painter(&self, ctx: &Context) -> egui::Painter { let layer = egui::LayerId::new(egui::Order::Tooltip, self.id.with("drop-preview")); diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 69e1313db5..21bfcc169a 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -133,7 +133,7 @@ fn a_group_is_a_picture_frame_whose_edges_split_it_in_half_and_whose_middle_join let at = inset(zone); d.hold(tab(&d, INFO), at); let half = zone_rect(timeline, zone).unwrap(); - assert!(d.filled(half.shrink(1.0)), "{zone:?}: the preview is that half of the group"); + assert!(d.outlined(half.shrink(1.0)), "{zone:?}: the preview outlines that half of the group"); let out = d.release(at); assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TIMELINE, placement: Placement::Split(zone) }], "{zone:?}"); d.settle(); @@ -275,7 +275,7 @@ fn a_drop_beside_a_narrow_group_splits_that_group_only() { assert!(tools.width() > 120.0, "{tools:?}"); let at = pos2(tools.right() - 8.0, tools.center().y + 13.0); d.hold(tab(&d, INFO), at); - assert!(d.filled(zone_rect(tools, Zone::Right).unwrap().shrink(1.0)), "the preview is Tools' right half"); + assert!(d.outlined(zone_rect(tools, Zone::Right).unwrap().shrink(1.0)), "the preview outlines Tools' right half"); let out = d.release(at); assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TOOLS, placement: Placement::Split(Zone::Right) }]); d.settle(); @@ -610,3 +610,45 @@ fn a_closed_floating_window_closes_its_panels_and_each_reopens_where_it_was() { let window = &d.layout.floating[0]; assert_eq!((&window.root, window.rect), (&tree, [700.0, 100.0, 600.0, 400.0])); } + +#[test] +fn the_preview_fills_the_zone_under_the_pointer_and_outlines_the_result() { + let d = film(); + let timeline = group(&d, TIMELINE); + let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0)); + // A side band: its trapezoid, and the half the panel takes. + for (zone, at) in [ + (Zone::Left, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)), + (Zone::Bottom, pos2(timeline.center().x, timeline.bottom() - 20.0)), + ] { + let mut d = film(); + d.hold(tab(&d, INFO), at); + assert!(d.filled_polygon(&zone_shape(timeline, zone).unwrap()), "{zone:?}"); + assert!(d.outlined(zone_rect(timeline, zone).unwrap().shrink(1.0)), "{zone:?}"); + d.key(egui::Key::Escape); + } + // The middle and the tab row: the center rectangle and the strip, and the whole group. + for at in [timeline.center() + vec2(0.0, 13.0), strip.center()] { + let mut d = film(); + d.hold(tab(&d, INFO), at); + assert!(d.filled_polygon(&zone_shape(timeline, Zone::Center).unwrap()), "{at:?}"); + assert!(d.filled(strip), "{at:?}"); + assert!(d.outlined(timeline.shrink(1.0)), "{at:?}"); + d.key(egui::Key::Escape); + } + // A group's drag bar shows the same. + let mut d = film(); + let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); + d.hold(bar, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)); + assert!(d.filled_polygon(&zone_shape(timeline, Zone::Left).unwrap())); + d.key(egui::Key::Escape); + + // The dock-and-canvas arrangement keeps its filled half. + let mut d = DockDriver::new(editing(), Film::default()); + d.screen = Rect::from_min_size(Pos2::ZERO, SCREEN); + d.area = d.screen; + d.settle(); + d.hold(tab(&d, INFO), pos2(timeline.left() + 8.0, timeline.center().y + 13.0)); + assert!(!d.filled_polygon(&zone_shape(timeline, Zone::Left).unwrap())); + assert!(d.filled(zone_rect(timeline, Zone::Left).unwrap().shrink(1.0))); +} diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index ff515ec0e0..7a816f1a97 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -1,4 +1,4 @@ -use egui::{Pos2, Rangef, Rect, pos2}; +use egui::{Pos2, Rangef, Rect, Vec2, pos2, vec2}; use super::{Placement, Side, Target, Zone}; @@ -45,8 +45,7 @@ pub fn drop_zone(rect: Rect, tab_height: f32, pointer: Pos2) -> Option { if pointer.y < rect.top() + tab_height.min(rect.height()) { return Some(Zone::Center); } - let depth = |extent: f32| (extent * 0.25).max(MIN_SIDE_ZONE).min(extent * 0.5); - let (x, y) = (depth(rect.width()), depth(rect.height())); + let Vec2 { x, y } = side_depths(rect); let distances = [ ((pointer.x - rect.left()) / x, Zone::Left), ((rect.right() - pointer.x) / x, Zone::Right), @@ -57,6 +56,30 @@ pub fn drop_zone(rect: Rect, tab_height: f32, pointer: Pos2) -> Option { Some(if distance > 1.0 { Zone::Center } else { zone }) } +/// How deep the side zones of a group drawn at `rect` reach in from its left and right edges +/// (`x`) and its top and bottom edges (`y`). +fn side_depths(rect: Rect) -> Vec2 { + let depth = |extent: f32| (extent * 0.25).max(MIN_SIDE_ZONE).min(extent * 0.5); + vec2(depth(rect.width()), depth(rect.height())) +} + +/// The outline of a drop zone of the group drawn at `rect`, as [`drop_zone`] finds it: a side's +/// trapezoid (its outer edge the whole side, its inner edge on the center rectangle), or the +/// center rectangle. The tab strip is a grouping zone too. +pub fn zone_shape(rect: Rect, zone: Zone) -> Option> { + if !usable(rect) { + return None; + } + let inner = rect.shrink2(side_depths(rect)); + Some(match zone { + Zone::Left => vec![rect.left_top(), inner.left_top(), inner.left_bottom(), rect.left_bottom()], + Zone::Right => vec![inner.right_top(), rect.right_top(), rect.right_bottom(), inner.right_bottom()], + Zone::Top => vec![rect.left_top(), rect.right_top(), inner.right_top(), inner.left_top()], + Zone::Bottom => vec![inner.left_bottom(), inner.right_bottom(), rect.right_bottom(), rect.left_bottom()], + Zone::Center => vec![inner.left_top(), inner.right_top(), inner.right_bottom(), inner.left_bottom()], + }) +} + /// Preview of the region occupied after a split or group merge. pub fn zone_rect(rect: Rect, zone: Zone) -> Option { if !usable(rect) { diff --git a/crates/ui/src/docking/testing.rs b/crates/ui/src/docking/testing.rs index 868a6c4cc3..81db476962 100644 --- a/crates/ui/src/docking/testing.rs +++ b/crates/ui/src/docking/testing.rs @@ -215,6 +215,18 @@ impl> Do }) } + /// Whether the last frame filled a polygon with these corners, each within half a point. + pub fn filled_polygon(&self, corners: &[Pos2]) -> bool { + self.shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Path(path) => { + path.fill != egui::Color32::TRANSPARENT + && path.points.len() == corners.len() + && path.points.iter().zip(corners).all(|(a, b)| a.distance(*b) <= 0.5) + } + _ => false, + }) + } + /// Whether the last frame outlined `rect` without filling it. pub fn outlined(&self, rect: Rect) -> bool { self.shapes.iter().any(|clipped| match &clipped.shape { diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 26b58eae6f..adaec4abb4 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -224,7 +224,10 @@ A flyout fits its content the same way, without the title bar. for one through `PanelLimits::max`: a panel without a maximum lifts the maximum of the panels it joins. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, - a filled half for a split. Escape or losing window focus cancels a drag. + a filled half for a split. With `side_edge_zones`, a drop on a group instead fills the zone + under the pointer (a side's trapezoid, or the center rectangle and the tab strip; `zone_shape` + gives the outline) and outlines the rect the drop gives what moves. Escape or losing window + focus cancels a drag. - With `float_on_empty_drop`, a release over no target floats what moves at the pointer, such as a panel dropped on a protected canvas. Without it, that release cancels the drag and nothing moves: the gap between two groups, a menu bar or a status bar is no target. A release From deec5af9cf6060f731573b836fae4cb4f683ea2a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 20:22:00 +0000 Subject: [PATCH 86/94] docking: random drops reach floating windows and move panels between windows The property test starts with a split floating window beside Info's, drags tabs and drag bars into, out of and between windows, floats some with Ctrl/Cmd, and checks after every drop that no panel is lost, every group in every window keeps its minimum and every divider can travel both ways. --- crates/ui/src/docking/split_tests.rs | 100 ++++++++++++++++++--------- 1 file changed, 67 insertions(+), 33 deletions(-) diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 21bfcc169a..9ad5e5c512 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -298,49 +298,71 @@ fn every_divider_travels_after_drops() { assert_dividers_travel(&mut d); } -/// Each split divider moves both ways when dragged, from the layout as it is. +/// Each split divider, in the docked layout and in floating windows, moves both ways when +/// dragged, from the layout as it is. fn assert_dividers_travel(d: &mut Driver) { let start = d.layout.clone(); - let paths: Vec> = d + let dividers: Vec> = d .hits() .into_iter() - .filter_map(|(hit, _)| match hit { - Hit::Divider(Divider::Split(path)) => Some(path), - _ => None, + .filter_map(|(hit, _)| matches!(hit, Hit::Divider(Divider::Split(_) | Divider::WindowSplit(..))).then_some(hit)) + .collect(); + assert!(!dividers.is_empty()); + // A floating window may cover the dividers of the main area and of other windows. + let covers: Vec<(Rect, &Floating)> = start + .floating + .iter() + .map(|w| { + let drawn = w.panels().filter(|p| d.content.bodies.contains_key(p)).map(|p| group(d, *p)); + let rect = Rect::from_min_size(pos2(w.rect[0], w.rect[1]), vec2(w.rect[2], w.rect[3])); + (drawn.fold(rect, |a, b| a.union(b)), w) }) .collect(); - assert!(!paths.is_empty()); - for path in paths { + for hit in dividers { + let own = |w: &Floating| matches!(&hit, Hit::Divider(Divider::WindowSplit(key, _)) if w.contains(key)); + if d.hit(&hit).is_some_and(|r| covers.iter().any(|(c, w)| c.intersects(r) && !own(w))) { + continue; + } for step in [12.0, -24.0] { - let Some(rect) = d.hit(÷r(&path)) else { continue }; + let Some(rect) = d.hit(&hit) else { continue }; let delta = if rect.width() < rect.height() { vec2(step, 0.0) } else { vec2(0.0, step) }; let before = d.layout.clone(); - drag_hit(d, divider(&path), delta); - assert_ne!(d.layout, before, "divider {path:?} does not move by {step}"); + drag_hit(d, hit.clone(), delta); + assert_ne!(d.layout, before, "divider {hit:?} does not move by {step}"); } d.layout = start.clone(); d.settle(); } } -/// Every group at or above its minimum, and every divider with room both ways. +/// Every group at or above its minimum, and every divider with room both ways, in the docked +/// layout and in each floating window. Reads the bodies drawn last. fn assert_sizes(d: &Driver, context: &str) { let mut style = DockStyle::default(); frame_style(&mut style); - let Some(root) = &d.layout.root else { return }; let sizer = Sizer { style: &style, content: &d.content }; - let mut groups: Vec> = Vec::new(); - sizer.groups(root, d.area, &mut groups); - for g in &groups { - let room = g.rect.size() - g.limits.min; - assert!(room.x >= -0.01 && room.y >= -0.01, "{context}: {:?} is below its minimum {:?}", g.rect, g.limits.min); + let mut trees: Vec<(&Node, Rect)> = d.layout.root.iter().map(|root| (root, d.area)).collect(); + for window in d.layout.floating.iter().filter(|w| !w.minimized) { + // The window's body is the union of its groups. + let drawn = window.panels().filter(|p| d.content.bodies.contains_key(p)).map(|p| group(d, *p)); + if let Some(rect) = drawn.reduce(|a, b| a.union(b)) { + trees.push((&window.root, rect)); + } } - let mut nodes = vec![(root, d.area)]; - while let Some((node, rect)) = nodes.pop() { - let Some(children) = sizer.children(node, rect) else { continue }; - let (lo, hi) = sizer.range(node, rect); - assert!(lo < -0.5 && hi > 0.5, "{context}: a divider is stuck ({lo}, {hi}) at {rect:?} in {:?}", d.layout); - nodes.extend(children); + for (root, area) in trees { + let mut groups: Vec> = Vec::new(); + sizer.groups(root, area, &mut groups); + for g in &groups { + let room = g.rect.size() - g.limits.min; + assert!(room.x >= -0.01 && room.y >= -0.01, "{context}: {:?} is below its minimum {:?}", g.rect, g.limits.min); + } + let mut nodes = vec![(root, area)]; + while let Some((node, rect)) = nodes.pop() { + let Some(children) = sizer.children(node, rect) else { continue }; + let (lo, hi) = sizer.range(node, rect); + assert!(lo < -0.5 && hi > 0.5, "{context}: a divider is stuck ({lo}, {hi}) at {rect:?} in {:?}", d.layout); + nodes.extend(children); + } } } @@ -362,16 +384,25 @@ impl Lcg { #[test] fn random_drops_leave_every_group_its_minimum_and_every_divider_travel() { + // Drops land in the docked layout and in two floating windows, one of them split; tabs and + // drag bars move panels and groups between all three, and Ctrl/Cmd floats some. + let windows = || { + let mut layout = editing(); + layout.floating.push(Floating::new(hsplit(0.5, tabs(&[8]), tabs(&[50, 51])), [80.0, 420.0, 640.0, 380.0])); + layout + }; for seed in 1..=6u64 { let mut rng = Lcg(seed); - let mut d = film(); - for step in 0..14 { + let mut d = driver(windows(), Film::default()); + let all = panel_set(&d.layout); + for step in 0..16 { // Only the bodies drawn now. d.content.bodies.clear(); d.settle(); let panels: Vec = d.layout.panels().into_iter().copied().collect(); let panel = panels[rng.below(panels.len())]; - let Some(from) = d.hit(&Hit::Tab(panel)).map(|r| r.center()) else { continue }; + let bar = d.hit(&Hit::DragBar(panel)).filter(|_| rng.below(3) == 0); + let Some(from) = bar.or_else(|| d.hit(&Hit::Tab(panel))).map(|r| r.center()) else { continue }; let target = panels[rng.below(panels.len())]; let Some(rect) = d.content.bodies.get(&target).copied() else { continue }; let to = match rng.below(8) { @@ -390,14 +421,17 @@ fn random_drops_leave_every_group_its_minimum_and_every_divider_travel() { // Anywhere in the body: an edge band or the middle. _ => rect.lerp_inside(vec2(0.02 + rng.unit() * 0.96, 0.02 + rng.unit() * 0.96)), }; - d.drag(from, to); - d.settle(); - if d.layout.floating.iter().any(|w| w.contains(&panel)) && panel != INFO { - // Back into the tree: this test is about the docked layout. - d.layout.apply(Action::Move { panel, anchor: target, placement: Placement::Split(Zone::Center) }).ok(); - d.settle(); + if rng.below(12) == 0 { + d.modifiers = Modifiers::COMMAND; } - assert_sizes(&d, &format!("seed {seed}, step {step}")); + d.drag(from, to); + d.modifiers = Modifiers::NONE; + d.content.bodies.clear(); + d.settle(); + let context = format!("seed {seed}, step {step}"); + assert_eq!(d.layout.validate(), Ok(()), "{context}"); + assert_eq!(panel_set(&d.layout), all, "{context}: a panel was lost"); + assert_sizes(&d, &context); } assert_dividers_travel(&mut d); } From 9ff107c2c182fbd30edffd446fb8ff2a55f2c11c Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 20:23:27 +0000 Subject: [PATCH 87/94] docking: rustfmt, and doc comments for floating trees --- crates/ui/src/docking/command.rs | 5 +++-- crates/ui/src/docking/dock_model.rs | 1 + crates/ui/src/docking/floating_tests.rs | 5 ++++- crates/ui/src/docking/hits.rs | 2 +- crates/ui/src/docking/model.rs | 19 +++++++++++-------- crates/ui/src/docking/render/dock.rs | 6 +----- crates/ui/src/docking/render/preview.rs | 8 +++----- crates/ui/src/docking/split_tests.rs | 7 +++---- crates/ui/src/docking/surface.rs | 3 +-- 9 files changed, 28 insertions(+), 28 deletions(-) diff --git a/crates/ui/src/docking/command.rs b/crates/ui/src/docking/command.rs index 132d8539a7..36b84bb87f 100644 --- a/crates/ui/src/docking/command.rs +++ b/crates/ui/src/docking/command.rs @@ -40,7 +40,7 @@ use crate::layout::SplitSize; /// | `ui.dock` | `{action}`, or `{operation, …}`, see [`DockOperation`] | /// /// `zone` is `tab` (the default for `move` and `dock`), `center`, `left`, `right`, `top`, -/// `bottom`, `above` or `below` (a new group in a dock column or floating stack). The side +/// `bottom`, `above` or `below` (a new group in a dock column, or a split in a floating window). The side /// zones map onto the anchor's container with [`Placement::for_zone`]. `before` /// names the tab to insert before; `null` appends. `group` moves the panel's whole group, /// `column` its dock column. `side` is `Start` or `End`. @@ -369,7 +369,8 @@ impl DockCommand

{ let any = given.iter().any(Option::is_some); let unit = Unit::of(*group, *column); let lone = layout.floating.iter().any(|w| w.contains(panel) && w.panels().count() == 1); - let whole = layout.floating.iter().any(|w| w.contains(panel) && matches!(w.root, super::Node::Tabs { .. } | super::Node::Stack { .. })); + let whole = + layout.floating.iter().any(|w| w.contains(panel) && matches!(w.root, super::Node::Tabs { .. } | super::Node::Stack { .. })); // The rect a drag would float the unit at, inside the area. let placed = || { let docked = layout.location(panel).ok().and_then(|l| l.group).and_then(|g| g.column).map(|c| c.width); diff --git a/crates/ui/src/docking/dock_model.rs b/crates/ui/src/docking/dock_model.rs index 9226bb4f4b..540c35e27e 100644 --- a/crates/ui/src/docking/dock_model.rs +++ b/crates/ui/src/docking/dock_model.rs @@ -264,6 +264,7 @@ pub(super) fn tree_panels

(root: &Node

) -> Vec<&P> { } /// The shown panel of a tree's first group. +#[cfg(feature = "native-windows")] pub(super) fn first_active

(root: &Node

) -> Option<&P> { match leaves(root).into_iter().next()?.0 { Node::Tabs { panels, active } => panels.get(*active), diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index 824809483c..f930aed4ec 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -676,7 +676,10 @@ fn top_edges_resize_from_the_band_above_the_title_bar() { #[test] fn undock_panel_group_floats_one_group_of_a_floating_window() { use egui_kittest::{Harness, kittest::Queryable}; - let stacked = || Layout { root: Some(tabs(&[1], 0)), floating: vec![Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 0)], [300.0, 80.0, 300.0, 400.0])] }; + let stacked = || Layout { + root: Some(tabs(&[1], 0)), + floating: vec![Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 0)], [300.0, 80.0, 300.0, 400.0])], + }; type State = (Content, Layout, Vec>); let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( |ui, (content, layout, actions): &mut State| { diff --git a/crates/ui/src/docking/hits.rs b/crates/ui/src/docking/hits.rs index 28bcf65d18..3e59e02233 100644 --- a/crates/ui/src/docking/hits.rs +++ b/crates/ui/src/docking/hits.rs @@ -66,7 +66,7 @@ pub enum Divider

{ Stack(P), /// [D] The inner edge of the column holding this panel first. Column(P), - /// Below the dock or floating group holding this panel first. + /// Below the dock group holding this panel first. Group(P), /// Where the divider of a split inside another split ends on the outer split's divider, /// by the outer and the inner split's paths. Dragging it moves both dividers. diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index 0a88dc73b0..23efd9eac0 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -1,7 +1,7 @@ use std::{collections::HashSet, fmt, hash::Hash}; use super::dock_model::{ - Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, split_frame, stack_tree, tree_panels, valid_column, + Column, ColumnLocation, Group, GroupLocation, Moving, PanelState, Place, Side, Target, Unit, node_at, split_frame, tree_panels, valid_column, }; use crate::layout::{SplitAxis, SplitSize}; @@ -90,7 +90,7 @@ impl

Floating

{ /// Groups stacked top to bottom, as a v1 layout stored them. #[cfg(test)] pub(crate) fn stack(groups: Vec>, rect: [f32; 4]) -> Self { - Self::new(stack_tree(groups).expect("a group"), rect) + Self::new(super::dock_model::stack_tree(groups).expect("a group"), rect) } /// The window's groups, first to last. @@ -116,7 +116,8 @@ impl

Floating

{ mod floating_serde { use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use super::{Floating, Group, Node, stack_tree}; + use super::{Floating, Group, Node}; + use crate::docking::dock_model::stack_tree; #[derive(Serialize)] struct V1<'a, P> { @@ -204,7 +205,8 @@ pub enum Placement

{ /// along the same axis keeps it: on its outer side the new split wraps the parent, on its /// inner side it halves the parent's other child. Split(Zone), - /// A new group above or below the anchor's group, in a dock column or a floating stack. + /// A new group above or below the anchor's group in a dock column. On an anchor in a + /// floating window, a split of the anchor's group above or below. /// `height` is the inserted group's preferred height ([`super::Group::height`]); `None` /// keeps a moved group's own height, or shares the free height for a new group. Group { @@ -236,7 +238,7 @@ pub struct Location

{ /// rather than accidentally inserting beside only its first leaf when restoring. #[cfg_attr(feature = "serde", serde(default))] pub sibling: Vec

, - /// Group and column state when the panel was in a dock or a floating stack. Applies when + /// Group and column state when the panel was in a dock. Applies when /// restoring creates a new group, column or dock for the panel. #[cfg_attr(feature = "serde", serde(default))] pub group: Option, @@ -273,7 +275,7 @@ pub enum Action

{ anchor: P, placement: Placement

, }, - /// Reposition/resize a floating group, identified by one of its panels. + /// Reposition/resize a floating window, identified by one of its panels. MoveFloating { panel: P, rect: [f32; 4], @@ -327,7 +329,8 @@ pub enum Action

{ CloseOthers { panel: P, }, - /// Minimize a dock or floating group to its tab strip. On an accordion entry, closes it. + /// Minimize a dock group to its tab strip, or the floating window holding the panel to its + /// title bar (and the strip of its only group). On an accordion entry, closes it. SetMinimized { panel: P, minimized: bool, @@ -340,7 +343,7 @@ pub enum Action

{ panel: P, width: f32, }, - /// Preferred height of a dock or floating group, or of an accordion entry. + /// Preferred height of a dock group or of an accordion entry. ResizeGroup { panel: P, height: Option, diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index eb4e4934a9..55336dca13 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -472,11 +472,7 @@ impl Renderer<'_, P> { fn dock_covered(&self, pointer: Pos2, moving: Option<&P>) -> bool { self.blockers.iter().any(|r| r.contains(pointer)) || self.iconic.covers(pointer) - || self - .frame - .windows - .iter() - .any(|window| window.window.contains(pointer) && !moving.is_some_and(|p| window.members.contains(p))) + || self.frame.windows.iter().any(|window| window.window.contains(pointer) && !moving.is_some_and(|p| window.members.contains(p))) } /// Dock targets, with the new-dock bands along the docked area's left and right edges that diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index cabb8cdcc9..96fc112095 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -6,9 +6,7 @@ use super::{DROP_MARGIN, Drawn, Renderer, clamp_float, dock::group_action}; use crate::docking::chrome::drop_preview; use crate::docking::{ Action, Drag, DropProposal, DropRequest, DropTarget, GroupDrag, GroupGesture, Layout, Node, Placement, Target, Zone, cancel_drag, - dock_model::Place, - resolve_drop, - surface::TAB_PADDING, + dock_model::Place, resolve_drop, surface::TAB_PADDING, }; /// Ctrl (Windows, Linux) or Cmd (macOS) held: the drop floats and no target is offered. @@ -259,8 +257,8 @@ impl Renderer<'_, P> { } let float_only = float_only(ctx) || drag.undock; let outside = gone || !ctx.content_rect().contains(pointer); - let empty_drop = self.style.float_on_empty_drop - && (!drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); + let empty_drop = + self.style.float_on_empty_drop && (!drag.source.contains(pointer) || self.layout.floating.iter().any(|g| g.contains(&drag.panel))); let floatable = self.permissions(&drag.panel).floatable && (float_only || outside || empty_drop); let floating_rect = floatable.then(|| self.tab_float_rect(&drag, pointer)); if self.host_drop(ctx, &drag.panel, pointer, false, released, floating_rect) { diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 9ad5e5c512..c94855573a 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -651,10 +651,9 @@ fn the_preview_fills_the_zone_under_the_pointer_and_outlines_the_result() { let timeline = group(&d, TIMELINE); let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0)); // A side band: its trapezoid, and the half the panel takes. - for (zone, at) in [ - (Zone::Left, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)), - (Zone::Bottom, pos2(timeline.center().x, timeline.bottom() - 20.0)), - ] { + for (zone, at) in + [(Zone::Left, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)), (Zone::Bottom, pos2(timeline.center().x, timeline.bottom() - 20.0))] + { let mut d = film(); d.hold(tab(&d, INFO), at); assert!(d.filled_polygon(&zone_shape(timeline, zone).unwrap()), "{zone:?}"); diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 0de4119a0c..2bfdb4dbc4 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -56,8 +56,7 @@ pub struct DockStyle { pub new_dock_zones: bool, /// [D] Height of the bar above each dock column. It drags the column and holds its »/« button. pub column_bar_height: f32, - /// [D] Height of the band around the seam between two stacked groups, in docks and - /// floating windows. + /// [D] Height of the band around the seam between two stacked groups in a dock column. pub seam_band: f32, /// [D] Width of the band along the docked area's left and right edges that makes a new dock. pub new_dock_band: f32, From 01ce7162a48dfca1026ea4e0da26afcb312564d6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 06:11:03 +0000 Subject: [PATCH 88/94] docking: Floating::stack is public, and four-way handles take the pointer only Floating::stack builds a window from groups stacked top to bottom, so an app's own stacked layouts migrate without building the split chain. The four-way handle no longer takes keyboard focus: it has no label or key action, and the two dividers it joins take arrow keys. --- crates/ui/src/docking/floating_tests.rs | 4 ++-- crates/ui/src/docking/group_tests.rs | 2 +- crates/ui/src/docking/iconic_tests.rs | 2 +- crates/ui/src/docking/model.rs | 8 ++++---- crates/ui/src/docking/model_tests.rs | 6 +++--- crates/ui/src/docking/render/mod.rs | 3 ++- docs/ui-docking.md | 5 +++-- 7 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/ui/src/docking/floating_tests.rs b/crates/ui/src/docking/floating_tests.rs index f930aed4ec..9217965e5d 100644 --- a/crates/ui/src/docking/floating_tests.rs +++ b/crates/ui/src/docking/floating_tests.rs @@ -38,7 +38,7 @@ fn workspace() -> Layout { second: Box::new(tabs(&[0], 0)), }), floating: vec![ - Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [300.0, 80.0, 240.0, 300.0]), + Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [300.0, 80.0, 240.0, 300.0]).unwrap(), Floating::single(vec![8], 0, [560.0, 300.0, 200.0, 200.0]), ], } @@ -678,7 +678,7 @@ fn undock_panel_group_floats_one_group_of_a_floating_window() { use egui_kittest::{Harness, kittest::Queryable}; let stacked = || Layout { root: Some(tabs(&[1], 0)), - floating: vec![Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 0)], [300.0, 80.0, 300.0, 400.0])], + floating: vec![Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 0)], [300.0, 80.0, 300.0, 400.0]).unwrap()], }; type State = (Content, Layout, Vec>); let mut h = Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( diff --git a/crates/ui/src/docking/group_tests.rs b/crates/ui/src/docking/group_tests.rs index a11e279608..f6027aed36 100644 --- a/crates/ui/src/docking/group_tests.rs +++ b/crates/ui/src/docking/group_tests.rs @@ -551,7 +551,7 @@ fn drag_bar_menu_has_the_group_items_and_opens_from_the_keyboard() { #[test] fn a_group_dragged_out_of_a_floating_stack_tears_out_alone() { - let stack = Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [80.0, 70.0, 300.0, 400.0]); + let stack = Floating::stack(vec![Group::new(vec![5], 0), Group::new(vec![6, 7], 1)], [80.0, 70.0, 300.0, 400.0]).unwrap(); let layout = Layout { root: Some(tabs(&[1], 0)), floating: vec![stack] }; let mut d = Driver::new(layout); let from = d.rect("drag-bar", 6).center(); diff --git a/crates/ui/src/docking/iconic_tests.rs b/crates/ui/src/docking/iconic_tests.rs index bc946daf9e..c648e43ef7 100644 --- a/crates/ui/src/docking/iconic_tests.rs +++ b/crates/ui/src/docking/iconic_tests.rs @@ -283,7 +283,7 @@ fn hit_rects_cover_every_gesture_source() { first: Box::new(Node::Tabs { panels: vec![0], active: 0 }), second: Box::new(stack), }; - let window = Floating::stack(vec![Group::new(vec![12], 0), Group::new(vec![13], 0)], [500.0, 60.0, 220.0, 300.0]); + let window = Floating::stack(vec![Group::new(vec![12], 0), Group::new(vec![13], 0)], [500.0, 60.0, 220.0, 300.0]).unwrap(); let layout = Layout { root: Some(Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(200.0), first: Box::new(dock), second: Box::new(frames) }), floating: vec![window], diff --git a/crates/ui/src/docking/model.rs b/crates/ui/src/docking/model.rs index e11a0417c1..ec4cb13722 100644 --- a/crates/ui/src/docking/model.rs +++ b/crates/ui/src/docking/model.rs @@ -87,10 +87,10 @@ impl

Floating

{ tree_panels(&self.root).into_iter() } - /// Groups stacked top to bottom, as a v1 layout stored them. - #[cfg(test)] - pub(crate) fn stack(groups: Vec>, rect: [f32; 4]) -> Self { - Self::new(super::dock_model::stack_tree(groups).expect("a group"), rect) + /// Groups stacked top to bottom, as a v1 layout stored them: each group over a vertical + /// split of the ones below it, sized by their heights. `None` without groups. + pub fn stack(groups: Vec>, rect: [f32; 4]) -> Option { + super::dock_model::stack_tree(groups).map(|root| Self::new(root, rect)) } /// The window's groups, first to last. diff --git a/crates/ui/src/docking/model_tests.rs b/crates/ui/src/docking/model_tests.rs index 583a2dd98a..11f3fcde78 100644 --- a/crates/ui/src/docking/model_tests.rs +++ b/crates/ui/src/docking/model_tests.rs @@ -23,7 +23,7 @@ pub(super) fn docked() -> Layout { Node::Dock { side: Side::End, columns: vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)], 180.0), Column::new(vec![g(&[5], 0)], 120.0)] }; Layout { root: Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), - floating: vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], [100.0, 100.0, 300.0, 400.0])], + floating: vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], [100.0, 100.0, 300.0, 400.0]).unwrap()], } } @@ -213,7 +213,7 @@ fn restore_into_a_column_group_seam_and_new_column_round_trips() { let start = Node::Dock { side: Side::Start, columns: vec![Column::new(vec![g(&[10], 0)], 200.0)] }; let original = Layout { root: Some(hsplit(SplitSize::FixedFirst(200.0), start, hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end))), - floating: vec![Floating::stack(vec![g(&[6], 0), Group { height: Some(90.0), ..g(&[7], 0) }], [10.0, 10.0, 200.0, 300.0])], + floating: vec![Floating::stack(vec![g(&[6], 0), Group { height: Some(90.0), ..g(&[7], 0) }], [10.0, 10.0, 200.0, 300.0]).unwrap()], }; original.validate().unwrap(); // 4: the seam between [2, 3] and [9]; 9: below [4]; 5: a new column after A; 10: alone in @@ -415,7 +415,7 @@ mod serde_tests { let plain = Floating::single(vec![4u32, 5], 1, rect); assert_eq!(serde_json::to_value(&plain).unwrap(), json!({"panels": [4, 5], "active": 1, "rect": rect})); let minimized = Floating { minimized: true, ..Floating::single(vec![4u32], 0, rect) }; - let stacked = Floating::stack(vec![g(&[4], 0), g(&[5], 0)], rect); + let stacked = Floating::stack(vec![g(&[4], 0), g(&[5], 0)], rect).unwrap(); let native = Floating { native: Some(rect), ..Floating::single(vec![4u32], 0, rect) }; for window in [minimized, stacked, native] { let value = serde_json::to_value(&window).unwrap(); diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index fc8fd3d448..f4fbf37ef7 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -295,7 +295,8 @@ impl Renderer<'_, P> { None => self.id.with(("intersection", outer, inner_layout)), Some((panel, _)) => self.id.with(("window-intersection", panel, outer, inner_layout)), }; - let response = ui.interact(hit, id, Sense::drag()); + // Pointer only: each of the two dividers it joins already takes keyboard focus. + let response = ui.interact(hit, id, Sense::DRAG); self.register_interaction(ui.ctx(), id); if response.hovered() || response.dragged() { ui.ctx().set_cursor_icon(CursorIcon::Move); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index adaec4abb4..177c1c2de5 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -39,8 +39,9 @@ their sides. A `Floating` window holds a tree like the docked layout's (`root`: splits, tab groups and accordions, no docks), a rect, an optional native-window rect and `minimized`. -`Floating::single` makes a window with one group and `Floating::new` one with a tree; `panels()` -and `contains()` read it. Saved layouts keep loading: a window stored as one group (v1) or as a +`Floating::single` makes a window with one group, `Floating::new` one with a tree, and +`Floating::stack` one with groups stacked top to bottom (a vertical split sized by the groups' +heights, as an app's own stacked layouts migrate); `panels()` and `contains()` read it. Saved layouts keep loading: a window stored as one group (v1) or as a stack of groups loads as that group or as a vertical split of the stacked groups, sized by their heights. From 53947dbfe8602f8c31e001ea2396cc147fa9d983 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 16:35:35 +0000 Subject: [PATCH 89/94] docking: the undock hint test expects the platform's key --- crates/ui/src/docking/split_tests.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index c94855573a..e87ed44fa1 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -439,7 +439,9 @@ fn random_drops_leave_every_group_its_minimum_and_every_divider_travel() { #[test] fn ctrl_or_cmd_floats_from_a_tab_or_a_drag_bar_and_the_preview_says_so() { - const HINT: &str = "Hold Ctrl to undock"; + // The hint names the platform's key, as `ctx.os()` reports it in tests. + let key = if egui::os::OperatingSystem::from_target_os() == egui::os::OperatingSystem::Mac { "⌘" } else { "Ctrl" }; + let hint = format!("Hold {key} to undock"); let floated = |actions: &[Action], panel: u32| match actions { [Action::Float { panel: p, .. }] => *p == panel, [Action::MoveGroup { panel: p, to: Target::Float { .. } }] => *p == panel, @@ -465,14 +467,14 @@ fn ctrl_or_cmd_floats_from_a_tab_or_a_drag_bar_and_the_preview_says_so() { // Without the modifier, a release over a group docks there; the preview names the modifier. let mut d = film(); d.hold(from, over); - assert!(texts(&d).iter().any(|t| t == HINT), "{from:?}: {:?}", texts(&d)); + assert!(texts(&d).iter().any(|t| *t == hint), "{from:?}: {:?}", texts(&d)); let out = d.release(over); assert!(!out.actions.is_empty() && !floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); // Held, it floats, and the hint is gone. let mut d = film(); d.modifiers = Modifiers::COMMAND; d.hold(from, over); - assert!(!texts(&d).iter().any(|t| t == HINT), "{from:?}"); + assert!(!texts(&d).iter().any(|t| *t == hint), "{from:?}"); let out = d.release(over); assert!(floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); } From e350bfdb0174870fe1460981e43b76ed6479bea1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 16:40:17 +0000 Subject: [PATCH 90/94] docking: the undock hint test uses contains, as clippy asks --- crates/ui/src/docking/split_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index e87ed44fa1..69048efd11 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -467,14 +467,14 @@ fn ctrl_or_cmd_floats_from_a_tab_or_a_drag_bar_and_the_preview_says_so() { // Without the modifier, a release over a group docks there; the preview names the modifier. let mut d = film(); d.hold(from, over); - assert!(texts(&d).iter().any(|t| *t == hint), "{from:?}: {:?}", texts(&d)); + assert!(texts(&d).contains(&hint), "{from:?}: {:?}", texts(&d)); let out = d.release(over); assert!(!out.actions.is_empty() && !floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); // Held, it floats, and the hint is gone. let mut d = film(); d.modifiers = Modifiers::COMMAND; d.hold(from, over); - assert!(!texts(&d).iter().any(|t| *t == hint), "{from:?}"); + assert!(!texts(&d).contains(&hint), "{from:?}"); let out = d.release(over); assert!(floated(&out.actions, PROJECT[0]), "{from:?}: {:?}", out.actions); } From e6c76f51517d0bff2bd479faf1c64b6e11f5afae Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 23:57:43 +0000 Subject: [PATCH 91/94] docking: drop zones are 40 pt bands below the tab strip, all outlined while dragging A frame's side zones reach DockStyle::zone_depth (40 pt) into the body below the tab strip, or a third of a smaller body, so a frame keeps its center. drop_zone, zone_shape and resolve_drop take the depth. In the Frame style a drag over a frame outlines every zone a drop there would change something in and fills the one under the pointer, without the outline of the resulting rect. --- crates/ui/src/docking/render/preview.rs | 161 +++++++++++++++++------- crates/ui/src/docking/split_tests.rs | 122 +++++++++++++++--- crates/ui/src/docking/surface.rs | 6 + crates/ui/src/docking/targets.rs | 97 ++++++++------ crates/ui/src/docking/tests.rs | 59 ++++++--- crates/ui/src/docking/trial_tests.rs | 2 +- docs/ui-docking.md | 15 ++- 7 files changed, 345 insertions(+), 117 deletions(-) diff --git a/crates/ui/src/docking/render/preview.rs b/crates/ui/src/docking/render/preview.rs index 96fc112095..33f234cb36 100644 --- a/crates/ui/src/docking/render/preview.rs +++ b/crates/ui/src/docking/render/preview.rs @@ -82,17 +82,25 @@ impl Renderer<'_, P> { /// moving live looks through itself and does not split frames or join a body's center. pub(super) fn group_proposal(&self, drag: &GroupDrag

, pointer: Pos2) -> Option> { let window = drag.gesture == GroupGesture::Window; - let valid = |proposal: DropProposal

| { - let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; - (proposal.noop || self.layout.clone().apply_with_permissions(group_action(drag, to), |p| self.permissions(p)).is_ok()).then_some(proposal) - }; if let Some(proposal) = self.extra_proposal(&drag.members, pointer, window) { - return valid(proposal); + return self.valid_group(drag, proposal); } - let own = |t: &crate::docking::DropTarget

| t.tabs.iter().any(|(p, _)| drag.members.contains(p)); - let target = - self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer) && !(window && own(t)))?; - if own(target) { + let target = self.group_target(drag, pointer)?; + self.group_proposal_at(drag, pointer, target) + } + + /// The group under the pointer that a group drag addresses. A window moving live looks + /// through itself. + fn group_target(&self, drag: &GroupDrag

, pointer: Pos2) -> Option<&DropTarget

> { + let window = drag.gesture == GroupGesture::Window; + let own = |t: &DropTarget

| t.tabs.iter().any(|(p, _)| drag.members.contains(p)); + self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer) && !(window && own(t))) + } + + /// [`Self::group_proposal`] on `target` alone. + fn group_proposal_at(&self, drag: &GroupDrag

, pointer: Pos2, target: &DropTarget

) -> Option> { + let window = drag.gesture == GroupGesture::Window; + if target.tabs.iter().any(|(p, _)| drag.members.contains(p)) { return Some(DropProposal { anchor: drag.panel.clone(), placement: Placement::Tab { before: None }, @@ -107,13 +115,19 @@ impl Renderer<'_, P> { if window && !into_window && matches!(proposal.placement, Placement::Split(_)) { return None; } - valid(proposal) + self.valid_group(drag, proposal) + } + + /// `proposal` when it is a no-op or the model takes it for the whole group. + fn valid_group(&self, drag: &GroupDrag

, proposal: DropProposal

) -> Option> { + let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; + (proposal.noop || self.layout.clone().apply_with_permissions(group_action(drag, to), |p| self.permissions(p)).is_ok()).then_some(proposal) } /// [`resolve_drop`], where a split that would leave a group without room becomes a join /// of the target group. fn resolve_roomy(&self, panel: &P, pointer: Pos2, targets: &[DropTarget

], action: impl Fn(Target

) -> Action

) -> Option> { - let proposal = resolve_drop(panel, pointer, targets)?; + let proposal = resolve_drop(panel, pointer, targets, self.style.zone_depth)?; if !matches!(proposal.placement, Placement::Split(zone) if zone != Zone::Center) { return Some(proposal); } @@ -121,7 +135,7 @@ impl Renderer<'_, P> { return Some(proposal); } let target = targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer))?; - resolve_drop(panel, pointer, std::slice::from_ref(&DropTarget { allow_splits: false, ..target.clone() })) + resolve_drop(panel, pointer, std::slice::from_ref(&DropTarget { allow_splits: false, ..target.clone() }), self.style.zone_depth) } /// Whether `action`, a drop that splits a group or the outer edge, leaves room: every group @@ -216,9 +230,11 @@ impl Renderer<'_, P> { } return; } - if let Some(proposal) = self.group_proposal(drag, pointer).filter(|p| !p.noop) { + let proposal = self.group_proposal(drag, pointer).filter(|p| !p.noop); + let zones = self.paint_group_zones(&painter, drag, pointer, proposal.as_ref()); + if let Some(proposal) = proposal { let split = matches!(proposal.placement, Placement::Split(zone) | Placement::Edge(zone) if zone != Zone::Center); - if crate::docking::targets::usable(proposal.preview) && !self.paint_zone(&painter, &proposal, pointer) { + if crate::docking::targets::usable(proposal.preview) && !zones { drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, split); } if let Some(marker) = proposal.insertion { @@ -281,17 +297,7 @@ impl Renderer<'_, P> { } return; } - let proposal = if float_only { - None - } else { - self.extra_proposal(std::slice::from_ref(&drag.panel), pointer, false).or_else(|| { - let panel = &drag.panel; - self.resolve_roomy(panel, pointer, &self.targets, |to| match to { - Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, - to => Action::MovePanel { panel: panel.clone(), to }, - }) - }) - }; + let proposal = if float_only { None } else { self.tab_proposal(&drag.panel, pointer) }; if released { cancel_drag::

(ctx, self.id); if pointer.distance(drag.origin) < 2.0 || proposal.as_ref().is_some_and(|proposal| proposal.noop && !outside) { @@ -316,11 +322,12 @@ impl Renderer<'_, P> { return; } let painter = self.preview_painter(ctx); + let zones = !float_only && self.paint_tab_zones(&painter, &drag.panel, pointer, proposal.as_ref()); if let Some(proposal) = proposal { // Reordering inside the source strip shows only the insertion line. let same_group = proposal.insertion.is_some() && self.targets.iter().any(|target| target.rect == proposal.preview && target.tabs.iter().any(|(panel, _)| panel == &drag.panel)); - if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) && !self.paint_zone(&painter, &proposal, pointer) { + if !same_group && !proposal.noop && crate::docking::targets::usable(proposal.preview) && !zones { drop_preview(&painter, proposal.preview.shrink(1.0), self.style.accent, true); } if let Some(marker) = proposal.insertion { @@ -334,26 +341,92 @@ impl Renderer<'_, P> { } } - /// With [`crate::docking::DockStyle::side_edge_zones`], a drop on a group shows the zone - /// under the pointer (a side's trapezoid, or the center rectangle with the tab strip) - /// filled, and the rect the drop gives what moves outlined. False when it painted nothing. - fn paint_zone(&self, painter: &egui::Painter, proposal: &DropProposal

, pointer: Pos2) -> bool { - let zone = match proposal.placement { - Placement::Split(zone) => zone, - Placement::Tab { .. } => Zone::Center, - _ => return false, + /// The group target a single tab drag would take at `pointer`. + pub(super) fn tab_proposal(&self, panel: &P, pointer: Pos2) -> Option> { + self.extra_proposal(std::slice::from_ref(panel), pointer, false).or_else(|| { + self.resolve_roomy(panel, pointer, &self.targets, |to| match to { + Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, + to => Action::MovePanel { panel: panel.clone(), to }, + }) + }) + } + + /// [`Self::paint_zones`] for a tab drag of `panel`. The center of the group holding the panel + /// is not a target: a drop there reorders or changes nothing. + pub(super) fn paint_tab_zones(&self, painter: &egui::Painter, panel: &P, pointer: Pos2, proposal: Option<&DropProposal

>) -> bool { + if !self.style.side_edge_zones || self.extra_proposal(std::slice::from_ref(panel), pointer, false).is_some() { + return false; + } + let Some(target) = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer)) else { + return false; }; - let target = self.targets.iter().rev().find(|t| crate::docking::targets::usable(t.rect) && t.rect.contains(pointer)); - let (Some(target), true) = (target, self.style.side_edge_zones) else { return false }; - let Some(points) = crate::docking::targets::zone_shape(target.rect, zone) else { return false }; - let fill = self.style.accent.gamma_multiply(0.25); - painter.add(egui::Shape::convex_polygon(points, fill, egui::Stroke::NONE)); - if zone == Zone::Center - && let Some(strip) = target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|r| crate::docking::targets::usable(*r)) - { - painter.rect_filled(strip, 0.0, fill); + let own = target.tabs.iter().any(|(p, _)| p == panel); + let at = |at: Pos2| { + let move_to = |to| match to { + Target::At { anchor, placement } => Action::Move { panel: panel.clone(), anchor, placement }, + to => Action::MovePanel { panel: panel.clone(), to }, + }; + let proposal = self.resolve_roomy(panel, at, std::slice::from_ref(target), move_to)?; + let to = Target::At { anchor: proposal.anchor.clone(), placement: proposal.placement.clone() }; + let joins = matches!(proposal.placement, Placement::Tab { .. } | Placement::Split(Zone::Center)); + (!(own && joins) && self.layout.clone().apply_with_permissions(move_to(to), |p| self.permissions(p)).is_ok()).then_some(proposal) + }; + self.paint_zones(painter, target, proposal, at) + } + + /// [`Self::paint_zones`] for a group drag. + pub(super) fn paint_group_zones(&self, painter: &egui::Painter, drag: &GroupDrag

, pointer: Pos2, proposal: Option<&DropProposal

>) -> bool { + let window = drag.gesture == GroupGesture::Window; + if !self.style.side_edge_zones || self.extra_proposal(&drag.members, pointer, window).is_some() { + return false; + } + let Some(target) = self.group_target(drag, pointer) else { return false }; + self.paint_zones(painter, target, proposal, |at| self.group_proposal_at(drag, at, target)) + } + + /// With [`crate::docking::DockStyle::side_edge_zones`], a drag over a group outlines each + /// of its drop zones that a drop would change something in (a side's trapezoid, the center + /// rectangle, the tab strip as part of the center) and fills the zone of `proposal`, the + /// drop under the pointer. `at` is the drop a point of `target` would get. False when it + /// painted nothing. + fn paint_zones( + &self, + painter: &egui::Painter, + target: &DropTarget

, + proposal: Option<&DropProposal

>, + at: impl Fn(Pos2) -> Option>, + ) -> bool { + use crate::docking::targets::{header_height, usable, zone_shape}; + let zone_of = |proposal: &DropProposal

| match proposal.placement { + _ if proposal.noop => None, + Placement::Split(zone) => Some(zone), + Placement::Tab { .. } => Some(Zone::Center), + _ => None, + }; + let header = header_height(target); + let centroid = |points: &[Pos2]| points.iter().fold(Vec2::ZERO, |sum, p| sum + p.to_vec2()) / points.len() as f32; + let takes = |zone: Zone, point: Pos2| at(point).as_ref().and_then(zone_of) == Some(zone); + let mut shapes: Vec<(Zone, Vec)> = [Zone::Left, Zone::Right, Zone::Top, Zone::Bottom, Zone::Center] + .into_iter() + .filter_map(|zone| Some((zone, zone_shape(target.rect, header, self.style.zone_depth, zone)?))) + .filter(|(zone, points)| takes(*zone, centroid(points).to_pos2())) + .collect(); + let strip = target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|strip| usable(*strip) && takes(Zone::Center, strip.center())); + if let Some(strip) = strip { + shapes.push((Zone::Center, vec![strip.left_top(), strip.right_top(), strip.right_bottom(), strip.left_bottom()])); + } + if shapes.is_empty() { + return false; + } + let hovered = proposal.and_then(zone_of); + let fill = self.style.accent.gamma_multiply(0.3); + for (_, points) in shapes.iter().filter(|(zone, _)| Some(*zone) == hovered) { + painter.add(egui::Shape::convex_polygon(points.clone(), fill, egui::Stroke::NONE)); + } + let stroke = egui::Stroke::new(1.0, self.style.accent.gamma_multiply(0.6)); + for (_, points) in shapes { + painter.add(egui::Shape::closed_line(points, stroke)); } - drop_preview(painter, proposal.preview.shrink(1.0), self.style.accent, false); true } diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 69048efd11..3c7c1c455d 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -23,11 +23,13 @@ const INFO: u32 = 9; const SCREEN: Vec2 = Vec2::new(1440.0, 860.0); -/// Panel bodies by their rects; `caps` are maximum widths a host asks for. +/// Panel bodies by their rects; `caps` are maximum widths a host asks for, `rules` the +/// permissions of panels that differ from the default. #[derive(Default)] struct Film { bodies: HashMap, caps: HashMap, + rules: HashMap, } impl DockContent for Film { @@ -43,6 +45,9 @@ impl DockContent for Film { None => PanelLimits::default(), } } + fn permissions(&self, panel: &u32) -> Permissions { + self.rules.get(panel).copied().unwrap_or_default() + } } type Driver = DockDriver; @@ -117,8 +122,9 @@ fn a_group_is_a_picture_frame_whose_edges_split_it_in_half_and_whose_middle_join let base = film(); let timeline = group(&base, TIMELINE); let others = [PROJECT[0], TOOLS, METERS, SOURCE[0], PROGRAM, PROPERTIES[0]]; + // Halfway into each 40 pt band of the body below the tab strip. let inset = |zone| { - let (w, h) = (timeline.width() * 0.08, (timeline.height() - 26.0) * 0.08); + let (w, h) = (20.0, 20.0); match zone { Zone::Left => pos2(timeline.left() + w, timeline.center().y + 13.0), Zone::Right => pos2(timeline.right() - w, timeline.center().y + 13.0), @@ -132,8 +138,7 @@ fn a_group_is_a_picture_frame_whose_edges_split_it_in_half_and_whose_middle_join let before = sizes(&d, &others); let at = inset(zone); d.hold(tab(&d, INFO), at); - let half = zone_rect(timeline, zone).unwrap(); - assert!(d.outlined(half.shrink(1.0)), "{zone:?}: the preview outlines that half of the group"); + assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, zone).unwrap()), "{zone:?}: the preview fills that band"); let out = d.release(at); assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TIMELINE, placement: Placement::Split(zone) }], "{zone:?}"); d.settle(); @@ -275,7 +280,7 @@ fn a_drop_beside_a_narrow_group_splits_that_group_only() { assert!(tools.width() > 120.0, "{tools:?}"); let at = pos2(tools.right() - 8.0, tools.center().y + 13.0); d.hold(tab(&d, INFO), at); - assert!(d.outlined(zone_rect(tools, Zone::Right).unwrap().shrink(1.0)), "the preview outlines Tools' right half"); + assert!(d.filled_polygon(&zone_shape(tools, 26.0, 40.0, Zone::Right).unwrap()), "the preview fills Tools' right band"); let out = d.release(at); assert_eq!(out.actions, vec![Action::Move { panel: INFO, anchor: TOOLS, placement: Placement::Split(Zone::Right) }]); d.settle(); @@ -647,35 +652,57 @@ fn a_closed_floating_window_closes_its_panels_and_each_reopens_where_it_was() { assert_eq!((&window.root, window.rect), (&tree, [700.0, 100.0, 600.0, 400.0])); } +/// The zone outlines of the last frame: closed 1 pt paths without a fill. +fn zone_outlines(d: &Driver) -> Vec> { + d.shapes() + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Path(path) if path.closed && path.fill == egui::Color32::TRANSPARENT && path.stroke.width == 1.0 => { + Some(path.points.clone()) + } + _ => None, + }) + .collect() +} + +fn same_polygon(a: &[Pos2], b: &[Pos2]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.distance(*b) <= 0.5) +} + +fn corners(rect: Rect) -> Vec { + vec![rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()] +} + #[test] -fn the_preview_fills_the_zone_under_the_pointer_and_outlines_the_result() { +fn the_preview_fills_the_zone_under_the_pointer_and_no_result_rect() { let d = film(); let timeline = group(&d, TIMELINE); let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0)); - // A side band: its trapezoid, and the half the panel takes. + // A side band: its trapezoid, without the half the panel takes. for (zone, at) in [(Zone::Left, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)), (Zone::Bottom, pos2(timeline.center().x, timeline.bottom() - 20.0))] { let mut d = film(); d.hold(tab(&d, INFO), at); - assert!(d.filled_polygon(&zone_shape(timeline, zone).unwrap()), "{zone:?}"); - assert!(d.outlined(zone_rect(timeline, zone).unwrap().shrink(1.0)), "{zone:?}"); + assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, zone).unwrap()), "{zone:?}"); + assert!(!d.outlined(zone_rect(timeline, zone).unwrap().shrink(1.0)), "{zone:?}"); d.key(egui::Key::Escape); } - // The middle and the tab row: the center rectangle and the strip, and the whole group. + // The middle and the tab row: the center rectangle and the strip. for at in [timeline.center() + vec2(0.0, 13.0), strip.center()] { let mut d = film(); d.hold(tab(&d, INFO), at); - assert!(d.filled_polygon(&zone_shape(timeline, Zone::Center).unwrap()), "{at:?}"); - assert!(d.filled(strip), "{at:?}"); - assert!(d.outlined(timeline.shrink(1.0)), "{at:?}"); + assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, Zone::Center).unwrap()), "{at:?}"); + assert!(d.filled_polygon(&corners(strip)), "{at:?}"); + assert!(!d.outlined(timeline.shrink(1.0)), "{at:?}"); d.key(egui::Key::Escape); } // A group's drag bar shows the same. let mut d = film(); let bar = d.hit(&Hit::DragBar(PROJECT[0])).unwrap().center(); d.hold(bar, pos2(timeline.left() + 8.0, timeline.center().y + 13.0)); - assert!(d.filled_polygon(&zone_shape(timeline, Zone::Left).unwrap())); + assert!(d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, Zone::Left).unwrap())); + assert_eq!(zone_outlines(&d).len(), 6); d.key(egui::Key::Escape); // The dock-and-canvas arrangement keeps its filled half. @@ -684,6 +711,71 @@ fn the_preview_fills_the_zone_under_the_pointer_and_outlines_the_result() { d.area = d.screen; d.settle(); d.hold(tab(&d, INFO), pos2(timeline.left() + 8.0, timeline.center().y + 13.0)); - assert!(!d.filled_polygon(&zone_shape(timeline, Zone::Left).unwrap())); + assert!(!d.filled_polygon(&zone_shape(timeline, 26.0, 40.0, Zone::Left).unwrap())); + assert!(zone_outlines(&d).is_empty()); assert!(d.filled(zone_rect(timeline, Zone::Left).unwrap().shrink(1.0))); } + +#[test] +fn a_drag_over_a_group_outlines_all_its_zones_and_fills_the_one_drop_zone_names() { + let d = film(); + let timeline = group(&d, TIMELINE); + let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0)); + let shape = |zone| zone_shape(timeline, 26.0, 40.0, zone).unwrap(); + let all: Vec> = + [Zone::Left, Zone::Right, Zone::Top, Zone::Bottom, Zone::Center].map(shape).into_iter().chain([corners(strip)]).collect(); + let body = Rect::from_min_max(pos2(timeline.left(), strip.bottom()), timeline.max); + // Each band, near its corners too, the middle, and the tab row. + let points = [ + pos2(body.left() + 30.0, body.center().y), + pos2(body.left() + 30.0, body.top() + 34.0), + pos2(body.right() - 2.0, body.bottom() - 12.0), + pos2(body.center().x, body.top() + 5.0), + pos2(body.left() + 50.0, body.bottom() - 30.0), + body.center(), + pos2(body.left() + 45.0, body.top() + 45.0), + strip.center(), + ]; + for at in points { + let mut d = film(); + d.hold(tab(&d, INFO), at); + let outlines = zone_outlines(&d); + assert_eq!(outlines.len(), all.len(), "{at:?}: four sides, the center and the strip"); + assert!(all.iter().all(|zone| outlines.iter().any(|o| same_polygon(o, zone))), "{at:?}: only Timeline's zones"); + let zone = drop_zone(timeline, 26.0, 40.0, at).unwrap(); + assert!(d.filled_polygon(&shape(zone)), "{at:?}: {zone:?} is filled"); + let filled = all.iter().filter(|z| d.filled_polygon(z)).count(); + assert_eq!(filled, if zone == Zone::Center { 2 } else { 1 }, "{at:?}: only {zone:?}"); + d.key(egui::Key::Escape); + } +} + +#[test] +fn zones_a_group_does_not_take_are_not_drawn() { + let timeline = group(&film(), TIMELINE); + let strip = Rect::from_min_size(timeline.min, vec2(timeline.width(), 26.0)); + let shape = |zone| zone_shape(timeline, 26.0, 40.0, zone).unwrap(); + let at = pos2(timeline.left() + 8.0, timeline.center().y + 13.0); + let content = |rules: Permissions| Film { rules: HashMap::from([(TIMELINE, rules)]), ..Film::default() }; + // No splits: the center and the strip only, and the left band under the pointer neither + // outlined nor filled. + let mut d = driver(editing(), content(Permissions { accepts_splits: false, ..Permissions::default() })); + d.hold(tab(&d, INFO), at); + let outlines = zone_outlines(&d); + assert_eq!(outlines.len(), 2, "{outlines:?}"); + assert!(outlines.iter().any(|o| same_polygon(o, &shape(Zone::Center))) && outlines.iter().any(|o| same_polygon(o, &corners(strip)))); + assert!(!d.filled_polygon(&shape(Zone::Left))); + d.key(egui::Key::Escape); + // No tabs: the four sides only. + let mut d = driver(editing(), content(Permissions { accepts_tabs: false, ..Permissions::default() })); + d.hold(tab(&d, INFO), at); + let outlines = zone_outlines(&d); + assert_eq!(outlines.len(), 4, "{outlines:?}"); + assert!([Zone::Left, Zone::Right, Zone::Top, Zone::Bottom].into_iter().all(|z| outlines.iter().any(|o| same_polygon(o, &shape(z))))); + assert!(d.filled_polygon(&shape(Zone::Left))); + d.key(egui::Key::Escape); + // A tab over its own single-tab group: nothing to drop on. + let mut d = film(); + d.hold(tab(&d, TIMELINE), timeline.center() + vec2(0.0, 13.0)); + assert!(zone_outlines(&d).is_empty()); +} diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 2bfdb4dbc4..1deff02051 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -51,6 +51,10 @@ pub struct DockStyle { /// The outer edge band also runs along the left and right edges, where a drop adds a /// full-height column. Off: only the top and bottom edges add a full-width row. pub side_edge_zones: bool, + /// How far a group's side drop zones reach into its body, below the tab strip. A body less + /// than three times as wide or tall gets zones a third of its extent deep in that axis, so + /// it keeps a center. + pub zone_depth: f32, /// [D] The docked area's left and right edges, where no dock is yet, take a drop as a new /// dock (see [`Self::new_dock_band`]). pub new_dock_zones: bool, @@ -163,6 +167,7 @@ impl DockStyle { title_height: super::chrome::TITLE_HEIGHT, edge_band: 8.0, side_edge_zones: false, + zone_depth: 40.0, new_dock_zones: true, column_bar_height: 14.0, seam_band: 8.0, @@ -209,6 +214,7 @@ impl DockStyle { self.floating_stroke.width, self.title_height, self.edge_band, + self.zone_depth, self.column_bar_height, self.seam_band, self.new_dock_band, diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index 7a816f1a97..89e235e0bc 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -31,55 +31,80 @@ pub(super) fn usable(rect: Rect) -> bool { rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0 && rect.width() <= 1_000_000.0 && rect.height() <= 1_000_000.0 } -/// Least depth of a side zone, so a narrow frame such as a tool strip keeps side targets wide -/// enough to hit. -const MIN_SIDE_ZONE: f32 = 32.0; - -/// Tab header is the center; otherwise the nearest side zone wins. A side zone is a quarter of -/// the frame deep, at least 32 pt and at most half the frame, so a frame up to 64 pt wide has no -/// center. Outside, non-finite, empty and inverted rectangles have no target. -pub fn drop_zone(rect: Rect, tab_height: f32, pointer: Pos2) -> Option { +/// Tab header (the top `tab_height` of `rect`) is the center; otherwise the nearest side zone of +/// the body below it wins. A side zone reaches `depth` into the body, or a third of the body's +/// extent in that axis when that is less, so a body always keeps a center; a `depth` of zero +/// or less leaves only the center. Outside, non-finite, empty and inverted rectangles have no +/// target. +pub fn drop_zone(rect: Rect, tab_height: f32, depth: f32, pointer: Pos2) -> Option { if !usable(rect) || !pointer.is_finite() || !rect.contains(pointer) || !tab_height.is_finite() || tab_height < 0.0 { return None; } - if pointer.y < rect.top() + tab_height.min(rect.height()) { + let body = body(rect, tab_height); + if pointer.y < body.top() || !usable(body) { return Some(Zone::Center); } - let Vec2 { x, y } = side_depths(rect); - let distances = [ - ((pointer.x - rect.left()) / x, Zone::Left), - ((rect.right() - pointer.x) / x, Zone::Right), - ((pointer.y - rect.top()) / y, Zone::Top), - ((rect.bottom() - pointer.y) / y, Zone::Bottom), + let Vec2 { x, y } = side_depths(body, depth); + let sides = [ + (pointer.x - body.left(), x, Zone::Left), + (body.right() - pointer.x, x, Zone::Right), + (pointer.y - body.top(), y, Zone::Top), + (body.bottom() - pointer.y, y, Zone::Bottom), ]; - let (distance, zone) = distances.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?; - Some(if distance > 1.0 { Zone::Center } else { zone }) + let nearest = + sides.into_iter().filter(|(_, depth, _)| *depth > 0.0).map(|(gap, depth, zone)| (gap / depth, zone)).min_by(|a, b| a.0.total_cmp(&b.0)); + Some(match nearest { + Some((distance, zone)) if distance <= 1.0 => zone, + _ => Zone::Center, + }) } -/// How deep the side zones of a group drawn at `rect` reach in from its left and right edges -/// (`x`) and its top and bottom edges (`y`). -fn side_depths(rect: Rect) -> Vec2 { - let depth = |extent: f32| (extent * 0.25).max(MIN_SIDE_ZONE).min(extent * 0.5); - vec2(depth(rect.width()), depth(rect.height())) +/// The part of a group drawn at `rect` below its tab header. +fn body(rect: Rect, tab_height: f32) -> Rect { + Rect::from_min_max(pos2(rect.left(), rect.top() + tab_height.min(rect.height())), rect.max) } -/// The outline of a drop zone of the group drawn at `rect`, as [`drop_zone`] finds it: a side's -/// trapezoid (its outer edge the whole side, its inner edge on the center rectangle), or the -/// center rectangle. The tab strip is a grouping zone too. -pub fn zone_shape(rect: Rect, zone: Zone) -> Option> { - if !usable(rect) { +/// How deep the side zones of `body` reach in from its left and right edges (`x`) and its top +/// and bottom edges (`y`). +fn side_depths(body: Rect, depth: f32) -> Vec2 { + let depth = if depth > 0.0 { depth } else { 0.0 }; + vec2(depth.min(body.width() / 3.0), depth.min(body.height() / 3.0)) +} + +/// The outline of a drop zone of the group drawn at `rect`, as [`drop_zone`] finds it with the +/// same `tab_height` and `depth`: a side's trapezoid (its outer edge the whole side of the body, +/// its inner edge on the center rectangle), or the center rectangle. The tab header, a grouping +/// zone too, is not part of any shape. None for a side without depth. +pub fn zone_shape(rect: Rect, tab_height: f32, depth: f32, zone: Zone) -> Option> { + if !usable(rect) || !tab_height.is_finite() || tab_height < 0.0 { return None; } - let inner = rect.shrink2(side_depths(rect)); + let body = body(rect, tab_height); + let depths = side_depths(body, depth); + let flat = match zone { + Zone::Left | Zone::Right => depths.x <= 0.0, + Zone::Top | Zone::Bottom => depths.y <= 0.0, + Zone::Center => false, + }; + if !usable(body) || flat { + return None; + } + let inner = body.shrink2(depths); Some(match zone { - Zone::Left => vec![rect.left_top(), inner.left_top(), inner.left_bottom(), rect.left_bottom()], - Zone::Right => vec![inner.right_top(), rect.right_top(), rect.right_bottom(), inner.right_bottom()], - Zone::Top => vec![rect.left_top(), rect.right_top(), inner.right_top(), inner.left_top()], - Zone::Bottom => vec![inner.left_bottom(), inner.right_bottom(), rect.right_bottom(), rect.left_bottom()], + Zone::Left => vec![body.left_top(), inner.left_top(), inner.left_bottom(), body.left_bottom()], + Zone::Right => vec![inner.right_top(), body.right_top(), body.right_bottom(), inner.right_bottom()], + Zone::Top => vec![body.left_top(), body.right_top(), inner.right_top(), inner.left_top()], + Zone::Bottom => vec![inner.left_bottom(), inner.right_bottom(), body.right_bottom(), body.left_bottom()], Zone::Center => vec![inner.left_top(), inner.right_top(), inner.right_bottom(), inner.left_bottom()], }) } +/// Height of the tab header of `target` that [`resolve_drop`] treats as a grouping zone: from the +/// top of its rect to the bottom of its tab strip. +pub(super) fn header_height

(target: &DropTarget

) -> f32 { + target.tab_strip.map(|strip| strip.intersect(target.rect)).filter(|strip| usable(*strip)).map_or(0.0, |strip| strip.bottom() - target.rect.top()) +} + /// Preview of the region occupied after a split or group merge. pub fn zone_rect(rect: Rect, zone: Zone) -> Option { if !usable(rect) { @@ -126,8 +151,10 @@ pub fn tab_insertion_marker(target: &DropTarget

, before: Option<&P>) - /// Resolve a pointer against visible groups. The frontmost containing group occludes groups /// behind it even if it rejects the drop. A strip reorders by midpoint; the body of the source -/// group is a no-op at center. Floating groups normally set `allow_splits` to false. -pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarget

]) -> Option> { +/// group is a no-op at center. The body's side zones are [`drop_zone`]'s with `zone_depth` (see +/// [`crate::docking::DockStyle::zone_depth`]). Floating groups normally set `allow_splits` to +/// false. +pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarget

], zone_depth: f32) -> Option> { if !pointer.is_finite() || targets.len() > super::MAX_PANELS { return None; } @@ -165,7 +192,7 @@ pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarg noop, }); } - let zone = if target.allow_splits { drop_zone(target.rect, 0.0, pointer)? } else { Zone::Center }; + let zone = if target.allow_splits { drop_zone(target.rect, header_height(target), zone_depth, pointer)? } else { Zone::Center }; if zone == Zone::Center && target.accepts_tabs && target.tabs.iter().any(|(p, _)| p == panel) { return Some(DropProposal { anchor: anchor.clone(), diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 2db1da78e3..3f21199a12 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -287,19 +287,46 @@ fn target(anchor: u32, members: &[u32], rect: Rect) -> DropTarget { fn pointer_targets_distinguish_reorder_center_split_and_occlusion() { let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(300.0, 200.0)); let group = target(2, &[2, 3], rect); - let placement = resolve_drop(&5, pos2(90.0, 30.0), std::slice::from_ref(&group)).unwrap(); + let placement = resolve_drop(&5, pos2(90.0, 30.0), std::slice::from_ref(&group), 40.0).unwrap(); assert_eq!(placement.placement, Placement::Tab { before: Some(3) }); assert!(placement.insertion.unwrap().is_finite()); - assert_eq!(resolve_drop(&5, rect.center(), std::slice::from_ref(&group)).unwrap().placement, Placement::Split(Zone::Center)); - assert_eq!(resolve_drop(&5, pos2(11.0, 90.0), std::slice::from_ref(&group)).unwrap().placement, Placement::Split(Zone::Left)); - assert!(resolve_drop(&3, rect.center(), std::slice::from_ref(&group)).unwrap().noop); - assert!(resolve_drop(&3, pos2(11.0, 90.0), std::slice::from_ref(&group)).is_some()); + assert_eq!(resolve_drop(&5, rect.center(), std::slice::from_ref(&group), 40.0).unwrap().placement, Placement::Split(Zone::Center)); + assert_eq!(resolve_drop(&5, pos2(11.0, 90.0), std::slice::from_ref(&group), 40.0).unwrap().placement, Placement::Split(Zone::Left)); + assert!(resolve_drop(&3, rect.center(), std::slice::from_ref(&group), 40.0).unwrap().noop); + assert!(resolve_drop(&3, pos2(11.0, 90.0), std::slice::from_ref(&group), 40.0).is_some()); let mut overlay = target(5, &[5], rect); overlay.accepts_tabs = false; overlay.allow_splits = false; - assert!(resolve_drop(&3, rect.center(), &[group, overlay]).is_none()); - assert!(drop_zone(Rect::NOTHING, 24.0, pos2(0.0, 0.0)).is_none()); - assert!(drop_zone(rect, 24.0, pos2(f32::NAN, 0.0)).is_none()); + assert!(resolve_drop(&3, rect.center(), &[group, overlay], 40.0).is_none()); + assert!(drop_zone(Rect::NOTHING, 24.0, 40.0, pos2(0.0, 0.0)).is_none()); + assert!(drop_zone(rect, 24.0, 40.0, pos2(f32::NAN, 0.0)).is_none()); +} + +#[test] +fn side_zones_are_40_pt_deep_or_a_third_of_a_small_body() { + let depth = DockStyle::default().zone_depth; + assert_eq!(depth, 40.0); + // The inner corner of the left trapezoid is the depth of both bands. + let inner = |rect: Rect| zone_shape(rect, 0.0, depth, Zone::Left).unwrap()[1] - rect.min; + for size in [vec2(600.0, 400.0), vec2(130.0, 130.0)] { + let rect = Rect::from_min_size(pos2(10.0, 20.0), size); + assert_eq!(inner(rect), vec2(40.0, 40.0), "{size:?}"); + let y = rect.center().y; + assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 39.0, y)), Some(Zone::Left), "{size:?}"); + assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 41.0, y)), Some(Zone::Center), "{size:?}"); + } + // A 90 pt body keeps a 30 pt center. + let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(90.0, 90.0)); + assert_eq!(inner(rect), vec2(30.0, 30.0)); + assert_eq!(drop_zone(rect, 0.0, depth, rect.center()), Some(Zone::Center)); + assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 29.0, rect.center().y)), Some(Zone::Left)); + // The bands start below the tab header. + let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(600.0, 400.0)); + assert_eq!(drop_zone(rect, 24.0, depth, pos2(rect.center().x, rect.top() + 60.0)), Some(Zone::Top)); + assert_eq!(zone_shape(rect, 24.0, depth, Zone::Top).unwrap()[0], rect.left_top() + vec2(0.0, 24.0)); + // Without depth there are no sides. + assert_eq!(drop_zone(rect, 0.0, 0.0, pos2(rect.left() + 1.0, rect.center().y)), Some(Zone::Center)); + assert!(zone_shape(rect, 0.0, 0.0, Zone::Left).is_none()); } #[test] @@ -1520,7 +1547,7 @@ fn returning_to_a_singleton_or_floating_source_body_is_an_explicit_noop() { accepts_tabs: true, right_to_left: false, }; - let proposal = resolve_drop(&1, rect.center(), &[target]).unwrap(); + let proposal = resolve_drop(&1, rect.center(), &[target], 40.0).unwrap(); assert!(proposal.noop); assert!(proposal.insertion.is_none()); } @@ -1583,13 +1610,13 @@ fn unchanged_tab_slots_are_explicit_noops_with_bounded_insertion_markers() { }; for (panel, positions) in [(1, [10.0, 50.0]), (2, [70.0, 110.0]), (3, [130.0, 210.0])] { for x in positions { - let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target)).unwrap(); + let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target), 40.0).unwrap(); assert!(proposal.noop, "{panel}/{x}"); assert!(target.tab_strip.unwrap().contains_rect(proposal.insertion.unwrap())); } } for (panel, x) in [(1, 140.0), (3, 10.0), (2, 210.0)] { - let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target)).unwrap(); + let proposal = resolve_drop(&panel, pos2(x, 12.0), std::slice::from_ref(&target), 40.0).unwrap(); assert!(!proposal.noop); assert!(proposal.insertion.is_some()); } @@ -1663,10 +1690,10 @@ fn overflow_noop_detection_uses_logical_order_including_hidden_tabs() { accepts_tabs: true, right_to_left: false, }; - assert!(resolve_drop(&1, pos2(10.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); + assert!(resolve_drop(&1, pos2(10.0, 12.0), std::slice::from_ref(&target), 40.0).unwrap().noop); // Before the next visible tab crosses hidden tab 2 and really changes the order. - assert!(!resolve_drop(&1, pos2(65.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); - assert!(resolve_drop(&3, pos2(130.0, 12.0), std::slice::from_ref(&target)).unwrap().noop); + assert!(!resolve_drop(&1, pos2(65.0, 12.0), std::slice::from_ref(&target), 40.0).unwrap().noop); + assert!(resolve_drop(&3, pos2(130.0, 12.0), std::slice::from_ref(&target), 40.0).unwrap().noop); } #[test] @@ -1685,7 +1712,7 @@ fn insertion_markers_stay_inside_clipped_and_singleton_strips() { right_to_left: false, }; for x in [rect.left(), rect.center().x, rect.right()] { - let proposal = resolve_drop(&1, pos2(x, 25.0), std::slice::from_ref(&target)).unwrap(); + let proposal = resolve_drop(&1, pos2(x, 25.0), std::slice::from_ref(&target), 40.0).unwrap(); assert!(proposal.noop); let marker = proposal.insertion.unwrap(); assert!(rect.intersect(target.tab_strip.unwrap()).contains_rect(marker)); @@ -1700,7 +1727,7 @@ fn insertion_marker_handles_subpixel_strip_crossing_zero_without_panicking() { let rect = Rect::from_min_max(pos2(-0.001, 0.0), pos2(0.002, 30.0)); let target = DropTarget { anchor: 1, rect, tab_strip: Some(rect), tabs: vec![(1, rect)], allow_splits: true, accepts_tabs: true, right_to_left: false }; - let proposal = resolve_drop(&1, pos2(0.0, 12.0), &[target]).unwrap(); + let proposal = resolve_drop(&1, pos2(0.0, 12.0), &[target], 40.0).unwrap(); assert!(proposal.noop); assert!(rect.contains_rect(proposal.insertion.unwrap())); } diff --git a/crates/ui/src/docking/trial_tests.rs b/crates/ui/src/docking/trial_tests.rs index d16cf98d44..c67706403f 100644 --- a/crates/ui/src/docking/trial_tests.rs +++ b/crates/ui/src/docking/trial_tests.rs @@ -260,7 +260,7 @@ fn right_to_left_mirrors_the_tab_strip_and_its_insertion_slots() { accepts_tabs: true, right_to_left: true, }; - let drop = |x: f32| resolve_drop(&9, pos2(x, 10.0), std::slice::from_ref(&target)).unwrap(); + let drop = |x: f32| resolve_drop(&9, pos2(x, 10.0), std::slice::from_ref(&target), 40.0).unwrap(); assert_eq!((drop(90.0).placement, drop(90.0).insertion.unwrap().center().x), (Placement::Tab { before: Some(1) }, 99.0)); assert_eq!((drop(70.0).placement, drop(70.0).insertion.unwrap().center().x), (Placement::Tab { before: Some(2) }, 60.0)); assert_eq!((drop(10.0).placement, drop(10.0).insertion.unwrap().center().x), (Placement::Tab { before: None }, 20.0)); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 177c1c2de5..fb6d0deeec 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -210,8 +210,9 @@ A flyout fits its content the same way, without the title bar. the title bar's buttons. A resize keeps the opposite edges in place and stays within the size limits and the screen. A focused resize handle moves its edge 8 pt per arrow key. - Over a frame, the tab strip and the middle join its tabs, and the nearest side splits it. The - side zones are trapezoids along the four edges, like a picture frame: a quarter of the frame - deep, at least 32 pt and at most half the frame. A split that would leave either half without + side zones are trapezoids along the four edges of the body below the tab strip, like a picture + frame: `DockStyle::zone_depth` (40 pt) deep, or a third of the body's width or height when that + is less, so every frame keeps a center. A split that would leave either half without `DockStyle::min_pane` joins the frame's tabs instead. The gap between two frames is no target. - The outer edge band (`DockStyle::edge_band`) takes a drop as a new frame across the whole window side: top and bottom, and left and right with `side_edge_zones`. It takes a quarter of @@ -225,10 +226,12 @@ A flyout fits its content the same way, without the title bar. for one through `PanelLimits::max`: a panel without a maximum lifts the maximum of the panels it joins. - Drop previews show the destination: an outline for tabs, a line for a new group, column or dock, - a filled half for a split. With `side_edge_zones`, a drop on a group instead fills the zone - under the pointer (a side's trapezoid, or the center rectangle and the tab strip; `zone_shape` - gives the outline) and outlines the rect the drop gives what moves. Escape or losing window - focus cancels a drag. + a filled half for a split. With `side_edge_zones`, a drag over a group instead outlines each of + its zones that a drop would change something in (the side trapezoids, the center rectangle and + the tab strip; `zone_shape` gives the outlines) and fills the zone under the pointer. Sides the + group does not take, by its permissions or because a split leaves no room, are not drawn; nor is + the center of the group a tab comes from. Escape or losing window focus cancels + a drag. - With `float_on_empty_drop`, a release over no target floats what moves at the pointer, such as a panel dropped on a protected canvas. Without it, that release cancels the drag and nothing moves: the gap between two groups, a menu bar or a status bar is no target. A release From 99d8fe537ed7a78b00621d595a167ba03ed6bab1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 03:03:07 +0000 Subject: [PATCH 92/94] docking: a dragged divider shrinks the groups beyond it in turn A divider dragged past the minimum of the group it shrinks moves on to the next group along the axis, and so on until every group on that side is at its minimum. The line follows same-axis splits up the tree and ends at a split across the axis or beside a dock. Groups touching the divider on the other side grow, up to their maximums, as before. Stacked panels and the groups of a dock column cascade the same way. --- crates/ui/src/docking/dock_tests.rs | 10 ++ crates/ui/src/docking/render/dock.rs | 47 +++-- crates/ui/src/docking/render/floating.rs | 2 +- crates/ui/src/docking/render/mod.rs | 87 ++++++---- crates/ui/src/docking/render/sizes.rs | 210 +++++++++++++++++++---- crates/ui/src/docking/split_tests.rs | 32 +++- crates/ui/src/docking/surface.rs | 2 +- crates/ui/src/docking/tests.rs | 11 ++ docs/ui-docking.md | 11 +- 9 files changed, 318 insertions(+), 94 deletions(-) diff --git a/crates/ui/src/docking/dock_tests.rs b/crates/ui/src/docking/dock_tests.rs index 654b637f5d..7819667f84 100644 --- a/crates/ui/src/docking/dock_tests.rs +++ b/crates/ui/src/docking/dock_tests.rs @@ -415,6 +415,16 @@ fn column_and_group_dividers_resize_and_minimized_groups_keep_their_height() { assert_eq!(d.tab(4).top(), 600.0 - 26.0); } +#[test] +fn a_group_divider_dragged_past_the_lower_groups_minimum_shrinks_the_next_group() { + let mut d = Driver::new(docked(Side::Start, &[&[&[2], &[3], &[4]]])); + let divider = d.rect("group-resize", 2).center(); + d.drag(divider, divider + vec2(0.0, 500.0)); + // Groups 3 and 4 are at their minimum: a tab strip and a 40 pt body. + let heights = column(&d.layout, 0).groups.iter().map(|g| g.height).collect::>(); + assert_eq!(heights[1..], [Some(66.0), Some(66.0)], "{heights:?}"); +} + #[test] fn double_click_on_a_docked_tab_minimizes_and_clicking_another_tab_expands() { let mut d = Driver::new(docked(Side::Start, &[&[&[2, 3], &[4]]])); diff --git a/crates/ui/src/docking/render/dock.rs b/crates/ui/src/docking/render/dock.rs index 55336dca13..7ce4e88f07 100644 --- a/crates/ui/src/docking/render/dock.rs +++ b/crates/ui/src/docking/render/dock.rs @@ -8,7 +8,7 @@ use std::{fmt::Debug, hash::Hash}; use egui::{Context, Key, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; -use super::{GroupKind, Renderer}; +use super::{GroupKind, Renderer, RowItem, row_drag, row_range}; use crate::docking::{ Action, Column, DockEvent, DockStyle, Group, GroupDrag, GroupGesture, Node, Placement, Side, Target, dock_model::Unit, @@ -144,7 +144,15 @@ pub(in crate::docking) fn fit_widths(columns: &[(f32, Option)], room: f32) impl Renderer<'_, P> { /// A horizontal split with a dock child: the dock takes its columns' width on its physical /// edge, the sibling the rest. False when neither child is a dock. - pub(super) fn dock_split(&mut self, ui: &mut Ui, first: &Node

, second: &Node

, rect: Rect, path: &mut Vec) -> bool { + pub(super) fn dock_split( + &mut self, + ui: &mut Ui, + first: &Node

, + second: &Node

, + rect: Rect, + path: &mut Vec, + root: (&Node

, Rect), + ) -> bool { let (dock_first, side, columns, other) = match (first, second) { (Node::Dock { side, columns }, other) => (true, *side, columns, other), (other, Node::Dock { side, columns }) => (false, *side, columns, other), @@ -153,7 +161,7 @@ impl Renderer<'_, P> { let (dock, rest, room) = dock_rects(side, columns, other, rect, self.style, &*self.content); self.dock(ui, side, columns, dock, room); path.push(dock_first); - self.node(ui, other, rest, path); + self.node(ui, other, rest, path, root); path.pop(); true } @@ -360,16 +368,18 @@ impl Renderer<'_, P> { push(&mut self.dock_targets, DockTarget::GroupBand { anchor: last.clone(), below: true }, band, horizontal_line(top, xs)); } // Height dividers between an open group and the next open one, after the groups so - // their hit areas win at the boundary. Both groups' heights are saved. + // their hit areas win at the boundary. The heights of the groups a drag changes are + // saved: the upper group, and the lower groups that give way in turn, or the reverse. let open: Vec = (0..column.groups.len()).filter(|i| column.groups.get(*i).is_some_and(|g| !g.minimized)).collect(); - for pair in open.windows(2) { - let &[i, j] = pair else { continue }; - let (Some(upper), Some(lower), Some(rect)) = (column.groups.get(i), column.groups.get(j), rects.get(i)) else { continue }; - let (Some(a), Some(b), Some(first), Some(second)) = (heights.get(i), heights.get(j), upper.panels.first(), lower.panels.first()) else { - continue; - }; - let (lo, hi) = (self.group_min(upper), a + b - self.group_min(lower)); - let hi = hi.max(lo); + let row: Vec = open + .iter() + .filter_map(|i| Some(RowItem { size: *heights.get(*i)?, min: self.group_min(column.groups.get(*i)?), max: f32::INFINITY })) + .collect(); + for (index, pair) in open.windows(2).enumerate() { + let &[i, _] = pair else { continue }; + let (Some(upper), Some(rect), Some(a)) = (column.groups.get(i), rects.get(i), heights.get(i)) else { continue }; + let Some(first) = upper.panels.first() else { continue }; + let (lo, hi) = row_range(&row, index); let divider = Rect::from_x_y_ranges(rect.x_range(), (rect.bottom() - 1.0)..=(rect.bottom() + 1.0)); let response = ResizeHandle::new( self.id.with(("group-resize", Some(first))), @@ -378,13 +388,16 @@ impl Renderer<'_, P> { &self.style.resize_label, self.handle_style(), ) - .value(*a, lo..=hi) + .value(*a, (a + lo)..=(a + hi)) .show(ui); self.register_interaction(ui.ctx(), response.response.id); - let next = (a + response.delta).clamp(lo, hi); - if response.delta != 0.0 && next != *a { - self.output.actions.push(Action::ResizeGroup { panel: first.clone(), height: Some(next) }); - self.output.actions.push(Action::ResizeGroup { panel: second.clone(), height: Some(a + b - next) }); + if response.delta == 0.0 { + continue; + } + for ((group, item), next) in open.iter().filter_map(|g| column.groups.get(*g)).zip(&row).zip(row_drag(&row, index, response.delta)) { + if let Some(panel) = group.panels.first().filter(|_| next != item.size) { + self.output.actions.push(Action::ResizeGroup { panel: panel.clone(), height: Some(next) }); + } } } } diff --git a/crates/ui/src/docking/render/floating.rs b/crates/ui/src/docking/render/floating.rs index 72ec389c35..a5168cb690 100644 --- a/crates/ui/src/docking/render/floating.rs +++ b/crates/ui/src/docking/render/floating.rs @@ -116,7 +116,7 @@ impl Renderer<'_, P> { (_, true) => {} (root, false) => { let outer = self.tree.replace((key, frame)); - self.node(ui, root, body, &mut Vec::new()); + self.node(ui, root, body, &mut Vec::new(), (root, body)); self.tree = outer; } } diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index f4fbf37ef7..2f16a8d05e 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -27,7 +27,7 @@ mod group; mod preview; mod sizes; -pub(in crate::docking) use sizes::{DROP_MARGIN, Drawn, Sizer}; +pub(in crate::docking) use sizes::{DROP_MARGIN, Drawn, RowItem, Sizer, row_drag, row_range}; pub(super) struct Renderer<'a, P> { pub(super) id: Id, @@ -63,8 +63,6 @@ pub(super) struct Renderer<'a, P> { pub(super) struct DrawnDivider { path: Vec, axis: SplitAxis, - /// The whole split's rect. - rect: Rect, divider: Rect, } @@ -107,23 +105,25 @@ impl Renderer<'_, P> { }); } - pub(in crate::docking) fn node(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &mut Vec) { + /// Draws `node` at view path `path` in `rect`, in the tree `root` (its root node and rect), + /// which a dragged divider resizes beyond `node`. + pub(in crate::docking) fn node(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &mut Vec, root: (&Node

, Rect)) { if !crate::docking::targets::usable(rect) { return; } self.note_edge(path, rect); match node { - Node::Split { axis: SplitAxis::Horizontal, first, second, .. } if self.dock_split(ui, first, second, rect, path) => {} + Node::Split { axis: SplitAxis::Horizontal, first, second, .. } if self.dock_split(ui, first, second, rect, path, root) => {} Node::Split { axis, size, first, second } => { let sizer = self.sizer(); let Some(split) = sizer.split(*axis, *size, first, second, rect) else { return }; - let (lo, hi) = sizer.range(node, rect); + let (lo, hi) = sizer.range(root, path); let mark = self.dividers.len(); path.push(false); - self.node(ui, first, split.first, path); + self.node(ui, first, split.first, path, root); path.pop(); path.push(true); - self.node(ui, second, split.second, path); + self.node(ui, second, split.second, path, root); path.pop(); // The divider's inner-edge hit margin must win over child scrollbars, just // as accordion dividers win over the adjacent panel's content. @@ -140,12 +140,12 @@ impl Renderer<'_, P> { .show(ui); self.register_interaction(ui.ctx(), response.response.id); if response.delta != 0.0 { - let actions = self.divider_actions(node, rect, path, response.delta); + let actions = self.divider_actions(root, path, response.delta); self.output.actions.extend(actions); } - self.intersections(ui, node, rect, path, split.divider, mark); + self.intersections(ui, node, rect, path, split.divider, mark, root); if self.dividers.len() < crate::docking::model::MAX_NODES { - self.dividers.push(DrawnDivider { path: path.clone(), axis: *axis, rect, divider: split.divider }); + self.dividers.push(DrawnDivider { path: path.clone(), axis: *axis, divider: split.divider }); } } Node::Tabs { panels, active } => { @@ -212,21 +212,30 @@ impl Renderer<'_, P> { } // Register dividers after the headers so their narrow hit regions win at the // shared boundary. Closed entries retain their saved sizes and are skipped. + let scale = if total_wanted > 0.0 { f64::from(remaining) / total_wanted } else { 0.0 }; + let body_limits = |panel: &P| { + let mut limits = self.limits(panel); + limits.min.y = limits.min.y.max(self.style.min_pane); + limits.max = limits.max.max(limits.min); + limits + }; + let open: Vec<&crate::docking::StackEntry

> = entries.iter().filter(|entry| entry.open).collect(); + let row: Vec = open + .iter() + .map(|entry| { + let limits = body_limits(&entry.panel); + let size = (f64::from(entry.height.unwrap_or(self.style.min_pane).max(1.0)) * scale) as f32; + RowItem { size, min: limits.min.y, max: limits.max.y } + }) + .collect(); for (index, divider) in dividers { let Some(first) = entries.get(index) else { continue }; - let Some(second) = entries.iter().skip(index.saturating_add(1)).find(|entry| entry.open) else { continue }; - let a = f64::from(first.height.unwrap_or(self.style.min_pane).max(1.0)); - let b = f64::from(second.height.unwrap_or(self.style.min_pane).max(1.0)); - let scale = f64::from(remaining) / total_wanted; - let first_size = (a * scale) as f32; - let pair_size = ((a + b) * scale) as f32; - let body_limits = |panel: &P| { - let mut limits = self.limits(panel); - limits.min.y = limits.min.y.max(self.style.min_pane); - limits.max = limits.max.max(limits.min); - limits - }; - let (lo, hi) = split_bounds(pair_size, SplitAxis::Vertical, body_limits(&first.panel), body_limits(&second.panel)); + let Some(position) = open.iter().position(|entry| std::ptr::eq(*entry, first)) else { continue }; + let Some(first_size) = row.get(position).map(|item| item.size) else { continue }; + if position + 1 >= row.len() { + continue; + } + let (lo, hi) = row_range(&row, position); let response = ResizeHandle::new( self.id.with(("stack-resize", &first.panel)), SplitAxis::Vertical, @@ -234,14 +243,16 @@ impl Renderer<'_, P> { &self.style.resize_label, ResizeHandleStyle { hovered: self.style.accent, dragged: self.style.accent, focused: self.style.accent }, ) - .value(first_size, lo..=hi) + .value(first_size, (first_size + lo)..=(first_size + hi)) .show(ui); self.register_interaction(ui.ctx(), response.response.id); if response.delta != 0.0 && scale > 0.0 { - let delta = f64::from((first_size + response.delta).clamp(lo, hi) - first_size) / scale; - let next_a = (a + delta).clamp((a + b - 1_000_000.0).max(1.0), (a + b - 1.0).min(1_000_000.0)); - self.output.actions.push(Action::ResizeStack { panel: first.panel.clone(), height: Some(next_a as f32) }); - self.output.actions.push(Action::ResizeStack { panel: second.panel.clone(), height: Some((a + b - next_a) as f32) }); + for ((entry, item), next) in open.iter().zip(&row).zip(row_drag(&row, position, response.delta)) { + if next != item.size { + let height = (f64::from(next) / scale).clamp(1.0, 1_000_000.0) as f32; + self.output.actions.push(Action::ResizeStack { panel: entry.panel.clone(), height: Some(height) }); + } + } } } } @@ -252,10 +263,10 @@ impl Renderer<'_, P> { Sizer { style: self.style, content: &*self.content } } - /// `ResizeSplit` actions that move the divider of the split `node`, drawn at view path - /// `path` in `rect`, by `delta` points. - fn divider_actions(&self, node: &Node

, rect: Rect, path: &[bool], delta: f32) -> Vec> { - let sizes = self.sizer().drag(node, rect, delta, &mut path.to_vec()); + /// `ResizeSplit` actions that move the divider of the split at view path `path` in the + /// tree `root` by `delta` points. + fn divider_actions(&self, root: (&Node

, Rect), path: &[bool], delta: f32) -> Vec> { + let sizes = self.sizer().drag(root, path, delta); let resize = |path: Vec, size| match &self.tree { None => Action::ResizeSplit { path, size }, Some((panel, _)) => Action::ResizeWindowSplit { panel: panel.clone(), path, size }, @@ -274,7 +285,7 @@ impl Renderer<'_, P> { /// Four-way handles where a divider drawn inside the split `node` (since `mark`) ends on /// the split's own divider: dragging one moves both dividers. - fn intersections(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &[bool], divider: Rect, mark: usize) { + fn intersections(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &[bool], divider: Rect, mark: usize, root: (&Node

, Rect)) { let Node::Split { axis, .. } = node else { return }; let side = (self.style.gap * 3.0).max(12.0); let mut found = Vec::new(); @@ -286,9 +297,9 @@ impl Renderer<'_, P> { SplitAxis::Horizontal => pos2(divider.center().x, inner.divider.center().y), SplitAxis::Vertical => pos2(inner.divider.center().x, divider.center().y), }; - found.push((inner.path.clone(), inner.rect, Rect::from_center_size(center, Vec2::splat(side)).intersect(rect))); + found.push((inner.path.clone(), Rect::from_center_size(center, Vec2::splat(side)).intersect(rect))); } - for (inner_path, inner_rect, hit) in found { + for (inner_path, hit) in found { let Some(inner) = inner_path.get(path.len()..).and_then(|rest| crate::docking::dock_model::node_at(node, rest)) else { continue }; let (outer, inner_layout) = (self.original_path(path), self.original_path(&inner_path)); let id = match &self.tree { @@ -305,8 +316,8 @@ impl Renderer<'_, P> { if delta != Vec2::ZERO && delta.is_finite() { let along = |axis: SplitAxis| if axis == SplitAxis::Horizontal { delta.x } else { delta.y }; let Node::Split { axis: inner_axis, .. } = inner else { continue }; - let mut actions = self.divider_actions(node, rect, path, along(*axis)); - actions.extend(self.divider_actions(inner, inner_rect, &inner_path, along(*inner_axis))); + let mut actions = self.divider_actions(root, path, along(*axis)); + actions.extend(self.divider_actions(root, &inner_path, along(*inner_axis))); self.output.actions.extend(actions); } } diff --git a/crates/ui/src/docking/render/sizes.rs b/crates/ui/src/docking/render/sizes.rs index bf7fd3dc53..8af0dd5ae3 100644 --- a/crates/ui/src/docking/render/sizes.rs +++ b/crates/ui/src/docking/render/sizes.rs @@ -1,5 +1,13 @@ //! Split-tree geometry: where each split draws its children, how far a divider can travel, -//! and the sizes that move a divider while every group away from it keeps its size. +//! and the sizes that move a divider. +//! +//! A dragged divider grows the groups touching it on one side, up to their maximums, and +//! shrinks the groups on the other side in turn: the group touching the divider gives way +//! down to its minimum, then the next group along the axis, and so on, until every group on +//! that side is at its minimum. Groups side by side across the axis shrink together, and the +//! line goes on past them once one is at its minimum. The line follows splits of the drag's +//! axis up the tree and ends at a split across it or beside a dock. Every other group keeps +//! its size. use egui::Rect; @@ -78,8 +86,9 @@ impl

Sizer<'_, P> { } /// How far the end edge (`end`) or start edge of `node` drawn in `rect` can move along - /// `axis`: inward while the groups touching it stay at their minimums, and outward up to - /// their maximums. + /// `axis`: inward until every group along the axis from that edge is at its minimum, and + /// outward while the groups touching it stay below their maximums. Groups side by side + /// across the axis move together, so the first of them to reach its limit stops them. pub(in crate::docking) fn travel(&self, node: &Node

, rect: Rect, axis: SplitAxis, end: bool) -> (f32, f32) { let docked = matches!(node, Node::Split { first, second, .. } if matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. })); @@ -89,8 +98,9 @@ impl

Sizer<'_, P> { self.travel(other, rect, axis, end) } (Node::Split { axis: split_axis, .. }, Some([a, b])) if *split_axis == axis => { - let (child, rect) = if end { b } else { a }; - self.travel(child, rect, axis, end) + let (near, far) = if end { (b, a) } else { (a, b) }; + let (near, far) = (self.travel(near.0, near.1, axis, end), self.travel(far.0, far.1, axis, end)); + (near.0 + far.0, near.1) } (_, Some([a, b])) => { let (a, b) = (self.travel(a.0, a.1, axis, end), self.travel(b.0, b.1, axis, end)); @@ -105,7 +115,9 @@ impl

Sizer<'_, P> { } /// The sizes that move the end (`end`) or start edge of `node` drawn in `rect` outward by - /// `grow` points: only the groups touching that edge change. Paths are relative to `path`. + /// `grow` points. Growing, only the groups touching that edge change. Shrinking, the group + /// at the edge gives way down to its minimum, then the next one along the axis, and so on. + /// Paths are relative to `path`. pub(in crate::docking) fn follow( &self, (node, rect): (&Node

, Rect), @@ -118,55 +130,195 @@ impl

Sizer<'_, P> { let Some([a, b]) = self.children(node, rect) else { return }; let Node::Split { axis: split_axis, first, second, .. } = node else { return }; let docked = matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. }); - let visit = |child: (&Node

, Rect), second_child: bool, path: &mut Vec, out: &mut Vec<(Vec, SplitSize)>| { + let visit = |child: (&Node

, Rect), second_child: bool, grow: f32, path: &mut Vec, out: &mut Vec<(Vec, SplitSize)>| { path.push(second_child); self.follow(child, axis, end, grow, path, out); path.pop(); }; if docked { let dock_first = matches!(**first, Node::Dock { .. }); - visit(if dock_first { b } else { a }, dock_first, path, out); + visit(if dock_first { b } else { a }, dock_first, grow, path, out); } else if *split_axis == axis { - let available = extent(a.1, axis) + extent(b.1, axis) + grow; - let first_size = extent(a.1, axis) + if end { 0.0 } else { grow }; - if available > 0.0 { - out.push((path.clone(), SplitSize::Ratio((first_size / available).clamp(0.0, 1.0)))); + let (near, far) = if end { (b, a) } else { (a, b) }; + let near_grow = if grow < 0.0 { grow.max(-self.travel(near.0, near.1, axis, end).0) } else { grow }; + let far_grow = grow - near_grow; + let (near_size, far_size) = (extent(near.1, axis) + near_grow, extent(far.1, axis) + far_grow); + let first_size = if end { far_size } else { near_size }; + push_ratio(path, first_size, near_size + far_size, out); + visit(near, end, near_grow, path, out); + if far_grow != 0.0 { + visit(far, !end, far_grow, path, out); } - visit(if end { b } else { a }, end, path, out); } else { - visit(a, false, path, out); - visit(b, true, path, out); + visit(a, false, grow, path, out); + visit(b, true, grow, path, out); } } - /// The divider of the split `node` drawn in `rect` moved by `delta` points, clamped to its - /// travel: the split's own size and those of the splits that keep the groups away from the - /// divider at their sizes. Paths are relative to `path`, the split's own. - pub(in crate::docking) fn drag(&self, node: &Node

, rect: Rect, delta: f32, path: &mut Vec) -> Vec<(Vec, SplitSize)> { + /// The drawn splits from `root` down to the one at `path`, each with its rect. + fn chain<'n>(&self, root: (&'n Node

, Rect), path: &[bool]) -> Option, Rect)>> { + let mut chain = vec![root]; + for &second in path { + let (node, rect) = *chain.last()?; + let [a, b] = self.children(node, rect)?; + chain.push(if second { b } else { a }); + } + Some(chain) + } + + /// The ancestors that continue the line of the split at the end of `chain` along `axis`: + /// each with its children and whether the line runs through its second child, nearest first. + /// The line ends at a split across the axis or beside a dock. + fn line<'n>(&self, chain: &[(&'n Node

, Rect)], path: &[bool], axis: SplitAxis) -> Vec<(usize, [(&'n Node

, Rect); 2], bool)> { + let mut line = Vec::new(); + for depth in (0..path.len()).rev() { + let Some(&(node, rect)) = chain.get(depth) else { break }; + let Node::Split { axis: split_axis, first, second, .. } = node else { break }; + if *split_axis != axis || matches!(**first, Node::Dock { .. }) || matches!(**second, Node::Dock { .. }) { + break; + } + let (Some(children), Some(&second_child)) = (self.children(node, rect), path.get(depth)) else { break }; + line.push((depth, children, second_child)); + } + line + } + + /// The divider of the split at `path` under `root` (a node and the rect it is drawn in) + /// moved by `delta` points, clamped to its travel. The groups touching the divider on the + /// side it moves toward give way, then the groups beyond them along the axis, one after + /// another, as far as the line of same-axis splits reaches; the groups on the other side + /// that touch the divider take the room. Paths are absolute, like `path`. + pub(in crate::docking) fn drag(&self, root: (&Node

, Rect), path: &[bool], delta: f32) -> Vec<(Vec, SplitSize)> { + let Some(chain) = self.chain(root, path) else { return Vec::new() }; + let Some(&(node, rect)) = chain.last() else { return Vec::new() }; let Node::Split { axis, size, first, second } = node else { return Vec::new() }; - let Some(split) = self.split(*axis, *size, first, second, rect) else { return Vec::new() }; - let (lo, hi) = self.range(node, rect); + let axis = *axis; + let Some(split) = self.split(axis, *size, first, second, rect) else { return Vec::new() }; + let (lo, hi) = self.range(root, path); let delta = delta.clamp(lo, hi); if delta == 0.0 || !delta.is_finite() || split.available() <= 0.0 { return Vec::new(); } - let mut out = vec![(path.clone(), SplitSize::Ratio(((split.first_size() + delta) / split.available()).clamp(0.0, 1.0)))]; + // Toward the end edge the second child gives way, toward the start the first. + let forward = delta > 0.0; + let moved = delta.abs(); + let given = if forward { + moved.min(self.travel(second, split.second, axis, false).0) + } else { + moved.min(self.travel(first, split.first, axis, true).0) + }; + let (first_grow, second_grow) = if forward { (moved, -given) } else { (-given, moved) }; + let mut out = Vec::new(); + let mut path = path.to_vec(); + let first_size = split.first_size() + first_grow; + push_ratio(&path, first_size, first_size + extent(split.second, axis) + second_grow, &mut out); path.push(false); - self.follow((first, split.first), *axis, true, delta, path, &mut out); + self.follow((first, split.first), axis, true, first_grow, &mut path, &mut out); path.pop(); path.push(true); - self.follow((second, split.second), *axis, false, -delta, path, &mut out); + self.follow((second, split.second), axis, false, second_grow, &mut path, &mut out); path.pop(); + // What the split's own child could not give, the ancestors' children beyond it give: + // the split grows by `rest` toward them, and so does each ancestor until one absorbs it. + let mut rest = moved - given; + for (depth, [a, b], second_child) in self.line(&chain, &path, axis) { + if rest <= 0.0 { + break; + } + path.truncate(depth); + let (a_size, b_size) = (extent(a.1, axis), extent(b.1, axis)); + let (first_size, second_size) = match (forward, second_child) { + (true, false) => { + let taken = rest.min(self.travel(b.0, b.1, axis, false).0); + path.push(true); + self.follow(b, axis, false, -taken, &mut path, &mut out); + path.pop(); + let sizes = (a_size + rest, b_size - taken); + rest -= taken; + sizes + } + (false, true) => { + let taken = rest.min(self.travel(a.0, a.1, axis, true).0); + path.push(false); + self.follow(a, axis, true, -taken, &mut path, &mut out); + path.pop(); + let sizes = (a_size - taken, b_size + rest); + rest -= taken; + sizes + } + (true, true) => (a_size, b_size + rest), + (false, false) => (a_size + rest, b_size), + }; + push_ratio(&path, first_size, first_size + second_size, &mut out); + } out } - /// How far the divider of the split `node` drawn in `rect` can move: `(lo, hi)`, with - /// `lo <= 0 <= hi`. - pub(in crate::docking) fn range(&self, node: &Node

, rect: Rect) -> (f32, f32) { + /// How far the divider of the split at `path` under `root` can move: `(lo, hi)`, with + /// `lo <= 0 <= hi`. Each way it is the lesser of the room the groups touching the divider + /// have to grow and the room every group beyond the divider, along the line of same-axis + /// splits, has to shrink. + pub(in crate::docking) fn range(&self, root: (&Node

, Rect), path: &[bool]) -> (f32, f32) { + let Some(chain) = self.chain(root, path) else { return (0.0, 0.0) }; + let Some(&(node, rect)) = chain.last() else { return (0.0, 0.0) }; let Node::Split { axis, size, first, second } = node else { return (0.0, 0.0) }; let Some(split) = self.split(*axis, *size, first, second, rect) else { return (0.0, 0.0) }; - let (first_in, first_out) = self.travel(first, split.first, *axis, true); - let (second_in, second_out) = self.travel(second, split.second, *axis, false); + let (mut first_in, first_out) = self.travel(first, split.first, *axis, true); + let (mut second_in, second_out) = self.travel(second, split.second, *axis, false); + for (_, [a, b], second_child) in self.line(&chain, path, *axis) { + if second_child { + first_in += self.travel(a.0, a.1, *axis, true).0; + } else { + second_in += self.travel(b.0, b.1, *axis, false).0; + } + } (-first_in.min(second_out), first_out.min(second_in)) } } + +/// The size of a split at `path` whose first child is `first` of `available` points. +fn push_ratio(path: &[bool], first: f32, available: f32, out: &mut Vec<(Vec, SplitSize)>) { + if available > 0.0 { + out.push((path.to_vec(), SplitSize::Ratio((first / available).clamp(0.0, 1.0)))); + } +} + +/// One group of a flat row, such as the panels of a stack or the groups of a dock column: +/// its size along the row and its limits. +#[derive(Clone, Copy)] +pub(in crate::docking) struct RowItem { + pub(in crate::docking) size: f32, + pub(in crate::docking) min: f32, + pub(in crate::docking) max: f32, +} + +/// How far the divider after `row[index]` can move: `(lo, hi)`, with `lo <= 0 <= hi`, by the +/// rule of [`row_drag`]. +pub(in crate::docking) fn row_range(row: &[RowItem], index: usize) -> (f32, f32) { + let room = |items: &[RowItem]| items.iter().map(|item| (item.size - item.min).max(0.0)).sum::(); + let grow = |item: Option<&RowItem>| item.map_or(0.0, |item| (item.max - item.size).max(0.0)); + let (before, after) = row.split_at((index + 1).min(row.len())); + (-room(before).min(grow(after.first())), room(after).min(grow(before.last()))) +} + +/// The sizes of `row` after the divider after `row[index]` moves by `delta`, clamped to its +/// travel: the item touching the divider on the side it moves toward gives way down to its +/// minimum, then the next one, and so on; the item on the other side takes the room. +pub(in crate::docking) fn row_drag(row: &[RowItem], index: usize, delta: f32) -> Vec { + let (lo, hi) = row_range(row, index); + let delta = if delta.is_finite() { delta.clamp(lo, hi) } else { 0.0 }; + let mut sizes: Vec = row.iter().map(|item| item.size).collect(); + let (grows, givers): (usize, Vec) = + if delta > 0.0 { (index, (index + 1..row.len()).collect()) } else { (index + 1, (0..=index).rev().collect()) }; + let mut rest = delta.abs(); + for giver in givers { + let (Some(size), Some(item)) = (sizes.get_mut(giver), row.get(giver)) else { continue }; + let taken = rest.min((item.size - item.min).max(0.0)); + *size -= taken; + rest -= taken; + } + if let Some(size) = sizes.get_mut(grows) { + *size += delta.abs() - rest; + } + sizes +} diff --git a/crates/ui/src/docking/split_tests.rs b/crates/ui/src/docking/split_tests.rs index 3c7c1c455d..ea3283adf3 100644 --- a/crates/ui/src/docking/split_tests.rs +++ b/crates/ui/src/docking/split_tests.rs @@ -227,6 +227,24 @@ fn a_divider_resizes_only_the_groups_that_share_it() { assert_eq!(group(&d, PROPERTIES[0]), properties); } +#[test] +fn a_divider_dragged_past_a_groups_minimum_shrinks_the_next_group_along_the_row() { + // A | B | C | D, 357 pt each, as (A | B) | (C | D): the cascade runs on past B's split. + let row = hsplit(0.5, hsplit(0.5, tabs(&[1]), tabs(&[2])), hsplit(0.5, tabs(&[3]), tabs(&[4]))); + let mut d = driver(Layout { root: Some(row), floating: Vec::new() }, Film::default()); + let widths = |d: &Driver| [1, 2, 3, 4].map(|panel| group(d, panel).width().round()); + assert_eq!(widths(&d), [357.0, 357.0, 357.0, 357.0]); + // B gives way down to its 40 pt minimum, then C. + drag_hit(&mut d, divider(&[false]), vec2(400.0, 0.0)); + assert_eq!(widths(&d), [757.0, 40.0, 274.0, 357.0]); + // The drag stops when B, C and D are all at their minimums. + drag_hit(&mut d, divider(&[false]), vec2(670.0, 0.0)); + assert_eq!(widths(&d), [1308.0, 40.0, 40.0, 40.0]); + // Back the other way, A gives way and only B, which touches the divider, grows. + drag_hit(&mut d, divider(&[false]), vec2(-1300.0, 0.0)); + assert_eq!(widths(&d), [40.0, 1308.0, 40.0, 40.0]); +} + #[test] fn an_intersection_moves_both_dividers() { let mut d = film(); @@ -361,12 +379,16 @@ fn assert_sizes(d: &Driver, context: &str) { let room = g.rect.size() - g.limits.min; assert!(room.x >= -0.01 && room.y >= -0.01, "{context}: {:?} is below its minimum {:?}", g.rect, g.limits.min); } - let mut nodes = vec![(root, area)]; - while let Some((node, rect)) = nodes.pop() { - let Some(children) = sizer.children(node, rect) else { continue }; - let (lo, hi) = sizer.range(node, rect); + let mut nodes = vec![(root, area, Vec::new())]; + while let Some((node, rect, path)) = nodes.pop() { + let Some([a, b]) = sizer.children(node, rect) else { continue }; + let (lo, hi) = sizer.range((root, area), &path); assert!(lo < -0.5 && hi > 0.5, "{context}: a divider is stuck ({lo}, {hi}) at {rect:?} in {:?}", d.layout); - nodes.extend(children); + for (second, (child, rect)) in [(false, a), (true, b)] { + let mut path = path.clone(); + path.push(second); + nodes.push((child, rect, path)); + } } } } diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index 1deff02051..f133f190fe 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -829,7 +829,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { tree: None, }; if let Some(root) = &view.root { - renderer.node(ui, root, rect, &mut Vec::new()); + renderer.node(ui, root, rect, &mut Vec::new(), (root, rect)); ui.allocate_rect(rect, Sense::hover()); } renderer.flyout(ui.ctx()); diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 3f21199a12..2a3d7c56f2 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -653,6 +653,17 @@ fn stack_dividers_resize_adjacent_open_bodies_by_pointer_and_keyboard() { let Node::Stack { entries } = layout.root.as_ref().unwrap() else { panic!() }; assert!(entries[0].height.unwrap() > after_pointer); assert!((entries[0].height.unwrap() + entries[2].height.unwrap() - 300.0).abs() < 0.001); + // Dragged past the next body's minimum, the one after it gives way too, down to the same + // minimum; the closed entry keeps its height. + let start = ctx.read_response(id).unwrap().rect.center(); + step(&ctx, &mut layout, vec![Event::PointerMoved(start), pointer_button(start, true)]); + step(&ctx, &mut layout, vec![Event::PointerMoved(start + vec2(0.0, 600.0))]); + step(&ctx, &mut layout, vec![pointer_button(start + vec2(0.0, 600.0), false)]); + let Node::Stack { entries } = layout.root.as_ref().unwrap() else { panic!() }; + let heights = entries.iter().map(|entry| entry.height.unwrap()).collect::>(); + assert!((heights[2] - heights[3]).abs() < 0.01 && heights[3] < 120.0, "{heights:?}"); + assert!((heights[0] + heights[2] + heights[3] - 420.0).abs() < 0.01, "{heights:?}"); + assert_eq!(heights[1], 91.0); } #[test] diff --git a/docs/ui-docking.md b/docs/ui-docking.md index fb6d0deeec..2cac493d9a 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -218,9 +218,14 @@ A flyout fits its content the same way, without the title bar. window side: top and bottom, and left and right with `side_edge_zones`. It takes a quarter of the window and is offered only when every frame keeps its minimum. Past the band, a frame's own side zones apply. -- A divider resizes only the frames that touch it; every other frame keeps its size. It stops - when a frame touching it reaches its minimum. Where a divider ends on another divider, a - four-way handle (`Divider::Intersection`) moves both. +- A dragged divider grows the frames that touch it on one side, up to their maximums. On the + other side the frame touching it shrinks to its minimum, then the next frame along the same + axis, and so on: the divider stops when every frame on that side is at its minimum. Frames + side by side across the axis shrink together, and the next frame gives way once one of them + is at its minimum. The line of frames ends at a split across the axis or at a dock; every + other frame keeps its size. Dividers between stacked panels and between the groups of a dock + column work the same way. Where a divider ends on another divider, a four-way handle + (`Divider::Intersection`) moves both. - Every frame has the same minimum, `DockStyle::min_pane` (plus its tab strip), unless its panels ask for more through `PanelLimits::min`. Frames have no maximum unless every panel in them asks for one through `PanelLimits::max`: a panel without a maximum lifts the maximum of the panels it From cb352b39ffa84cd94060c1ac1b0a756937969854 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 03:06:11 +0000 Subject: [PATCH 93/94] docking: all four drop zones of a group share one depth Each side zone reaches zone_depth into the body, or a quarter of the body's smaller side when that is less. A tall narrow group's top and bottom zones are no deeper than its left and right ones. --- crates/ui/src/docking/surface.rs | 6 +++--- crates/ui/src/docking/targets.rs | 19 ++++++++++--------- crates/ui/src/docking/tests.rs | 17 ++++++++++++----- docs/ui-docking.md | 4 ++-- 4 files changed, 27 insertions(+), 19 deletions(-) diff --git a/crates/ui/src/docking/surface.rs b/crates/ui/src/docking/surface.rs index f133f190fe..64046b3230 100644 --- a/crates/ui/src/docking/surface.rs +++ b/crates/ui/src/docking/surface.rs @@ -51,9 +51,9 @@ pub struct DockStyle { /// The outer edge band also runs along the left and right edges, where a drop adds a /// full-height column. Off: only the top and bottom edges add a full-width row. pub side_edge_zones: bool, - /// How far a group's side drop zones reach into its body, below the tab strip. A body less - /// than three times as wide or tall gets zones a third of its extent deep in that axis, so - /// it keeps a center. + /// How far a group's side drop zones reach into its body, below the tab strip. All four + /// zones share one depth: this, or a quarter of the body's smaller side when that is less, + /// so the body keeps a center. pub zone_depth: f32, /// [D] The docked area's left and right edges, where no dock is yet, take a drop as a new /// dock (see [`Self::new_dock_band`]). diff --git a/crates/ui/src/docking/targets.rs b/crates/ui/src/docking/targets.rs index 89e235e0bc..82eec32507 100644 --- a/crates/ui/src/docking/targets.rs +++ b/crates/ui/src/docking/targets.rs @@ -1,4 +1,4 @@ -use egui::{Pos2, Rangef, Rect, Vec2, pos2, vec2}; +use egui::{Pos2, Rangef, Rect, Vec2, pos2}; use super::{Placement, Side, Target, Zone}; @@ -32,10 +32,11 @@ pub(super) fn usable(rect: Rect) -> bool { } /// Tab header (the top `tab_height` of `rect`) is the center; otherwise the nearest side zone of -/// the body below it wins. A side zone reaches `depth` into the body, or a third of the body's -/// extent in that axis when that is less, so a body always keeps a center; a `depth` of zero -/// or less leaves only the center. Outside, non-finite, empty and inverted rectangles have no -/// target. +/// the body below it wins. Every side zone reaches the same depth into the body: `depth`, or a +/// quarter of the body's smaller side when that is less, so a body always keeps a center and a +/// narrow body's top and bottom zones are no deeper than its left and right ones. A `depth` of +/// zero or less leaves only the center. Outside, non-finite, empty and inverted rectangles have +/// no target. pub fn drop_zone(rect: Rect, tab_height: f32, depth: f32, pointer: Pos2) -> Option { if !usable(rect) || !pointer.is_finite() || !rect.contains(pointer) || !tab_height.is_finite() || tab_height < 0.0 { return None; @@ -65,10 +66,10 @@ fn body(rect: Rect, tab_height: f32) -> Rect { } /// How deep the side zones of `body` reach in from its left and right edges (`x`) and its top -/// and bottom edges (`y`). +/// and bottom edges (`y`): the same on all four sides. fn side_depths(body: Rect, depth: f32) -> Vec2 { let depth = if depth > 0.0 { depth } else { 0.0 }; - vec2(depth.min(body.width() / 3.0), depth.min(body.height() / 3.0)) + Vec2::splat(depth.min(body.width().min(body.height()) / 4.0)) } /// The outline of a drop zone of the group drawn at `rect`, as [`drop_zone`] finds it with the @@ -152,8 +153,8 @@ pub fn tab_insertion_marker(target: &DropTarget

, before: Option<&P>) - /// Resolve a pointer against visible groups. The frontmost containing group occludes groups /// behind it even if it rejects the drop. A strip reorders by midpoint; the body of the source /// group is a no-op at center. The body's side zones are [`drop_zone`]'s with `zone_depth` (see -/// [`crate::docking::DockStyle::zone_depth`]). Floating groups normally set `allow_splits` to -/// false. +/// [`crate::docking::DockStyle::zone_depth`]): one depth on all four sides, at most a quarter of +/// the body's smaller side. Floating groups normally set `allow_splits` to false. pub fn resolve_drop(panel: &P, pointer: Pos2, targets: &[DropTarget

], zone_depth: f32) -> Option> { if !pointer.is_finite() || targets.len() > super::MAX_PANELS { return None; diff --git a/crates/ui/src/docking/tests.rs b/crates/ui/src/docking/tests.rs index 2a3d7c56f2..80c1fb97d3 100644 --- a/crates/ui/src/docking/tests.rs +++ b/crates/ui/src/docking/tests.rs @@ -303,23 +303,30 @@ fn pointer_targets_distinguish_reorder_center_split_and_occlusion() { } #[test] -fn side_zones_are_40_pt_deep_or_a_third_of_a_small_body() { +fn side_zones_are_40_pt_deep_or_a_quarter_of_the_bodys_smaller_side() { let depth = DockStyle::default().zone_depth; assert_eq!(depth, 40.0); // The inner corner of the left trapezoid is the depth of both bands. let inner = |rect: Rect| zone_shape(rect, 0.0, depth, Zone::Left).unwrap()[1] - rect.min; - for size in [vec2(600.0, 400.0), vec2(130.0, 130.0)] { + for size in [vec2(600.0, 400.0), vec2(160.0, 160.0)] { let rect = Rect::from_min_size(pos2(10.0, 20.0), size); assert_eq!(inner(rect), vec2(40.0, 40.0), "{size:?}"); let y = rect.center().y; assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 39.0, y)), Some(Zone::Left), "{size:?}"); assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 41.0, y)), Some(Zone::Center), "{size:?}"); } - // A 90 pt body keeps a 30 pt center. + // A 90 pt body keeps a 45 pt center. let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(90.0, 90.0)); - assert_eq!(inner(rect), vec2(30.0, 30.0)); + assert_eq!(inner(rect), vec2(22.5, 22.5)); assert_eq!(drop_zone(rect, 0.0, depth, rect.center()), Some(Zone::Center)); - assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 29.0, rect.center().y)), Some(Zone::Left)); + assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.left() + 22.0, rect.center().y)), Some(Zone::Left)); + // A tall narrow body: its top and bottom zones are as deep as its left and right ones. + let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(120.0, 600.0)); + assert_eq!(inner(rect), vec2(30.0, 30.0)); + let top = zone_shape(rect, 0.0, depth, Zone::Top).unwrap(); + assert_eq!(top[2].y - rect.top(), 30.0); + assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.center().x, rect.top() + 29.0)), Some(Zone::Top)); + assert_eq!(drop_zone(rect, 0.0, depth, pos2(rect.center().x, rect.top() + 31.0)), Some(Zone::Center)); // The bands start below the tab header. let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(600.0, 400.0)); assert_eq!(drop_zone(rect, 24.0, depth, pos2(rect.center().x, rect.top() + 60.0)), Some(Zone::Top)); diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 2cac493d9a..33b27d0924 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -211,8 +211,8 @@ A flyout fits its content the same way, without the title bar. limits and the screen. A focused resize handle moves its edge 8 pt per arrow key. - Over a frame, the tab strip and the middle join its tabs, and the nearest side splits it. The side zones are trapezoids along the four edges of the body below the tab strip, like a picture - frame: `DockStyle::zone_depth` (40 pt) deep, or a third of the body's width or height when that - is less, so every frame keeps a center. A split that would leave either half without + frame, all four the same depth: `DockStyle::zone_depth` (40 pt), or a quarter of the body's + smaller side when that is less, so every frame keeps a center. A split that would leave either half without `DockStyle::min_pane` joins the frame's tabs instead. The gap between two frames is no target. - The outer edge band (`DockStyle::edge_band`) takes a drop as a new frame across the whole window side: top and bottom, and left and right with `side_edge_zones`. It takes a quarter of From 2cad4d2bec62f80b4bf59e6376504e63ec5a25b2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 24 Oct 2026 03:13:34 +0000 Subject: [PATCH 94/94] docking: clippy, a type for a split's children and one argument for a node and its rect --- crates/ui/src/docking/render/mod.rs | 4 ++-- crates/ui/src/docking/render/sizes.rs | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/docking/render/mod.rs b/crates/ui/src/docking/render/mod.rs index 2f16a8d05e..9867b24d6f 100644 --- a/crates/ui/src/docking/render/mod.rs +++ b/crates/ui/src/docking/render/mod.rs @@ -143,7 +143,7 @@ impl Renderer<'_, P> { let actions = self.divider_actions(root, path, response.delta); self.output.actions.extend(actions); } - self.intersections(ui, node, rect, path, split.divider, mark, root); + self.intersections(ui, (node, rect), path, split.divider, mark, root); if self.dividers.len() < crate::docking::model::MAX_NODES { self.dividers.push(DrawnDivider { path: path.clone(), axis: *axis, divider: split.divider }); } @@ -285,7 +285,7 @@ impl Renderer<'_, P> { /// Four-way handles where a divider drawn inside the split `node` (since `mark`) ends on /// the split's own divider: dragging one moves both dividers. - fn intersections(&mut self, ui: &mut Ui, node: &Node

, rect: Rect, path: &[bool], divider: Rect, mark: usize, root: (&Node

, Rect)) { + fn intersections(&mut self, ui: &mut Ui, (node, rect): (&Node

, Rect), path: &[bool], divider: Rect, mark: usize, root: (&Node

, Rect)) { let Node::Split { axis, .. } = node else { return }; let side = (self.style.gap * 3.0).max(12.0); let mut found = Vec::new(); diff --git a/crates/ui/src/docking/render/sizes.rs b/crates/ui/src/docking/render/sizes.rs index 8af0dd5ae3..1c44cc1ad4 100644 --- a/crates/ui/src/docking/render/sizes.rs +++ b/crates/ui/src/docking/render/sizes.rs @@ -15,6 +15,9 @@ use super::{dock::dock_rects, node_limits, split_bounds}; use crate::docking::{DockContent, DockStyle, Node, PanelLimits}; use crate::layout::{SplitAxis, SplitLayout, SplitSize, split_rect}; +/// A split's two children with the rects they are drawn in. +type Children<'n, P> = [(&'n Node

, Rect); 2]; + /// Room a group keeps above its minimum after a drop, so each of its dividers can still /// travel both ways. pub(in crate::docking) const DROP_MARGIN: f32 = 1.0; @@ -169,7 +172,7 @@ impl

Sizer<'_, P> { /// The ancestors that continue the line of the split at the end of `chain` along `axis`: /// each with its children and whether the line runs through its second child, nearest first. /// The line ends at a split across the axis or beside a dock. - fn line<'n>(&self, chain: &[(&'n Node

, Rect)], path: &[bool], axis: SplitAxis) -> Vec<(usize, [(&'n Node

, Rect); 2], bool)> { + fn line<'n>(&self, chain: &[(&'n Node

, Rect)], path: &[bool], axis: SplitAxis) -> Vec<(usize, Children<'n, P>, bool)> { let mut line = Vec::new(); for depth in (0..path.len()).rev() { let Some(&(node, rect)) = chain.get(depth) else { break };