From c518493f938c2746201574ad3e04dea47c69af6d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:08:49 +0000 Subject: [PATCH 01/18] Dock model: a floating window is one column; column rights; stepped columns A floating window holds one Column, the type a dock holds, so collapse to icons (Column.iconic) is the one collapsed state of every column, docked or floating. PanelPlace::Floating names a group of the window's column, and column(), group(), take, insert and every column action work the same for both places. Groups taken out of a column carry its state into any new column they make, so an icon group floated out of a collapsed column stays icons; groups that join a column take that column's state. A floating anchor takes Top, Bottom and Center drops only. Column.steps and SetColumnSteps size a grid panel's column in its own content columns; ResizeColumn refuses a stepped column. Permissions gain collapses and shares_column, checked on the result of every apply (so dry runs refuse alike), and reconcile repairs saved layouts that break them. Workspace format v4: v3 floating trees load as columns, a tree split side by side becoming one window per part at its share of the saved rect. Floating.minimized and ResizeWindowSplit are removed. --- crates/behavior/src/dock/action.rs | 72 ++--- crates/behavior/src/dock/apply.rs | 61 +++- crates/behavior/src/dock/edit.rs | 392 ++++++++++---------------- crates/behavior/src/dock/groups.rs | 139 ++++++--- crates/behavior/src/dock/inner.rs | 147 ++++++---- crates/behavior/src/dock/layout.rs | 122 ++++---- crates/behavior/src/dock/node.rs | 229 ++++++++++----- crates/behavior/src/dock/policy.rs | 28 +- crates/behavior/src/dock/workspace.rs | 72 ++++- 9 files changed, 721 insertions(+), 541 deletions(-) diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index eb862807a..3b8b7b5d2 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -22,7 +22,7 @@ pub enum DockPlacement

{ before: Option

, }, /// Center inserts after the anchor; sides split the anchor's frame into two halves, and - /// every other frame keeps its size. Sides apply to `Tabs` and `Stack` nodes only. + /// every other frame keeps its size. Sides apply to `Tabs` and `Stack` nodes of the docked tree only. Split(DockSide), /// A side [`DockPlacement::Split`] that gives the new frame its own room instead of half the /// anchor's frame: the new split takes `size`, and `outer` replaces the size of the nearest @@ -40,8 +40,7 @@ pub enum DockPlacement

{ /// New size of the enclosing split that gives up the room. outer: SplitSize, }, - /// 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. + /// A new group above or below the anchor's group in its column, docked or floating. /// `height` is the inserted group's preferred height (`Group::height`); `None` /// keeps a moved group's own height, or shares the free height for a new group. #[non_exhaustive] @@ -52,7 +51,8 @@ pub enum DockPlacement

{ #[serde(default, skip_serializing_if = "Option::is_none")] height: Option, }, - /// A new column before (towards the window edge) or after the anchor's column. + /// A new column before (towards the window edge) or after the anchor's column in a dock. A floating window is + /// one column, so an anchor there refuses it. #[non_exhaustive] Column { /// Places the new column after the anchor's column; false places it before. @@ -170,17 +170,6 @@ pub enum Action

{ /// The new size. size: SplitSize, }, - /// [`Action::ResizeSplit`] in the floating window holding `panel`, with a path from its - /// root. - #[non_exhaustive] - ResizeWindowSplit { - /// The panel the action applies to. - panel: P, - /// Path from the root: false is the first child, true the second. - path: Vec, - /// The new size. - size: SplitSize, - }, /// Open or close the panel's entry in its accordion stack. #[non_exhaustive] SetStackOpen { @@ -218,7 +207,8 @@ pub enum Action

{ /// Moves towards the start; false moves towards the end. up: bool, }, - /// Move the dock column containing `panel`. `Float` makes a window of its groups. + /// Move the column containing `panel`, docked or a floating window's, with its state. `Float` makes a window of + /// it. #[non_exhaustive] MoveColumn { /// The panel the action applies to. @@ -252,8 +242,7 @@ pub enum Action

{ /// The panel the action applies to. panel: P, }, - /// 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. + /// Minimize the panel's group to its tab strip, docked or floating. On an accordion entry, closes it. #[non_exhaustive] SetMinimized { /// The panel the action applies to. @@ -261,7 +250,9 @@ pub enum Action

{ /// Only the title bar or tab strip shows. minimized: bool, }, - /// Collapse the panel's dock column to icons, or expand it. + /// Collapse the panel's column to icons, or expand it, docked or floating. Refused + /// ([`DockError::NotAllowed`](super::DockError::NotAllowed)) for a column holding a panel that does not + /// collapse ([`Permissions::collapses`]). #[non_exhaustive] SetIconic { /// The panel the action applies to. @@ -269,7 +260,9 @@ pub enum Action

{ /// Collapses the column to an icon strip. iconic: bool, }, - /// Set the expanded width in points of the panel's dock column. + /// Set the expanded width in points of the panel's column; a floating window's rect takes it. Refused + /// ([`DockError::InvalidPlacement`](super::DockError::InvalidPlacement)) for a stepped column + /// ([`Column::steps`](super::Column::steps)). #[non_exhaustive] ResizeColumn { /// The panel the action applies to. @@ -277,6 +270,15 @@ pub enum Action

{ /// Width in points. width: f32, }, + /// Set the width of the panel's column, docked or floating, to `steps` of its panel's content columns + /// ([`Column::steps`](super::Column::steps)). At least 1. + #[non_exhaustive] + SetColumnSteps { + /// The panel the action applies to. + panel: P, + /// Content columns. + steps: u16, + }, /// Preferred height of a dock group or of an accordion entry. #[non_exhaustive] ResizeGroup { @@ -285,7 +287,7 @@ pub enum Action

{ /// Preferred height in points; `None` shares the free height. height: Option, }, - /// Set the width in points of the flyout of the dock group holding the panel; `None` takes the column's width. + /// Set the width in points of the flyout of the group holding the panel; `None` takes the column's width. #[non_exhaustive] ResizeFlyoutWidth { /// The panel the action applies to. @@ -293,7 +295,7 @@ pub enum Action

{ /// Width in points. width: Option, }, - /// Set the offset in points of the flyout's top from its icons' top, for the dock group holding the panel; + /// Set the offset in points of the flyout's top from its icons' top, for the group holding the panel; /// `None` aligns the flyout with its icons. #[non_exhaustive] MoveFlyoutTop { @@ -302,7 +304,7 @@ pub enum Action

{ /// Offset in points; negative is above the icons. offset: Option, }, - /// Set the width in points of the panel's dock column while iconic; `None` clears it. + /// Set the width in points of the panel's column while iconic; `None` clears it. #[non_exhaustive] ResizeIconic { /// The panel the action applies to. @@ -378,11 +380,6 @@ impl

Action

{ Self::ResizeSplit { path, size } } - /// Builds [`Action::ResizeWindowSplit`]. - pub fn resize_window_split(panel: P, path: Vec, size: SplitSize) -> Self { - Self::ResizeWindowSplit { panel, path, size } - } - /// Builds [`Action::SetStackOpen`]. pub fn set_stack_open(panel: P, open: bool) -> Self { Self::SetStackOpen { panel, open } @@ -443,6 +440,11 @@ impl

Action

{ Self::ResizeColumn { panel, width } } + /// Builds [`Action::SetColumnSteps`]. + pub fn set_column_steps(panel: P, steps: u16) -> Self { + Self::SetColumnSteps { panel, steps } + } + /// Builds [`Action::ResizeGroup`]. pub fn resize_group(panel: P, height: Option) -> Self { Self::ResizeGroup { panel, height } @@ -492,15 +494,15 @@ impl

DockPlacement

{ } impl

DockPlacement

{ - /// Whether the anchor's permissions take this placement: tabs need `accepts_tabs`, side - /// splits `accepts_splits`, and so does a group placed at an anchor in a floating window - /// (`floating`), which splits the anchor's frame. - pub fn allowed_by(&self, anchor: Permissions, floating: bool) -> bool { + /// Whether the anchor's permissions take this placement: tabs need `accepts_tabs` and `shares_column`, a group + /// in the anchor's column `shares_column`, and side splits `accepts_splits`. Whether the moving panels share a + /// column is the apply's own check. + pub fn allowed_by(&self, anchor: Permissions) -> bool { match self { - Self::Tab { .. } | Self::Split(DockSide::Center) => anchor.accepts_tabs, + Self::Tab { .. } | Self::Split(DockSide::Center) => anchor.accepts_tabs && anchor.shares_column, + Self::Group { .. } => anchor.shares_column, Self::Split(_) | Self::SplitSized { .. } => anchor.accepts_splits, - Self::Group { .. } if floating => anchor.accepts_splits, - _ => true, + Self::Column { .. } | Self::Edge(_) => true, } } } diff --git a/crates/behavior/src/dock/apply.rs b/crates/behavior/src/dock/apply.rs index 6e92e556f..d0e6a2a73 100644 --- a/crates/behavior/src/dock/apply.rs +++ b/crates/behavior/src/dock/apply.rs @@ -1,12 +1,14 @@ //! The public transactions of a layout: an action under permissions, atomic, with the panels it closed. -use std::hash::Hash; +use std::{collections::HashSet, hash::Hash}; use super::{ action::Action, + edit::{leaves, tree_panels}, groups::{Target, Unit}, inner::unit_of, layout::Layout, + node::Node, policy::{DockError, Permissions}, }; @@ -19,12 +21,14 @@ impl Layout

{ /// 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. + /// application, particularly Open. The column rights ([`Permissions::collapses`], + /// [`Permissions::shares_column`]) are checked on the result: an action that leaves a panel breaking them, + /// which did not before, is refused, so a drag's dry run refuses it alike. pub fn apply_with_permissions(&mut self, action: Action

, permissions: impl Fn(&P) -> Permissions) -> Result, DockError> { self.validate()?; let action = match action { Action::Open { panel, anchor: None } if self.root.is_some() && !self.contains(&panel) => { - let (anchor, placement) = self.open_place(&permissions).ok_or(DockError::MissingTarget)?; + let (anchor, placement) = self.open_place(&panel, &permissions).ok_or(DockError::MissingTarget)?; Action::OpenAt { panel, anchor, placement } } Action::StepGroup { panel, up } => { @@ -36,8 +40,7 @@ impl Layout

{ } action => action, }; - // A destination in a floating window takes only floatable panels, and a group placed - // there becomes a split of the anchor's frame. + // A destination in a floating window takes only floatable panels. let floats = |anchor: &P| self.floating.iter().any(|w| w.contains(anchor)); match &action { Action::Move { panel, anchor, placement } | Action::OpenAt { panel, anchor, placement } => { @@ -46,7 +49,7 @@ impl Layout

{ if !opens && !permissions(panel).movable { return Err(DockError::NotAllowed); } - if !placement.allowed_by(permissions(anchor), floats(anchor)) || floats(anchor) && !permissions(panel).floatable { + if !placement.allowed_by(permissions(anchor)) || floats(anchor) && !permissions(panel).floatable { return Err(DockError::NotAllowed); } } @@ -69,7 +72,7 @@ impl Layout

{ && match to { Target::Float { .. } => policy.floatable, Target::At { anchor, placement } => { - placement.allowed_by(permissions(anchor), floats(anchor)) && (!floats(anchor) || policy.floatable) + placement.allowed_by(permissions(anchor)) && (!floats(anchor) || policy.floatable) } Target::NewDock { .. } => true, }; @@ -86,7 +89,7 @@ impl Layout

{ Target::Float { .. } if members.iter().any(|p| !permissions(p).floatable) => return Err(DockError::NotAllowed), Target::At { anchor, placement } if !members.contains(anchor) - && (!placement.allowed_by(permissions(anchor), floats(anchor)) + && (!placement.allowed_by(permissions(anchor)) || floats(anchor) && members.iter().any(|p| !permissions(p).floatable)) => { return Err(DockError::NotAllowed); @@ -110,8 +113,46 @@ impl Layout

{ let mut proposed = self.clone(); proposed.apply_inner(action, &|p| permissions(p).is_protected())?; proposed.validate()?; - *self = proposed; - Ok(closed) + if !proposed.breaks_columns_beyond(self, &permissions) { + *self = proposed; + return Ok(closed); + } + Err(DockError::NotAllowed) + } + + /// Whether a panel breaks its column rights in this layout that did not in `before`. + pub(super) fn breaks_columns_beyond(&self, before: &Self, permissions: &impl Fn(&P) -> Permissions) -> bool { + let breaches = self.column_breaches(permissions); + !breaches.is_empty() && !breaches.is_subset(&before.column_breaches(permissions)) + } + + /// The panels that break their column rights: a panel that does not collapse ([`Permissions::collapses`]) in + /// a collapsed column, and every panel of a column (or node of the docked tree) that holds a panel that does + /// not share it ([`Permissions::shares_column`]) beside another panel. + pub(super) fn column_breaches(&self, permissions: &impl Fn(&P) -> Permissions) -> HashSet

{ + let mut breaches = HashSet::new(); + let mut check = |panels: Vec<&P>, iconic: bool| { + if iconic { + breaches.extend(panels.iter().filter(|p| !permissions(p).collapses).map(|p| (*p).clone())); + } + if panels.len() > 1 && panels.iter().any(|p| !permissions(p).shares_column) { + breaches.extend(panels.into_iter().cloned()); + } + }; + for window in &self.floating { + check(window.panels().collect(), window.column.iconic); + } + for (leaf, _) in self.root.as_ref().map(leaves).unwrap_or_default() { + match leaf { + Node::Dock { columns, .. } => { + for column in columns { + check(column.panels().collect(), column.iconic); + } + } + leaf => check(tree_panels(leaf), false), + } + } + breaches } /// Apply every action in order, or none: the first rejection leaves the layout unchanged. diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 791a97638..bceb449b5 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -87,43 +87,6 @@ pub fn first_active

(root: &Node

) -> Option<&P> { } } -/// The groups of a tree, first to last: what a dock column takes from a floating window. -pub(crate) 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: Axis::Y, 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: DockSide) -> bool { @@ -194,10 +157,8 @@ impl Layout

{ /// The place of `panel`, or `None` when it is absent. pub fn place(&self, panel: &P) -> Option { for (w, window) in self.floating.iter().enumerate() { - for (leaf, path) in leaves(&window.root) { - if leaf_holds(leaf, panel) { - return Some(PanelPlace::Floating { window: w, path }); - } + if let Some(g) = window.column.groups.iter().position(|group| group.panels.contains(panel)) { + return Some(PanelPlace::Floating { window: w, group: g }); } } for (leaf, path) in self.root.as_ref().map(leaves).unwrap_or_default() { @@ -216,10 +177,9 @@ impl Layout

{ None } - /// The `Tabs` or `Stack` node at a tree place. + /// The `Tabs` or `Stack` node at a place of the docked tree. pub fn node_of(&self, place: &PanelPlace) -> Option<&Node

> { - let (window, path) = place.tree_path()?; - node_at(self.tree(window)?, path) + node_at(self.root.as_ref()?, place.tree_path()?) } /// The path of the `Dock` node on `side`, when the layout has one. @@ -296,21 +256,37 @@ impl Layout

{ docked.iter().find(|p| protected(p) == narrowed).or(docked.first()).map(|p| (*p).clone()) } - /// The dock column at `place`; `None` for a place outside a dock. + /// The column at `place`: a dock column or a floating window's column; `None` for a node of the docked tree. pub fn column(&self, place: &PanelPlace) -> Option<&Column

> { - let PanelPlace::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, + match place { + PanelPlace::Dock { path, column, .. } => match self.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Dock { columns, .. }) => columns.get(*column), + _ => None, + }, + PanelPlace::Floating { window, .. } => self.floating.get(*window).map(|w| &w.column), + PanelPlace::Node(_) => None, } } - /// The dock group at `place`; `None` for a `Tabs` or `Stack` node. + /// The group at `place` of a dock column or a floating window; `None` for a `Tabs` or `Stack` node. pub fn group(&self, place: &PanelPlace) -> Option<&Group

> { - match place { - PanelPlace::Dock { group, .. } => self.column(place)?.groups.get(*group), - PanelPlace::Node(_) | PanelPlace::Floating { .. } => None, - } + self.column(place)?.groups.get(place.group_index()?) + } + + /// Whether opening `panel` shows its column's flyout instead of the column: its column is collapsed to icons. + pub fn opens_in_flyout(&self, panel: &P) -> bool { + self.place(panel).is_some_and(|place| self.column(&place).is_some_and(|column| column.iconic)) + } +} + +/// A column without its sizes: its groups and their state, and whether it is collapsed. +fn column_shape(column: &Column

) -> Column

{ + Column { + groups: column.groups.iter().map(|g| Group { height: None, flyout_width: None, flyout_offset: None, ..g.clone() }).collect(), + width: None, + iconic: column.iconic, + iconic_width: None, + steps: None, } } @@ -344,49 +320,17 @@ impl Layout

{ } Node::Tabs { panels, active } => Node::Tabs { panels: panels.clone(), active: *active }, Node::Stack { entries } => Node::Stack { entries: entries.iter().map(|e| StackEntry { height: None, ..e.clone() }).collect() }, - Node::Dock { side, columns } => Node::Dock { - side: *side, - columns: columns - .iter() - .map(|c| Column { - groups: c.groups.iter().map(|g| Group { height: None, flyout_width: None, flyout_offset: None, ..g.clone() }).collect(), - width: None, - iconic: c.iconic, - iconic_width: None, - }) - .collect(), - }, + Node::Dock { side, columns } => Node::Dock { side: *side, columns: columns.iter().map(column_shape).collect() }, } } Layout { root: self.root.as_ref().map(node), - floating: self.floating.iter().map(|w| Floating { root: node(&w.root), rect: Rect::ZERO, native: None, ..w.clone() }).collect(), + floating: self.floating.iter().map(|w| Floating { column: column_shape(&w.column), rect: Rect::ZERO, native: None, ..w.clone() }).collect(), } } - /// The docked layout (`None`) or a floating window's tree. - pub(crate) 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)) - } - pub(super) fn node_of_mut(&mut self, place: &PanelPlace) -> Option<&mut Node

> { - let (window, path) = place.tree_path()?; - node_at_mut(self.tree_mut(window)?, path) + node_at_mut(self.root.as_mut()?, place.tree_path()?) } pub(super) fn columns_mut(&mut self, path: &[bool]) -> Option<&mut Vec>> { @@ -397,33 +341,55 @@ impl Layout

{ } pub(super) fn column_mut(&mut self, place: &PanelPlace) -> Option<&mut Column

> { - let PanelPlace::Dock { path, column, .. } = place else { return None }; - self.columns_mut(path)?.get_mut(*column) + match place { + PanelPlace::Dock { path, column, .. } => self.columns_mut(path)?.get_mut(*column), + PanelPlace::Floating { window, .. } => self.floating.get_mut(*window).map(|w| &mut w.column), + PanelPlace::Node(_) => None, + } } pub(super) fn group_mut(&mut self, place: &PanelPlace) -> Option<&mut Group

> { + let group = place.group_index()?; + self.column_mut(place)?.groups.get_mut(group) + } + + /// The state a new column made of groups taken from the column at `place` keeps ([`Column::emptied`]), with a + /// floating window's width; no state for a place outside a column. + pub(super) fn source_column(&self, place: &PanelPlace) -> Column

{ + let mut state = self.column(place).map_or_else(|| Column::new(Vec::new()), Column::emptied); + if let PanelPlace::Floating { window, .. } = place + && let Some(window) = self.floating.get(*window) + { + state.width = Some(window.rect.width()); + } + state + } + + /// Removes the column at `place` when it holds no group: a dock column (and its dock when that empties too), or + /// a floating window. Returns the id of a window it removed. + fn drop_if_empty(&mut self, place: &PanelPlace) -> Option { + if !self.column(place).is_some_and(|column| column.groups.is_empty()) { + return None; + } match place { - PanelPlace::Dock { group, .. } => self.column_mut(place)?.groups.get_mut(*group), - PanelPlace::Node(_) | PanelPlace::Floating { .. } => None, + PanelPlace::Dock { path, column, .. } => { + let columns = self.columns_mut(path)?; + columns.remove(*column); + if columns.is_empty() { + self.take_node(path); + } + None + } + PanelPlace::Floating { window, .. } => Some(self.floating.remove(*window).id), + PanelPlace::Node(_) => None, } } /// 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> { - self.take_node_in(None, path) - } - - /// [`Self::take_node`] in the docked layout (`None`) or a floating window, which closes - /// when its root goes. - pub(super) 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))?; + 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; } @@ -445,19 +411,14 @@ 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, PanelPlace::Node(_) | PanelPlace::Floating { .. }) => match self.node_of(&place) { + (Unit::Group, PanelPlace::Node(_)) => match self.node_of(&place) { 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, PanelPlace::Dock { .. }) => { - let column = self.column(&place).ok_or(DockError::MissingPanel)?; - Ok(column.groups.iter().flat_map(|g| g.panels.iter().cloned()).collect()) - } - (Unit::Window, PanelPlace::Floating { window, .. }) => { - let window = self.floating.get(*window).ok_or(DockError::MissingPanel)?; - Ok(window.panels().cloned().collect()) + (Unit::Column, PanelPlace::Dock { .. } | PanelPlace::Floating { .. }) | (Unit::Window, PanelPlace::Floating { .. }) => { + Ok(self.column(&place).ok_or(DockError::MissingPanel)?.panels().cloned().collect()) } (Unit::Column | Unit::Window, _) => Err(DockError::InvalidPlacement), } @@ -471,114 +432,74 @@ impl Layout

{ } } - /// Detaches the panel's group, keeping its dock dimensions and floating-window geometry. A stack entry becomes a - /// single-panel group with its saved height. + /// Detaches the panel's group with the state of the column it leaves; a floating window's last group carries + /// the window's id. A stack entry becomes a single-panel group with its saved height. pub(super) fn take_group(&mut self, panel: &P) -> Result, DockError> { let place = self.place(panel).ok_or(DockError::MissingPanel)?; - match place { - PanelPlace::Node(_) | PanelPlace::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.minimized, w.id)); - let whole = |moving: Moving

| match source { - Some((rect, minimized, id)) if path.is_empty() => Moving { width: Some(rect.width()), minimized, id: Some(id), ..moving }, - Some((rect, ..)) => Moving { width: Some(rect.width()), ..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, - flyout_width: None, - flyout_offset: None, - }; - let moving = whole(Moving::group(group)); - return Ok(Moving { id: None, ..moving }); - } - 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(whole(Moving::group(Group { - panels: vec![entry.panel], - active: 0, - minimized: !entry.open, - height: entry.height, - flyout_width: None, - flyout_offset: None, - }))) - } - _ => Err(DockError::MissingPanel), - } + let PanelPlace::Node(path) = &place else { + let source = self.source_column(&place); + let group = place.group_index().ok_or(DockError::MissingPanel)?; + let column = self.column_mut(&place).ok_or(DockError::MissingPanel)?; + if group >= column.groups.len() { + return Err(DockError::MissingPanel); } - PanelPlace::Dock { path, column, group } => { + let taken = column.groups.remove(group); + let id = self.drop_if_empty(&place); + return Ok(Moving { id, ..Moving::taken(taken, source) }); + }; + if let Some(Node::Stack { entries }) = self.node_of_mut(&place) + && entries.len() > 1 + && let Some(index) = entries.iter().position(|e| &e.panel == panel) + { + return Ok(Moving::group(entries.remove(index).into_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 => Ok(Moving::group(entries.remove(0).into_group())), + _ => Err(DockError::MissingPanel), + } + } + + /// Detaches the panel's column: a dock column, or a floating window's, which takes the window's width and id + /// along. + pub(super) fn take_column(&mut self, panel: &P) -> Result, DockError> { + match self.place(panel) { + Some(PanelPlace::Dock { path, column, .. }) => { 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() { + if column >= columns.len() { return Err(DockError::MissingPanel); } - let taken = source.groups.remove(group); - let width = source.width; - if source.groups.is_empty() { - columns.remove(column); - } + let taken = columns.remove(column); if columns.is_empty() { self.take_node(&path); } - Ok(Moving { width, ..Moving::group(taken) }) + Ok(Moving { column: taken, id: None }) } + Some(PanelPlace::Floating { window, .. }) => { + if window >= self.floating.len() { + return Err(DockError::MissingPanel); + } + let taken = self.floating.remove(window); + Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) }) + } + Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement), } } - pub(super) fn take_column(&mut self, panel: &P) -> Result, DockError> { - let Some(PanelPlace::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, - node: None, - minimized: false, - width: taken.width, - iconic: taken.iconic, - iconic_width: taken.iconic_width, - id: None, - }) - } - + /// Detaches the floating window holding the panel: its column. pub(super) fn take_window(&mut self, panel: &P) -> Result, DockError> { - let Some(PanelPlace::Floating { window, .. }) = self.place(panel) else { return Err(DockError::InvalidPlacement) }; - if window >= self.floating.len() { - return Err(DockError::MissingPanel); + match self.place(panel) { + Some(PanelPlace::Floating { .. }) => self.take_column(panel), + _ => Err(DockError::InvalidPlacement), } - let taken = self.floating.remove(window); - Ok(Moving { - groups: tree_groups(&taken.root), - node: Some(taken.root), - minimized: taken.minimized, - width: Some(taken.rect.width()), - iconic: false, - iconic_width: None, - id: Some(taken.id), - }) } - /// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). + /// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating, + /// keeps the moving column's state; groups that join a column take that column's. /// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]). pub(super) fn insert_moving(&mut self, moving: Moving

, to: Target

, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> { - if moving.groups.is_empty() || moving.groups.iter().any(|g| g.panels.is_empty()) { + let mut moving = moving; + if moving.column.groups.is_empty() || moving.column.groups.iter().any(|g| g.panels.is_empty()) { return Err(DockError::MissingPanel); } match to { @@ -586,11 +507,8 @@ impl Layout

{ if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } - let root = match moving.node { - Some(node) => node, - None => stack_tree(moving.groups).ok_or(DockError::MissingPanel)?, - }; - let window = Floating { minimized: moving.minimized, ..Floating::new(root, rect) }; + // A window's width is its rect's. + let window = Floating::new(Column { width: None, ..moving.column }, rect); self.floating.push(Floating { id: moving.id.unwrap_or(window.id), ..window }); Ok(()) } @@ -627,48 +545,32 @@ impl Layout

{ self.merge(&place, index, moving) } DockPlacement::Split(zone) => { - 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) } + let path = place.tree_path().ok_or(DockError::InvalidPlacement)?; + let (panels, active) = flatten(moving.column.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) } } DockPlacement::SplitSized { zone, size, outer } => { - 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_sized(root, path, new, zone, size, outer) { Ok(()) } else { Err(DockError::InvalidPlacement) } - } - // A floating window is a tree: a group above or below splits the anchor's group. - DockPlacement::Group { below, .. } if matches!(place, PanelPlace::Floating { .. }) => { - let zone = if below { DockSide::Bottom } else { DockSide::Top }; - self.insert_moving(moving, Target::At { anchor, placement: DockPlacement::Split(zone) }, canvas) + let path = place.tree_path().ok_or(DockError::InvalidPlacement)?; + let (panels, active) = flatten(moving.column.groups); + let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; + if split_frame_sized(root, path, Node::Tabs { panels, active }, zone, size, outer) { + Ok(()) + } else { + Err(DockError::InvalidPlacement) + } } DockPlacement::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); + moving.column.groups.iter_mut().for_each(|group| group.height = height); } - let (groups, index) = match &place { - PanelPlace::Dock { group, .. } => (&mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups, *group), - PanelPlace::Node(_) | PanelPlace::Floating { .. } => return Err(DockError::InvalidPlacement), - }; + let index = place.group_index().ok_or(DockError::InvalidPlacement)?; + let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups; let index = (index + usize::from(below)).min(groups.len()); - groups.splice(index..index, moving.groups); + groups.splice(index..index, moving.column.groups); Ok(()) } DockPlacement::Edge(zone) => { @@ -681,7 +583,7 @@ impl Layout

{ if matches!(node, Node::Dock { .. }) { return Err(DockError::InvalidPlacement); } - let (panels, active) = flatten(moving.groups); + let (panels, active) = flatten(moving.column.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, DockSide::Top | DockSide::Bottom) { Axis::Y } else { Axis::X }; @@ -720,7 +622,7 @@ impl Layout

{ pub(super) fn index_in(&self, place: &PanelPlace, panel: &P) -> Option { match place { - PanelPlace::Node(_) | PanelPlace::Floating { .. } => match self.node_of(place)? { + PanelPlace::Node(_) => 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, @@ -732,9 +634,9 @@ impl Layout

{ /// Join every moving panel to the group at `place`, before `index` or at the end. The first /// moving group's active panel becomes active. pub(super) fn merge(&mut self, place: &PanelPlace, index: Option, moving: Moving

) -> Result<(), DockError> { - let (panels, selected) = flatten(moving.groups); + let (panels, selected) = flatten(moving.column.groups); match place { - PanelPlace::Node(_) | PanelPlace::Floating { .. } => match self.node_of_mut(place) { + PanelPlace::Node(_) => match self.node_of_mut(place) { Some(Node::Tabs { panels: target, active }) => { splice(target, active, index.unwrap_or(target.len()), panels, selected); Ok(()) @@ -771,5 +673,5 @@ pub(super) fn flatten

(groups: Vec>) -> (Vec

, usize) { } pub(super) fn valid_column

(column: &Column

) -> bool { - column.width.is_none_or(valid_width) && column.iconic_width.is_none_or(valid_width) + column.width.is_none_or(valid_width) && column.iconic_width.is_none_or(valid_width) && column.steps != Some(0) } diff --git a/crates/behavior/src/dock/groups.rs b/crates/behavior/src/dock/groups.rs index 38475c93e..8738b920b 100644 --- a/crates/behavior/src/dock/groups.rs +++ b/crates/behavior/src/dock/groups.rs @@ -18,7 +18,7 @@ pub enum DockEdge { End, } -/// Tabs that move, minimize and size together in a dock column. +/// Tabs that move, minimize and size together in a column, docked or floating. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(bound(deserialize = "P: serde::Deserialize<'de>"))] #[non_exhaustive] @@ -55,7 +55,7 @@ impl

Group

{ } } -/// One column of a dock: groups from top to bottom. +/// One column of groups from top to bottom: a column of a dock, or the whole of a floating window. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(bound(deserialize = "P: serde::Deserialize<'de>"))] #[non_exhaustive] @@ -63,14 +63,20 @@ pub struct Column

{ /// The groups, top to bottom. pub groups: Vec>, /// Expanded width in points once the user has resized the column; the theme's column width until then. + /// A floating window's width is its rect's, so a floating column leaves this `None`. #[serde(default)] pub width: Option, - /// Collapsed to one icon per panel. + /// Collapsed to one icon per panel. The one collapsed state of every column, docked or floating. #[serde(default)] pub iconic: bool, /// Width while iconic; labels show beside the icons when it is wide enough. #[serde(default)] pub iconic_width: Option, + /// The column's width as a count of its panel's own content columns, for a panel that lays its content in a + /// grid (a toolbar). When set, `width` is unused and the column is as tall as its content, docked or floating; + /// the renderer computes the shown size from the panel. At least 1. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub steps: Option, } impl GroupLocation { @@ -95,16 +101,29 @@ impl GroupLocation { } impl ColumnLocation { - /// A column location on `side`, `width` points wide when expanded (the theme's column width for `None`). - pub const fn new(side: DockEdge, width: Option, iconic: bool, iconic_width: Option) -> Self { - Self { side, width, iconic, iconic_width } + /// A column location on `side` (`None` for a floating window's column), `width` points wide when expanded (the + /// theme's column width for `None`). + pub const fn new(side: Option, width: Option, iconic: bool, iconic_width: Option) -> Self { + Self { side, width, iconic, iconic_width, steps: None } + } + + /// The location with the column `steps` content columns wide ([`Column::steps`]). + #[must_use] + pub const fn with_steps(mut self, steps: Option) -> Self { + self.steps = steps; + self + } + + /// The location of `column`, docked on `side` or floating (`None`). + pub(super) fn of

(column: &Column

, side: Option) -> Self { + Self { side, width: column.width, iconic: column.iconic, iconic_width: column.iconic_width, steps: column.steps } } } impl

Column

{ /// A column of `groups`, expanded at the theme's column width until the user resizes it. pub fn new(groups: Vec>) -> Self { - Self { groups, width: None, iconic: false, iconic_width: None } + Self { groups, width: None, iconic: false, iconic_width: None, steps: None } } /// The column resized to `width` points. @@ -113,6 +132,30 @@ impl

Column

{ self.width = Some(width); self } + + /// The column collapsed to icons, or expanded. + #[must_use] + pub fn with_iconic(mut self, iconic: bool) -> Self { + self.iconic = iconic; + self + } + + /// The column `steps` content columns wide ([`Self::steps`]). + #[must_use] + pub fn with_steps(mut self, steps: u16) -> Self { + self.steps = Some(steps); + self + } + + /// Every panel of the column, top group first. + pub fn panels(&self) -> impl Iterator { + self.groups.iter().flat_map(|g| &g.panels) + } + + /// The column's state without its groups: what a new column made from groups taken out of this one keeps. + pub(super) fn emptied(&self) -> Self { + Self { groups: Vec::new(), width: self.width, iconic: self.iconic, iconic_width: self.iconic_width, steps: self.steps } + } } /// Where a group, column or floating window goes. @@ -149,16 +192,21 @@ impl DockPlacement

{ /// /// | Anchor in | `Center` | `Top`, `Bottom` | `Start`, `End` | /// |---|---|---|---| - /// | the split tree or a floating window | [`DockPlacement::Split`] | `Split` | `Split` | + /// | the split tree | [`DockPlacement::Split`] | `Split` | `Split` | /// | a dock column | `Split(Center)` (join as tabs) | [`DockPlacement::Group`] above or below | [`DockPlacement::Column`] on that side | + /// | a floating window | `Split(Center)` (join as tabs) | `Group` above or below | refused ([`DockError::InvalidPlacement`]) | /// - /// A dock's `Column { after }` counts from its window edge, which is the dock's [`DockEdge`] in reading order; - /// this picks `after` so the new column lands on the side of the anchor's column. + /// A floating window is one column, so nothing goes beside it. A dock's `Column { after }` counts from its + /// window edge, which is the dock's [`DockEdge`] in reading order; this picks `after` so the new column lands on + /// the side of the anchor's column. pub fn for_zone(layout: &Layout

, anchor: &P, side: DockSide) -> Result { let place = layout.place(anchor).ok_or(DockError::MissingTarget)?; Ok(match (place, side) { - (PanelPlace::Node(_) | PanelPlace::Floating { .. }, side) | (_, side @ DockSide::Center) => DockPlacement::Split(side), - (PanelPlace::Dock { .. }, DockSide::Top | DockSide::Bottom) => DockPlacement::Group { below: side == DockSide::Bottom, height: None }, + (PanelPlace::Node(_), side) | (_, side @ DockSide::Center) => DockPlacement::Split(side), + (PanelPlace::Dock { .. } | PanelPlace::Floating { .. }, DockSide::Top | DockSide::Bottom) => { + DockPlacement::Group { below: side == DockSide::Bottom, height: None } + } + (PanelPlace::Floating { .. }, _) => return Err(DockError::InvalidPlacement), (PanelPlace::Dock { path, .. }, _) => { let edge = match layout.root.as_ref().and_then(|root| node_at(root, &path)) { Some(Node::Dock { side, .. }) => *side, @@ -172,7 +220,8 @@ impl DockPlacement

{ } /// 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. +/// windows, so `Front` means "showing": the active tab of an expanded group in an expanded column, docked or +/// floating. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum PanelState { @@ -185,7 +234,7 @@ pub enum PanelState { Front, } -/// The group a closed panel was in, when that group was in a dock. +/// The group a closed panel was in, when that group was in a column, docked or floating. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub struct GroupLocation { @@ -199,7 +248,7 @@ pub struct GroupLocation { /// The offset in points of the group's flyout top from its icons' top, if the user had moved it. #[serde(default, skip_serializing_if = "Option::is_none")] pub flyout_offset: Option, - /// The column, when the group was docked. + /// The column the group was in. pub column: Option, } @@ -207,17 +256,23 @@ pub struct GroupLocation { #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub struct ColumnLocation { - /// The dock edge the column was on. - pub side: DockEdge, + /// The dock edge the column was on; `None` for a floating window's column. + #[serde(default)] + pub side: Option, /// Expanded width in points, if the user had resized the column. pub width: Option, /// Whether the column was collapsed to icons. pub iconic: bool, /// Width in points while iconic. pub iconic_width: Option, + /// The column's width in content columns ([`Column::steps`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub steps: Option, } /// Where a panel is. Paths lead from the root: false is a split's first child, true its second. +/// A dock column and a floating window are both a column of groups, so `Dock` and `Floating` name a group the +/// same way. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum PanelPlace { @@ -233,24 +288,30 @@ pub enum PanelPlace { /// The group's index in the column. group: usize, }, - /// A `Tabs` or `Stack` node of a floating window's tree. + /// A group of a floating window's column. #[non_exhaustive] Floating { /// The window's index. window: usize, - /// The path of the node in the window's tree. - path: Vec, + /// The group's index in the window's column. + group: usize, }, } impl PanelPlace { - /// The tree (`None` for the docked layout, else a floating window) and the path of a - /// `Tabs` or `Stack` node. - pub fn tree_path(&self) -> Option<(Option, &[bool])> { + /// The path of a `Tabs` or `Stack` node of the docked tree; `None` for a group of a column. + pub fn tree_path(&self) -> Option<&[bool]> { match self { - PanelPlace::Node(path) => Some((None, path)), - PanelPlace::Floating { window, path } => Some((Some(*window), path)), - PanelPlace::Dock { .. } => None, + PanelPlace::Node(path) => Some(path), + PanelPlace::Dock { .. } | PanelPlace::Floating { .. } => None, + } + } + + /// The group's index in its column; `None` for a `Tabs` or `Stack` node of the docked tree. + pub fn group_index(&self) -> Option { + match self { + PanelPlace::Dock { group, .. } | PanelPlace::Floating { group, .. } => Some(*group), + PanelPlace::Node(_) => None, } } } @@ -263,27 +324,29 @@ pub(super) enum Unit { Window, } -/// Groups in transit, with the size and state of the container they came from. +/// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or +/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they +/// join keeps its own. 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, - /// The id of a whole floating window in transit, which a new window keeps. + pub column: Column

, + /// The id of a floating window whose last group is in transit, which a new window keeps. pub id: Option, } impl

Moving

{ + /// `group` with no column state: a new column made of it is expanded at the theme's width. pub(super) fn group(group: Group

) -> Self { - Self { groups: vec![group], node: None, minimized: false, width: None, iconic: false, iconic_width: None, id: None } + Self::taken(group, Column::new(Vec::new())) } + /// `group` taken out of a column whose state is `source` ([`Column::emptied`]). + pub(super) fn taken(group: Group

, source: Column

) -> Self { + Self { column: Column { groups: vec![group], ..source }, id: None } + } + + /// The column a new dock column gets: the moving column, `width` points wide unless it brings a width. pub(super) fn into_column(self, width: Option) -> Column

{ - Column { groups: self.groups, width: self.width.or(width), iconic: self.iconic, iconic_width: self.iconic_width } + Column { width: self.column.width.or(width), ..self.column } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index 0cbec3de3..129e1c595 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -3,6 +3,8 @@ use std::{collections::HashSet, hash::Hash}; +use emath::{Rect, vec2}; + use crate::flow::Axis; use super::{ @@ -12,7 +14,7 @@ use super::{ groups::{Column, DockEdge, Group, Moving, PanelPlace, Target, Unit}, layout::Layout, limits::{MAX_DEPTH, MAX_PANELS, valid_active, valid_height, valid_offset, valid_rect, valid_size, valid_width}, - node::{Floating, Node, StackEntry}, + node::{Node, StackEntry}, policy::{DockError, Permissions}, split::SplitSize, }; @@ -37,20 +39,18 @@ impl Layout

{ return Err(DockError::MissingTarget); } } + let source = self.source_of(&panel); let entry = self.take(&panel).ok_or(DockError::MissingPanel)?; - self.insert(entry, &anchor, placement, canvas) + self.insert(entry, source, &anchor, placement, canvas) } Action::Float { panel, rect } => { - if !valid_rect(rect) { - return Err(DockError::InvalidGeometry); - } // A window's only panel keeps the window's id. let lone = self.floating.iter().find(|w| w.contains(&panel)).filter(|w| w.panels().count() == 1).map(|w| w.id); + let source = self.source_of(&panel); // A panel the layout does not hold opens in the new window. let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None }); - let window = Floating::single(vec![entry.panel], 0, rect); - self.floating.push(Floating { id: lone.unwrap_or(window.id), ..window }); - Ok(()) + let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) }; + self.insert_moving(moving, Target::Float { rect }, canvas) } Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel), Action::Activate { panel } => { @@ -61,12 +61,7 @@ impl Layout

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

{ } let entry = StackEntry { panel, open: true, height: None }; if let Some(anchor) = anchor { - self.insert(entry, &anchor, DockPlacement::Tab { before: None }, canvas) + self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas) } else if self.root.is_none() { self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 }); Ok(()) @@ -94,7 +89,7 @@ impl Layout

{ { return Err(DockError::MissingTarget); } - self.insert(StackEntry { panel, open: true, height: None }, &anchor, placement, canvas) + self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas) } Action::MoveFloating { panel, rect } => { if !valid_rect(rect) { @@ -113,18 +108,8 @@ impl Layout

{ } 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); - } - 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.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::MissingPanel)?; + let entry = self.stack_entry_mut(&panel).ok_or(DockError::MissingPanel)?; entry.open = open; Ok(()) } @@ -132,7 +117,7 @@ impl Layout

{ if !valid_height(height) { return Err(DockError::InvalidGeometry); } - let entry = self.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::MissingPanel)?; + let entry = self.stack_entry_mut(&panel).ok_or(DockError::MissingPanel)?; entry.height = height; Ok(()) } @@ -154,8 +139,9 @@ impl Layout

{ Action::MovePanel { panel, to } => match to { Target::At { anchor, placement } => self.apply_inner(Action::Move { panel, anchor, placement }, canvas), to => { + let source = self.source_of(&panel); let entry = self.take(&panel).ok_or(DockError::MissingPanel)?; - self.insert_moving(Moving::group(Group::new(vec![entry.panel], 0)), to, canvas) + self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas) } }, Action::CloseGroup { ref panel } | Action::CloseWindow { ref panel } => self.take_unit(panel, unit_of(&action)).map(|_| ()), @@ -173,11 +159,7 @@ impl Layout

{ group.minimized = minimized; return Ok(()); } - if let PanelPlace::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)?; + let entry = self.stack_entry_mut(&panel).ok_or(DockError::InvalidPlacement)?; entry.open = !minimized; Ok(()) } @@ -190,7 +172,7 @@ impl Layout

{ group.height = height; return Ok(()); } - let entry = self.trees_mut().find_map(|n| stack_entry_mut(n, &panel)).ok_or(DockError::InvalidPlacement)?; + let entry = self.stack_entry_mut(&panel).ok_or(DockError::InvalidPlacement)?; entry.height = height; Ok(()) } @@ -218,7 +200,25 @@ impl Layout

{ if !valid_width(width) { return Err(DockError::InvalidGeometry); } - self.column_of(&panel)?.width = Some(width); + let place = self.place(&panel).ok_or(DockError::MissingPanel)?; + // A stepped column's width is its step count. + if self.column(&place).ok_or(DockError::InvalidPlacement)?.steps.is_some() { + return Err(DockError::InvalidPlacement); + } + if let PanelPlace::Floating { window, .. } = place { + // A floating column is as wide as its window. + let window = self.floating.get_mut(window).ok_or(DockError::MissingPanel)?; + window.rect = Rect::from_min_size(window.rect.min, vec2(width, window.rect.height())); + } else { + self.column_of(&panel)?.width = Some(width); + } + Ok(()) + } + Action::SetColumnSteps { panel, steps } => { + if steps == 0 { + return Err(DockError::InvalidGeometry); + } + self.column_of(&panel)?.steps = Some(steps); Ok(()) } Action::ResizeIconic { panel, width } => { @@ -240,11 +240,23 @@ impl Layout

{ } } + /// The column holding `panel`, docked or floating. pub(super) 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) } + /// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel + /// outside a column or absent. + pub(super) fn source_of(&self, panel: &P) -> Column

{ + self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place)) + } + + /// The accordion entry of `panel` in the docked tree. + pub(super) fn stack_entry_mut(&mut self, panel: &P) -> Option<&mut StackEntry

> { + stack_entry_mut(self.root.as_mut()?, panel) + } + pub(super) fn same_group(&self, panel: &P, anchor: &P) -> bool { let place = self.place(panel); place.is_some() && place == self.place(anchor) @@ -256,24 +268,20 @@ impl Layout

{ if removed.is_some() { return removed; } - 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); - } - } + let index = self.floating.iter().position(|w| w.contains(panel))?; + let window = self.floating.get_mut(index)?; + let removed = remove_from_column(&mut window.column, panel); + if window.column.groups.is_empty() { + self.floating.remove(index); } removed } - /// Where [`Action::Open`] without an anchor puts an absent panel in a layout with a root: + /// Where [`Action::Open`] without an anchor puts an absent `panel` in a layout with a root: /// the end of the first shown dock group that accepts tabs, in the end-side dock if one has - /// such a group, else a new frame at the end edge of the docked area. - pub(super) fn open_place(&self, permissions: impl Fn(&P) -> Permissions) -> Option<(P, DockPlacement

)> { + /// such a group, else a new frame at the end edge of the docked area. A panel that shares no column + /// ([`Permissions::shares_column`]) joins no group. + pub(super) fn open_place(&self, panel: &P, permissions: impl Fn(&P) -> Permissions) -> Option<(P, DockPlacement

)> { let docked: Vec<(&P, PanelPlace)> = self .panels() .into_iter() @@ -292,7 +300,11 @@ impl Layout

{ PanelPlace::Dock { group, .. } => self.column(place).is_some_and(|c| !c.iconic && c.groups.get(*group).is_some_and(|g| !g.minimized)), _ => false, }; - let groups = docked.iter().filter(|(p, place)| side(place).is_some() && shown(place) && permissions(p).accepts_tabs); + let joins = permissions(panel).shares_column; + let groups = docked.iter().filter(|(p, place)| { + let anchor = permissions(p); + joins && side(place).is_some() && shown(place) && anchor.accepts_tabs && anchor.shares_column + }); if let Some((panel, _)) = groups.clone().find(|(_, place)| side(place) == Some(DockEdge::End)).or_else(|| groups.clone().next()) { return Some(((*panel).clone(), DockPlacement::Tab { before: None })); } @@ -301,22 +313,26 @@ impl Layout

{ edge.map(|(panel, _)| ((*panel).clone(), DockPlacement::Edge(DockSide::End))) } + /// Put `entry` at `placement` relative to `anchor`. `source` is the state of the column the panel left + /// ([`Self::source_of`]), which a new column made of it keeps. pub(super) fn insert( &mut self, entry: StackEntry

, + source: Column

, anchor: &P, placement: DockPlacement

, canvas: &dyn Fn(&P) -> bool, ) -> Result<(), DockError> { let place = self.place(anchor).ok_or(DockError::MissingTarget)?; - let tree = place.tree_path().map(|(window, path)| (window, path.to_vec())); - let Some((window, path)) = - tree.filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_))) + let Some(path) = place + .tree_path() + .filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_))) + .map(<[bool]>::to_vec) else { - let group = Group::new(vec![entry.panel], 0); - return self.insert_moving(Moving::group(group), Target::At { anchor: anchor.clone(), placement }, canvas); + let moving = Moving::taken(Group::new(vec![entry.panel], 0), source); + return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas); }; - let root = self.tree_mut(window).ok_or(DockError::MissingTarget)?; + let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; if let DockPlacement::Split(zone) = placement && zone != DockSide::Center { @@ -435,12 +451,9 @@ pub(super) fn remove_node(node: Node

, panel: &P, removed: &mut // 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 }); - } + if let Some(entry) = remove_from_column(column, panel) { + *removed = Some(entry); } - 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 }) @@ -448,6 +461,18 @@ pub(super) fn remove_node(node: Node

, panel: &P, removed: &mut } } +/// Removes `panel` from the groups of `column`, dropping a group it empties. +pub(super) fn remove_from_column(column: &mut Column

, panel: &P) -> Option> { + let mut removed = None; + 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()); + removed +} + pub(super) fn resize_split

(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) }; diff --git a/crates/behavior/src/dock/layout.rs b/crates/behavior/src/dock/layout.rs index 467ef40c7..d4102cac4 100644 --- a/crates/behavior/src/dock/layout.rs +++ b/crates/behavior/src/dock/layout.rs @@ -98,26 +98,15 @@ impl Layout

{ } } for floating in &self.floating { - if !valid_rect(floating.rect) { + if !valid_rect(floating.rect) || !valid_column(&floating.column) || floating.column.groups.is_empty() { return Err(DockError::InvalidGeometry); } - 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)?, - } + count = count.saturating_add(floating.column.groups.len().saturating_add(1)); + if count > MAX_NODES { + return Err(DockError::LimitExceeded); + } + for group in &floating.column.groups { + check_group(group, &mut seen)?; } } Ok(()) @@ -177,11 +166,11 @@ impl Layout

{ .is_ok() } - /// The anchor and placement that move `panel`'s dock group past its neighbour in the column. + /// The anchor and placement that move `panel`'s group past its neighbour in its column, docked or floating. /// `pinned` panels stay put: the group and its neighbour must hold none. pub(super) fn step_target(&self, panel: &P, up: bool, pinned: &dyn Fn(&P) -> bool) -> Result<(P, DockPlacement

), DockError> { let place = self.place(panel).ok_or(DockError::MissingPanel)?; - let PanelPlace::Dock { group, .. } = place else { return Err(DockError::InvalidPlacement) }; + let group = place.group_index().ok_or(DockError::InvalidPlacement)?; let groups = &self.column(&place).ok_or(DockError::MissingPanel)?.groups; let neighbour = if up { group.checked_sub(1) } else { group.checked_add(1) }.and_then(|i| groups.get(i)).ok_or(DockError::MissingTarget)?; let own = groups.get(group).ok_or(DockError::MissingPanel)?; @@ -196,32 +185,26 @@ impl Layout

{ pub fn location(&self, panel: &P) -> Result, DockError> { self.validate()?; let place = self.place(panel).ok_or(DockError::MissingPanel)?; - let (groups, group, column) = match &place { + let (side, floating) = match &place { PanelPlace::Node(_) => return self.root.as_ref().and_then(|node| node_location(node, panel)).ok_or(DockError::MissingPanel), - PanelPlace::Floating { window, .. } => { - let window = self.floating.get(*window).ok_or(DockError::MissingPanel)?; - let mut location = node_location(&window.root, panel).ok_or(DockError::MissingPanel)?; - location.floating = Some(window.rect); - return Ok(location); - } - PanelPlace::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, Some(state)) - } + PanelPlace::Floating { window, .. } => (None, Some(self.floating.get(*window).ok_or(DockError::MissingPanel)?.rect)), + PanelPlace::Dock { path, .. } => match self.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Dock { side, .. }) => (Some(*side), None), + _ => return Err(DockError::MissingPanel), + }, }; + let column = self.column(&place).ok_or(DockError::MissingPanel)?; + let group = place.group_index().ok_or(DockError::MissingPanel)?; + let groups = &column.groups; 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, flyout_width: own.flyout_width, flyout_offset: own.flyout_offset, - column, + column: Some(ColumnLocation::of(column, side)), }); if location.anchor.is_some() { return Ok(location); @@ -250,19 +233,16 @@ impl Layout

{ Ok(location) } - /// Hidden, open behind another tab or in a collapsed container, or showing. + /// Hidden, open behind another tab or in a collapsed container, or showing. In a column, docked or floating, + /// a panel shows when it is its group's active tab, the group is not minimized and the column not collapsed. pub fn panel_state(&self, panel: &P) -> PanelState { let showing = match self.place(panel) { None => return PanelState::Hidden, - Some(place @ (PanelPlace::Node(_) | PanelPlace::Floating { .. })) => { - let minimized = matches!(place, PanelPlace::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 @ PanelPlace::Node(_)) => 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 @@ -288,11 +268,13 @@ impl Layout

{ !valid_height(s.height) || s.flyout_width.is_some_and(|w| !valid_width(w)) || s.flyout_offset.is_some_and(|o| !valid_offset(o)) - || s.column.is_some_and(|c| c.width.is_some_and(|w| !valid_width(w)) || c.iconic_width.is_some_and(|w| !valid_width(w))) + || s.column.is_some_and(|c| { + c.width.is_some_and(|w| !valid_width(w)) || c.iconic_width.is_some_and(|w| !valid_width(w)) || c.steps == Some(0) + }) }) { return Err(DockError::InvalidGeometry); } - // A restore that creates a group, column or dock gives it the saved state. + // A restore that creates a group, column, dock or window gives it the saved state. let moving = || { let group = Group { panels: vec![panel.clone()], @@ -303,12 +285,14 @@ impl Layout

{ flyout_offset: state.and_then(|s| s.flyout_offset), }; let column = state.and_then(|s| s.column); - Moving { + let source = Column { + groups: Vec::new(), width: column.and_then(|c| c.width), iconic: column.is_some_and(|c| c.iconic), iconic_width: column.and_then(|c| c.iconic_width), - ..Moving::group(group) - } + steps: column.and_then(|c| c.steps), + }; + Moving::taken(group, source) }; let mut proposed = self.clone(); if location.floating.is_some_and(|rect| !valid_rect(rect)) { @@ -325,15 +309,11 @@ impl Layout

{ return Err(DockError::MissingTarget); } proposed.insert_moving(moving(), Target::At { anchor: anchor.clone(), placement: location.placement.clone() }, &|_| false)?; - } else if let Some(column) = state.and_then(|s| s.column).filter(|_| location.anchor.is_none()) { + } else if let Some(side) = state.and_then(|s| s.column).and_then(|c| c.side).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 }, &|_| false)?, + match proposed.dock_path(side) { + Some(path) => proposed.columns_mut(&path).ok_or(DockError::MissingTarget)?.insert(0, moving().column), + None => proposed.insert_moving(moving(), Target::NewDock { side }, &|_| false)?, } } else if let Some(anchor) = &location.anchor { if !proposed.contains(anchor) { @@ -351,7 +331,7 @@ impl Layout

{ return Err(DockError::InvalidPlacement); } let size = location.size.unwrap_or(SplitSize::Ratio(0.5)); - around = proposed.trees_mut().any(|root| restore_around_subtree(root, &panel, &members, zone, size)); + around = proposed.root.as_mut().is_some_and(|root| restore_around_subtree(root, &panel, &members, zone, size)); } // A subtree that changed since (a migrated or reconciled layout) splits the anchor. if !around { @@ -361,8 +341,10 @@ impl Layout

{ placement => placement.clone(), }; proposed.apply_inner(Action::OpenAt { panel: panel.clone(), anchor: anchor.clone(), placement }, &|_| false)?; - if let Some(size) = location.size { - proposed.trees_mut().any(|root| restore_parent_size(root, &panel, size)); + if let Some(size) = location.size + && let Some(root) = proposed.root.as_mut() + { + restore_parent_size(root, &panel, size); } } } else if proposed.root.is_none() { @@ -370,13 +352,13 @@ impl Layout

{ } else { return Err(DockError::MissingTarget); } - 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; - } + 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; } } proposed.validate()?; diff --git a/crates/behavior/src/dock/node.rs b/crates/behavior/src/dock/node.rs index 7ceb6f998..f835a15fe 100644 --- a/crates/behavior/src/dock/node.rs +++ b/crates/behavior/src/dock/node.rs @@ -5,7 +5,6 @@ use emath::Rect; use crate::{flow::Axis, placement::Placement}; use super::{ - edit::{stack_tree, tree_groups, tree_panels}, groups::{Column, DockEdge, Group}, split::SplitSize, }; @@ -64,13 +63,12 @@ pub struct StackEntry

{ pub height: Option, } -/// A floating window: a tree of groups like the docked layout's, without docks. +/// A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column +/// inside a window; its collapsed state is the column's [`Column::iconic`]. /// -/// 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. Every window writes its `id`; a window read without one gets a -/// fresh one. +/// Serde reads every saved shape (see `floating_serde`); a window that is one expanded column with one plain group +/// and no native rect writes the v1 shape `{panels, active, rect}`, so older builds can read files that use no +/// newer feature. Every window writes its `id`; a window read without one gets a fresh one. /// /// Equality ignores `id`: two windows with the same contents and place are the same layout. #[derive(Clone, Debug)] @@ -81,20 +79,20 @@ pub struct Floating

{ /// loading keeps the saved id (or draws one when it is missing or taken), and merging /// windows keeps the receiving window's. pub id: u64, - /// `Split`, `Tabs` and `Stack` nodes; a `Dock` is invalid here. - pub root: Node

, - /// The window's area in logical points, in the application's viewport. Saved as `[x, y, width, height]`. + /// The window's groups, top to bottom, and its collapsed state. Its `width` is unused: the window's width is + /// `rect`'s. + pub column: Column

, + /// The window's expanded area in logical points, in the application's viewport. Saved as + /// `[x, y, width, height]`. pub rect: Rect, /// Where the window is on the desktop while it is in its own OS window: the record app windows keep too, placed /// with [`place`](crate::placement::place). pub native: Option, - /// Only the title bar shows. - pub minimized: bool, } impl PartialEq for Floating

{ fn eq(&self, other: &Self) -> bool { - self.root == other.root && self.rect == other.rect && self.native == other.native && self.minimized == other.minimized + self.column == other.column && self.rect == other.rect && self.native == other.native } } @@ -115,6 +113,11 @@ impl

StackEntry

{ pub fn new(panel: P) -> Self { Self { panel, open: true, height: None } } + + /// The section as a group of its own: minimized when the section was closed, at the section's height. + pub(super) fn into_group(self) -> Group

{ + Group { minimized: !self.open, height: self.height, ..Group::new(vec![self.panel], 0) } + } } /// A window id no other window of this process has drawn, from a random start so ids saved @@ -131,16 +134,16 @@ pub(super) fn fresh_window_id() -> u64 { } impl

Floating

{ - /// A window holding `root`. Each call makes a new window, with a fresh [`Self::id`]: build + /// A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build /// a layout once and keep it, or give its windows ids with [`Self::with_id`]. A layout /// built anew each frame without them opens new OS windows each frame. - pub fn new(root: Node

, rect: Rect) -> Self { - Self { id: fresh_window_id(), root, rect, native: None, minimized: false } + pub fn new(column: Column

, rect: Rect) -> Self { + Self { id: fresh_window_id(), column, rect, native: None } } /// A window with one group. Each call makes a new window, as [`Self::new`] does. pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self { - Self::new(Node::Tabs { panels, active }, rect) + Self::new(Column::new(vec![Group::new(panels, active)]), rect) } /// The window with `id`, for a layout the app builds in code, such as a default layout: @@ -151,24 +154,20 @@ impl

Floating

{ self } - /// Every panel in the window, in tree order. + /// Every panel in the window, top group first. pub fn panels(&self) -> impl Iterator { - tree_panels(&self.root).into_iter() + self.column.panels() } - /// 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. Each call - /// makes a new window, as [`Self::new`] does. + /// A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, + /// as [`Self::new`] does. pub fn stack(groups: Vec>, rect: Rect) -> Option { - stack_tree(groups).map(|root| Self::new(root, rect)) + (!groups.is_empty()).then(|| Self::new(Column::new(groups), rect)) } - /// The window's groups, first to last. - pub fn groups(&self) -> Vec> - where - P: Clone, - { - tree_groups(&self.root) + /// The window's groups, top to bottom. + pub fn groups(&self) -> &[Group

] { + &self.column.groups } /// True when a group of this window holds `panel`. Takes any borrowed form of `P`, such @@ -181,13 +180,27 @@ impl

Floating

{ } } +/// The saved shapes of a floating window, read by [`unique_ids`](floating_serde::unique_ids) into the windows of a +/// layout: +/// +/// | Saved shape | Becomes | +/// |---|---| +/// | v1 `{panels, active, rect}` | one window, one group | +/// | v2 `{groups, rect}` | one window of those groups | +/// | v3 `{root, rect, native, minimized}` | a window per part the tree's top splits side by side, each at its share of `rect`; each part's leaves in reading order become its groups (an accordion entry a group, minimized when its section was closed); `minimized` minimizes every group | +/// | v4 `{column, rect, native}` | one window | +/// +/// The first window of a saved one keeps its id; the others get fresh ones. pub(super) mod floating_serde { + use emath::{Rect, pos2, vec2}; use serde::de::IgnoredAny; use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use super::{Floating, Group, Node, fresh_window_id}; - use crate::dock::edit::stack_tree; + use super::{Column, Floating, Group, Node, fresh_window_id}; + use crate::dock::limits::MAX_NODES; use crate::dock::rect_serde::{from_array, to_array}; + use crate::dock::split::SplitSize; + use crate::flow::Axis; use crate::placement::Placement; #[derive(Serialize)] @@ -199,34 +212,44 @@ pub(super) mod floating_serde { } #[derive(Serialize)] - struct Tree<'a, P> { + struct V4<'a, P> { id: u64, - root: &'a Node

, + column: &'a Column

, rect: [f32; 4], #[serde(skip_serializing_if = "Option::is_none")] native: Option<&'a Placement>, - #[serde(skip_serializing_if = "std::ops::Not::not")] - minimized: bool, + } + + /// One expanded column holding one group with no state of its own: what v1 can hold. + fn plain

(column: &Column

, group: &Group

) -> bool { + column.width.is_none() + && !column.iconic + && column.iconic_width.is_none() + && column.steps.is_none() + && !group.minimized + && group.height.is_none() + && group.flyout_width.is_none() + && group.flyout_offset.is_none() } impl Serialize for Floating

{ fn serialize(&self, serializer: S) -> Result { - match &self.root { - Node::Tabs { panels, active } if !self.minimized && self.native.is_none() => { - V1 { id: self.id, panels, active: *active, rect: to_array(self.rect) }.serialize(serializer) + match self.column.groups.as_slice() { + [group] if self.native.is_none() && plain(&self.column, group) => { + V1 { id: self.id, panels: &group.panels, active: group.active, rect: to_array(self.rect) }.serialize(serializer) } - root => Tree { id: self.id, root, rect: to_array(self.rect), native: self.native.as_ref(), minimized: self.minimized } - .serialize(serializer), + _ => V4 { id: self.id, column: &self.column, rect: to_array(self.rect), native: self.native.as_ref() }.serialize(serializer), } } } - /// The fields of a saved window, whichever of the three shapes it was written in. A key is - /// read as [`Serialize`] writes it: `id`, `root`, `groups`, `panels` and `rect` plain, and the - /// optional `native` as an option, which RON marks with `Some` and JSON writes bare. A - /// `native` that does not parse is no placement, and keys it does not know are skipped. + /// The fields of a saved window, whichever shape it was written in. A key is read as [`Serialize`] writes it: + /// `id`, `column`, `root`, `groups`, `panels` and `rect` plain, and the optional `native` as an option, which + /// RON marks with `Some` and JSON writes bare. A `native` that does not parse is no placement, and keys it does + /// not know are skipped. struct Repr

{ id: Option, + column: Option>, root: Option>, groups: Option>>, panels: Option>, @@ -258,7 +281,7 @@ pub(super) mod floating_serde { use serde::de::{MapAccess, Visitor}; use std::marker::PhantomData; - const FIELDS: &[&str] = &["id", "root", "groups", "panels", "active", "rect", "native", "minimized"]; + const FIELDS: &[&str] = &["id", "column", "root", "groups", "panels", "active", "rect", "native", "minimized"]; struct V

(PhantomData

); impl<'de, P: Deserialize<'de>> Visitor<'de> for V

{ @@ -269,10 +292,12 @@ pub(super) mod floating_serde { } fn visit_map>(self, mut map: A) -> Result, A::Error> { - let mut repr = Repr { id: None, root: None, groups: None, panels: None, active: 0, rect: None, native: None, minimized: false }; + let mut repr = + Repr { id: None, column: None, root: None, groups: None, panels: None, active: 0, rect: None, native: None, minimized: false }; while let Some(key) = map.next_key::()? { match key.as_str() { "id" => repr.id = Some(map.next_value()?), + "column" => repr.column = Some(map.next_value()?), "root" => repr.root = Some(map.next_value()?), "groups" => repr.groups = Some(map.next_value()?), "panels" => repr.panels = Some(map.next_value()?), @@ -293,9 +318,93 @@ pub(super) mod floating_serde { } } - /// Floating windows with a fresh id for each one whose id an earlier window took. + impl

Repr

{ + /// The windows the saved window becomes, first to last. + fn into_windows(self) -> Result>, E> { + let Repr { id, column, root, groups, panels, active, rect, native, minimized } = self; + let rect = from_array(rect.ok_or_else(|| E::missing_field("rect"))?); + let columns = match (column, root, groups, panels) { + (Some(column), None, None, None) => vec![(column, rect)], + (None, Some(root), None, None) => { + let mut parts = Vec::new(); + side_by_side(root, rect, &mut parts); + parts + .into_iter() + .map(|(node, rect)| { + let mut groups = node_groups(node); + groups.iter_mut().for_each(|group| group.minimized |= minimized); + (Column::new(groups), rect) + }) + .collect() + } + (None, None, Some(groups), None) => vec![(Column::new(groups), rect)], + (None, None, None, Some(panels)) => vec![(Column::new(vec![Group::new(panels, active)]), rect)], + (None, None, None, None) => return Err(E::missing_field("column")), + _ => return Err(E::duplicate_field("column")), + }; + if columns.iter().any(|(column, _)| column.groups.is_empty()) { + return Err(E::invalid_length(0, &"at least one group")); + } + let native = native.and_then(|native| native.repaired()); + let mut id = Some(id.unwrap_or_else(fresh_window_id)); + Ok(columns + .into_iter() + .map(|(column, rect)| Floating { id: id.take().unwrap_or_else(fresh_window_id), column, rect, native: native.clone() }) + .collect()) + } + } + + /// The parts a v3 window tree's top splits side by side, in reading order, each with its share of `rect` by + /// the split sizes. Every part keeps some width, so the window it becomes is valid. + fn side_by_side

(node: Node

, rect: Rect, parts: &mut Vec<(Node

, Rect)>) { + match node { + Node::Split { axis: Axis::X, size, first, second } => { + let width = rect.width(); + let lead = match size { + SplitSize::Ratio(ratio) => width * ratio, + SplitSize::FixedFirst(first) => first, + SplitSize::FixedSecond(second) => width - second, + }; + let lead = if lead.is_finite() { lead } else { width / 2.0 }; + let lead = lead.min(width - 1.0).max(1.0); + side_by_side(*first, Rect::from_min_size(rect.min, vec2(lead, rect.height())), parts); + side_by_side(*second, Rect::from_min_max(pos2(rect.min.x + lead, rect.min.y), rect.max), parts); + } + node => parts.push((node, rect)), + } + } + + /// The groups of a v3 window part in reading order: a `Tabs` leaf is a group, each accordion entry a group of + /// its own. Stops at [`MAX_NODES`] for an invalid tree. + fn node_groups

(node: Node

) -> Vec> { + let mut groups = Vec::new(); + let mut visit = vec![node]; + let mut visited = 0usize; + while let Some(node) = visit.pop() { + visited = visited.saturating_add(1); + if visited > MAX_NODES { + break; + } + match node { + Node::Split { first, second, .. } => { + visit.push(*second); + visit.push(*first); + } + Node::Tabs { panels, active } => groups.push(Group::new(panels, active)), + Node::Stack { entries } => groups.extend(entries.into_iter().map(super::StackEntry::into_group)), + Node::Dock { columns, .. } => groups.extend(columns.into_iter().flat_map(|column| column.groups)), + } + } + groups + } + + /// Floating windows as saved, each read into the windows it becomes, with a fresh id for each one whose id an + /// earlier window took. pub(in crate::dock) fn unique_ids<'de, D: Deserializer<'de>, P: Deserialize<'de>>(deserializer: D) -> Result>, D::Error> { - let mut windows = Vec::>::deserialize(deserializer)?; + let mut windows = Vec::new(); + for saved in Vec::>::deserialize(deserializer)? { + windows.extend(saved.into_windows::()?); + } let mut seen = std::collections::HashSet::new(); for window in &mut windows { while !seen.insert(window.id) { @@ -304,30 +413,6 @@ pub(super) mod floating_serde { } Ok(windows) } - - impl<'de, P: Deserialize<'de>> Deserialize<'de> for Floating

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

::deserialize(deserializer)?; - 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 { - id: repr.id.unwrap_or_else(fresh_window_id), - root, - rect: from_array(repr.rect.ok_or_else(|| serde::de::Error::missing_field("rect"))?), - native: repr.native.and_then(|native| native.repaired()), - minimized, - }) - } - } } impl

Node

{ diff --git a/crates/behavior/src/dock/policy.rs b/crates/behavior/src/dock/policy.rs index aaaebec7f..99a9f4005 100644 --- a/crates/behavior/src/dock/policy.rs +++ b/crates/behavior/src/dock/policy.rs @@ -19,6 +19,13 @@ pub struct Permissions { /// Other panels may split this panel's frame (`DockPlacement::Split` with a side zone). /// Outer-edge frames (`DockPlacement::Edge`) are not splits of the anchor. pub accepts_splits: bool, + /// The panel's column may collapse to icons: refused are `SetIconic` to icons on a column holding it, and a + /// move of it into a collapsed column. + pub collapses: bool, + /// Other groups may share the panel's column, and the panel may join a column or group that holds other + /// panels: refused are tab, center, group and seam placements across that boundary in either direction, while a + /// new column, a new dock and a float stay allowed. A toolbar takes its own column. + pub shares_column: bool, } impl Default for Permissions { @@ -28,13 +35,14 @@ impl Default for Permissions { } impl Permissions { - /// Every right: the panel moves, floats, closes and takes tabs and splits. - pub const ALL: Self = Self { movable: true, floatable: true, closable: true, accepts_tabs: true, accepts_splits: true }; + /// Every right: the panel moves, floats, closes, takes tabs and splits, collapses and shares its column. + pub const ALL: Self = + Self { movable: true, floatable: true, closable: true, accepts_tabs: true, accepts_splits: true, collapses: true, shares_column: true }; /// 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::PROTECTED.accepts_splits(true)`. - pub const PROTECTED: Self = Self { movable: false, floatable: false, closable: false, accepts_tabs: false, accepts_splits: false }; + pub const PROTECTED: Self = Self { movable: false, floatable: false, closable: false, accepts_tabs: false, accepts_splits: false, ..Self::ALL }; /// These permissions with [`Self::movable`] set to `movable`. pub const fn movable(mut self, movable: bool) -> Self { @@ -66,13 +74,25 @@ impl Permissions { self } + /// These permissions with [`Self::collapses`] set to `collapses`. + pub const fn collapses(mut self, collapses: bool) -> Self { + self.collapses = collapses; + self + } + + /// These permissions with [`Self::shares_column`] set to `shares_column`. + pub const fn shares_column(mut self, shares_column: bool) -> Self { + self.shares_column = shares_column; + self + } + /// 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. + /// Lock Workspace: nothing moves, floats or closes; tab and split drops and the column rights keep their policy. /// A workspace applies this when it is locked; an application with a global lock preference /// applies it in its own permissions callback. pub fn locked(self) -> Self { diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index e6b826eb9..112ed9c24 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -9,9 +9,11 @@ use std::{collections::HashSet, hash::Hash}; use super::{ DockSide, action::{Action, DockPlacement, Location}, - groups::PanelPlace, + edit::tree_panels, + groups::{Column, PanelPlace, Target}, layout::Layout, limits::MAX_PANELS, + node::Node, policy::{DockError, Permissions}, }; @@ -65,8 +67,9 @@ impl

Default for Workspace

{ } impl

Workspace

{ - /// The format version written to files. - pub const VERSION: u32 = 3; + /// The format version written to files. Version 4 saves a floating window as one column; older floating + /// windows load as columns (see [`Floating`](super::Floating)). + pub const VERSION: u32 = 4; /// A workspace of `layout`, with no hidden panels. pub fn new(layout: Layout

) -> Self { @@ -211,9 +214,9 @@ impl Workspace

{ let allowed = layout .location(panel) .ok() - .and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor), floats(&layout, &anchor)))) + .and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor)))) .unwrap_or(true); - if !allowed { + if !allowed || layout.breaks_columns_beyond(&self.layout, permissions) { return Ok(false); } layout.apply(Action::Activate { panel: panel.clone() })?; @@ -281,7 +284,10 @@ impl Workspace

{ /// 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. + /// area. A layout that breaks the column rights is repaired: a collapsed column holding a panel that does not + /// collapse ([`Permissions::collapses`]) expands, and a panel that shares no column + /// ([`Permissions::shares_column`]) moves to a column of its own. 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, permissions: impl Fn(&P) -> Permissions, default: &Workspace

) { if self.validate().is_err() { @@ -329,6 +335,7 @@ impl Workspace

{ self.hidden.retain(|(p, _)| p != &panel); } } + self.repair_columns(&permissions); let mut excess = self.hidden.len().saturating_sub(MAX_PANELS); self.hidden.retain(|(p, _)| { let drop = excess > 0 && !registered(p); @@ -339,6 +346,59 @@ impl Workspace

{ } } +impl Workspace

{ + /// Moves each panel that shares no column but has company to a column of its own: a new dock column beside its + /// column, a new window over its window, or a frame beside its node of the docked tree. Then expands each + /// collapsed column that holds a panel that does not collapse. A repair the layout refuses leaves it as it was. + fn repair_columns(&mut self, permissions: &impl Fn(&P) -> Permissions) { + let lonely: Vec

= self.layout.panels().into_iter().filter(|p| !permissions(p).shares_column).cloned().collect(); + for panel in lonely { + let Some(place) = self.layout.place(&panel) else { continue }; + let company = match &place { + PanelPlace::Node(_) => self.layout.node_of(&place).map(|node| tree_panels(node).into_iter().cloned().collect()), + _ => self.layout.column(&place).map(|column| column.panels().cloned().collect::>()), + }; + let Some(anchor) = company.unwrap_or_default().into_iter().find(|p| p != &panel) else { continue }; + let to = match place { + PanelPlace::Dock { .. } => Target::At { anchor, placement: DockPlacement::Column { after: false } }, + PanelPlace::Floating { window, .. } => match self.layout.floating.get(window) { + Some(window) => Target::Float { rect: window.rect }, + None => continue, + }, + PanelPlace::Node(_) => Target::At { anchor, placement: DockPlacement::Split(DockSide::Start) }, + }; + let mut layout = self.layout.clone(); + if layout.apply_inner(Action::MovePanel { panel, to }, &|p| permissions(p).is_protected()).is_ok() && layout.validate().is_ok() { + self.layout = layout; + } + } + let windows = self.layout.floating.iter_mut().map(|w| &mut w.column); + let docked = self.layout.root.iter_mut().flat_map(dock_columns_mut); + for column in windows.chain(docked) { + if column.iconic && column.panels().any(|p| !permissions(p).collapses) { + column.iconic = false; + } + } + } +} + +/// The columns of every dock of a docked tree. +fn dock_columns_mut

(root: &mut Node

) -> Vec<&mut Column

> { + let mut out = Vec::new(); + let mut visit = vec![root]; + while let Some(node) = visit.pop() { + match node { + Node::Split { first, second, .. } => { + visit.push(second); + visit.push(first); + } + Node::Dock { columns, .. } => out.extend(columns.iter_mut()), + Node::Tabs { .. } | Node::Stack { .. } => {} + } + } + out +} + /// Whether `panel` is in a floating window of `layout`. fn floats(layout: &Layout

, panel: &P) -> bool { matches!(layout.place(panel), Some(PanelPlace::Floating { .. })) From 6d1596c53127d1fa25b0e02cf5df07b8067c7db9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:12:10 +0000 Subject: [PATCH 02/18] Dock model tests: column state on float and join, floating drops, column rights, steps, v3 migration Collapse is kept when a column or its groups float and decided by the joined column; a floating window takes Top, Bottom and Center drops and nothing beside it; collapses and shares_column refuse their placements in both directions and reconcile repairs them; a stepped column keeps its count through JSON and refuses widths; v3 floating trees load as one column window per side-by-side part. --- crates/behavior/src/dock/action.rs | 4 +- crates/behavior/tests/dock.rs | 41 ++++++++ crates/behavior/tests/dock_apply.rs | 145 +++++++++++++++++++++++++++- 3 files changed, 185 insertions(+), 5 deletions(-) diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index 3b8b7b5d2..8ab13bd08 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -89,8 +89,8 @@ pub struct Location

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

, - /// Group and column state when the panel was in a dock. Applies when - /// restoring creates a new group, column or dock for the panel. + /// Group and column state when the panel was in a column, docked or floating. Applies when + /// restoring creates a new group, column, dock or window for the panel. #[serde(default)] pub group: Option, } diff --git a/crates/behavior/tests/dock.rs b/crates/behavior/tests/dock.rs index dbed7c178..e9d825400 100644 --- a/crates/behavior/tests/dock.rs +++ b/crates/behavior/tests/dock.rs @@ -236,3 +236,44 @@ fn a_saved_native_window_that_no_longer_parses_loads_with_default_placement() { let back: Layout = serde_json::from_str(&serde_json::to_string(&placed).unwrap()).unwrap(); assert_eq!(back, placed); } + +/// Floating windows saved by format v3 load as columns: a tree split side by side becomes one window per part, side +/// by side within the saved rect, the first keeping the saved id; stacked frames and accordion sections become groups +/// (a closed section a minimized group), and a minimized window minimizes every group. The v4 shape round-trips. +#[test] +fn a_v3_floating_tree_loads_as_one_column_window_per_side_by_side_part() { + let saved = r#"{ + "root": {"Tabs": {"panels": [1], "active": 0}}, + "floating": [ + {"id": 7, "rect": [0.0, 0.0, 400.0, 300.0], "root": {"Split": {"axis": "X", "size": {"Ratio": 0.25}, + "first": {"Tabs": {"panels": [2, 3], "active": 1}}, + "second": {"Split": {"axis": "Y", "size": {"Ratio": 0.5}, + "first": {"Tabs": {"panels": [4], "active": 0}}, + "second": {"Stack": {"entries": [{"panel": 5, "open": false, "height": 80.0}, {"panel": 6, "open": true, "height": null}]}}}}}}}, + {"id": 8, "rect": [500.0, 0.0, 200.0, 300.0], "minimized": true, "root": {"Split": {"axis": "Y", "size": {"Ratio": 0.5}, + "first": {"Tabs": {"panels": [9], "active": 0}}, "second": {"Tabs": {"panels": [10], "active": 0}}}}} + ] + }"#; + let layout: Layout = serde_json::from_str(saved).unwrap(); + layout.validate().unwrap(); + let [left, right, stacked] = layout.floating.as_slice() else { panic!("{:?}", layout.floating) }; + assert_eq!((left.id, stacked.id), (7, 8), "the first part keeps the saved id"); + assert!(right.id != 7 && right.id != 8); + let whole = area(0.0, 0.0, 400.0, 300.0); + assert_eq!((left.rect.left(), left.rect.right(), right.rect.right()), (whole.left(), right.rect.left(), whole.right()), "side by side"); + assert!(left.rect.width() < right.rect.width(), "each part takes its share"); + assert_eq!((left.rect.height(), right.rect.height()), (whole.height(), whole.height())); + + let members = |window: &Floating| window.groups().iter().map(|g| (g.panels.clone(), g.minimized)).collect::>(); + assert_eq!(members(left), [(vec![2, 3], false)]); + assert_eq!(left.groups()[0].active, 1); + assert_eq!(members(right), [(vec![4], false), (vec![5], true), (vec![6], false)]); + assert_eq!(right.groups()[1].height, Some(80.0), "a section keeps its height"); + assert_eq!(members(stacked), [(vec![9], true), (vec![10], true)]); + + let written = serde_json::to_value(&layout).unwrap(); + assert!(written["floating"][1].get("column").is_some(), "{written}"); + let back: Layout = serde_json::from_str(&written.to_string()).unwrap(); + assert_eq!(back, layout); + assert_eq!(back.floating.iter().map(|w| w.id).collect::>(), layout.floating.iter().map(|w| w.id).collect::>()); +} diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 58a758e6b..b7f769b9b 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -2,8 +2,8 @@ use craft_behavior::Axis; use craft_behavior::dock::{ - Action, Column, DockEdge, DockError, DockPlacement, Floating, Group, Layout, NamedWorkspace, Node, PanelPlace, Permissions, SplitSize, Workspace, - WorkspaceChrome, WorkspaceKeeps, WorkspaceSet, node_at, + Action, Column, DockEdge, DockError, DockPlacement, DockSide, Floating, Group, Layout, NamedWorkspace, Node, PanelPlace, PanelState, Permissions, + SplitSize, Target, Workspace, WorkspaceChrome, WorkspaceKeeps, WorkspaceSet, node_at, }; use emath::{Rect, pos2, vec2}; @@ -49,7 +49,7 @@ fn sorted(layout: &Layout) -> Vec { fn group_members(layout: &Layout, panel: u32) -> Vec { match layout.place(&panel).unwrap() { - place @ (PanelPlace::Node(_) | PanelPlace::Floating { .. }) => match layout.node_of(&place).unwrap() { + place @ PanelPlace::Node(_) => match layout.node_of(&place).unwrap() { Node::Tabs { panels, .. } => panels.clone(), other => panic!("{other:?}"), }, @@ -203,3 +203,142 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { workspace.apply(Action::close(3), false, allow).unwrap(); assert!(workspace.floated.is_empty(), "closing drops the record"); } + +/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. +fn columns() -> Layout { + let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); + Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(vec![6], 0, window())]) +} + +fn floats(layout: &Layout, panel: u32) -> bool { + matches!(layout.place(&panel), Some(PanelPlace::Floating { .. })) +} + +fn column_of(layout: &Layout, panel: u32) -> &Column { + layout.column(&layout.place(&panel).unwrap()).unwrap() +} + +/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a +/// column float in its state; groups joining a column, docked or floating, take that column's state. +#[test] +fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides() { + let mut layout = columns(); + layout.apply(Action::set_iconic(6, true)).unwrap(); + assert!(floats(&layout, 6) && column_of(&layout, 6).iconic); + assert_eq!(layout.panel_state(&6), PanelState::Open, "a collapsed floating panel is open, not showing"); + layout.apply(Action::set_iconic(6, false)).unwrap(); + assert_eq!(layout.panel_state(&6), PanelState::Front); + + for action in [Action::move_column(3, Target::float(window())), Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] + { + let mut moved = columns(); + moved.apply(action.clone()).unwrap(); + assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons"); + } + let mut moved = columns(); + moved.apply(Action::move_group(2, Target::float(window()))).unwrap(); + assert!(floats(&moved, 2) && !column_of(&moved, 2).iconic, "out of an expanded column it floats expanded"); + + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(layout.panel_state(&2), PanelState::Open, "into a collapsed column it shows as an icon"); + layout.apply(Action::move_group(2, Target::at(6, DockPlacement::group(false, None)))).unwrap(); + assert_eq!(layout.panel_state(&2), PanelState::Front, "into an expanded floating column it shows"); + + layout.apply(Action::set_iconic(6, true)).unwrap(); + layout.apply(Action::move_group(3, Target::at(6, DockPlacement::Split(DockSide::Center)))).unwrap(); + assert_eq!(group_members(&layout, 6), [6, 3], "a group dropped on a floating icon group joins its tabs"); + assert_eq!(layout.panel_state(&3), PanelState::Open); + layout.apply(Action::move_group(4, Target::float(window()))).unwrap(); + assert_eq!(layout.floating.len(), 2); + layout.apply(Action::move_group(4, Target::at(6, DockPlacement::Split(DockSide::Center)))).unwrap(); + assert_eq!(layout.floating.len(), 1, "a floating icon group merged into another closes its window"); + assert_eq!(group_members(&layout, 6), [6, 4, 3], "it joins after the anchor"); +} + +/// A floating window is one column: drops above, below and into its groups land, and nothing goes beside it. +#[test] +fn a_floating_window_takes_drops_above_below_and_into_its_groups_and_none_beside() { + let layout = columns(); + for side in [DockSide::Start, DockSide::End] { + assert_eq!(DockPlacement::for_zone(&layout, &6, side), Err(DockError::InvalidPlacement), "{side:?}"); + } + assert_eq!(DockPlacement::for_zone(&layout, &6, DockSide::Bottom), Ok(DockPlacement::group(true, None))); + assert_eq!(DockPlacement::for_zone(&layout, &6, DockSide::Center), Ok(DockPlacement::Split(DockSide::Center))); + for placement in [DockPlacement::column(true), DockPlacement::Split(DockSide::End), DockPlacement::Edge(DockSide::Start)] { + let mut moved = layout.clone(); + assert_eq!(moved.apply(Action::move_group(2, Target::at(6, placement.clone()))), Err(DockError::InvalidPlacement), "{placement:?}"); + assert_eq!(moved, layout); + } +} + +/// A panel that does not collapse refuses a collapse of its column and a move into a collapsed one, so a drag's dry +/// run refuses alike; reconcile expands a saved collapsed column that holds it. +#[test] +fn a_panel_that_does_not_collapse_keeps_its_column_expanded() { + let rigid = |p: &u32| if *p == 2 { Permissions::ALL.collapses(false) } else { Permissions::ALL }; + let mut layout = columns(); + let before = layout.clone(); + assert_eq!(layout.apply_with_permissions(Action::set_iconic(2, true), rigid), Err(DockError::NotAllowed)); + for to in [Target::at(3, DockPlacement::group(true, None)), Target::at(3, DockPlacement::tab(None))] { + assert_eq!(layout.apply_with_permissions(Action::move_group(2, to), rigid), Err(DockError::NotAllowed)); + } + assert_eq!(layout, before); + layout.apply_with_permissions(Action::set_iconic(3, false), rigid).unwrap(); + layout.apply_with_permissions(Action::move_group(2, Target::at(3, DockPlacement::group(true, None))), rigid).unwrap(); + + let mut saved = Workspace::new(columns()); + saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + assert!(column_of(&saved.layout, 2).iconic); + saved.reconcile(|_| true, rigid, &Workspace::new(columns())); + assert!(!column_of(&saved.layout, 2).iconic, "reconcile expands the column"); + assert_eq!(group_members(&saved.layout, 2), [2]); +} + +/// A panel that shares no column (a toolbar) refuses every placement that puts it beside other panels in a column +/// or group, in either direction, and still moves to a new column, a new dock or a float; reconcile gives a saved +/// one a column of its own. +#[test] +fn a_panel_that_shares_no_column_moves_only_to_a_column_of_its_own() { + let alone = |p: &u32| if *p == 2 { Permissions::ALL.shares_column(false) } else { Permissions::ALL }; + let layout = columns(); + let joins = [DockPlacement::tab(None), DockPlacement::Split(DockSide::Center), DockPlacement::group(true, None), DockPlacement::group(false, Some(80.0))]; + for placement in joins { + for (panel, anchor) in [(2, 3), (3, 2), (2, 6), (6, 2)] { + let mut moved = layout.clone(); + let action = Action::move_group(panel, Target::at(anchor, placement.clone())); + assert_eq!(moved.apply_with_permissions(action, alone), Err(DockError::NotAllowed), "{panel} to {anchor}: {placement:?}"); + } + } + for to in [Target::at(3, DockPlacement::column(true)), Target::new_dock(DockEdge::Start), Target::float(window())] { + let mut moved = layout.clone(); + moved.apply_with_permissions(Action::move_group(2, to.clone()), alone).unwrap_or_else(|e| panic!("{to:?}: {e}")); + assert_eq!(column_of(&moved, 2).panels().count(), 1, "{to:?}"); + } + + let mut saved = Workspace::new(columns()); + saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + saved.reconcile(|_| true, alone, &Workspace::new(columns())); + assert_eq!(column_of(&saved.layout, 2).panels().collect::>(), [&2], "reconcile gives it a column of its own"); + assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]); +} + +/// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only +/// by steps. +#[test] +fn a_stepped_column_keeps_its_step_count_and_refuses_a_width() { + let mut layout = columns(); + assert_eq!(layout.apply(Action::set_column_steps(2, 0)), Err(DockError::InvalidGeometry)); + layout.apply(Action::set_column_steps(2, 2)).unwrap(); + assert_eq!(column_of(&layout, 2).steps, Some(2)); + let before = layout.clone(); + assert_eq!(layout.apply(Action::resize_column(2, 200.0)), Err(DockError::InvalidPlacement)); + assert_eq!(layout, before); + let saved: Layout = serde_json::from_str(&serde_json::to_string(&layout).unwrap()).unwrap(); + assert_eq!(saved, layout); + + layout.apply(Action::move_column(2, Target::float(window()))).unwrap(); + assert!(floats(&layout, 2)); + assert_eq!(column_of(&layout, 2).steps, Some(2), "a floated stepped column keeps its steps"); + let saved: Layout = serde_json::from_str(&serde_json::to_string(&layout).unwrap()).unwrap(); + assert_eq!(saved, layout); +} From cbf445ff5222653d83d8b3f6b06934d775b1ef81 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:13:40 +0000 Subject: [PATCH 03/18] Dock model: SetMinimized documents the tab strip only --- crates/behavior/src/dock/action.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index 8ab13bd08..fe4b8ff55 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -247,7 +247,7 @@ pub enum Action

{ SetMinimized { /// The panel the action applies to. panel: P, - /// Only the title bar or tab strip shows. + /// Only the tab strip shows. minimized: bool, }, /// Collapse the panel's column to icons, or expand it, docked or floating. Refused From 1cd660da930d23c0343ed109db08b8ab75bfa909 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:19:51 +0000 Subject: [PATCH 04/18] Dock UI: frame view, drops and commands for one-column floating windows; rail.rs removed FrameView prunes a floating window's column like a dock column and writes back only the docked tree's splits. Drop placements ask the anchor's rights wherever its column is. Collapse to Icons applies to every column, docked or floating, and is off for a column holding a panel that does not collapse; Float Tab Group keeps a window's only group where it is. rail_actions and rail_lit go with the rail links; Minimize reads group and accordion state in the commands. --- crates/ui-panels/src/docking/commands/dock.rs | 43 ++++++++--- crates/ui-panels/src/docking/drop.rs | 7 +- crates/ui-panels/src/docking/frame.rs | 72 ++++++++----------- crates/ui-panels/src/docking/mod.rs | 2 - crates/ui-panels/src/docking/rail.rs | 34 --------- 5 files changed, 65 insertions(+), 93 deletions(-) delete mode 100644 crates/ui-panels/src/docking/rail.rs diff --git a/crates/ui-panels/src/docking/commands/dock.rs b/crates/ui-panels/src/docking/commands/dock.rs index 1ee24161e..81fef5765 100644 --- a/crates/ui-panels/src/docking/commands/dock.rs +++ b/crates/ui-panels/src/docking/commands/dock.rs @@ -4,7 +4,7 @@ use crate::docking::drop::{beside, members, moving_panels, to_target}; use crate::docking::{DockEvent, DragUnit, FloatSpace}; use crate::runtime::commands::CommandState; use craft_behavior::DockSide; -use craft_behavior::dock::{Action, DockEdge, DockError, DockPlacement, Layout, Location, Node, PanelPlace, Permissions, Target, node_at}; +use craft_behavior::dock::{Action, Column, DockEdge, DockError, DockPlacement, Layout, Location, Node, PanelPlace, Permissions, Target, node_at}; use egui::{Rect, Vec2}; use std::hash::Hash; @@ -200,11 +200,14 @@ pub fn actions(scene: &DockScene<'_, P>, command: DockComm DockCommands::StepGroupDown => one(Action::step_group(panel.clone(), false)), DockCommands::ToggleMinimized => { shown()?; - one(Action::set_minimized(panel.clone(), !crate::docking::rail::minimized(layout, panel))) + one(Action::set_minimized(panel.clone(), !minimized(layout, panel))) } DockCommands::CollapseToIcons => { let place = layout.place(panel).ok_or(DockError::MissingPanel)?; let column = layout.column(&place).ok_or(DockError::InvalidPlacement)?; + if !column.iconic && !collapses(scene, column) { + return Err(DockError::NotAllowed); + } one(Action::set_iconic(panel.clone(), !column.iconic)) } DockCommands::MovePanelTo | DockCommands::MoveGroupTo | DockCommands::ToggleMaximize | DockCommands::AutoCollapse => Ok(Vec::new()), @@ -265,16 +268,37 @@ pub fn move_actions(scene: &DockScene<'_, P>, unit: &DragU } } -/// The state of each panel command for `panel`: enabled as its permissions and place allow, Collapse to Icons -/// checked while its column is iconic. Maximize Frame applies to a frame of the docked layout, never to a floating -/// one. `DockArea` publishes them in the panel's group scope. +/// Whether the group or accordion section of `panel` is minimized to its tab strip. An accordion entry is minimized +/// while it is closed. A panel the layout does not hold is not. +fn minimized(layout: &Layout

, panel: &P) -> bool { + let Some(place) = layout.place(panel) else { return false }; + match layout.group(&place) { + Some(group) => group.minimized, + None => match layout.node_of(&place) { + Some(Node::Stack { entries, .. }) => entries.iter().any(|entry| &entry.panel == panel && !entry.open), + _ => false, + }, + } +} + +/// Whether `column` may collapse to icons: every panel in it collapses ([`Permissions::collapses`]). +fn collapses(scene: &DockScene<'_, P>, column: &Column

) -> bool { + column.panels().all(|panel| scene.policy(panel).collapses) +} + +/// The state of each panel command for `panel`: enabled as its permissions and place allow. Collapse to Icons applies +/// to every column, docked or floating, checked while it is iconic, and is off for a column that holds a panel that +/// does not collapse. Maximize Frame applies to a frame of the docked layout, never to a floating one. `DockArea` +/// publishes them in the panel's group scope. pub fn dock_states(scene: &DockScene<'_, P>, panel: &P) -> Vec<(DockCommands, CommandState)> { let layout = scene.layout; let policy = |p: &P| scene.policy(p); let allowed = scene.policy(panel); let place = layout.place(panel); let floatable = place.is_some() && allowed.movable && allowed.floatable; - let iconic = place.as_ref().and_then(|place| layout.column(place)).map(|column| column.iconic); + let column = place.as_ref().and_then(|place| layout.column(place)); + let iconic = column.map(|column| column.iconic); + let collapsible = column.is_some_and(|column| column.iconic || collapses(scene, column)); let enabled = |on: bool| CommandState::new().enabled(on); let shown = place.is_some(); let floating = matches!(place, Some(PanelPlace::Floating { .. })); @@ -296,19 +320,20 @@ pub fn dock_states(scene: &DockScene<'_, P>, panel: &P) -> (DockCommands::StepGroupUp, enabled(layout.can_step_group(panel, true, policy))), (DockCommands::StepGroupDown, enabled(layout.can_step_group(panel, false, policy))), (DockCommands::ToggleMinimized, enabled(shown)), - (DockCommands::CollapseToIcons, CommandState::new().enabled(iconic.is_some()).checked(iconic.unwrap_or(false))), + (DockCommands::CollapseToIcons, CommandState::new().enabled(collapsible).checked(iconic.unwrap_or(false))), (DockCommands::ToggleMaximize, enabled(shown && !floating)), (DockCommands::AutoCollapse, enabled(true)), ] } -/// The actions that float `unit` at the rect a drag would float it at, or keep its window where it is. +/// The actions that float `unit` at the rect a drag would float it at, or keep its window where it is: a window's +/// only panel, and a window's only group, already float alone. fn float_actions(scene: &DockScene<'_, P>, unit: &DragUnit

) -> Vec> { let layout = scene.layout; let panel = unit.lead(); let window = layout.floating.iter().find(|window| window.contains(panel)); let lone = window.is_some_and(|window| window.panels().count() == 1); - let whole = window.is_some_and(|window| matches!(window.root, Node::Tabs { .. } | Node::Stack { .. })); + let whole = window.is_some_and(|window| window.groups().len() == 1); let kept = window.map(|window| window.rect); let action = match (unit, kept) { (DragUnit::Panel(_), Some(rect)) if lone => Action::move_floating(panel.clone(), rect), diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 627bded35..6ca845a26 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -11,7 +11,7 @@ use crate::contract::{Component, Cx, DropMark, DropOperation, DropTarget, Pointe use crate::runtime::drag::{self, DragPreview}; use crate::runtime::env::{AppValues, EnvValue, EnvView, Label}; use crate::runtime::pointer; -use craft_behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, PanelPlace, Permissions, Target}; +use craft_behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, Permissions, Target}; use craft_behavior::{CancelReason, DockSide}; use egui::{Context, Id, Pos2, Rect, Vec2}; use std::hash::Hash; @@ -165,10 +165,7 @@ fn spot_action( return None; } let moved = moving_panels(layout, unit); - let place = |anchor: P, placement: DockPlacement

| { - let floating = matches!(layout.place(&anchor), Some(PanelPlace::Floating { .. })); - placement.allowed_by(permissions(&anchor), floating).then(|| beside(unit, anchor, placement)) - }; + let place = |anchor: P, placement: DockPlacement

| placement.allowed_by(permissions(&anchor)).then(|| beside(unit, anchor, placement)); match spot { DockSpot::Tab { anchor, index } => { let destination = outside(layout, anchor, &moved)?; diff --git a/crates/ui-panels/src/docking/frame.rs b/crates/ui-panels/src/docking/frame.rs index 6b92d1e33..d7db4a713 100644 --- a/crates/ui-panels/src/docking/frame.rs +++ b/crates/ui-panels/src/docking/frame.rs @@ -23,15 +23,12 @@ pub struct FrameView<'a, P: Clone> { pub hidden: Vec

, /// The layout path of each split of the view, by the split's view path; `None` when the view is the layout. pub paths: Option, Vec>>, - /// The layout index of each floating window of the view, in order. - pub windows: Vec, - /// For each floating window of the view, the path in the window's layout tree of each split of its pruned tree. - window_paths: Vec, Vec>>, } impl FrameView<'_, P> { /// Writes the split sizes of `edited`, an edit of the view's layout, into `layout`, the layout the view was made - /// from. Panels the view left out keep their place; only sizes change. + /// from. Panels the view left out keep their place; only the docked tree's split sizes change: floating windows + /// have no splits. pub fn write_back(&self, edited: &Layout

, layout: &mut Layout

) { let Some(paths) = &self.paths else { layout.clone_from(edited); @@ -40,11 +37,6 @@ impl FrameView<'_, P> { if let (Some(shown), Some(root)) = (edited.root.as_ref(), layout.root.as_mut()) { tree::apply_sizes(root, &split_sizes(shown, paths)); } - for ((shown, at), paths) in edited.floating.iter().zip(&self.windows).zip(&self.window_paths) { - if let Some(window) = layout.floating.get_mut(*at) { - tree::apply_sizes(&mut window.root, &split_sizes(&shown.root, paths)); - } - } } } @@ -93,42 +85,36 @@ pub fn maximize<'a, P: Clone + Eq + Hash>( }); let unchanged = frame.is_none() && matches!(hide, HidePanels::None); if unchanged { - return FrameView { - layout: Cow::Borrowed(layout), - maximized: None, - hidden: Vec::new(), - paths: None, - windows: (0..layout.floating.len()).collect(), - window_paths: Vec::new(), - }; + return FrameView { layout: Cow::Borrowed(layout), maximized: None, hidden: Vec::new(), paths: None }; } let left_out = layout.panels().into_iter().filter(|panel| hidden(panel)).cloned().collect(); let mut paths = HashMap::new(); - let mut windows = Vec::new(); - let mut window_paths = Vec::new(); let (shown, kept) = match frame { Some((panel, path, node)) => (Layout::new(prune(&node, path, Vec::new(), &hidden, &mut paths), Vec::new()), Some(panel)), None => { let root = layout.root.as_ref().and_then(|root| prune(root, Vec::new(), Vec::new(), &hidden, &mut paths)); - let mut floating = Vec::new(); - for (at, window) in layout.floating.iter().enumerate() { - let mut window_map = HashMap::new(); - let Some(root) = prune(&window.root, Vec::new(), Vec::new(), &hidden, &mut window_map) else { continue }; - window_paths.push(window_map); - let mut shown: Floating

= window.clone(); - shown.root = root; - floating.push(shown); - windows.push(at); - } + // A window whose panels are all hidden is left out. + let floating = layout + .floating + .iter() + .filter_map(|window| { + let column = prune_column(&window.column, &hidden)?; + let mut shown: Floating

= window.clone(); + shown.column = column; + Some(shown) + }) + .collect(); (Layout::new(root, floating), None) } }; - FrameView { layout: Cow::Owned(shown), maximized: kept, hidden: left_out, paths: Some(paths), windows, window_paths } + FrameView { layout: Cow::Owned(shown), maximized: kept, hidden: left_out, paths: Some(paths) } } +/// The path of the docked node that holds a place of the docked tree: the `Tabs` or `Stack` node, or the `Dock` node +/// of a column's group. fn path_of(place: &PanelPlace) -> Vec { match place { - PanelPlace::Node(path) | PanelPlace::Dock { path, .. } | PanelPlace::Floating { path, .. } => path.clone(), + PanelPlace::Node(path) | PanelPlace::Dock { path, .. } => path.clone(), _ => Vec::new(), } } @@ -174,23 +160,23 @@ fn prune( (!entries.is_empty()).then(|| Node::stack(entries)) } Node::Dock { side, columns, .. } => { - let columns: Vec> = columns - .iter() - .filter_map(|column| { - let groups: Vec<_> = column.groups.iter().filter_map(|group| prune_group(group, hidden)).collect(); - (!groups.is_empty()).then(|| { - let mut kept = column.clone(); - kept.groups = groups; - kept - }) - }) - .collect(); + let columns: Vec> = columns.iter().filter_map(|column| prune_column(column, hidden)).collect(); (!columns.is_empty()).then(|| Node::dock(*side, columns)) } _ => Some(node.clone()), } } +/// A column without hidden panels, keeping its state; `None` when none of its panels shows. +fn prune_column(column: &Column

, hidden: &dyn Fn(&P) -> bool) -> Option> { + let groups: Vec<_> = column.groups.iter().filter_map(|group| prune_group(group, hidden)).collect(); + (!groups.is_empty()).then(|| { + let mut kept = column.clone(); + kept.groups = groups; + kept + }) +} + /// 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(); diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 06b607412..306939775 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -13,7 +13,6 @@ mod group; mod floating; mod panels; -mod rail; mod root; mod spec; mod splitter; @@ -61,7 +60,6 @@ pub use dock_column::{ }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes}; -pub use rail::{rail_actions, rail_lit}; pub use window_menu::{WindowMenuRows, WindowMenuRowsOutput}; use crate::contract::{ diff --git a/crates/ui-panels/src/docking/rail.rs b/crates/ui-panels/src/docking/rail.rs deleted file mode 100644 index 952427876..000000000 --- a/crates/ui-panels/src/docking/rail.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! What a rail icon does for a panel and whether it shows lit, from the dock layout. - -use craft_behavior::dock::{Action, Layout, Node, PanelPlace, PanelState}; -use std::hash::Hash; - -/// Whether the group, window or accordion section of `panel` is minimized. An accordion entry is minimized while it -/// is closed. A panel the layout does not hold is not. -pub(crate) fn minimized(layout: &Layout

, panel: &P) -> bool { - let Some(place) = layout.place(panel) else { return false }; - match &place { - PanelPlace::Node(_) => match layout.node_of(&place) { - Some(Node::Stack { entries, .. }) => entries.iter().any(|entry| &entry.panel == panel && !entry.open), - _ => false, - }, - PanelPlace::Floating { window, .. } => layout.floating.get(*window).is_some_and(|window| window.minimized), - _ => layout.group(&place).is_some_and(|group| group.minimized), - } -} - -/// The actions a click on the rail icon of `panel` takes: minimize a docked and shown panel, restore and activate a -/// minimized one, close a floating one's window, open a hidden one. -pub fn rail_actions(layout: &Layout

, panel: &P) -> Vec> { - match layout.place(panel) { - None => vec![Action::open(panel.clone(), None)], - Some(PanelPlace::Floating { .. }) => vec![Action::close_window(panel.clone())], - Some(_) if minimized(layout, panel) => vec![Action::set_minimized(panel.clone(), false), Action::activate(panel.clone())], - Some(_) => vec![Action::set_minimized(panel.clone(), true)], - } -} - -/// Whether the rail icon of `panel` shows lit: its group is in the layout and not minimized. -pub fn rail_lit(layout: &Layout

, panel: &P) -> bool { - layout.panel_state(panel) != PanelState::Hidden && !minimized(layout, panel) -} From c7d1a376d7d39ee62df0bd9454f4d033809a2209 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:24:14 +0000 Subject: [PATCH 05/18] Dock UI: ColumnBar for a column in a floating window; FloatingGroup carries its column's bar DockColumn and IconicColumn take ColumnBar::Window inside a floating window: no bar, no frame and no edge bands, and an expanded column no edge divider, since the window's title row, frame and edges carry them. FloatingGroup takes the window's WindowColumn: the title row shows the column's double arrow at the end the window keeps to, the arrow or a double click on the band reports iconic, and a collapsed column shows at its collapsed size against that edge of the rect, not resizable, a move keeping the rect's size. IconicSizes::of and icons_height size a collapsed window. --- crates/ui-panels/src/docking/dock_column.rs | 112 +++++++++++---- crates/ui-panels/src/docking/floating.rs | 135 ++++++++++++++++-- .../ui-panels/src/docking/floating/stories.rs | 39 ++++- crates/ui-panels/src/docking/iconic.rs | 67 ++++++--- crates/ui-panels/src/docking/mod.rs | 2 +- 5 files changed, 296 insertions(+), 59 deletions(-) diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index b44039f5f..2e5b9558a 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -37,6 +37,30 @@ pub use sizing::{GroupSize, fit_widths, group_heights, scale_widths, stacked, wi const DIVIDER: PartKey = PartKey::new("divider"); const EDGE: PartKey = PartKey::new("edge"); +/// Where a column's bar is. A dock column and a floating window are both one column; the window's title row is the +/// bar of the column it holds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum ColumnBar { + /// The column shows its own bar (the double arrow and the band that moves the column and opens its menu), the + /// divider of its inner edge, its frame and the drop bands of its two edges: a column of a side dock. + #[default] + Own, + /// The column fills a floating window, whose frame, edges and title row carry what `Own` shows: the column shows + /// no bar, no edge divider and no frame, and registers no edge bands, since nothing goes beside a floating column. + Window, +} + +impl ColumnBar { + /// The height of the column's bar: the dock's bar height for `Own`, none for `Window`. + pub(super) fn height(self, sizes: &DockSizes) -> f32 { + match self { + ColumnBar::Own => sizes.bar, + ColumnBar::Window => 0.0, + } + } +} + /// The caller's view of one group: the group, the rect it takes and the body step's context. The dock passes the /// group to `DockPanels::group_view` or shows a `DockGroup` in it. pub type GroupView<'a, P> = Box, Rect, &mut Ui, &mut BodyCx<'_>) + 'a>; @@ -85,6 +109,9 @@ pub struct DockColumnStyle { /// /// The column registers the drop bands of its two edges (`DockSpot::column`) and of the seams between its groups /// (`DockSpot::seam`) with the dock `dock` every pass. A dock hidden by the shell shows nothing. +/// +/// In a floating window ([`ColumnBar::Window`]) the window's title row is the column's bar and the window's edges +/// size it: the column shows its groups and their dividers only, and registers its seams. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, probe(DockColumn<'static, u8>))] pub struct DockColumn<'a, P: Value + Hash + 'static> { @@ -101,6 +128,9 @@ pub struct DockColumn<'a, P: Value + Hash + 'static> { /// The window edge the column's dock sits on; the column's inner edge faces away from it. #[prop] edge: DockEdge, + /// Where the column's bar is: its own (a dock column) or its floating window's title row. + #[prop] + bar: ColumnBar, /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. #[prop] within: Rect, @@ -124,6 +154,7 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { spec, auto_collapse: false, edge: DockEdge::Start, + bar: ColumnBar::Own, within: Rect::NOTHING, laid: None, resized: Vec::new(), @@ -151,19 +182,22 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { at: Option, mut view: impl FnMut(&Group

, Rect, &mut Ui, &mut BodyCx<'_>) + 'a, ) -> DockColumnOutput

{ - let (column, spec, auto_collapse, edge) = (self.column, self.spec, self.auto_collapse, self.edge); + let (column, spec, auto_collapse, edge, own) = (self.column, self.spec, self.auto_collapse, self.edge, self.bar); let mut bar = BarRecord::default(); let shown = &mut bar; let body = move |ui: &mut Ui, body: &mut BodyCx<'_>| { - if body.shell().is_some_and(|shell| !shell.dock_visible()) { + // A floating window shows where the area shows it; the shell hides docks only. + if own == ColumnBar::Own && body.shell().is_some_and(|shell| !shell.dock_visible()) { return; } let Some(sizes) = body.style::>().map(|style| style.sizes) else { return }; // The bar and the groups at the heights this pass's drag leaves them, in the measuring run and the real // run alike: the same plan `parts` lays out, so the dividers sit at the seams. let drags = |key: u64, divider: &Divider| divider::drag(body.part_press(DIVIDER.at(key)).phase, body.rect, false, divider); - let plan = column_plan(column, spec, body.rect, &sizes, drags); - if let Some(grip) = column_grip(column, spec, body) { + let plan = column_plan(column, spec, body.rect, own, &sizes, drags); + if own == ColumnBar::Own + && let Some(grip) = column_grip(column, spec, body) + { *shown = show_bar(ui, body, plan.bar, true, auto_collapse, edge, grip); } for (group, rect) in column.groups.iter().zip(&plan.groups) { @@ -200,15 +234,17 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { } /// The bar and body of the column in `rect`, and the groups stacked in the body, with the drags `drags` makes of -/// the dividers between open groups (the divider's part index and the divider as laid out before the drag). +/// the dividers between open groups (the divider's part index and the divider as laid out before the drag). A +/// column in a floating window has an empty bar on top. fn column_plan( column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, rect: Rect, + own: ColumnBar, sizes: &DockSizes, drags: impl Fn(u64, &Divider) -> Option, ) -> Plan { - let bar = Rect::from_min_max(rect.min, Pos2::new(rect.right(), (rect.top() + sizes.bar).min(rect.bottom()))); + let bar = Rect::from_min_max(rect.min, Pos2::new(rect.right(), (rect.top() + own.height(sizes)).min(rect.bottom()))); let body = Rect::from_min_max(Pos2::new(rect.left(), bar.bottom()), rect.max); body_plan(column, spec, bar, body, sizes, drags) } @@ -297,27 +333,33 @@ impl Component for DockColumn<'_, P> { Sense::empty() } - /// The chevron at the bar's outer end, and a divider between every two open groups. + /// The chevron at the bar's outer end, a divider between every two open groups and the inner edge's divider; a + /// column in a floating window has the group dividers only. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let sizes = cx.style.sizes; - let plan = column_plan(self.column, self.spec, rect, &sizes, |_, _| None); - let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); - let name = chevron_name(&cx.words::(), true); - let _ = cx.part(CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); + let plan = column_plan(self.column, self.spec, rect, self.bar, &sizes, |_, _| None); + if self.bar == ColumnBar::Own { + let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); + let name = chevron_name(&cx.words::(), true); + let _ = cx.part(CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); + } let dividers = plan.dividers(rect, sizes.reach); for (key, _, divider) in dividers { divider::declare(cx, rect, DIVIDER, key, ÷r); } - divider::declare(cx, rect, EDGE, 0, &self.edge_divider(rect, &sizes)); + if self.bar == ColumnBar::Own { + divider::declare(cx, rect, EDGE, 0, &self.edge_divider(rect, &sizes)); + } self.laid = Some(plan); } fn update(&mut self, cx: &mut Cx<'_, Self>) { let sizes = cx.style.sizes; let (rect, rtl, ctx) = (cx.rect, cx.flow.is_rtl(), cx.core.ctx.clone()); - self.collapse = cx.part_activated(CHEVRON).is_some(); + let own = self.bar == ColumnBar::Own; + self.collapse = own && cx.part_activated(CHEVRON).is_some(); let Some(base) = self.laid.take() else { return }; - let mut plan = column_plan(self.column, self.spec, rect, &sizes, |key, divider| divider::pointer(cx, DIVIDER, key, divider)); + let mut plan = column_plan(self.column, self.spec, rect, self.bar, &sizes, |key, divider| divider::pointer(cx, DIVIDER, key, divider)); let dividers = base.dividers(rect, sizes.reach); let keyed: Vec<(u64, Divider)> = dividers.iter().map(|(key, _, divider)| (*key, *divider)).collect(); if let Some((key, coord)) = divider::keys(cx, DIVIDER, &keyed, sizes.step, sizes.jump) @@ -333,12 +375,14 @@ impl Component for DockColumn<'_, P> { self.resized.push((anchor.clone(), plan.heights[group])); } } - let edge = self.edge_divider(rect, &sizes); - if let Some(Drag::To(coord)) = divider::pointer(cx, EDGE, 0, &edge) { - self.move_edge(rect, &edge, coord); - } - if let Some((_, coord)) = divider::keys(cx, EDGE, &[(0, edge)], sizes.step, sizes.jump) { - self.move_edge(rect, &edge, coord); + if own { + let edge = self.edge_divider(rect, &sizes); + if let Some(Drag::To(coord)) = divider::pointer(cx, EDGE, 0, &edge) { + self.move_edge(rect, &edge, coord); + } + if let Some((_, coord)) = divider::keys(cx, EDGE, &[(0, edge)], sizes.step, sizes.jump) { + self.move_edge(rect, &edge, coord); + } } self.register(&ctx, rect, rtl, &plan, &sizes); self.laid = Some(plan); @@ -348,13 +392,21 @@ impl Component for DockColumn<'_, P> { let Some(plan) = self.laid.as_ref() else { return }; // Painted here, not as the container's surface, which lies over what `paint` draws. ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); - ui.draw().surface(plan.bar, SurfaceKind::Background, Corners::None); - paint_chevron(ui, self.edge, true, cx.flow.is_rtl(), chevron_name(&cx.words::(), true)); + if self.bar == ColumnBar::Own { + ui.draw().surface(plan.bar, SurfaceKind::Background, Corners::None); + paint_chevron(ui, self.edge, true, cx.flow.is_rtl(), chevron_name(&cx.words::(), true)); + } } - /// The column's frame, then the dividers over it. + /// The column's frame, then the dividers over it. The frame of a column in a floating window is the window's. fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let Some(plan) = self.laid.as_ref() else { return }; + if self.bar == ColumnBar::Window { + for pair in plan.open.windows(2) { + ui.face(DIVIDER.at(pair[0] as u64), Splitter::new(Axis::Y)); + } + return; + } ui.draw().surface(cx.rect, SurfaceKind::Frame, Corners::None); for pair in plan.open.windows(2) { ui.face(DIVIDER.at(pair[0] as u64), Splitter::new(Axis::Y)); @@ -372,9 +424,11 @@ impl Component for DockColumn<'_, P> { for (key, _, divider) in plan.dividers(cx.rect, sizes.reach) { divider::describe(access, DIVIDER, key, ÷r, words.resize.as_str(), sizes.step); } - let edge = self.edge_divider(cx.rect, &sizes); - divider::describe(access, EDGE, 0, &edge, words.resize.as_str(), sizes.step); - describe_chevron(access, &chevron_name(&words, true)); + if self.bar == ColumnBar::Own { + let edge = self.edge_divider(cx.rect, &sizes); + divider::describe(access, EDGE, 0, &edge, words.resize.as_str(), sizes.step); + describe_chevron(access, &chevron_name(&words, true)); + } } fn finish(self, cx: Cx<'_, Self>) -> DockColumnOutput

{ @@ -413,10 +467,12 @@ pub(super) fn register_edges(ctx: &Context, dock: Id, } impl DockColumn<'_, P> { - /// Registers the drop bands of the column's two edges and of the seams between its groups. + /// Registers the drop bands of the column's two edges, for a dock column, and of the seams between its groups. fn register(&self, ctx: &Context, rect: Rect, rtl: bool, plan: &Plan, sizes: &DockSizes) { let Some(first) = self.anchor(0) else { return }; - register_edges(ctx, self.dock, first, rect, rtl, sizes); + if self.bar == ColumnBar::Own { + register_edges(ctx, self.dock, first, rect, rtl, sizes); + } let (mut before, half) = (first, sizes.seam_band * 0.5); for (at, group) in plan.groups.iter().enumerate().skip(1) { let Some(after) = self.anchor(at) else { continue }; diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 3e819847a..9d753dc97 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -4,15 +4,18 @@ //! caller places it with the rect the dock model keeps and takes the rect the output reports after each step of //! a gesture. The title row carries the active panel's title and the Menu, Float and Close actions; the Menu action //! opens the `menu` rows. The body step supplies the move band, the edge grips and the keyboard Move and Size modes. +//! A dock window's title row is also the bar of the column the window holds, with the column's double arrow. +use super::dock_column::{CHEVRON, chevron_name, describe_chevron, paint_chevron}; use super::drop::{DragUnit, start_group_drag}; use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup}; use crate::contract::{ - Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, OsFiles, Outcome, Overlay, Pad, - Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderEdge, HeaderParts, HeaderRegion, Inner, MeasureCx, Mount, + NoValue, OsFiles, Outcome, Overlay, Pad, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, + WordSetCx as _, }; use crate::runtime::drag::OsFile; use crate::runtime::env::{Env, Label}; @@ -20,9 +23,10 @@ use crate::runtime::overlay::CloseReason; use crate::runtime::windows::WindowSpec; use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow}; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; +use craft_behavior::dock::DockEdge; use craft_behavior::{GesturePhase, Metrics, Sense}; use craft_ui_widgets::popover::WholeWindow; -use egui::{Id, Rect, Response, Ui, Vec2}; +use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; use std::cell::RefCell; use std::hash::Hash; @@ -40,6 +44,36 @@ pub struct FloatingGroupStyle { metrics: Metrics, } +/// The column a dock's floating window holds. The window's title row is the column's bar: it shows the column's +/// double arrow at the end on `edge`, and a collapsed column shows against that edge of the window's rect. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct WindowColumn { + /// The edge of the float area, in reading order, that the window keeps to: the one nearer the window. + pub edge: DockEdge, + /// The size of the collapsed column under the title row; `None` while the column is expanded. + pub collapsed: Option, +} + +impl WindowColumn { + /// An expanded column that keeps to `edge`. + pub fn expanded(edge: DockEdge) -> Self { + WindowColumn { edge, collapsed: None } + } + + /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. + pub fn collapsed(edge: DockEdge, size: Vec2) -> Self { + WindowColumn { edge, collapsed: Some(size) } + } + + /// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is + /// in the half of the bounds there or `bounds` is empty. + pub fn nearer_edge(rect: Rect, bounds: Rect, rtl: bool) -> DockEdge { + let at_left = !bounds.is_positive() || rect.center().x - bounds.left() <= bounds.right() - rect.center().x; + if at_left != rtl { DockEdge::Start } else { DockEdge::End } + } +} + /// What a floating group reports in a pass. #[derive(Debug)] #[non_exhaustive] @@ -52,8 +86,12 @@ pub struct FloatingGroupOutput { /// The title row's action part taken this pass, or Close when the OS asked the group's window to close. Float and /// Close are the host's: the dock model docks or closes the group. Menu opens the `menu` rows. pub action: Option, - /// Whether a double click on the title band asks to minimize the group, or restore it when it is minimized. + /// Whether a double click on the title band asks to minimize the group, or restore it when it is minimized. A + /// group with a [`WindowColumn`] reports that click in `iconic` instead. pub minimized_toggled: bool, + /// The user asked to collapse the window's column to icons (`true`) or expand it (`false`): a click on the double + /// arrow, or a double click on the title band. Only a group with a [`WindowColumn`] reports it. + pub iconic: Option, /// The files dropped on the group's window that no target there took. pub files: Vec, } @@ -76,6 +114,9 @@ impl Outcome for FloatingGroupOutput { /// the body; with another sizing the rect is the size. The user's resizes are reported either way. /// - Minimized: only the title row shows, at the width of the rect, and the edges do not resize. The rect given to /// `new` keeps the height the group has when restored. +/// - Column: a dock window holds one column ([`column`](FloatingGroup::column)); its title row is the column's bar, +/// with the double arrow at the end the window keeps to. While the column is collapsed the group shows at the +/// collapsed size against that edge of the rect, the edges do not resize, and a move keeps the rect's size. /// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag /// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release. /// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where @@ -103,6 +144,9 @@ pub struct FloatingGroup<'a> { /// Whether only the title row shows. #[prop] minimized: bool, + /// The column the window holds, whose bar the title row is. + #[prop] + column: Option, /// Whether the height follows the body (`Sizing::Content`) or the rect gives it. #[prop] sized: Sizing, @@ -118,6 +162,12 @@ pub struct FloatingGroup<'a> { taken: Option, menu_opener: Option, toggled: bool, + /// The double arrow was declared this pass, and whether it was clicked. + chevron_declared: bool, + chevron: bool, + /// The title row's height and the layout direction, read when the group shows. + header: f32, + rtl: bool, placed: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, @@ -149,6 +199,7 @@ impl<'a> FloatingGroup<'a> { limits: SizeLimits::default(), opacity: 1.0, minimized: false, + column: None, sized: Sizing::Content, native: None, menu: None, @@ -157,6 +208,10 @@ impl<'a> FloatingGroup<'a> { taken: None, menu_opener: None, toggled: false, + chevron_declared: false, + chevron: false, + header: 0.0, + rtl: false, placed: None, start_drag: None, take_drop: None, @@ -203,7 +258,9 @@ impl<'a> FloatingGroup<'a> { /// Shows the group; `body` fills the area under the title row unless the group is minimized. pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - let header = Env::of(ui).tokens.size.panel_header; + let env = Env::of(ui); + let header = env.tokens.size.panel_header; + (self.header, self.rtl) = (header, env.direction.is_rtl()); let mount = self.mount(header); self.props = self.props.mount(mount); let minimized = self.minimized; @@ -218,8 +275,12 @@ impl<'a> FloatingGroup<'a> { fn mount(&self, header: f32) -> Mount { // The frame's limits are the body's with the title row on top. let frame = self.limits.around(Vec2::new(0.0, header)); - let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized).opacity(self.opacity).body_scroll(false); - overlay = if self.minimized { + let collapsed = self.collapsed_rect(); + let mut overlay = + Overlay::floating().movable(true).resizable(!self.minimized && collapsed.is_none()).opacity(self.opacity).body_scroll(false); + overlay = if let Some(shown) = collapsed { + overlay.placed(shown).size_limits(SizeLimits::new(shown.size(), shown.size())) + } else if self.minimized { let width = self.rect.width(); overlay.placed_at(self.rect.min).size_limits(SizeLimits::new(Vec2::new(width, 0.0), Vec2::new(width, f32::INFINITY))) } else if self.sized == Sizing::Content { @@ -236,12 +297,25 @@ impl<'a> FloatingGroup<'a> { None => Mount::Layer(overlay), } } + + /// Where the group shows while its column is collapsed: the collapsed column under the title row, at the top of + /// the rect and against its edge the window keeps to. `None` while the column is expanded. + fn collapsed_rect(&self) -> Option { + let column = self.column?; + let size = column.collapsed? + Vec2::new(0.0, self.header); + let at_left = (column.edge == DockEdge::Start) != self.rtl; + let left = if at_left { self.rect.left() } else { self.rect.right() - size.x }; + Some(Rect::from_min_size(Pos2::new(left, self.rect.top()), size)) + } + + /// The double arrow's square at the end of the title row the window keeps to. + fn chevron_edge(&self) -> Option { + self.column.map(|column| if column.edge == DockEdge::End { HeaderEdge::End } else { HeaderEdge::Start }) + } } impl Component for FloatingGroup<'_> { const ROLE: Role = Role::GROUP; - const PARTS: bool = false; - const STOPS: bool = false; type Style = FloatingGroupStyle; type Output = FloatingGroupOutput; @@ -253,7 +327,17 @@ impl Component for FloatingGroup<'_> { Sense::empty() } + /// The column's double arrow, in its square of the title row. + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let (Some(edge), Some(column)) = (self.chevron_edge(), self.column) else { return }; + let Some(slot) = cx.header_slot(edge) else { return }; + let name = chevron_name(&cx.words::(), column.collapsed.is_none()); + let _ = cx.header_part(edge, CHEVRON, slot).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); + self.chevron_declared = true; + } + fn update(&mut self, cx: &mut Cx<'_, Self>) { + self.chevron = self.chevron_declared && cx.part_activated(CHEVRON).is_some(); if let Some(mut take) = self.take_drop.take() { take(cx); self.take_drop = Some(take); @@ -267,6 +351,19 @@ impl Component for FloatingGroup<'_> { } } + /// The double arrow, over the title row's surface. + fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(column) = self.column.filter(|_| self.chevron_declared) else { return }; + let expanded = column.collapsed.is_none(); + paint_chevron(ui, column.edge, expanded, cx.flow.is_rtl(), chevron_name(&cx.words::(), expanded)); + } + + fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { + if let Some(column) = self.column.filter(|_| self.chevron_declared) { + describe_chevron(access, &chevron_name(&cx.words::(), column.collapsed.is_none())); + } + } + fn finish(mut self, mut cx: Cx<'_, Self>) -> FloatingGroupOutput { if self.start_drag.is_some() { native::keeps_app_drag(&cx.core.ctx, cx.core.id); @@ -279,11 +376,15 @@ impl Component for FloatingGroup<'_> { if let Some(opener) = self.menu_opener { Popup::toggle(opener, &mut cx); } + // A dock window's band double click collapses or expands its column, as a dock column's bar does. + let collapsed = self.column.map(|column| column.collapsed.is_some()); + let iconic = collapsed.filter(|_| self.chevron || self.toggled).map(|collapsed| !collapsed); let output = FloatingGroupOutput { response: cx.response.clone(), placed: self.placed, action: self.taken, - minimized_toggled: self.toggled, + minimized_toggled: self.toggled && self.column.is_none(), + iconic, files: self.files, }; native::raise(&cx.core.ctx, &output); @@ -293,6 +394,15 @@ impl Component for FloatingGroup<'_> { } impl Container for FloatingGroup<'_> { + /// The double arrow's square at the end of the title row the window keeps to. + fn header_parts(&self, _: &MeasureCx<'_, Self>) -> HeaderParts { + match self.chevron_edge() { + Some(HeaderEdge::End) => HeaderParts::NONE.end(self.header), + Some(_) => HeaderParts::NONE.start(self.header), + None => HeaderParts::NONE, + } + } + fn open(&mut self) -> Option> { Some(self.open.reborrow()) } @@ -315,7 +425,10 @@ impl Container for FloatingGroup<'_> { fn placement_changed(&mut self, change: &PlacementChange) { let mut change = *change; - if self.minimized { + if let Some(shown) = self.collapsed_rect() { + // The collapsed window moves; the rect keeps its expanded size. + change.rect = self.rect.translate(change.rect.min - shown.min); + } else if self.minimized { change.rect = Rect::from_min_size(change.rect.min, Vec2::new(change.rect.width(), self.rect.height())); } self.moving |= change.kind == PlacementKind::Move && change.phase == GesturePhase::Begin; diff --git a/crates/ui-panels/src/docking/floating/stories.rs b/crates/ui-panels/src/docking/floating/stories.rs index 541f4c0cb..61fc81fb7 100644 --- a/crates/ui-panels/src/docking/floating/stories.rs +++ b/crates/ui-panels/src/docking/floating/stories.rs @@ -1,11 +1,12 @@ //! Stories of `FloatingGroup`. -use super::FloatingGroup; +use super::{FloatingGroup, WindowColumn}; use crate::buttons::Button; use crate::contract::Show as _; use crate::menu::MenuItem; use crate::testing::{Drive, StoryData, StoryOutput, story}; -use egui::{Pos2, Rect, Ui}; +use craft_behavior::dock::DockEdge; +use egui::{Pos2, Rect, Ui, Vec2}; const START: Rect = Rect { min: Pos2::new(40.0, 40.0), max: Pos2::new(280.0, 220.0) }; @@ -24,3 +25,37 @@ fn floating_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { } shown.output.into() } + +/// A dock window: its title row is its column's bar, with the double arrow at the end the window keeps to. The +/// arrow and a double click on the band collapse the column to a strip of icons against that edge. +#[story(FloatingGroup<'static>, covers = [Open], drive = Drive::Never)] +fn floating_dock_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let rect = *data.value("rect", START); + let collapsed = *data.value("collapsed", false); + // A strip of three icon cells, as an iconic column of three panels is. + let column = if collapsed { WindowColumn::collapsed(DockEdge::Start, Vec2::new(40.0, 120.0)) } else { WindowColumn::expanded(DockEdge::Start) }; + let shown = FloatingGroup::new("Layers", rect).column(column).sized(crate::contract::Sizing::Fill).show_group(ui, |ui, _| { + Button::new(if collapsed { "L" } else { "Add layer" }).show(ui); + }); + if let Some(change) = shown.output.placed { + *data.value("rect", START) = change.rect; + } + if let Some(iconic) = shown.output.iconic { + *data.value("collapsed", false) = iconic; + } + shown.output.into() +} + +/// A dock window whose column is collapsed to icons, against the float area's end edge. +#[story(FloatingGroup<'static>, covers = [Mixed], drive = Drive::Never)] +fn floating_collapsed_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let rect = *data.value("rect", START); + let column = WindowColumn::collapsed(DockEdge::End, Vec2::new(40.0, 120.0)); + let shown = FloatingGroup::new("Layers", rect).column(column).sized(crate::contract::Sizing::Fill).show_group(ui, |ui, _| { + Button::new("L").show(ui); + }); + if let Some(change) = shown.output.placed { + *data.value("rect", START) = change.rect; + } + shown.output.into() +} diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 39bf60718..900d85c5a 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -1,7 +1,9 @@ //! `IconicColumn`: a column collapsed to one icon per panel, and the flyouts its icons open. use super::divider::{self, Divider, Drag}; -use super::dock_column::{BarRecord, CHEVRON, bar_slots, chevron_name, column_grip, describe_chevron, paint_chevron, register_edges, show_bar}; +use super::dock_column::{ + BarRecord, CHEVRON, ColumnBar, bar_slots, chevron_name, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, +}; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_group_drag}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; @@ -62,6 +64,18 @@ impl IconicSizes { labels: size.rail.width * LABELS_IN_RAIL_WIDTHS, } } + + /// The sizes in the root scope's style, for code outside a style pass: + /// `StyleCx::with_root(ctx, IconicSizes::style)`. + pub fn of(ctx: &egui::Context) -> Self { + StyleCx::with_root(ctx, IconicSizes::style) + } + + /// The height of the icons of `column` under its bar: a cell per panel and the room between every two groups. + pub fn icons_height

(&self, column: &Column

) -> f32 { + let cells: usize = column.groups.iter().map(|group| group.panels.len()).sum(); + cells as f32 * self.cell + column.groups.len().saturating_sub(1) as f32 * self.separator + } } /// What an iconic column reports. @@ -143,6 +157,9 @@ pub struct IconicColumnStyle { /// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`. /// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in /// [`IconicColumnOutput::flyout`], which the host keeps in the group (`flyout_width`, `height`, `flyout_offset`). +/// +/// In a floating window ([`ColumnBar::Window`]) the window's title row is the column's bar: the column shows its +/// icons under it and keeps the divider of its inner edge, which sets its width, and registers no edge bands. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, overlay, probe(IconicColumn<'static, u8>))] pub struct IconicColumn<'a, P: Value + Hash + 'static> { @@ -156,6 +173,9 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// The window edge the column sits on, which the flyout opens away from. #[prop] edge: DockEdge, + /// Where the column's bar is: its own (a dock column) or its floating window's title row. + #[prop] + bar: ColumnBar, /// Whether Auto-Collapse Iconic Panels is on. #[prop] auto_collapse: bool, @@ -164,7 +184,8 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { within: Rect, open: Bind<'a, Option

>, view: Option>, - bar: Rect, + /// The bar's rect this pass. + bar_rect: Rect, record: BarRecord, shown: Option, width: Option, @@ -213,11 +234,12 @@ impl<'a, P: Value + Hash + 'static> IconicColumn<'a, P> { column, spec, edge: DockEdge::Start, + bar: ColumnBar::Own, auto_collapse: false, within: Rect::NOTHING, open, view: None, - bar: Rect::NOTHING, + bar_rect: Rect::NOTHING, record: BarRecord::default(), shown: None, width: None, @@ -277,7 +299,7 @@ impl<'a, P: Value + Hash + 'static> IconicColumn<'a, P> { } fn plan(&self, rect: Rect, sizes: &IconicSizes, rtl: bool) -> Plan { - let bar = Rect::from_min_max(rect.min, Pos2::new(rect.right(), (rect.top() + sizes.column.bar).min(rect.bottom()))); + let bar = Rect::from_min_max(rect.min, Pos2::new(rect.right(), (rect.top() + self.bar.height(&sizes.column)).min(rect.bottom()))); let body = Rect::from_min_max(Pos2::new(rect.left(), bar.bottom()), rect.max); let wide = body.width() >= sizes.labels; let (mut y, mut cells, mut names, mut grips, mut groups) = (body.top(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); @@ -386,10 +408,12 @@ impl Component for IconicColumn<'_, P> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let sizes = cx.style.sizes; let plan = self.plan(rect, &sizes, cx.flow.is_rtl()); - self.bar = plan.bar; - let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); - let name = chevron_name(&cx.words::(), false); - let _ = cx.header_part(chevron_edge(self.edge), CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); + self.bar_rect = plan.bar; + if self.bar == ColumnBar::Own { + let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); + let name = chevron_name(&cx.words::(), false); + let _ = cx.header_part(chevron_edge(self.edge), CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); + } for (at, (_, _, cell)) in plan.cells.iter().enumerate() { let Some(panel) = self.flat().get(at).and_then(|(group, panel)| self.panel(*group, *panel)) else { continue }; let label = (self.spec)(panel).label; @@ -417,7 +441,7 @@ impl Component for IconicColumn<'_, P> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let sizes = cx.style.sizes; let (rect, rtl, ctx) = (cx.rect, cx.flow.is_rtl(), cx.core.ctx.clone()); - self.expand = cx.part_activated(CHEVRON).is_some(); + self.expand = self.bar == ColumnBar::Own && cx.part_activated(CHEVRON).is_some(); let Some(plan) = self.laid.take() else { return }; let flat = self.flat(); let popup = cx.popup("flyout"); @@ -491,8 +515,10 @@ impl Component for IconicColumn<'_, P> { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { // Painted here, not as the container's surface, which lies over what `paint` draws. ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); - ui.draw().surface(self.bar, SurfaceKind::Background, Corners::None); - paint_chevron(ui, self.edge, false, cx.flow.is_rtl(), chevron_name(&cx.words::(), false)); + if self.bar == ColumnBar::Own { + ui.draw().surface(self.bar_rect, SurfaceKind::Background, Corners::None); + paint_chevron(ui, self.edge, false, cx.flow.is_rtl(), chevron_name(&cx.words::(), false)); + } let flat = self.flat(); for (at, (group, panel)) in flat.iter().enumerate() { let Some(panel) = self.panel(*group, *panel) else { continue }; @@ -527,7 +553,9 @@ impl Component for IconicColumn<'_, P> { access.node(GRIP.at(*group as u64), Role::BUTTON).name = Name::Text(name); } divider::describe(access, EDGE, 0, &self.edge_divider(cx.rect, &sizes.column), words.resize.as_str(), sizes.column.step); - describe_chevron(access, &chevron_name(&words, false)); + if self.bar == ColumnBar::Own { + describe_chevron(access, &chevron_name(&words, false)); + } } /// The flyout of every cell whose popup is open, beside the column on the canvas side. A resize the user makes @@ -591,11 +619,13 @@ impl Component for IconicColumn<'_, P> { } impl IconicColumn<'_, P> { - /// Registers the drop bands of the column's edges, and the upper and lower half of every icon group: a drop on + /// Registers the drop bands of a dock column's edges, and the upper and lower half of every icon group: a drop on /// the upper half stacks above the group, one on the lower half below it. fn register(&self, ctx: &egui::Context, rect: Rect, rtl: bool, plan: &Plan, sizes: &IconicSizes) { let Some(first) = self.column.groups.first().and_then(|group| group.panels.first()) else { return }; - register_edges(ctx, self.dock, first, rect, rtl, &sizes.column); + if self.bar == ColumnBar::Own { + register_edges(ctx, self.dock, first, rect, rtl, &sizes.column); + } let half = sizes.separator * 0.5; let last = plan.groups.len().saturating_sub(1); for (at, group) in &plan.groups { @@ -629,19 +659,22 @@ fn chevron_edge(edge: DockEdge) -> HeaderEdge { } impl Container for IconicColumn<'_, P> { - /// The chevron's square at the bar's outer end. + /// The chevron's square at the bar's outer end; nothing in a floating window, whose title row is the bar. fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts { + if self.bar == ColumnBar::Window { + return HeaderParts::NONE; + } let side = cx.style.sizes.column.bar; if chevron_edge(self.edge) == HeaderEdge::End { HeaderParts::NONE.end(side) } else { HeaderParts::NONE.start(side) } } /// The column bar, over the icons. What the user did on it is read in `finish`. fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { - if cx.shell().is_some_and(|shell| !shell.dock_visible()) { + if self.bar == ColumnBar::Window || cx.shell().is_some_and(|shell| !shell.dock_visible()) { return; } if let Some(grip) = column_grip(self.column, self.spec, cx) { - self.record = show_bar(ui, cx, self.bar, false, self.auto_collapse, self.edge, grip); + self.record = show_bar(ui, cx, self.bar_rect, false, self.auto_collapse, self.edge, grip); } } } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 306939775..2e42fa853 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -56,7 +56,7 @@ mod flyout; mod iconic; pub use dock_column::{ - DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, width_bounds, + ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, width_bounds, }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes}; From aa46612ac9d3ca98c62fe2cffd24c464830a677d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:28:18 +0000 Subject: [PATCH 06/18] Dock area: a floating window draws its one column as a dock column does Pass::column shows a column, docked or floating: an IconicColumn while it is collapsed, else a DockColumn, with what the user did turned into actions in column_work. Each dock column calls it with its own bar; each floating window calls it inside a FloatingGroup with ColumnBar::Window, the title row being the column's bar: its double arrow sets the column iconic, and a collapsed window shows its icons at their size against the float area's nearer edge. The window's split tree, its split resizes and its minimized toggle are gone. Trial: the double arrow collapses a floating window's column and expands it, the window keeping its rect. --- crates/ui-panels/src/docking/mod.rs | 2 +- crates/ui-patterns/src/patterns/dock/area.rs | 133 ++++++++++-------- crates/ui-patterns/tests/it/docking/drop.rs | 2 +- .../tests/it/docking/floating_area.rs | 31 ++++ docs/ui-docking.md | 6 +- 5 files changed, 108 insertions(+), 66 deletions(-) diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 2e42fa853..f1ca68ce7 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -36,7 +36,7 @@ pub use drop::{DockDrag, DockDropTarget, DockDropped, DragUnit, float_drop, reso pub use event::{DockEvent, FloatSpace, HidePanels}; pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook}; -pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle}; +pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, WindowColumn}; pub use panels::{DockPanels, request_actions}; #[doc(hidden)] pub use panels::{close_requests, open_requests}; diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 18a9ee759..07964bad7 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -11,9 +11,9 @@ use crate::docking::stack::{StackSection, StackSections, section_heights}; use crate::docking::tree::FrameRules; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ - DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, DockSpot, - DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, IconicColumn, PanelDrag, - PanelKey, PanelSpec, PanelTitle, SplitArea, actions, dock_states, fit_widths, frame, move_actions, + ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, + DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, IconicColumn, + IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, Commands as _, focus_within}; @@ -94,8 +94,8 @@ impl

Outcome for DockAreaOutput

{ /// The docking pattern over a workspace. /// /// - Shape: the docked tree is a `SplitArea`; a dock's columns are `DockColumn`s, or `IconicColumn`s with their -/// flyouts; a group is a `DockGroup`; a floating window is a `FloatingGroup`. The host's `DockPanels` supplies the -/// panels. +/// flyouts; a group is a `DockGroup`; a floating window is a `FloatingGroup` holding one column, shown as a dock's +/// column is, whose bar is the window's title row. The host's `DockPanels` supplies the panels. /// - Edits: a divider drag and every [`Action`] of the pass (menu rows, drags, drops) are written to the workspace /// through its binding, with the panels' [`DockPanels::permissions`] (narrowed when `locked`). The output lists the /// actions the workspace took, divider sizes and window moves included. A given workspace is not written. @@ -283,6 +283,16 @@ struct DockPlan<'p, P> { open: Option

, } +/// Where and how a column shows: its rect; the edge it keeps to, a dock's window edge or the float area's edge a +/// floating window keeps to; where its bar is; the rect its inner edge and flyouts stay within; and the open flyout. +struct ColumnAt

{ + cell: Rect, + edge: DockEdge, + bar: ColumnBar, + within: Rect, + open: Option

, +} + /// What a column reported. struct ColumnWork

{ iconic: Option, @@ -559,7 +569,7 @@ fn show_area( _ => Vec::new(), }; register_bands(&scene, ctx, body.rect, &leaves); - let moved = if floating { pass.windows(ui, body) } else { None }; + let moved = if floating { pass.windows(ui, body, &open) } else { None }; let mut report = pass.report; let label: Arc = Arc::from(body.words::().move_window.as_str()); if let Some((anchor, change)) = moved @@ -890,38 +900,48 @@ impl Pass<'_, P> { let reading = plan.flow.to_physical(plan.rect); let start = plan.edge == DockEdge::Start; let mut cursor = if start { reading.left() } else { reading.right() }; - let name = Label::from(body.words::().panels.as_str().to_owned()); for (column, width) in plan.columns.iter().zip(widths) { let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) }; cursor = if start { span.1 } else { span.0 }; let cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())); let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { continue }; self.report.placed.push((first.clone(), cell)); - if column.iconic { - let open = plan.open.clone(); - let output = IconicColumn::new(name.clone(), scene.dock, column, Bind::given(open.clone()), &spec) - .edge(plan.edge) - .within(body.rect) - .auto_collapse(scene.auto_collapse) - .show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at)); - self.report.flyout.extend(output.edit.events); - let work = - ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout }; - self.column_work(column, work); - } else { - let output = DockColumn::new(name.clone(), scene.dock, column, &spec) - .edge(plan.edge) - .within(body.rect) - .auto_collapse(scene.auto_collapse) - .show_groups_at(ui, cell, |group, rect, ui, body| { - self.group_of(ui, body, group, GroupAt::Show(rect)); - }); - let work = ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width: output.width, flyout: None }; - self.column_work(column, work); - } + let at = ColumnAt { cell, edge: plan.edge, bar: ColumnBar::Own, within: body.rect, open: plan.open.clone() }; + self.column(ui, body, column, at); } } + /// One column, docked or floating: its icons and their flyouts while it is collapsed, else its stacked groups, + /// each group shown by `group_of`. What the user did on it becomes actions. + fn column(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, at: ColumnAt

) { + let scene = self.scene; + let spec = |panel: &P| scene.spec(panel); + let name = Label::from(body.words::().panels.as_str().to_owned()); + let dock = self.dock; + let ColumnAt { cell, edge, bar, within, open } = at; + let work = if column.iconic { + let output = IconicColumn::new(name, dock, column, Bind::given(open), &spec) + .edge(edge) + .bar(bar) + .within(within) + .auto_collapse(scene.auto_collapse) + .show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at)); + self.report.flyout.extend(output.edit.events); + ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout } + } else { + let output = DockColumn::new(name, dock, column, &spec) + .edge(edge) + .bar(bar) + .within(within) + .auto_collapse(scene.auto_collapse) + .show_groups_at(ui, cell, |group, rect, ui, body| { + self.group_of(ui, body, group, GroupAt::Show(rect)); + }); + ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width: output.width, flyout: None } + }; + self.column_work(column, work); + } + /// Turns what a column reported into actions and drags. fn column_work(&mut self, column: &Column

, work: ColumnWork

) { let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { return }; @@ -955,21 +975,21 @@ impl Pass<'_, P> { } } - /// The floating windows of the pruned layout, each a `FloatingGroup` holding its tree's groups, in an OS window - /// where the config, the platform and its panels allow one. A window takes the drops over it on its own layer, - /// from the spots its groups register in its own registry. Returns the move or resize of a window in the app window - /// this pass, which the area reports as a workspace edit. - fn windows(&mut self, ui: &mut Ui, body: &BodyCx<'_>) -> Option<(P, PlacementChange)> { + /// The floating windows of the pruned layout, each a `FloatingGroup` holding its one column, drawn as a dock + /// column is with the window's title row as the column's bar, in an OS window where the config, the platform and + /// its panels allow one. A window takes the drops over it on its own layer, from the spots its column registers in + /// its own registry. `open` is the open flyout, which a collapsed window's icons share with the docks'. Returns the + /// move or resize of a window in the app window this pass, which the area reports as a workspace edit. + fn windows(&mut self, ui: &mut Ui, body: &BodyCx<'_>, open: &Option

) -> Option<(P, PlacementChange)> { let scene = self.scene; let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); + let spec_of = |panel: &P| scene.spec(panel); let mut moved = None; for window in &scene.layout.floating { let Some(anchor) = window.panels().next().cloned() else { continue }; - let active = match &window.root { - Node::Tabs { panels, active, .. } => panels.get(*active).cloned().unwrap_or_else(|| anchor.clone()), - _ => anchor.clone(), - }; + // The window's menu acts on the shown panel of its top group. + let active = window.groups().first().and_then(Group::active_panel).cloned().unwrap_or_else(|| anchor.clone()); let specs: Vec = window.panels().map(|panel| scene.spec(panel)).collect(); let rights: Vec = window.panels().map(|panel| scene.permissions(panel)).collect(); let dock = scene.dock.with(("floating", window.id)); @@ -995,10 +1015,17 @@ impl Pass<'_, P> { let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated), &active); let mut commands = Vec::new(); let spec = scene.spec(&active); + let edge = WindowColumn::nearer_edge(opening.rect, scene.bounds, scene.rtl); + let shape = if window.column.iconic { + let size = Vec2::new(scene.sizes.width(&window.column, &spec_of), IconicSizes::of(&ctx).icons_height(&window.column)); + WindowColumn::collapsed(edge, size) + } else { + WindowColumn::expanded(edge) + }; let mut group = FloatingGroup::new(spec.label, opening.rect) .limits(scene.spec(&anchor).limits) .sized(Sizing::Fill) - .minimized(window.minimized) + .column(shape) .actions(actions) .window_of(anchor.clone()) .takes_drops(target, &dropped) @@ -1024,23 +1051,10 @@ impl Pass<'_, P> { while let Some((command, _)) = body.take_command::() { commands.push(command); } - let limits = |panel: &P| scene.spec(panel).limits; - let rules = FrameRules::new(&limits); - let name = Label::from(body.words::().panels.as_str().to_owned()); - let tree = Layout::new(Some(window.root.clone()), Vec::new()); - let area = SplitArea::new(name, Bind::given(tree), rules).show_at(ui, body.rect, |ui, split| { - for (leaf, rect) in split.group_frames::

() { - let Some(place) = scene.layout.place(&leaf) else { continue }; - let Some(node) = scene.layout.node_of(&place) else { continue }; - self.leaf(ui, split, node, rect); - } - }); - area.output.edit.events + let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within: scene.bounds, open: open.clone() }; + self.column(ui, body, &window.column, at); }); self.dock = area_dock; - if let Some(edited) = shown.inner.as_ref().and_then(EditEvents::value).and_then(|tree| tree.root.as_ref()) { - self.report.actions.extend(split_resizes(&anchor, &window.root, edited)); - } let output = shown.output; self.report.files.extend(output.files); if let Some(dropped) = dropped.into_inner() { @@ -1079,20 +1093,15 @@ impl Pass<'_, P> { for command in commands { self.run(&active, command, Some(body)); } - if output.minimized_toggled { - self.report.actions.push(Action::set_minimized(anchor.clone(), !window.minimized)); + // The title row is the column's bar: its double arrow collapses or expands the column. + if let Some(iconic) = output.iconic { + self.report.actions.push(Action::set_iconic(anchor.clone(), iconic)); } } moved } } -/// The `ResizeWindowSplit` actions that take the splits of the floating window holding `anchor`, whose tree is -/// `from`, to the sizes `to` has. -fn split_resizes(anchor: &P, from: &Node

, to: &Node

) -> Vec> { - split_changes(from, to).into_iter().map(|(path, size)| Action::resize_window_split(anchor.clone(), path, size)).collect() -} - /// The splits whose size `to` changes from `from`, each with its path from the root, where both trees split alike. fn split_changes

(from: &Node

, to: &Node

) -> Vec<(Vec, SplitSize)> { fn walk

(from: &Node

, to: &Node

, path: &mut Vec, out: &mut Vec<(Vec, SplitSize)>) { diff --git a/crates/ui-patterns/tests/it/docking/drop.rs b/crates/ui-patterns/tests/it/docking/drop.rs index c570d08fa..f490138ab 100644 --- a/crates/ui-patterns/tests/it/docking/drop.rs +++ b/crates/ui-patterns/tests/it/docking/drop.rs @@ -18,7 +18,7 @@ const COLUMN_WIDTH: f32 = 200.0; fn layout() -> Layout { let column = Column::new(vec![Group::new(vec![TOP_GROUP, TOP_SECOND_TAB], 0), Group::new(vec![LOWER_GROUP], 0)]).with_width(COLUMN_WIDTH); let dock = Node::dock(DockEdge::Start, vec![column]); - let window = Floating::new(Node::tabs(vec![WINDOW], 0), Rect::from_min_size(at(500.0, 0.0), Vec2::new(200.0, 150.0))); + let window = Floating::single(vec![WINDOW], 0, Rect::from_min_size(at(500.0, 0.0), Vec2::new(200.0, 150.0))); Layout::new(Some(Node::split(Axis::X, SplitSize::FixedFirst(COLUMN_WIDTH), dock, Node::tabs(vec![CANVAS], 0))), vec![window]) } diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index f8272007f..0b3b504a8 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -276,3 +276,34 @@ fn a_floated_panel_fits_its_content_up_to_the_float_height() { assert!((short.width() - group.width()).abs() <= SLACK, "floated {short:?}, docked group {group:?}"); assert!(short.height() < cap - SLACK, "short content floats at its height: {short:?}, cap {cap}"); } + +/// A floating window's title row is its column's bar: its double arrow collapses the column to icons, which show in +/// the window in place of the groups, and expands it again; the window keeps its expanded rect throughout. +#[trial] +fn a_floating_windows_double_arrow_collapses_its_column_to_icons_and_expands_it() { + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let button = |bed: &Bed, name: &str| { + let tree = bed.fixture.tree(); + bed.fixture + .by_role(Role::BUTTON) + .into_iter() + .find(|button| WINDOW_AT.expand(SLACK).contains_rect(button.rect) && craft_ui::testing::access::name(tree, button.node) == Some(name)) + }; + let in_window = |bed: &Bed| bed.fixture.by_role(Role::TAB_PANEL).into_iter().filter(|panel| WINDOW_AT.expand(SLACK).contains_rect(panel.rect)).count(); + assert_eq!(in_window(&bed), 1, "the expanded window shows its group"); + let collapse = button(&bed, "Collapse column to icons").expect("the title row shows the column's double arrow"); + bed.fixture.click(&collapse); + bed.fixture.settle(); + let window = bed.workspace.borrow().layout.floating[0].clone(); + assert!(window.column.iconic, "the window's column collapsed: {:?}", bed.actions.borrow()); + assert_eq!(window.rect, WINDOW_AT, "the window keeps its expanded rect"); + assert_eq!(in_window(&bed), 0, "the collapsed window shows no group"); + let icon = button(&bed, &title(WINDOW)).expect("the collapsed window shows the panel's icon"); + assert!(icon.rect.width() < WINDOW_AT.width() / 2.0, "the window shows as a strip of icons: {:?}", icon.rect); + let expand = button(&bed, "Expand column").expect("the collapsed window's title row shows the double arrow"); + bed.fixture.click(&expand); + bed.fixture.settle(); + let window = bed.workspace.borrow().layout.floating[0].clone(); + assert!(!window.column.iconic && window.rect == WINDOW_AT, "the column expanded at its rect: {window:?}"); + assert_eq!(in_window(&bed), 1, "the expanded window shows its group again"); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index b8a5d3193..2f6bdd863 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -21,9 +21,11 @@ A `Workspace` is a saved arrangement: its `layout` and the `hidden` panels with - `Stack`: an accordion; each `StackEntry` keeps its open state and height when other panels move. - `Dock`: the dock on one window edge (`DockEdge`), with its `Column`s from the edge inwards. At most one per side. +A floating window is one `Column` that floats: its groups stacked top to bottom, nothing beside them. Every column, docked or floating, collapses to icons (`Column::iconic`, `Action::SetIconic`) on its own. + The tree is in reading order: a split's first child is its start (or top) child. Under right-to-left the renderer maps rects with `Flow::to_physical`. -Edits are `Action`s: `Move`, `Float`, `Close`, `Activate`, `Open`, `OpenAt`, `MoveFloating`, `ResizeSplit`, `ResizeWindowSplit` and the rest. `Workspace::apply` and `Workspace::apply_all` apply them against each panel's `Permissions` and the lock, and refuse what the rules forbid with a `DockError`. `Permissions::ALL` allows everything. `Permissions::PROTECTED` is a document canvas: it stays docked and open, and takes neither tabs nor side splits. +Edits are `Action`s: `Move`, `Float`, `Close`, `Activate`, `Open`, `OpenAt`, `MoveFloating`, `ResizeSplit`, `SetIconic` and the rest. `Workspace::apply` and `Workspace::apply_all` apply them against each panel's `Permissions` and the lock, and refuse what the rules forbid with a `DockError`. `Permissions::ALL` allows everything. `Permissions::PROTECTED` is a document canvas: it stays docked and open, and takes neither tabs nor side splits. To load a saved workspace: @@ -114,7 +116,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Floating and native windows -A floating window is a `Floating` in the layout: its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the window host runs that move (`runtime::windows::keeps_app_drag`). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). +A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. A collapsed window shows its icons against the float area's edge nearer it, and keeps its expanded size for when it expands. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the window host runs that move (`runtime::windows::keeps_app_drag`). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). A panel or group floated out of the dock (a drag, the Float command, a tab torn out of the window) opens at the width it had docked and at the height its group measures at in a floating window's room (`Proposal::Size`), at most `size.float.height`: content that fills its body opens at that height, other content at its own. A column opens at its docked size, at most that height. The area measures once, where the float starts: for a drag in the pass it starts, which adds the size to the drag's payload (`runtime::drag::amend`). A panel's own `PanelSpec` float size wins, and a window that already floats keeps its size. From 7fdb17d53c46a21f96f099a6161d5f567cb486f3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:29:24 +0000 Subject: [PATCH 07/18] Dock UI: rustfmt --- crates/ui-panels/src/docking/floating.rs | 4 ++-- crates/ui-patterns/tests/it/docking/floating_area.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 9d753dc97..72bbf779c 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -13,8 +13,8 @@ use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup}; use crate::contract::{ - Access, Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderEdge, HeaderParts, HeaderRegion, Inner, MeasureCx, Mount, - NoValue, OsFiles, Outcome, Overlay, Pad, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, + Access, Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderEdge, HeaderParts, HeaderRegion, Inner, MeasureCx, + Mount, NoValue, OsFiles, Outcome, Overlay, Pad, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::runtime::drag::OsFile; diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 0b3b504a8..2eb04b223 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -289,7 +289,8 @@ fn a_floating_windows_double_arrow_collapses_its_column_to_icons_and_expands_it( .into_iter() .find(|button| WINDOW_AT.expand(SLACK).contains_rect(button.rect) && craft_ui::testing::access::name(tree, button.node) == Some(name)) }; - let in_window = |bed: &Bed| bed.fixture.by_role(Role::TAB_PANEL).into_iter().filter(|panel| WINDOW_AT.expand(SLACK).contains_rect(panel.rect)).count(); + let in_window = + |bed: &Bed| bed.fixture.by_role(Role::TAB_PANEL).into_iter().filter(|panel| WINDOW_AT.expand(SLACK).contains_rect(panel.rect)).count(); assert_eq!(in_window(&bed), 1, "the expanded window shows its group"); let collapse = button(&bed, "Collapse column to icons").expect("the title row shows the column's double arrow"); bed.fixture.click(&collapse); From 1933ed236ddb3d47648116874154eb5ca6bf7b5d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:39:31 +0000 Subject: [PATCH 08/18] Dock UI: icon groups register the drop spots of expanded groups; groups in a floating window take no side drops --- crates/ui-panels/src/docking/group.rs | 17 +++++-- crates/ui-panels/src/docking/iconic.rs | 50 +++++++++++++------ crates/ui-panels/src/docking/iconic/trials.rs | 40 ++++++++++++++- crates/ui-panels/src/docking/stories.rs | 7 +++ crates/ui-patterns/src/patterns/dock/area.rs | 21 +++++--- 5 files changed, 108 insertions(+), 27 deletions(-) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 9ad29c1e5..d0e886a3d 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -18,7 +18,7 @@ use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusTarget}; use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind}; use crate::tabs::{Tab, TabKind, TabStrip, TornOff}; -use craft_behavior::{IconId, Metrics, PartKey, PressPhase, Sense, keyed}; +use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; use craft_theme::{ControlSize, Tokens}; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; use std::borrow::Cow; @@ -205,8 +205,9 @@ struct Reported { /// A group of panels: a header of tab strip and panel menu button, dragged by its empty part, over the active panel's /// body. Show it with `show_at(group_rect)` in the body of a `SplitArea`, with an `IdSource::Id` made from the /// group's anchor so its state survives a re-dock. Under a `dock` id it registers the spots a drop lands on: the -/// strip, and (while expanded) the sides and the middle of the body. The group is an instance of the `dockGroup` -/// command scope: it publishes the panel command states it is given and reports the commands that reach it. +/// strip, and (while expanded) the sides and the middle of the body; in a floating window +/// ([`in_window`](DockGroup::in_window)) the top, the bottom and the middle only. The group is an instance of the +/// `dockGroup` command scope: it publishes the panel command states it is given and reports the commands that reach it. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, overlay, probe(DockGroup<'static, usize>))] pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { @@ -235,6 +236,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { /// How the body's side zones are sized. #[prop] zones: ZoneRule, + /// The group is in a floating window, which is one column with nothing beside it: the body's start and end + /// sides take no drop, and its top, bottom and middle zones reach across them. + #[prop(flag)] + in_window: bool, /// The rows of the group menu: the panel menu button and a context request on a tab open them. #[prop] menu: Vec, @@ -271,6 +276,7 @@ impl<'a, P: Clone + Hash + Send + Sync + 'static> DockGroup<'a, P> { wheel_selects_tabs: false, dock: None, zones: ZoneRule::Fraction, + in_window: false, menu: Vec::new(), panel_menu_shown: true, command_states: Vec::new(), @@ -394,6 +400,11 @@ impl Component for DockGroup<'_, P> { } let body = Rect::from_min_max(Pos2::new(rect.left(), strip.bottom()), rect.max); for (side, zone) in self.zones.zones(body, &cx.style.sizes, rtl) { + let zone = match side { + DockSide::Start | DockSide::End if self.in_window => continue, + _ if self.in_window => Rect::from_x_y_ranges(body.x_range(), zone.y_range()), + _ => zone, + }; DockTargets::

::register_in(&cx.core.ctx, dock, DockSpot::group(self.anchor.clone(), side), zone, rect); } } diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 900d85c5a..57b493e27 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -150,9 +150,10 @@ pub struct IconicColumnStyle { /// outside close the flyout; with `auto_collapse` the focus leaving it does too. /// /// The open flyout is the bound `Option

` of [`new`](IconicColumn::new), owned by the host like the layout: a click -/// on an icon, Escape and auto-collapse write it, and the host opens a panel (the Window menu) by writing it. The column registers the drop bands of its edges and of the halves of -/// each icon group with the dock `dock`. The flyout shows its group through the `view` of -/// [`show_flyouts`](IconicColumn::show_flyouts), with the opened panel active, as tall as the view measures the +/// on an icon, Escape and auto-collapse write it, and the host opens a panel (the Window menu) by writing it. The +/// column registers its drop spots with the dock `dock` as an expanded column does: its edges, the seams between its +/// icon groups, the top and bottom of the stack and each icon group's cells, which join its tabs. The flyout shows +/// its group through the `view` of [`show_flyouts`](IconicColumn::show_flyouts), with the opened panel active, as tall as the view measures the /// group within the room and at least the height of its panels' default heights; a group the user sized keeps that /// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`. /// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in @@ -619,24 +620,41 @@ impl Component for IconicColumn<'_, P> { } impl IconicColumn<'_, P> { - /// Registers the drop bands of a dock column's edges, and the upper and lower half of every icon group: a drop on - /// the upper half stacks above the group, one on the lower half below it. + /// Registers the drop spots of the column the way an expanded column registers them: the bands of a dock + /// column's two edges (a new column beside it), the seam on the separator between two icon groups (a new group + /// between them), the top of the first group and the bottom of the last down to the column's foot (a new group + /// above or below), and the cells of each icon group (join its tabs). A floating column registers no edge bands: + /// nothing goes beside it. fn register(&self, ctx: &egui::Context, rect: Rect, rtl: bool, plan: &Plan, sizes: &IconicSizes) { - let Some(first) = self.column.groups.first().and_then(|group| group.panels.first()) else { return }; + let anchor = |group: usize| self.column.groups.get(group).and_then(|group| group.panels.first()); + let Some(first) = anchor(0) else { return }; if self.bar == ColumnBar::Own { register_edges(ctx, self.dock, first, rect, rtl, &sizes.column); } - let half = sizes.separator * 0.5; - let last = plan.groups.len().saturating_sub(1); + let half = sizes.column.seam_band * 0.5; + // How far the top and bottom bands reach into a group's cells: a quarter of a short group leaves its middle + // to the join. + let reach = |group: &Rect| half.min(group.height() * 0.25); + let mut above: Option<(&P, Rect)> = None; for (at, group) in &plan.groups { - let Some(anchor) = self.column.groups.get(*at).and_then(|group| group.panels.first()) else { continue }; - let middle = group.center().y; - let upper_top = if *at == 0 { plan.body.top() } else { group.top() - half }; - let lower_bottom = if *at == last { plan.body.bottom() } else { group.bottom() + half }; - let upper = Rect::from_x_y_ranges(group.x_range(), upper_top..=middle); - let lower = Rect::from_x_y_ranges(group.x_range(), middle..=lower_bottom); - DockTargets::register(ctx, self.dock, DockSpot::group(anchor.clone(), DockSide::Top), upper); - DockTargets::register(ctx, self.dock, DockSpot::group(anchor.clone(), DockSide::Bottom), lower); + let Some(panel) = anchor(*at) else { continue }; + DockTargets::register(ctx, self.dock, DockSpot::group(panel.clone(), DockSide::Center), *group); + if let Some((before, over)) = above { + let middle = (over.bottom() + group.top()) * 0.5; + let seam = Rect::from_x_y_ranges(group.x_range(), (middle - half)..=(middle + half)); + DockTargets::register(ctx, self.dock, DockSpot::seam(before.clone(), panel.clone()), seam); + } + above = Some((panel, *group)); + } + if let Some((_, top)) = plan.groups.first() { + let band = Rect::from_x_y_ranges(top.x_range(), plan.body.top()..=(top.top() + reach(top))); + DockTargets::register_in(ctx, self.dock, DockSpot::group(first.clone(), DockSide::Top), band, *top); + } + if let Some((at, bottom)) = plan.groups.last() + && let Some(last) = anchor(*at) + { + let band = Rect::from_x_y_ranges(bottom.x_range(), (bottom.bottom() - reach(bottom))..=plan.body.bottom().max(bottom.bottom())); + DockTargets::register_in(ctx, self.dock, DockSpot::group(last.clone(), DockSide::Bottom), band, *bottom); } } } diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index c3e001e65..af527e627 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -3,11 +3,12 @@ #![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] use crate::contract::{Bind, Show as _, ShowContainer as _}; -use crate::docking::{DockHeights, DockSizes, DragUnit, FlyoutResize, GroupAt, GroupGrip, IconicColumn, PanelKey, PanelSpec}; +use crate::docking::{DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutResize, GroupAt, GroupGrip, IconicColumn, PanelKey, PanelSpec}; use crate::sections::Panel; use crate::style::StyleCx; use crate::testing::memory::global; use crate::testing::{Fixture, trial}; +use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node}; use egui::{Pos2, Rect, Vec2}; use std::cell::{Cell, RefCell}; @@ -336,3 +337,40 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt assert!(bounds.contains_rect(after), "{height}: {after:?}"); } } + +/// The icon groups take drops as an expanded column's groups do: the middle of a group joins its tabs, the separator +/// between two groups is the seam between them and wins there, the top of the first group stacks above it, and the +/// bottom of the last group, down through the column's empty foot, stacks below it. +#[trial] +fn icon_groups_take_the_drops_of_an_expanded_columns_groups() { + let dock = global("iconic column", "spots"); + let probes: Rc>> = Rc::default(); + let found: Rc>>>> = Rc::default(); + let (asked, seen) = (Rc::clone(&probes), Rc::clone(&found)); + let mut fixture = Fixture::new(move |ui| { + let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)]); + column.iconic = true; + let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)); + IconicColumn::new("Panels", dock, &column, Bind::kept(), &named).within(screen()).show_flyouts_at(ui, place, |_, _, _, _| None); + // The registry a drop reads is the previous pass's. + *seen.borrow_mut() = asked.borrow().iter().map(|at| DockTargets::::resolve(ui.ctx(), dock, *at).map(|(spot, _)| spot)).collect(); + }); + fixture.room(SCREEN).settle(); + let icon = |label: &str| fixture.by_label(label).expect("the panel's icon").rect; + let (brushes, layers, swatches) = (icon("Brushes"), icon("Layers"), icon("Swatches")); + let x = brushes.center().x; + *probes.borrow_mut() = vec![ + Pos2::new(x, brushes.bottom()), + Pos2::new(x, (layers.bottom() + swatches.top()) / 2.0), + Pos2::new(x, brushes.top() + 1.0), + Pos2::new(x, swatches.center().y), + Pos2::new(x, swatches.bottom() + 2.0 * swatches.height()), + ]; + fixture.idle(2); + let found = found.borrow().clone(); + assert_eq!(found[0], Some(DockSpot::group(1, DockSide::Center)), "the middle of a group joins its tabs"); + assert_eq!(found[1], Some(DockSpot::seam(1, 3)), "the separator is the seam between the groups"); + assert_eq!(found[2], Some(DockSpot::group(1, DockSide::Top)), "the first group's top stacks above it"); + assert_eq!(found[3], Some(DockSpot::group(3, DockSide::Center)), "a one-icon group keeps its middle for the join"); + assert_eq!(found[4], Some(DockSpot::group(3, DockSide::Bottom)), "the foot under the icons stacks below the last group"); +} diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 596b0e907..9e08e6d01 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -87,6 +87,13 @@ fn two_panels(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { DockGroup::new(LAYERS, &panels, panels[0].key).show(ui, |_, _| ()).output.into() } +/// A group in a floating window: nothing goes beside it, so a drop on its body joins it or stacks above or below. +#[story(DockGroup<'static, usize>, covers = [Default])] +fn a_group_in_a_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let panels = titles(&[LAYERS, CHANNELS]); + DockGroup::new(LAYERS, &panels, panels[0].key).in_window().show(ui, |_, _| ()).output.into() +} + /// A click on the panel menu button opens the group's panel menu. fn open_panel_menu(fixture: &mut Fixture) { if let Some(button) = fixture.root_id().and_then(|id| fixture.part(id, MENU)) { diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 07964bad7..a877a99de 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -267,11 +267,13 @@ struct Passed

{ files: Vec, } -/// How a group is shown: minimized, and whether it is an accordion section (with its open state). +/// How a group is shown: minimized, whether it is an accordion section (with its open state), and whether it is in +/// a floating window, where nothing goes beside it. #[derive(Clone, Copy)] struct Look { minimized: bool, section: Option, + in_window: bool, } /// A dock to show: its window edge, its columns and its rect. @@ -662,7 +664,7 @@ impl Pass<'_, P> { let scene = self.scene; match node { Node::Tabs { panels: members, active, .. } => { - self.group(ui, body, members, *active, Look { minimized: false, section: None }, GroupAt::Show(rect)); + self.group(ui, body, members, *active, Look { minimized: false, section: None, in_window: false }, GroupAt::Show(rect)); } Node::Stack { entries, .. } => { let sections: Vec = entries @@ -678,7 +680,7 @@ impl Pass<'_, P> { for (entry, height) in entries.iter().zip(&heights) { let section = Rect::from_min_size(Pos2::new(rect.left(), top), Vec2::new(rect.width(), *height)); top += height; - let look = Look { minimized: !entry.open, section: Some(entry.open) }; + let look = Look { minimized: !entry.open, section: Some(entry.open), in_window: false }; self.group(ui, inner, std::slice::from_ref(&entry.panel), 0, look, GroupAt::Show(section)); } }); @@ -813,6 +815,9 @@ impl Pass<'_, P> { .menu(menu.clone()) .panel_menu_shown(hosted) .command_states(states.clone()); + if look.in_window { + group = group.in_window(); + } if minimized { group = group.minimized(); } else if !document(&scene.spec(&members[at])) { @@ -887,8 +892,9 @@ impl Pass<'_, P> { None } - fn group_of(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, group: &Group

, at: GroupAt) -> Option { - let look = Look { minimized: group.minimized, section: None }; + /// A group of a column, docked or in a floating window (`in_window`). + fn group_of(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, group: &Group

, at: GroupAt, in_window: bool) -> Option { + let look = Look { minimized: group.minimized, section: None, in_window }; self.group(ui, body, &group.panels, group.active, look, at) } @@ -919,13 +925,14 @@ impl Pass<'_, P> { let name = Label::from(body.words::().panels.as_str().to_owned()); let dock = self.dock; let ColumnAt { cell, edge, bar, within, open } = at; + let in_window = bar == ColumnBar::Window; let work = if column.iconic { let output = IconicColumn::new(name, dock, column, Bind::given(open), &spec) .edge(edge) .bar(bar) .within(within) .auto_collapse(scene.auto_collapse) - .show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at)); + .show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at, in_window)); self.report.flyout.extend(output.edit.events); ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout } } else { @@ -935,7 +942,7 @@ impl Pass<'_, P> { .within(within) .auto_collapse(scene.auto_collapse) .show_groups_at(ui, cell, |group, rect, ui, body| { - self.group_of(ui, body, group, GroupAt::Show(rect)); + self.group_of(ui, body, group, GroupAt::Show(rect), in_window); }); ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width: output.width, flyout: None } }; From e52471190d5aa872cc30c9f1144869c8f5446a6d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:44:05 +0000 Subject: [PATCH 09/18] Dock UI: flyouts open on a side; a floating window keeps the edge its move began with; trials for floating columns --- crates/ui-panels/src/docking/floating.rs | 18 +++ crates/ui-panels/src/docking/flyout.rs | 14 +-- crates/ui-panels/src/docking/iconic.rs | 19 ++- .../ui-panels/src/docking/iconic/stories.rs | 3 +- crates/ui-panels/src/docking/iconic/trials.rs | 2 + crates/ui-patterns/src/patterns/dock/area.rs | 27 ++++- .../tests/it/docking/floating_area.rs | 109 ++++++++++++++++++ 7 files changed, 172 insertions(+), 20 deletions(-) diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 72bbf779c..40b357b5f 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -72,6 +72,24 @@ impl WindowColumn { let at_left = !bounds.is_positive() || rect.center().x - bounds.left() <= bounds.right() - rect.center().x; if at_left != rtl { DockEdge::Start } else { DockEdge::End } } + + /// The rect a collapsed window keeps when a move that showed it against `edge` ends at `rect`, so its strip + /// stays where it was dropped once the window keeps to the edge nearer it again: `rect` while that edge is still + /// `edge`; else `rect` shifted so the strip, against the other edge, is where it was, when the other edge is the + /// nearer one of the shifted rect. A strip dropped near the middle of `bounds`, where neither holds, keeps + /// `rect`. An expanded window keeps `rect`. + pub fn anchored(self, rect: Rect, bounds: Rect, rtl: bool) -> Rect { + let Some(size) = self.collapsed else { return rect }; + if Self::nearer_edge(rect, bounds, rtl) == self.edge { + return rect; + } + let at_left = |edge: DockEdge| (edge == DockEdge::Start) != rtl; + let strip = if at_left(self.edge) { rect.left() } else { rect.right() - size.x }; + let other = if self.edge == DockEdge::Start { DockEdge::End } else { DockEdge::Start }; + let left = if at_left(other) { strip } else { strip + size.x - rect.width() }; + let shifted = Rect::from_min_size(Pos2::new(left, rect.top()), rect.size()); + if Self::nearer_edge(shifted, bounds, rtl) == other { shifted } else { rect } + } } /// What a floating group reports in a pass. diff --git a/crates/ui-panels/src/docking/flyout.rs b/crates/ui-panels/src/docking/flyout.rs index 28cbbd716..a17f91b56 100644 --- a/crates/ui-panels/src/docking/flyout.rs +++ b/crates/ui-panels/src/docking/flyout.rs @@ -5,7 +5,7 @@ use crate::contract::{ BodyCx, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, OverlayUi, Pad, PopupHandle, Role, SizeLimits, Sizing, }; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; -use craft_behavior::dock::DockEdge; +use craft_behavior::overlay::Side; use craft_behavior::{Metrics, Sense}; use egui::{Pos2, Rect, Response, Ui, Vec2}; @@ -63,7 +63,7 @@ pub struct Flyout { common: Common, #[container] props: ContainerProps, - edge: DockEdge, + opens: Side, size: Vec2, auto_collapse: bool, /// The rect the flyout and every resize of it stay inside. @@ -76,17 +76,17 @@ pub struct Flyout { } impl Flyout { - /// A flyout at least `size` for the column on the window edge `edge`, closing when the focus leaves it if - /// `auto_collapse`. - pub fn new(edge: DockEdge, size: Vec2, auto_collapse: bool) -> Self { + /// A flyout at least `size` that opens on the side `opens` of its column, in reading order (`Side::Start` or + /// `Side::End`), closing when the focus leaves it if `auto_collapse`. + pub fn new(opens: Side, size: Vec2, auto_collapse: bool) -> Self { let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(Pad::None).sizing(Sizing::Content); - Flyout { common: Common::new(), props, edge, size, auto_collapse, within: Rect::EVERYTHING, least: Vec2::ZERO, placed: None } + Flyout { common: Common::new(), props, opens, size, auto_collapse, within: Rect::EVERYTHING, least: Vec2::ZERO, placed: None } } /// The layer the flyout shows in, its top left at `top_left`: placed by the caller, resizable on every edge but /// the one facing the column. The side away from the column mirrors in a right-to-left layout (`rtl`). fn overlay(&self, top_left: Pos2, rtl: bool) -> Overlay { - let free = if (self.edge == DockEdge::End) == rtl { ResizeEdges::RIGHT } else { ResizeEdges::LEFT }; + let free = if (self.opens == Side::End) != rtl { ResizeEdges::RIGHT } else { ResizeEdges::LEFT }; let bounded = self.within.is_finite(); let least = if bounded { self.least.min(self.within.size().max(Vec2::ZERO)) } else { self.least }; // A float place as well as the caller's position: the placement pins no edge, so the edge set alone decides diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 57b493e27..4500ca4e8 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -19,6 +19,7 @@ use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; use crate::style::{ComponentStyle, Corners, StyleColor, StyleCx, SurfaceKind}; use craft_behavior::dock::{Column, DockEdge, Group}; +use craft_behavior::overlay::Side; use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value}; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; use std::hash::Hash; @@ -171,9 +172,14 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { dock: Id, column: &'a Column

, spec: &'a dyn Fn(&P) -> PanelSpec, - /// The window edge the column sits on, which the flyout opens away from. + /// The edge the column keeps to: a dock's window edge, or the edge of the float area a floating window keeps to. + /// The bar's double arrow sits at that end and the inner edge, which sets the column's width, faces away from it. #[prop] edge: DockEdge, + /// The side of the column, in reading order, its flyouts open on (`Side::Start` or `Side::End`): away from a + /// dock's window edge, towards the room of the float area for a floating column. + #[prop] + opens: Side, /// Where the column's bar is: its own (a dock column) or its floating window's title row. #[prop] bar: ColumnBar, @@ -235,6 +241,7 @@ impl<'a, P: Value + Hash + 'static> IconicColumn<'a, P> { column, spec, edge: DockEdge::Start, + opens: Side::End, bar: ColumnBar::Own, auto_collapse: false, within: Rect::NOTHING, @@ -559,14 +566,14 @@ impl Component for IconicColumn<'_, P> { } } - /// The flyout of every cell whose popup is open, beside the column on the canvas side. A resize the user makes + /// The flyout of every cell whose popup is open, beside the column on the side it opens on. A resize the user makes /// comes back as the open group's new size and, when its top moved, its top's offset from the group's icons. fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { let popup = cx.popup("flyout"); let sizes = cx.style.sizes.column; - let (edge, auto_collapse, column) = (self.edge, self.auto_collapse, cx.rect); - // The screen side the canvas is on: away from the window edge, mirrored in a right-to-left layout. - let right = (edge == DockEdge::End) == cx.flow.is_rtl(); + let (opens, auto_collapse, column) = (self.opens, self.auto_collapse, cx.rect); + // The screen side the flyouts open on, mirrored in a right-to-left layout. + let right = (opens == Side::End) != cx.flow.is_rtl(); let within = if self.within.is_positive() { self.within } else { cx.core.ctx.content_rect() }; // The column side of the bounds stops at the column, so a saved width wider than the room keeps that side. let bounds = if right { within.with_min_x(within.min.x.max(column.right())) } else { within.with_max_x(within.max.x.min(column.left())) }; @@ -582,7 +589,7 @@ impl Component for IconicColumn<'_, P> { let mut resized = None; for (at, plan) in plans.into_iter().enumerate() { let Some(FlyoutPlan { group, top_left, size, fixed, icons_top }) = plan else { continue }; - let shown = Flyout::new(edge, size, auto_collapse).within(bounds).least(least).show_popup( + let shown = Flyout::new(opens, size, auto_collapse).within(bounds).least(least).show_popup( ui, popup.at(at), Anchor::Point(top_left), diff --git a/crates/ui-panels/src/docking/iconic/stories.rs b/crates/ui-panels/src/docking/iconic/stories.rs index cdaf00c4f..d16dd7824 100644 --- a/crates/ui-panels/src/docking/iconic/stories.rs +++ b/crates/ui-panels/src/docking/iconic/stories.rs @@ -11,6 +11,7 @@ use crate::testing::memory::global; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, stage, story}; use craft_behavior::Mixed; use craft_behavior::dock::{Column, DockEdge, Group}; +use craft_behavior::overlay::Side; use egui::{Rect, Ui}; /// Panels without icons, so each cell shows the first letter of its panel's name. @@ -33,7 +34,7 @@ fn at_stage<'a>( } else { Rect::from_min_max(egui::pos2(room.right() - width, room.top()), room.max) }; - column.edge(DockEdge::End).within(room).show_flyouts_at(ui, cell, view) + column.edge(DockEdge::End).opens(Side::Start).within(room).show_flyouts_at(ui, cell, view) } #[story(IconicColumn<'static, u8>, covers = [Default], drive = Drive::Never)] diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index af527e627..3bdf299d5 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -10,6 +10,7 @@ use crate::testing::memory::global; use crate::testing::{Fixture, trial}; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node}; +use craft_behavior::overlay::Side; use egui::{Pos2, Rect, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -146,6 +147,7 @@ impl Flyouts { let groups = RefCell::new(Vec::new()); let output = IconicColumn::new("Panels", global("iconic column", "flyouts"), &column, Bind::bound(&mut now), &named) .edge(edge) + .opens(if right { Side::Start } else { Side::End }) .within(within) .show_flyouts_at(ui, place, |group, at, ui, _| { let GroupAt::Show(rect) = at else { return None }; diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index a877a99de..041524db9 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -25,6 +25,7 @@ use crate::sections::HeaderAction; use craft_behavior::dock::{ Action, Column, DockEdge, DockError, Group, Layout, Location, Node, PanelPlace, Permissions, SplitSize, Workspace, node_at, }; +use craft_behavior::overlay::Side; use craft_behavior::{CancelReason, DockSide, EditEvent, EditEvents, Flow, GestureId, GesturePhase, Mixed, Proposal}; use craft_host::target::WindowKind; use egui::{Context, Id, Pos2, Rect, Response, Ui, UiBuilder, Vec2, ViewportId}; @@ -287,6 +288,8 @@ struct DockPlan<'p, P> { /// Where and how a column shows: its rect; the edge it keeps to, a dock's window edge or the float area's edge a /// floating window keeps to; where its bar is; the rect its inner edge and flyouts stay within; and the open flyout. +/// Its flyouts open away from its edge: towards the canvas for a dock column, towards the float area's room for a +/// floating one. struct ColumnAt

{ cell: Rect, edge: DockEdge, @@ -571,7 +574,8 @@ fn show_area( _ => Vec::new(), }; register_bands(&scene, ctx, body.rect, &leaves); - let moved = if floating { pass.windows(ui, body, &open) } else { None }; + let started = memory.moving.as_ref().map(|moving| &moving.before.layout); + let moved = if floating { pass.windows(ui, body, &open, started) } else { None }; let mut report = pass.report; let label: Arc = Arc::from(body.words::().move_window.as_str()); if let Some((anchor, change)) = moved @@ -926,9 +930,11 @@ impl Pass<'_, P> { let dock = self.dock; let ColumnAt { cell, edge, bar, within, open } = at; let in_window = bar == ColumnBar::Window; + let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; let work = if column.iconic { let output = IconicColumn::new(name, dock, column, Bind::given(open), &spec) .edge(edge) + .opens(opens) .bar(bar) .within(within) .auto_collapse(scene.auto_collapse) @@ -985,9 +991,15 @@ impl Pass<'_, P> { /// The floating windows of the pruned layout, each a `FloatingGroup` holding its one column, drawn as a dock /// column is with the window's title row as the column's bar, in an OS window where the config, the platform and /// its panels allow one. A window takes the drops over it on its own layer, from the spots its column registers in - /// its own registry. `open` is the open flyout, which a collapsed window's icons share with the docks'. Returns the - /// move or resize of a window in the app window this pass, which the area reports as a workspace edit. - fn windows(&mut self, ui: &mut Ui, body: &BodyCx<'_>, open: &Option

) -> Option<(P, PlacementChange)> { + /// its own registry. `open` is the open flyout, which a collapsed window's icons share with the docks'. `started` + /// is the layout a running move or resize of a window began on. Returns the move or resize of a window in the app + /// window this pass, which the area reports as a workspace edit. + /// + /// A window keeps to the edge of the float area nearer it: its title row's double arrow sits at that end, and its + /// collapsed column shows against that edge of its rect. A move or resize keeps the edge the window had when it + /// began, so nothing jumps while the window crosses the middle; a collapsed window's move ends with the rect + /// that keeps its strip where it was dropped ([`WindowColumn::anchored`]). + fn windows(&mut self, ui: &mut Ui, body: &BodyCx<'_>, open: &Option

, started: Option<&Layout

>) -> Option<(P, PlacementChange)> { let scene = self.scene; let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); @@ -1022,7 +1034,9 @@ impl Pass<'_, P> { let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated), &active); let mut commands = Vec::new(); let spec = scene.spec(&active); - let edge = WindowColumn::nearer_edge(opening.rect, scene.bounds, scene.rtl); + let began = + started.and_then(|layout| layout.floating.iter().find(|began| began.id == window.id)).map_or(opening.rect, |began| began.rect); + let edge = WindowColumn::nearer_edge(began, scene.bounds, scene.rtl); let shape = if window.column.iconic { let size = Vec2::new(scene.sizes.width(&window.column, &spec_of), IconicSizes::of(&ctx).icons_height(&window.column)); WindowColumn::collapsed(edge, size) @@ -1073,8 +1087,9 @@ impl Pass<'_, P> { self.report.windows.push((anchor.clone(), viewport)); self.report.actions.extend(native::reported(&ctx, window, viewport)); } - } else if let Some(change) = output.placed { + } else if let Some(mut change) = output.placed { if change.phase == GesturePhase::Commit { + change.rect = shape.anchored(change.rect, scene.bounds, scene.rtl); self.report.events.push(DockEvent::FloatPlaced { panel: anchor.clone(), rect: change.rect }); } moved = Some((anchor.clone(), change)); diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 2eb04b223..c0e27cb9e 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -308,3 +308,112 @@ fn a_floating_windows_double_arrow_collapses_its_column_to_icons_and_expands_it( assert!(!window.column.iconic && window.rect == WINDOW_AT, "the column expanded at its rect: {window:?}"); assert_eq!(in_window(&bed), 1, "the expanded window shows its group again"); } + +/// The window of `with_window` at `rect` with its column collapsed to icons, and no docked tree under it. +fn collapsed_at(rect: Rect) -> Layout { + let mut window = Floating::single(vec![WINDOW], 0, rect); + window.column.iconic = true; + Layout::new(None, vec![window]) +} + +/// The rect of the button named `name`. +fn button_rect(bed: &Bed, name: &str) -> Option { + let tree = bed.fixture.tree(); + bed.fixture + .by_role(Role::BUTTON) + .into_iter() + .find(|button| craft_ui::testing::access::name(tree, button.node) == Some(name)) + .map(|button| button.rect) +} + +/// A collapsed window keeps to the edge it kept when its move began: dragged across the middle of the float area, +/// its strip stays under the pointer, and it stays where it is dropped. +#[trial] +fn a_collapsed_window_dragged_across_the_middle_keeps_its_strip_under_the_pointer() { + let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); + let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); + // The title row's band, clear of the double arrow at the end the window keeps to. + let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); + let by = Vec2::new(-250.0, 0.0); + bed.fixture.drag_hold_at(band, by); + let held = button_rect(&bed, &title(WINDOW)).expect("the icon shows while the window moves"); + assert!((held.left() - (icon.left() + by.x)).abs() <= SLACK, "the strip follows the pointer across the middle: {icon:?}, then {held:?}"); + bed.fixture.release_at(band + by).settle(); + let dropped = button_rect(&bed, &title(WINDOW)).expect("the icon shows after the move"); + assert!((dropped.left() - held.left()).abs() <= SLACK, "the strip stays where it was dropped: {held:?}, then {dropped:?}"); + assert!(bed.workspace.borrow().layout.floating[0].column.iconic, "the window stays collapsed"); +} + +/// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. +#[trial] +fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { + // In the end half of the area, then in the start half. + for (rect, opens_right) in [(WINDOW_AT, false), (WINDOW_AT.translate(Vec2::new(-110.0, 0.0)), true)] { + let mut bed = bed(collapsed_at(rect), |_| Permissions::ALL); + let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); + bed.fixture.click_at(icon.center()).settle(); + let flyout = bed.fixture.by_role(Role::TAB_PANEL).first().map(|group| group.rect).expect("the flyout shows the panel's group"); + let towards = if opens_right { flyout.left() >= icon.right() - SLACK } else { flyout.right() <= icon.left() + SLACK }; + assert!(towards, "window at {rect:?}: the flyout {flyout:?} opens on the side with room of the icon {icon:?}"); + } +} + +/// A double click on a floating window's title band collapses its column, as one on a dock column's bar does, and a +/// double click on the collapsed window's band expands it again; the groups keep their state. +#[trial] +fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column() { + let mut bed = bed(with_window(None), |_| Permissions::ALL); + let band = Pos2::new(WINDOW_AT.left() + 40.0, WINDOW_AT.top() + 6.0); + bed.fixture.click_at(band).click_at(band).settle(); + let window = bed.workspace.borrow().layout.floating[0].clone(); + assert!(window.column.iconic, "the band's double click collapsed the column: {:?}", bed.actions.borrow()); + assert!(window.groups().iter().all(|group| !group.minimized), "no group minimized"); + let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); + let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); + bed.fixture.click_at(band).click_at(band).settle(); + assert!(!bed.workspace.borrow().layout.floating[0].column.iconic, "a second double click expanded it: {:?}", bed.actions.borrow()); +} + +/// Nothing goes beside a floating window: a tab dragged over the start side of its group marks the join of the +/// group, not a split; and a tab dropped on a collapsed window's icon joins its group, which stays collapsed. +#[trial] +fn a_drag_over_a_floating_window_joins_or_stacks_and_never_splits() { + let docked_tab = |bed: &Bed| { + let tabs = bed.fixture.by_role(Role::TAB); + let mut docked: Vec<_> = tabs.iter().filter(|tab| !WINDOW_AT.contains(tab.center())).map(|tab| tab.rect).collect(); + docked.sort_by(|a, b| a.min.x.total_cmp(&b.min.x)); + docked.last().copied().expect("the second docked tab shows") + }; + let mut expanded = bed(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))), |_| Permissions::ALL); + let tab = docked_tab(&expanded); + let side = Pos2::new(WINDOW_AT.left() + 6.0, WINDOW_AT.center().y + 20.0); + press_and_move(&mut expanded.fixture, tab.center(), side - tab.center()); + expanded.fixture.frame(Vec::new()); + let mark = drag::mark(expanded.fixture.ctx()).expect("the window takes the drop"); + assert!(matches!(mark, DropMark::Into(_)), "the start side of a floating group joins it: {mark:?}"); + expanded.fixture.frame(vec![release(side)]).settle(); + + let mut window = Floating::single(vec![WINDOW], 0, WINDOW_AT); + window.column.iconic = true; + let mut collapsed = bed(Layout::new(Some(Node::tabs(vec![DOCKED, SECOND], 0)), vec![window]), |_| Permissions::ALL); + let tab = docked_tab(&collapsed); + let icon = button_rect(&collapsed, &title(WINDOW)).expect("the collapsed window shows its icon"); + press_and_move(&mut collapsed.fixture, tab.center(), icon.center() - tab.center()); + collapsed.fixture.frame(Vec::new()); + collapsed.fixture.frame(vec![release(icon.center())]).settle(); + let window = collapsed.workspace.borrow().layout.floating[0].clone(); + assert!(window.groups().len() == 1 && window.contains(&SECOND), "the tab joined the icon's group: {:?}", collapsed.actions.borrow()); + assert!(window.column.iconic, "the window stays collapsed"); +} + +/// A settled collapsed window runs no more passes than a settled expanded one. +#[trial] +fn a_settled_collapsed_window_runs_no_more_passes_than_an_expanded_one() { + let passes = |layout: Layout| { + let mut bed = bed(layout, |_| Permissions::ALL); + bed.fixture.idle(3); + bed.fixture.passes() + }; + let (collapsed, expanded) = (passes(collapsed_at(WINDOW_AT)), passes(with_window(None))); + assert!(collapsed <= expanded, "a still frame runs {collapsed} passes collapsed, {expanded} expanded"); +} From b9ae41c9956e737dba975d7d5541d3dcc1babc9c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:48:35 +0000 Subject: [PATCH 10/18] Dock UI: stepped columns: whole content columns wide, as tall as their content docked and floating, edge drags and the double arrow set steps --- crates/ui-panels/src/docking/dock_column.rs | 7 +- .../src/docking/dock_column/sizing.rs | 10 +- crates/ui-panels/src/docking/floating.rs | 24 +++- crates/ui-panels/src/docking/mod.rs | 5 +- crates/ui-panels/src/docking/spec.rs | 63 ++++++++++ crates/ui-panels/src/docking/targets.rs | 37 ++++-- crates/ui-patterns/src/patterns/dock/area.rs | 94 +++++++++++++-- .../ui-patterns/tests/it/docking/columns.rs | 109 +++++++++++++++++- 8 files changed, 316 insertions(+), 33 deletions(-) diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 2e5b9558a..7ea58c8de 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -32,7 +32,7 @@ use bar::panel_names; pub(super) use bar::{BarRecord, CHEVRON, bar_name, bar_slots, chevron_name, describe_chevron, paint_chevron, show_bar}; use sizing::group_sizes; -pub use sizing::{GroupSize, fit_widths, group_heights, scale_widths, stacked, width_bounds}; +pub use sizing::{GroupSize, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; const DIVIDER: PartKey = PartKey::new("divider"); const EDGE: PartKey = PartKey::new("edge"); @@ -214,9 +214,10 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { output } - /// The divider on the column's inner edge, which moves between the width bounds of its panels. + /// The divider on the column's inner edge, which moves between the width bounds of its panels, or of its steps + /// for a stepped column ([`stepped`](super::stepped)), whose host takes the width as whole steps. fn edge_divider(&self, rect: Rect, sizes: &DockSizes) -> Divider { - let (least, most) = sizes.width_bounds(self.column, self.spec); + let (least, most) = sizes.shown_bounds(self.column, self.spec); Divider::column_edge(rect, self.edge, (least, most.min((self.within.width() - sizes.least_pane).max(rect.width()))), sizes.reach) } diff --git a/crates/ui-panels/src/docking/dock_column/sizing.rs b/crates/ui-panels/src/docking/dock_column/sizing.rs index 868ed67ae..879a7afce 100644 --- a/crates/ui-panels/src/docking/dock_column/sizing.rs +++ b/crates/ui-panels/src/docking/dock_column/sizing.rs @@ -1,7 +1,7 @@ //! The widths of dock columns and the heights of the groups stacked in one. use crate::contract::SizeLimits; -use crate::docking::{DockHeights, DockSizes, PanelSpec}; +use crate::docking::{DockGrid, DockHeights, DockSizes, PanelSpec}; use craft_behavior::dock::Column; use egui::{Pos2, Rect}; @@ -29,6 +29,14 @@ pub fn fit_widths(columns: &[(f32, Option)], room: f32) -> Vec { scale_widths(&bounded, room) } +/// The grid and steps of a stepped column: its [`Column::steps`] and the [`DockGrid`] of its first panel that +/// declares a valid one. `None` for a column without steps or whose panels declare none, which sizes as any other. +pub fn stepped

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> { + let steps = column.steps?; + let grid = column.panels().find_map(|panel| spec(panel).grid.filter(|grid| grid.valid()))?; + Some((grid, grid.clamp(steps))) +} + /// Column widths that add up to `total` as far as their bounds allow. Each entry is `(width, (lo, hi))`. The /// columns that can still move towards `total` scale by one factor; a column that reaches a bound stops there and /// the others take the rest, so a total past the bounds ends at their sum. diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 40b357b5f..855ef7337 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -53,17 +53,27 @@ pub struct WindowColumn { pub edge: DockEdge, /// The size of the collapsed column under the title row; `None` while the column is expanded. pub collapsed: Option, + /// The size of an expanded column whose content sets it (a column with steps) under the title row; `None` for a + /// column the rect sizes. + pub fitted: Option, } impl WindowColumn { /// An expanded column that keeps to `edge`. pub fn expanded(edge: DockEdge) -> Self { - WindowColumn { edge, collapsed: None } + WindowColumn { edge, collapsed: None, fitted: None } } /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. pub fn collapsed(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: Some(size) } + WindowColumn { edge, collapsed: Some(size), fitted: None } + } + + /// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at + /// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's + /// steps, and a move keeps the rect's size. + pub fn fitted(edge: DockEdge, size: Vec2) -> Self { + WindowColumn { edge, collapsed: None, fitted: Some(size) } } /// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is @@ -134,7 +144,9 @@ impl Outcome for FloatingGroupOutput { /// `new` keeps the height the group has when restored. /// - Column: a dock window holds one column ([`column`](FloatingGroup::column)); its title row is the column's bar, /// with the double arrow at the end the window keeps to. While the column is collapsed the group shows at the -/// collapsed size against that edge of the rect, the edges do not resize, and a move keeps the rect's size. +/// collapsed size against that edge of the rect, the edges do not resize, and a move keeps the rect's size. A +/// column its content sizes ([`WindowColumn::fitted`]) shows at that size at the rect's place; its resizes are +/// reported as the user makes them. /// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag /// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release. /// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where @@ -298,6 +310,8 @@ impl<'a> FloatingGroup<'a> { Overlay::floating().movable(true).resizable(!self.minimized && collapsed.is_none()).opacity(self.opacity).body_scroll(false); overlay = if let Some(shown) = collapsed { overlay.placed(shown).size_limits(SizeLimits::new(shown.size(), shown.size())) + } else if let Some(size) = self.column.and_then(|column| column.fitted) { + overlay.placed(Rect::from_min_size(self.rect.min, size + Vec2::new(0.0, header))) } else if self.minimized { let width = self.rect.width(); overlay.placed_at(self.rect.min).size_limits(SizeLimits::new(Vec2::new(width, 0.0), Vec2::new(width, f32::INFINITY))) @@ -443,9 +457,13 @@ impl Container for FloatingGroup<'_> { fn placement_changed(&mut self, change: &PlacementChange) { let mut change = *change; + let fitted = self.column.is_some_and(|column| column.fitted.is_some()); if let Some(shown) = self.collapsed_rect() { // The collapsed window moves; the rect keeps its expanded size. change.rect = self.rect.translate(change.rect.min - shown.min); + } else if fitted && change.kind == PlacementKind::Move { + // A window its content sizes moves; the rect keeps its size. + change.rect = Rect::from_min_size(change.rect.min, self.rect.size()); } else if self.minimized { change.rect = Rect::from_min_size(change.rect.min, Vec2::new(change.rect.width(), self.rect.height())); } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index f1ca68ce7..2fdcc16d8 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -41,7 +41,7 @@ pub use panels::{DockPanels, request_actions}; #[doc(hidden)] pub use panels::{close_requests, open_requests}; pub use root::{DockRoot, DockRootOutput, DockRootStyle}; -pub use spec::{DockHeights, PanelSpec}; +pub use spec::{DockGrid, DockHeights, PanelSpec}; pub use splitter::{Splitter, SplitterStyle}; pub use targets::{DockSizes, DockSpot, DockTargets, GroupDrag, ZoneRule}; pub use words::DockWords; @@ -56,7 +56,8 @@ mod flyout; mod iconic; pub use dock_column::{ - ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, width_bounds, + ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, stepped, + width_bounds, }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes}; diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index a888703a7..b395cd6f0 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -48,6 +48,58 @@ impl DockHeights { } } +/// How a panel that lays its content in a grid of equal columns (a toolbar) sizes its dock column. The column is a +/// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as +/// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag +/// of the column's edge sets whole steps; the content lays out as many columns as fit the width it gets. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct DockGrid { + /// The content's width at one column: a cell and the content's own padding on both sides. + pub first: f32, + /// The width each further column adds: a cell and the gap before it. + pub step: f32, + /// The most columns the content fills, its cell count: more steps show it no wider. + pub most: u16, +} + +impl DockGrid { + /// A grid `first` wide at one column, `step` wider for each further column, up to `most` columns. + pub const fn new(first: f32, step: f32, most: u16) -> Self { + DockGrid { first, step, most } + } + + /// Whether the widths are finite and positive and the grid has a column. + pub fn valid(self) -> bool { + self.first.is_finite() && self.first > 0.0 && self.step.is_finite() && self.step > 0.0 && self.most > 0 + } + + /// `steps` kept between one column and [`most`](Self::most). + pub fn clamp(self, steps: u16) -> u16 { + steps.clamp(1, self.most.max(1)) + } + + /// The content's width at `steps` columns, kept within the grid's columns. + pub fn width(self, steps: u16) -> f32 { + self.first + f32::from(self.clamp(steps) - 1) * self.step + } + + /// The most columns whose width fits `width`, at least one. + pub fn steps_within(self, width: f32) -> u16 { + (1..=self.most.max(1)).rev().find(|steps| self.width(*steps) <= width + WIDTH_SLACK).unwrap_or(1) + } + + /// The fewest columns at which `height`, the content's height at a width ([`width`](Self::width)), fits `room`; + /// the most columns when none fits. + pub fn steps_for_height(self, room: f32, mut height: impl FnMut(f32) -> f32) -> u16 { + let most = self.most.max(1); + (1..=most).find(|steps| height(self.width(*steps)) <= room + WIDTH_SLACK).unwrap_or(most) + } +} + +/// How far a width or height may pass the room and still fit it: the rounding of laid-out sizes. +const WIDTH_SLACK: f32 = 0.5; + /// What the dock reads of a panel: its name and icon, its size policy and how its floating window behaves. The /// permissions of a panel (movable, floatable, closable, takes tabs, takes splits) belong to the dock model, not /// to this spec. @@ -75,6 +127,9 @@ pub struct PanelSpec { /// The panel is a document canvas: its group shows it without the tab and side drops of a panel group, and the /// host draws it with `DockPanels::group_view`. pub canvas: bool, + /// The grid the panel lays its content in, which makes a column with steps whole content columns wide and as + /// tall as its content. `None` for a panel that fills the width it gets. + pub grid: Option, } impl PanelSpec { @@ -89,6 +144,7 @@ impl PanelSpec { allow_native: true, window_kind: WindowKind::Tool, canvas: false, + grid: None, } } @@ -140,4 +196,11 @@ impl PanelSpec { self.canvas = true; self } + + /// The grid the panel lays its content in. + #[must_use] + pub fn grid(mut self, grid: DockGrid) -> Self { + self.grid = Some(grid); + self + } } diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index aa3fb5beb..164390f63 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -4,7 +4,7 @@ //! previous pass's registry, because a drop is decided against what was on screen when the pointer moved. Every //! zone is a rect. A spot names a group by an anchor panel, as the dock model does. -use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; +use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; use crate::style::StyleCx; @@ -100,18 +100,25 @@ impl DockSizes { } /// The width an expanded column's panels draw at, whether the column is expanded or iconic (its flyout and a - /// floated iconic column use it): the stored width kept within the panels' limits. + /// floated iconic column use it): the stored width kept within the panels' limits, or a stepped column's width + /// at its steps ([`stepped`]). pub fn expanded_width

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> f32 { + if let Some((grid, steps)) = stepped(column, spec) { + return grid.width(steps); + } let (lo, hi) = self.width_bounds(column, spec); column.width.unwrap_or(self.column).clamp(lo, hi) } /// The bounds [`width`](Self::width) keeps a column in: an expanded column's [`width_bounds`](Self::width_bounds); - /// an iconic column's rail width up to the width it expands to. + /// a stepped one's width at one step up to its width at all its grid's columns; an iconic column's rail width up + /// to the width it expands to. pub fn shown_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { if column.iconic { // Widening an iconic column stops at the width it expands to. (self.iconic_least, self.expanded_width(column, spec).max(self.iconic_least)) + } else if let Some((grid, _)) = stepped(column, spec) { + (grid.width(1), grid.width(grid.most)) } else { self.width_bounds(column, spec) } @@ -129,7 +136,8 @@ impl DockSizes { /// The actions that give the dock on `side` of `layout` the total width `total`, its columns scaled within /// their [`shown_bounds`](Self::shown_bounds) ([`scale_widths`]): [`Action::ResizeColumn`] for an expanded column, - /// [`Action::ResizeIconic`] for an iconic one, which keeps its expanded width. Apply them together + /// [`Action::ResizeIconic`] for an iconic one, which keeps its expanded width. A stepped column keeps its width, + /// which only its steps set. Apply them together /// ([`Workspace::apply_all`](craft_behavior::dock::Workspace::apply_all)). Empty when the side has no dock or the /// columns already add up to the width; a column without panels keeps its width. pub fn resize_side( @@ -143,12 +151,19 @@ impl DockSizes { Some(Node::Dock { columns, .. }) => columns, _ => return Vec::new(), }; - let current: Vec<(f32, (f32, f32))> = columns.iter().map(|column| (self.width(column, spec), self.shown_bounds(column, spec))).collect(); + let fixed = |column: &Column

| !column.iconic && stepped(column, spec).is_some(); + let current: Vec<(f32, (f32, f32))> = columns + .iter() + .map(|column| { + let width = self.width(column, spec); + (width, if fixed(column) { (width, width) } else { self.shown_bounds(column, spec) }) + }) + .collect(); let widths = scale_widths(¤t, total); columns .iter() .zip(current.iter().zip(widths)) - .filter(|(_, ((width, _), scaled))| (scaled - width).abs() >= 0.01) + .filter(|(column, ((width, _), scaled))| !fixed(column) && (scaled - width).abs() >= 0.01) .filter_map(|(column, (_, width))| { let panel = column.groups.iter().find_map(|group| group.panels.first())?.clone(); Some(if column.iconic { Action::resize_iconic(panel, Some(width)) } else { Action::resize_column(panel, width) }) @@ -157,9 +172,15 @@ impl DockSizes { } /// The `(width, floor)` of every column, for [`fit_widths`](super::fit_widths): an expanded column shrinks down to - /// its least width, an iconic one keeps its width. + /// its least width, an iconic or stepped one keeps its width. pub fn natural

(&self, columns: &[Column

], spec: &dyn Fn(&P) -> PanelSpec) -> Vec<(f32, Option)> { - columns.iter().map(|column| (self.width(column, spec), (!column.iconic).then(|| self.width_bounds(column, spec).0.max(1.0)))).collect() + columns + .iter() + .map(|column| { + let keeps = column.iconic || stepped(column, spec).is_some(); + (self.width(column, spec), (!keeps).then(|| self.width_bounds(column, spec).0.max(1.0))) + }) + .collect() } } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 041524db9..3f24d0b90 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -2,7 +2,7 @@ //! the parts of `docking`, takes the drops of tab and group drags, and applies their actions to the workspace. use super::hide::{self, Shown}; -use crate::contract::overlay::PlacementChange; +use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ Bind, BindMut, BodyCx, Cx, Entry, Lazy, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, }; @@ -13,7 +13,7 @@ use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_dra use crate::docking::{ ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, IconicColumn, - IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, + IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, stepped, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, Commands as _, focus_within}; @@ -913,14 +913,47 @@ impl Pass<'_, P> { for (column, width) in plan.columns.iter().zip(widths) { let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) }; cursor = if start { span.1 } else { span.0 }; - let cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())); + let mut cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())); let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { continue }; + // A stepped column is as tall as its bar and content, from the top of the dock; content taller than the + // dock gets the dock's height and scrolls inside. The rest of its slot is the dock's empty room. + if let Some(content) = self.stepped_height(ui, body, column, cell.width(), false) { + cell.max.y = (cell.top() + scene.sizes.bar + content).min(cell.bottom()); + } self.report.placed.push((first.clone(), cell)); let at = ColumnAt { cell, edge: plan.edge, bar: ColumnBar::Own, within: body.rect, open: plan.open.clone() }; self.column(ui, body, column, at); } } + /// The height of the groups of an expanded stepped column ([`stepped`]) measured at `width`, the width of its + /// steps: what the column shows under its bar. `None` for any other column. + fn stepped_height(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, width: f32, in_window: bool) -> Option { + let scene = self.scene; + let spec = |panel: &P| scene.spec(panel); + if column.iconic || stepped(column, &spec).is_none() { + return None; + } + let mut height = 0.0; + for group in &column.groups { + height += self.group_of(ui, body, group, GroupAt::Measure(width), in_window).unwrap_or(0.0); + } + Some(height) + } + + /// What a click on the double arrow of `column`, whose first panel is `first`, asks for when it reports + /// `iconic`: an expanded stepped column whose panels do not collapse switches between one and two steps; any + /// other column collapses to icons or expands. + fn arrow(&self, column: &Column

, first: &P, iconic: bool) -> Action

{ + let scene = self.scene; + let spec = |panel: &P| scene.spec(panel); + let collapses = column.panels().all(|panel| scene.permissions(panel).collapses); + match stepped(column, &spec) { + Some((_, steps)) if !collapses && !column.iconic => Action::set_column_steps(first.clone(), if steps == 1 { 2 } else { 1 }), + _ => Action::set_iconic(first.clone(), iconic), + } + } + /// One column, docked or floating: its icons and their flyouts while it is collapsed, else its stacked groups, /// each group shown by `group_of`. What the user did on it becomes actions. fn column(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, at: ColumnAt

) { @@ -959,7 +992,8 @@ impl Pass<'_, P> { fn column_work(&mut self, column: &Column

, work: ColumnWork

) { let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { return }; if let Some(iconic) = work.iconic { - self.report.actions.push(Action::set_iconic(first.clone(), iconic)); + let action = self.arrow(column, first, iconic); + self.report.actions.push(action); } if let Some(item) = work.picked { self.pick(first, item); @@ -967,12 +1001,23 @@ impl Pass<'_, P> { for (anchor, height) in work.resized { self.report.actions.push(Action::resize_group(anchor, Some(height))); } + let scene = self.scene; + let spec = |panel: &P| scene.spec(panel); if let Some(width) = work.width { - self.report.actions.push(if column.iconic { - Action::resize_iconic(first.clone(), Some(width)) - } else { - Action::resize_column(first.clone(), width) - }); + match stepped(column, &spec) { + // The edge of a stepped column moves in whole steps: the most that fit where it is dragged. + Some((grid, steps)) if !column.iconic => { + let to = grid.steps_within(width); + if to != steps { + self.report.actions.push(Action::set_column_steps(first.clone(), to)); + } + } + _ => self.report.actions.push(if column.iconic { + Action::resize_iconic(first.clone(), Some(width)) + } else { + Action::resize_column(first.clone(), width) + }), + } } if let Some(resize) = work.flyout { let panel = resize.panel; @@ -999,7 +1044,11 @@ impl Pass<'_, P> { /// collapsed column shows against that edge of its rect. A move or resize keeps the edge the window had when it /// began, so nothing jumps while the window crosses the middle; a collapsed window's move ends with the rect /// that keeps its strip where it was dropped ([`WindowColumn::anchored`]). - fn windows(&mut self, ui: &mut Ui, body: &BodyCx<'_>, open: &Option

, started: Option<&Layout

>) -> Option<(P, PlacementChange)> { + /// + /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that + /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or + /// bottom the fewest whose content fits the height, and the window keeps its place. + fn windows(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, open: &Option

, started: Option<&Layout

>) -> Option<(P, PlacementChange)> { let scene = self.scene; let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); @@ -1037,9 +1086,12 @@ impl Pass<'_, P> { let began = started.and_then(|layout| layout.floating.iter().find(|began| began.id == window.id)).map_or(opening.rect, |began| began.rect); let edge = WindowColumn::nearer_edge(began, scene.bounds, scene.rtl); + let width = scene.sizes.expanded_width(&window.column, &spec_of); let shape = if window.column.iconic { let size = Vec2::new(scene.sizes.width(&window.column, &spec_of), IconicSizes::of(&ctx).icons_height(&window.column)); WindowColumn::collapsed(edge, size) + } else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) { + WindowColumn::fitted(edge, Vec2::new(width, content)) } else { WindowColumn::expanded(edge) }; @@ -1090,6 +1142,25 @@ impl Pass<'_, P> { } else if let Some(mut change) = output.placed { if change.phase == GesturePhase::Commit { change.rect = shape.anchored(change.rect, scene.bounds, scene.rtl); + } + if !matches!(change.kind, PlacementKind::Move) + && let Some(fitted) = shape.fitted + && let Some((grid, steps)) = stepped(&window.column, &spec_of) + { + let column = &window.column; + let to = if (change.rect.width() - fitted.x).abs() > 0.5 { + grid.steps_within(change.rect.width()) + } else { + let room = change.rect.height() - scene.sizes.strip; + grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) + }; + if to != steps { + self.report.actions.push(Action::set_column_steps(anchor.clone(), to)); + } + // The window keeps its place; its steps set its size. + change.rect = Rect::from_min_size(change.rect.min, opening.rect.size()); + } + if change.phase == GesturePhase::Commit { self.report.events.push(DockEvent::FloatPlaced { panel: anchor.clone(), rect: change.rect }); } moved = Some((anchor.clone(), change)); @@ -1117,7 +1188,8 @@ impl Pass<'_, P> { } // The title row is the column's bar: its double arrow collapses or expands the column. if let Some(iconic) = output.iconic { - self.report.actions.push(Action::set_iconic(anchor.clone(), iconic)); + let action = self.arrow(&window.column, &anchor, iconic); + self.report.actions.push(action); } } moved diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index e31b78cab..f5d4e3071 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -1,11 +1,15 @@ //! Dock columns: room sharing between groups, and a dock side's total width shared between its columns. use craft_behavior::Axis; -use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; -use craft_ui::contract::SizeLimits; -use craft_ui::docking::{DockHeights, GroupSize, PanelSpec, group_heights}; -use craft_ui::testing::trial; -use egui::Vec2; +use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; +use craft_ui::contract::{Bind, BodyCx, Role, Show as _, SizeLimits}; +use craft_ui::display::Text; +use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, GroupSize, PanelSpec, group_heights}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::testing::{Fixture, trial}; +use egui::{Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; const STRIP: f32 = 20.0; const MIN: f32 = 60.0; @@ -103,3 +107,98 @@ fn a_dock_sides_total_width_scales_its_columns_within_their_bounds() { assert!(sizes.resize_side(&live.layout, DockEdge::End, spec, least).is_empty(), "the width it has asks for nothing"); assert!(sizes.resize_side(&live.layout, DockEdge::Start, spec, 500.0).is_empty(), "a side without a dock asks for nothing"); } + +/// The panel that lays its content in a grid, as a toolbar does. +const TOOLS: u32 = 5; + +fn grid() -> DockGrid { + DockGrid::new(40.0, 32.0, 6) +} + +/// A stepped column keeps its width, which only its steps set, while the side's other columns scale; a width that +/// its edge is dragged to takes the most whole steps that fit it. +#[trial] +fn a_stepped_column_keeps_its_width_while_the_others_scale() { + let sizes = super::sizes(4.0, 100.0, STRIP); + let with_tools = |panel: &u32| if *panel == TOOLS { PanelSpec::new("Tools").grid(grid()) } else { spec(panel) }; + let spec: &dyn Fn(&u32) -> PanelSpec = &with_tools; + let columns = vec![Column::new(vec![Group::new(vec![2], 0)]).with_width(250.0), Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(2)]; + let root = Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, columns)); + let mut live = Workspace::new(Layout::new(Some(root), Vec::new())); + let widths = |live: &Workspace| end_columns(&live.layout).iter().map(|column| sizes.width(column, spec)).collect::>(); + let before = widths(&live); + assert_eq!(before[1], grid().width(2), "a stepped column is as wide as its steps"); + let actions = sizes.resize_side(&live.layout, DockEdge::End, spec, sum(&before) + 80.0); + let touches_tools = |action: &Action| matches!(action, Action::ResizeColumn { panel: TOOLS, .. } | Action::SetColumnSteps { .. }); + assert!(!actions.iter().any(touches_tools), "the side's width leaves the stepped column alone: {actions:?}"); + live.apply_all(actions, false, |_| Permissions::ALL).expect("the side resizes"); + let after = widths(&live); + assert_eq!(after[1], before[1], "the stepped column keeps its width"); + assert!(after[0] > before[0], "the other column took the room: {after:?}"); + + let grid = grid(); + assert_eq!(grid.steps_within(grid.width(3) - 1.0), 2, "a width short of three steps takes two"); + assert_eq!(grid.steps_within(grid.width(3)), 3, "the width of three steps takes three"); + assert_eq!(grid.steps_within(0.0), 1, "a column keeps one step"); + assert_eq!(grid.steps_within(f32::MAX), grid.most, "no more steps than the grid has columns"); +} + +/// A toolbar: a panel whose two lines of content lay out in a grid and never collapse. +struct Tools; + +impl DockPanels for Tools { + fn spec(&self, panel: &u32) -> PanelSpec { + if *panel == TOOLS { PanelSpec::new("Tools").grid(grid()) } else { PanelSpec::new("Canvas") } + } + + fn permissions(&self, panel: &u32) -> Permissions { + if *panel == TOOLS { Permissions::ALL.collapses(false) } else { Permissions::ALL } + } + + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel == TOOLS { + Text::new("One").show(ui); + Text::new("Two").show(ui); + } + } +} + +/// A docked stepped column is only as tall as its content, not the dock's height; the double arrow of a column that +/// does not collapse switches it between one and two steps. +#[trial] +fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_and_two_steps() { + let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1)]); + let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0)); + let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); + let placed: Rc>> = Rc::default(); + let (held, seen) = (Rc::clone(&workspace), Rc::clone(&placed)); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = held.borrow().clone(); + let out = DockArea::new("Stepped dock", Bind::bound(&mut workspace), &mut Tools, DockConfig::default()).show(ui); + *held.borrow_mut() = workspace; + *seen.borrow_mut() = out.columns; + }); + fixture.settle(); + let tools = placed.borrow().iter().find(|(panel, _)| *panel == TOOLS).map(|(_, rect)| *rect).expect("the stepped column shows"); + let canvas = + fixture.by_role(Role::TAB_PANEL).into_iter().map(|group| group.rect).find(|rect| !tools.contains_rect(*rect)).expect("the canvas shows"); + assert!(tools.bottom() < canvas.bottom() - 10.0, "the column ends below its content, above the dock's foot: {tools:?}, canvas {canvas:?}"); + + let steps = |workspace: &Workspace| match &workspace.layout.root { + Some(Node::Split { first, .. }) => match first.as_ref() { + Node::Dock { columns, .. } => columns[0].steps, + other => panic!("{other:?}"), + }, + other => panic!("{other:?}"), + }; + for expected in [2, 1] { + let tree = fixture.tree(); + let arrow = fixture + .by_role(Role::BUTTON) + .into_iter() + .find(|button| craft_ui::testing::access::name(tree, button.node) == Some("Collapse column to icons")) + .expect("the column bar shows its double arrow"); + fixture.click(&arrow).settle(); + assert_eq!(steps(&workspace.borrow()), Some(expected), "the double arrow switches the steps"); + } +} From 92f11d415b8b075fed0a3e18025cc9912a6d178b Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:49:47 +0000 Subject: [PATCH 11/18] Dock UI: the Window menu opens and closes the flyout of a panel in a collapsed column --- crates/ui-panels/src/docking/window_menu.rs | 32 ++++++++++++--- crates/ui-patterns/src/patterns/dock/area.rs | 5 ++- .../tests/it/docking/panel_menu.rs | 41 +++++++++++++++++-- 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/ui-panels/src/docking/window_menu.rs b/crates/ui-panels/src/docking/window_menu.rs index 0c6037ebe..054037daa 100644 --- a/crates/ui-panels/src/docking/window_menu.rs +++ b/crates/ui-panels/src/docking/window_menu.rs @@ -12,12 +12,17 @@ use std::hash::Hash; /// that shows the panel (open a closed one, bring a panel behind another tab to the front) or closes it (a panel /// showing); the app applies it through the same path as the actions of a `DockArea`. A Hidden pick's `Action::open` /// restores the panel's last place through `Workspace::apply_all`. +/// +/// A panel in a column collapsed to icons ([`Layout::opens_in_flyout`]) shows in its flyout: its row is checked +/// while its flyout is open ([`flyout`](WindowMenuRows::flyout)), and a pick opens the flyout, or closes it when it is +/// open, through [`WindowMenuRowsOutput::flyout`], which the app writes to the binding it gives `DockArea::flyout`. #[derive(crate::contract::Pattern)] #[pattern(probe(WindowMenuRows<'static, u32>))] pub struct WindowMenuRows<'a, P> { layout: &'a Layout

, panels: &'a dyn DockPanels

, order: &'a [P], + flyout: Option<&'a P>, } /// What the rows report. @@ -26,25 +31,42 @@ pub struct WindowMenuRows<'a, P> { pub struct WindowMenuRowsOutput

{ /// What the picked row asks for. pub action: Option>, + /// The open flyout the picked row asks for, when its panel is in a column collapsed to icons: that panel, or + /// `None` to close the flyout it had open. + pub flyout: Option>, } impl<'a, P: Clone + Eq + Hash> WindowMenuRows<'a, P> { /// Rows for `order` (every panel the app has, open or not), checked from `layout`, labelled by `panels`. pub fn new(layout: &'a Layout

, panels: &'a dyn DockPanels

, order: &'a [P]) -> Self { - WindowMenuRows { layout, panels, order } + WindowMenuRows { layout, panels, order, flyout: None } + } + + /// The panel whose flyout is open: the value of the binding the app gives `DockArea::flyout`. + #[must_use] + pub fn flyout(mut self, open: Option<&'a P>) -> Self { + self.flyout = open; + self } /// Shows the rows in the menu body `ui`. pub fn show(self, ui: &mut Ui) -> WindowMenuRowsOutput

{ - let mut action = None; + let (mut action, mut flyout) = (None, None); for panel in self.order { let spec = self.panels.spec(panel); let state = self.layout.panel_state(panel); - let mut row = MenuItem::new(spec.label).check(state != PanelState::Hidden); + let in_flyout = self.layout.opens_in_flyout(panel); + let open = self.flyout == Some(panel); + let mut row = MenuItem::new(spec.label).check(if in_flyout { open } else { state != PanelState::Hidden }); if let Some(icon) = spec.icon { row = row.icon(icon); } - if row.show(ui).ran { + if !row.show(ui).ran { + continue; + } + if in_flyout { + flyout = Some((!open).then(|| panel.clone())); + } else { action = Some(match state { PanelState::Hidden => Action::open(panel.clone(), None), PanelState::Open => Action::activate(panel.clone()), @@ -52,6 +74,6 @@ impl<'a, P: Clone + Eq + Hash> WindowMenuRows<'a, P> { }); } } - WindowMenuRowsOutput { action } + WindowMenuRowsOutput { action, flyout } } } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 3f24d0b90..bc63bc405 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -129,7 +129,10 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { /// The workspace is locked: nothing moves, floats or closes. #[prop(flag)] locked: bool, - /// The panel open in an iconic column's flyout, owned by the host. Without it the area keeps the value. + /// The panel open in an iconic column's flyout, owned by the host. Without it the area keeps the value. A host + /// that opens a panel whose column is collapsed to icons ([`Layout::opens_in_flyout`]), from its Window menu + /// ([`WindowMenuRowsOutput::flyout`](crate::docking::WindowMenuRowsOutput::flyout)) or a command, writes this + /// binding: the panel shows in its flyout, and the layout does not change. #[prop] flyout: Option>>, } diff --git a/crates/ui-patterns/tests/it/docking/panel_menu.rs b/crates/ui-patterns/tests/it/docking/panel_menu.rs index aaf820992..1067d9d9f 100644 --- a/crates/ui-patterns/tests/it/docking/panel_menu.rs +++ b/crates/ui-patterns/tests/it/docking/panel_menu.rs @@ -3,10 +3,10 @@ use craft_behavior::Axis; use craft_behavior::PartKey; -use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node, SplitSize, Workspace}; use craft_ui::contract::{Bind, BodyCx, Role}; -use craft_ui::docking::{DockConfig, DockPanels, PanelSpec}; -use craft_ui::menu::PanelRow; +use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, WindowMenuRows}; +use craft_ui::menu::{Menu, PanelRow}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Ui, Vec2}; @@ -71,3 +71,38 @@ fn tab_reaches_the_tabs_then_the_drag_band_then_the_panel_menu_button() { } assert_eq!(parts, vec![Some(PartKey::new("grip")), Some(PartKey::new("panel_menu"))], "Tab order after the tabs"); } + +/// A panel in a column collapsed to icons shows in its flyout: its Window menu row opens the flyout, is checked while +/// the flyout is open, and closes it on a second pick; the row of a panel elsewhere asks for an action instead. +#[trial] +fn the_window_menu_opens_and_closes_the_flyout_of_a_panel_in_a_collapsed_column() { + let mut iconic = Column::new(vec![Group::new(vec![2], 0)]); + iconic.iconic = true; + let dock = Node::dock(DockEdge::Start, vec![iconic]); + let layout = Layout::new(Some(Node::split(Axis::X, SplitSize::FixedFirst(40.0), dock, Node::tabs(vec![1], 0))), Vec::new()); + let flyout: Rc>> = Rc::default(); + let actions: Rc>>> = Rc::default(); + let (open, taken) = (Rc::clone(&flyout), Rc::clone(&actions)); + let mut fixture = Fixture::new(move |ui| { + let shown = *open.borrow(); + let mut menu_open = true; + Menu::new("Window").open(Bind::bound(&mut menu_open)).show(ui, |ui, _| { + let out = WindowMenuRows::new(&layout, &Panels, &[1, 2]).flyout(shown.as_ref()).show(ui); + if let Some(next) = out.flyout { + *open.borrow_mut() = next; + } + taken.borrow_mut().extend(out.action); + }); + }); + fixture.settle(); + for expected in [Some(2), None] { + let row = fixture.by_label("Panel 2").expect("the collapsed panel's row shows"); + fixture.click(&row).settle(); + assert_eq!(*flyout.borrow(), expected, "the row opens, then closes, the panel's flyout"); + } + assert!(actions.borrow().is_empty(), "the collapsed panel's row changes no layout: {:?}", actions.borrow()); + let row = fixture.by_label("Panel 1").expect("the docked panel's row shows"); + fixture.click(&row).settle(); + assert_eq!(*actions.borrow(), vec![Action::close(1)], "the row of a showing panel closes it"); + assert_eq!(*flyout.borrow(), None, "and leaves the flyout alone"); +} From 19f1b7b4eaa205b66741dca6bf31924f6561f44e Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:50:28 +0000 Subject: [PATCH 12/18] Dock stories: columns in floating windows, a stepped toolbar column and a collapsed floating window --- .../src/docking/dock_column/stories.rs | 16 +++++++++- .../ui-panels/src/docking/iconic/stories.rs | 17 +++++++++- .../src/patterns/dock/area/stories.rs | 31 +++++++++++++++---- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/ui-panels/src/docking/dock_column/stories.rs b/crates/ui-panels/src/docking/dock_column/stories.rs index 9977cf9f8..9e7409a50 100644 --- a/crates/ui-panels/src/docking/dock_column/stories.rs +++ b/crates/ui-panels/src/docking/dock_column/stories.rs @@ -1,7 +1,7 @@ //! Stories of `DockColumn`. use crate::contract::ShowContainer as _; -use crate::docking::{DockColumn, PanelSpec}; +use crate::docking::{ColumnBar, DockColumn, PanelSpec}; use crate::sections::Panel; use crate::testing::memory::global; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -22,3 +22,17 @@ fn two_groups(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { }) .into() } + +/// The column of a floating window: the window's title row is its bar, so it shows its groups and the dividers +/// between them only. +#[story(DockColumn<'static, u8>, covers = [Default], drive = Drive::Never)] +fn in_a_floating_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let column = Column::new(vec![Group::new(vec![0, 1], 0), Group::new(vec![2], 0)]); + DockColumn::new("Panels", global("dock column", "window story"), &column, &spec) + .bar(ColumnBar::Window) + .show_groups(ui, |group, rect, ui, _| { + let title = group.active_panel().map_or_else(String::new, |panel| spec(panel).label.as_str().to_owned()); + Panel::new(title).show_at(ui, rect, |_, _| ()); + }) + .into() +} diff --git a/crates/ui-panels/src/docking/iconic/stories.rs b/crates/ui-panels/src/docking/iconic/stories.rs index d16dd7824..98fed0018 100644 --- a/crates/ui-panels/src/docking/iconic/stories.rs +++ b/crates/ui-panels/src/docking/iconic/stories.rs @@ -4,7 +4,7 @@ use super::CELL; use crate::buttons::Button; use crate::contract::ShowContainer as _; use crate::contract::{Bind, BodyCx, Show as _, Validity}; -use crate::docking::{GroupAt, IconicColumn, IconicColumnOutput, PanelSpec}; +use crate::docking::{ColumnBar, GroupAt, IconicColumn, IconicColumnOutput, PanelSpec}; use crate::runtime::env::{Env, Message}; use crate::sections::Panel; use crate::testing::memory::global; @@ -50,6 +50,21 @@ fn icon_groups(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { .into() } +/// The column of a floating window collapsed to icons: the window's title row is its bar, so the icons start at its +/// top, and its flyouts open towards the room. +#[story(IconicColumn<'static, u8>, covers = [Default], drive = Drive::Never)] +fn icons_in_a_floating_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let column = Column::new(vec![Group::new(vec![0, 1], 0), Group::new(vec![2], 0)]); + let column = IconicColumn::new("Panels", global("iconic column", "window story"), &column, Bind::kept(), &spec).bar(ColumnBar::Window); + at_stage(ui, column, |group, at, ui, _| { + let GroupAt::Show(rect) = at else { return None }; + let title = group.active_panel().map_or_else(String::new, |panel| spec(panel).label.as_str().to_owned()); + Panel::new(title).titled().show_at(ui, rect, |_, _| ()); + None + }) + .into() +} + /// A click on the first icon opens the flyout of its panel, which the bound value then names. fn open_first_flyout(fixture: &mut Fixture) { let Some(id) = fixture.root_id() else { return }; diff --git a/crates/ui-patterns/src/patterns/dock/area/stories.rs b/crates/ui-patterns/src/patterns/dock/area/stories.rs index 5aa4d5297..c6d6b82fa 100644 --- a/crates/ui-patterns/src/patterns/dock/area/stories.rs +++ b/crates/ui-patterns/src/patterns/dock/area/stories.rs @@ -4,7 +4,7 @@ use super::DockArea; use crate::contract::SizeLimits; use crate::contract::{Bind, BodyCx, Show as _}; use crate::display::Text; -use crate::docking::{DockConfig, DockPanels, GroupAt, PanelSpec}; +use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, PanelSpec}; use crate::menu::PanelRow; use crate::patterns::presets::{PresetPanelMenu, PresetView}; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -18,8 +18,13 @@ const PROPERTIES: usize = 2; const HISTORY: usize = 3; const CANVAS: usize = 4; const SWATCHES: usize = 5; +/// A toolbar: its content lays out in a grid, and its column never collapses or holds another group. +const TOOLS: usize = 6; +const NAVIGATOR: usize = 7; const SIDE: f32 = 220.0; const WINDOW: Rect = Rect { min: Pos2::new(320.0, 80.0), max: Pos2::new(520.0, 220.0) }; +/// Where the collapsed floating window keeps its expanded size. +const COLLAPSED_WINDOW: Rect = Rect { min: Pos2::new(320.0, 240.0), max: Pos2::new(520.0, 380.0) }; /// Panels that show their own name. struct Demo { @@ -36,6 +41,8 @@ fn name(panel: usize) -> &'static str { PROPERTIES => "Properties", HISTORY => "History", SWATCHES => "Swatches", + TOOLS => "Tools", + NAVIGATOR => "Navigator", _ => "Canvas", } } @@ -43,11 +50,19 @@ fn name(panel: usize) -> &'static str { impl DockPanels for Demo { fn spec(&self, panel: &usize) -> PanelSpec { let spec = PanelSpec::new(name(*panel)).limits(SizeLimits::default()); - if *panel == CANVAS { spec.canvas() } else { spec } + match *panel { + CANVAS => spec.canvas(), + TOOLS => spec.grid(DockGrid::new(40.0, 32.0, 4)), + _ => spec, + } } fn permissions(&self, panel: &usize) -> Permissions { - if *panel == CANVAS { Permissions::PROTECTED } else { Permissions::ALL } + match *panel { + CANVAS => Permissions::PROTECTED, + TOOLS => Permissions::ALL.collapses(false).shares_column(false), + _ => Permissions::ALL, + } } fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { @@ -73,15 +88,19 @@ impl DockPanels for Demo { } } -/// A canvas between a docked column of panels at the start and an iconic column at the end, with one floating group. +/// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the +/// end, with one floating group and one floating window collapsed to icons. fn workspace() -> Workspace { + let tools = Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1); let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS], 0), Group::new(vec![PROPERTIES], 0)]).with_width(SIDE); let mut icons = Column::new(vec![Group::new(vec![SWATCHES], 0)]).with_width(SIDE); icons.iconic = true; let centre = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![icons])); - let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![side]), centre); + let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![tools, side]), centre); let window = Floating::single(vec![HISTORY], 0, WINDOW).with_id(1); - Workspace::new(Layout::new(Some(root), vec![window])) + let mut collapsed = Floating::single(vec![NAVIGATOR], 0, COLLAPSED_WINDOW).with_id(2); + collapsed.column.iconic = true; + Workspace::new(Layout::new(Some(root), vec![window, collapsed])) } fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput { From 4baf9d937b6cf95bb314c62cc550be26b5a4edde Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:50:46 +0000 Subject: [PATCH 13/18] Docking docs: icon drop spots, flyout side, stepped columns, flyouts from the Window menu --- docs/ui-docking.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 2f6bdd863..1b544ef66 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -67,6 +67,8 @@ A panel body, or code a body calls, changes the workspace during the pass with ` Props: `hide` (`HidePanels::None`, `All` or `Except`), `maximized`, `auto_collapse`, `locked`, and `flyout`, which binds the open flyout to the host's value (the area keeps it otherwise). A hidden panel keeps its place for restore. +A panel in a column collapsed to icons shows in its flyout (`Layout::opens_in_flyout`). The host opens and closes it by writing the `flyout` binding, not the layout: `WindowMenuRows` checks such a panel's row while its flyout is open (`WindowMenuRows::flyout`) and reports a pick in `WindowMenuRowsOutput::flyout`. + `DockAreaOutput` holds the `actions` taken, the bodies' `requested` actions, the `events` for the host, the `focused` and `picked` panels, `edit`, `float_space`, `columns`, the OS `windows` the floating windows showed in (by a panel of each), `window_files`, and `error`: an `InvalidGeometry` when the workspace fails `validate`, in which case the area draws nothing. The host handles these `DockEvent`s: @@ -98,6 +100,10 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Rules - A tab drag carries a `PanelDrag`; a group or column drag carries a `GroupDrag`. Groups and columns register `DockSpot`s in `DockTargets`, and `resolve_drop` maps the spot under the pointer to an `Action`. +- A column collapsed to icons takes drops as an expanded column does: its edges (a new column beside it, docked only), the seams between its icon groups, the top of the first group and the bottom of the last (a new group above or below), and each icon group's cells (join its tabs). The column's state wins: a panel dropped into a collapsed column shows as an icon, one dropped into an expanded column shows expanded. +- Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides. +- A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to the edge of the float area nearer it; a move keeps the edge it began with, and a collapsed window's move ends with its strip where it was dropped (`WindowColumn::anchored`). +- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit; a drag of a floating window's top or bottom the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. - A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. From 2997c6c91b53dbf760903eb2fb6c2c245a440bdc Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:52:13 +0000 Subject: [PATCH 14/18] API map: WindowMenuRows flyout, Flyout side --- migration/api-map/docking-and-panes.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/migration/api-map/docking-and-panes.toml b/migration/api-map/docking-and-panes.toml index c873f7831..c8448e2d4 100644 --- a/migration/api-map/docking-and-panes.toml +++ b/migration/api-map/docking-and-panes.toml @@ -649,7 +649,7 @@ name = "Flyout" old = "" new = "craft_ui::docking::Flyout" status = "replaced" -note = "The popup beside an iconic column, built on `Overlay::popover` and hung from the icon's part." +note = "The popup beside an iconic column, built on `Overlay::popover` and hung from the icon's part; `Flyout::new(opens: Side, size, auto_collapse)` opens it on that side of the column." # Drop resolution (dock-drop-a). @@ -1384,14 +1384,14 @@ name = "WindowMenuRows" old = "" new = "craft_ui::docking::WindowMenuRows" status = "replaced" -note = "The Window menu's check rows over a layout: `WindowMenuRows::new(&Layout

, &dyn DockPanels

, &[P]).show(ui) -> WindowMenuRowsOutput

{ action: Option> }`. Replaces a menu's hand-written panel rows." +note = "The Window menu's check rows over a layout: `WindowMenuRows::new(&Layout

, &dyn DockPanels

, &[P]).flyout(open).show(ui) -> WindowMenuRowsOutput

{ action: Option>, flyout: Option> }`; a panel in a collapsed column opens and closes its flyout through `flyout`. Replaces a menu's hand-written panel rows." [[type]] name = "WindowMenuRowsOutput" old = "" new = "craft_ui::docking::WindowMenuRowsOutput" status = "replaced" -note = "What `WindowMenuRows::show` reports: the action the picked row asks for." +note = "What `WindowMenuRows::show` reports: the action the picked row asks for, or the open flyout it asks for when its panel is in a collapsed column." [[type]] name = "StackSections" From 83e5cee5965329bdc573f697bd9a99f5b0c26e41 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 03:54:49 +0000 Subject: [PATCH 15/18] Dock sizes: fixed() takes the column by reference --- crates/ui-panels/src/docking/targets.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 164390f63..294ba3563 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -163,7 +163,7 @@ impl DockSizes { columns .iter() .zip(current.iter().zip(widths)) - .filter(|(column, ((width, _), scaled))| !fixed(column) && (scaled - width).abs() >= 0.01) + .filter(|(column, ((width, _), scaled))| !fixed(*column) && (scaled - width).abs() >= 0.01) .filter_map(|(column, (_, width))| { let panel = column.groups.iter().find_map(|group| group.panels.first())?.clone(); Some(if column.iconic { Action::resize_iconic(panel, Some(width)) } else { Action::resize_column(panel, width) }) From 2f35c5be5969d08ab1571caa22d49e00c50b064e Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 04:03:22 +0000 Subject: [PATCH 16/18] Dock UI: a stepped column's double arrow is named for the steps it switches to; a floating stepped window's left grip keeps its right edge --- crates/ui-panels/src/docking/dock_column.rs | 62 +++++++++++++++++-- .../ui-panels/src/docking/dock_column/bar.rs | 26 ++++---- crates/ui-panels/src/docking/floating.rs | 23 ++++--- crates/ui-panels/src/docking/iconic.rs | 8 +-- crates/ui-panels/src/docking/mod.rs | 2 +- crates/ui-panels/src/docking/words.rs | 4 ++ crates/ui-patterns/src/patterns/dock/area.rs | 57 +++++++++++------ .../ui-patterns/tests/it/docking/columns.rs | 36 +++++++++-- docs/ui-docking.md | 2 +- migration/api-map/docking-and-panes.toml | 7 +++ 10 files changed, 169 insertions(+), 58 deletions(-) diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 7ea58c8de..9bbe8b4d2 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -30,7 +30,7 @@ mod sizing; use bar::panel_names; -pub(super) use bar::{BarRecord, CHEVRON, bar_name, bar_slots, chevron_name, describe_chevron, paint_chevron, show_bar}; +pub(super) use bar::{BarRecord, CHEVRON, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar}; use sizing::group_sizes; pub use sizing::{GroupSize, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; @@ -61,6 +61,56 @@ impl ColumnBar { } } +/// What a column's double arrow does, which names it and sets where it points. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum ColumnArrow { + /// Collapses the column to icons, or expands it. + #[default] + Collapse, + /// Switches a stepped column ([`stepped`]) between one and two steps. Holds the steps it shows. + Steps(u16), +} + +impl ColumnArrow { + /// The arrow of `column`: an expanded stepped column whose panels do not collapse (`collapses` false) switches + /// steps; any other column collapses or expands. + pub fn of

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, collapses: bool) -> Self { + match stepped(column, spec) { + Some((_, steps)) if !collapses && !column.iconic => ColumnArrow::Steps(steps), + _ => ColumnArrow::Collapse, + } + } + + /// The steps a click gives a stepped column: two from one, else one. `None` for an arrow that collapses. + pub fn switched_steps(self) -> Option { + match self { + ColumnArrow::Collapse => None, + ColumnArrow::Steps(steps) => Some(if steps == 1 { 2 } else { 1 }), + } + } + + /// Whether a click sends the column towards the edge it keeps to: collapsing the `expanded` column, or narrowing a + /// stepped one. + pub(super) fn towards_edge(self, expanded: bool) -> bool { + match self { + ColumnArrow::Collapse => expanded, + ColumnArrow::Steps(steps) => steps > 1, + } + } + + /// The arrow's name: what a click on it does to the `expanded` or collapsed column. + pub(super) fn name(self, words: &DockWords, expanded: bool) -> Label { + let word = match self { + ColumnArrow::Collapse if expanded => &words.collapse_column, + ColumnArrow::Collapse => &words.expand_column, + ColumnArrow::Steps(1) => &words.two_steps, + ColumnArrow::Steps(_) => &words.one_step, + }; + Label::from(word.as_str().to_owned()) + } +} + /// The caller's view of one group: the group, the rect it takes and the body step's context. The dock passes the /// group to `DockPanels::group_view` or shows a `DockGroup` in it. pub type GroupView<'a, P> = Box, Rect, &mut Ui, &mut BodyCx<'_>) + 'a>; @@ -131,6 +181,9 @@ pub struct DockColumn<'a, P: Value + Hash + 'static> { /// Where the column's bar is: its own (a dock column) or its floating window's title row. #[prop] bar: ColumnBar, + /// What the double arrow of the column's own bar does ([`ColumnArrow::of`]). + #[prop] + arrow: ColumnArrow, /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. #[prop] within: Rect, @@ -155,6 +208,7 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { auto_collapse: false, edge: DockEdge::Start, bar: ColumnBar::Own, + arrow: ColumnArrow::Collapse, within: Rect::NOTHING, laid: None, resized: Vec::new(), @@ -341,7 +395,7 @@ impl Component for DockColumn<'_, P> { let plan = column_plan(self.column, self.spec, rect, self.bar, &sizes, |_, _| None); if self.bar == ColumnBar::Own { let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); - let name = chevron_name(&cx.words::(), true); + let name = self.arrow.name(&cx.words::(), true); let _ = cx.part(CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); } let dividers = plan.dividers(rect, sizes.reach); @@ -395,7 +449,7 @@ impl Component for DockColumn<'_, P> { ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); if self.bar == ColumnBar::Own { ui.draw().surface(plan.bar, SurfaceKind::Background, Corners::None); - paint_chevron(ui, self.edge, true, cx.flow.is_rtl(), chevron_name(&cx.words::(), true)); + paint_chevron(ui, self.edge, self.arrow, true, cx.flow.is_rtl(), &cx.words::()); } } @@ -428,7 +482,7 @@ impl Component for DockColumn<'_, P> { if self.bar == ColumnBar::Own { let edge = self.edge_divider(cx.rect, &sizes); divider::describe(access, EDGE, 0, &edge, words.resize.as_str(), sizes.step); - describe_chevron(access, &chevron_name(&words, true)); + describe_chevron(access, &self.arrow.name(&words, true)); } } diff --git a/crates/ui-panels/src/docking/dock_column/bar.rs b/crates/ui-panels/src/docking/dock_column/bar.rs index 5110047a2..ac4976c02 100644 --- a/crates/ui-panels/src/docking/dock_column/bar.rs +++ b/crates/ui-panels/src/docking/dock_column/bar.rs @@ -6,7 +6,7 @@ use crate::buttons::icon_button::IconButtonStyleKey; use crate::contract::overlay::Trigger; use crate::contract::{Access, BodyCx, Name, PaintUi, Props as _, Role, Show as _, ShowContainer as _, WordSetCx as _}; use crate::docking::group::GroupGrip; -use crate::docking::{DockWords, PanelSpec}; +use crate::docking::{ColumnArrow, DockWords, PanelSpec}; use crate::menu::{GroupItem, Menu, MenuWords, PanelMenu, PanelRow}; use crate::runtime::env::Label; use craft_behavior::PartKey; @@ -38,11 +38,11 @@ fn collapse_look(tokens: &Tokens) -> VariantLook { const COLLAPSE: CustomVariant = CustomVariant::new::("craft_ui.dock-collapse", collapse_look); -/// Whether the column's collapse control points to the right of the screen: towards the window edge when it collapses -/// to icons and away from it when it expands. -fn points_right(edge: DockEdge, expanded: bool, rtl: bool) -> bool { +/// Whether the column's double arrow points to the right of the screen: towards the edge it keeps to when a click sends +/// the column there (`towards_edge`), else away from it. +fn points_right(edge: DockEdge, towards_edge: bool, rtl: bool) -> bool { let at_left = (edge == DockEdge::Start) != rtl; - at_left != expanded + at_left != towards_edge } /// The chevron's slot at the bar's outer end, the window edge the dock is on, as high and wide as the bar is high; and @@ -58,15 +58,11 @@ pub(in crate::docking) fn bar_slots(bar: Rect, edge: DockEdge, rtl: bool) -> (Re } } -/// The name of the chevron of an expanded or an iconic column. -pub(in crate::docking) fn chevron_name(words: &DockWords, expanded: bool) -> Label { - Label::from(if expanded { words.collapse_column.as_str() } else { words.expand_column.as_str() }.to_owned()) -} - -/// Paints the chevron part: a small ghost button with the double chevron pointing where the column goes. -pub(in crate::docking) fn paint_chevron(ui: &mut PaintUi<'_>, edge: DockEdge, expanded: bool, rtl: bool, name: Label) { - let chevrons = crate::collapse::chevrons(points_right(edge, expanded, rtl)); - ui.face(CHEVRON, IconButton::new(chevrons).size(ControlSize::Sm).variant(Variant::Custom(COLLAPSE)).label(name)); +/// Paints the chevron part of the `expanded` or collapsed column whose double arrow is `arrow`: a small ghost button +/// with the double chevron pointing where the column goes, named for what a click does. +pub(in crate::docking) fn paint_chevron(ui: &mut PaintUi<'_>, edge: DockEdge, arrow: ColumnArrow, expanded: bool, rtl: bool, words: &DockWords) { + let chevrons = crate::collapse::chevrons(points_right(edge, arrow.towards_edge(expanded), rtl)); + ui.face(CHEVRON, IconButton::new(chevrons).size(ControlSize::Sm).variant(Variant::Custom(COLLAPSE)).label(arrow.name(words, expanded))); } /// The chevron's node. @@ -89,7 +85,7 @@ pub(in crate::docking) fn show_bar( let words = body.words::(); let menu_words = body.words::(); let rtl = crate::runtime::env::Env::of(ui).direction.is_rtl(); - let toggle = chevron_name(&words, expanded); + let toggle = ColumnArrow::Collapse.name(&words, expanded); let (_, band) = bar_slots(bar, edge, rtl); let mut record = BarRecord::default(); if band.width() <= 0.0 { diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 855ef7337..bbbfd5857 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -6,7 +6,7 @@ //! opens the `menu` rows. The body step supplies the move band, the edge grips and the keyboard Move and Size modes. //! A dock window's title row is also the bar of the column the window holds, with the column's double arrow. -use super::dock_column::{CHEVRON, chevron_name, describe_chevron, paint_chevron}; +use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron}; use super::drop::{DragUnit, start_group_drag}; use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; @@ -56,24 +56,32 @@ pub struct WindowColumn { /// The size of an expanded column whose content sets it (a column with steps) under the title row; `None` for a /// column the rect sizes. pub fitted: Option, + /// What the double arrow does: collapse or expand the column unless [`arrow`](Self::arrow) says otherwise. + pub arrow: ColumnArrow, } impl WindowColumn { /// An expanded column that keeps to `edge`. pub fn expanded(edge: DockEdge) -> Self { - WindowColumn { edge, collapsed: None, fitted: None } + WindowColumn { edge, collapsed: None, fitted: None, arrow: ColumnArrow::Collapse } } /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. pub fn collapsed(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: Some(size), fitted: None } + WindowColumn { edge, collapsed: Some(size), fitted: None, arrow: ColumnArrow::Collapse } } /// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at /// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's /// steps, and a move keeps the rect's size. pub fn fitted(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: None, fitted: Some(size) } + WindowColumn { edge, collapsed: None, fitted: Some(size), arrow: ColumnArrow::Collapse } + } + + /// The column with the double arrow `arrow` ([`ColumnArrow::of`]). + pub fn arrow(mut self, arrow: ColumnArrow) -> Self { + self.arrow = arrow; + self } /// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is @@ -363,7 +371,7 @@ impl Component for FloatingGroup<'_> { fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { let (Some(edge), Some(column)) = (self.chevron_edge(), self.column) else { return }; let Some(slot) = cx.header_slot(edge) else { return }; - let name = chevron_name(&cx.words::(), column.collapsed.is_none()); + let name = column.arrow.name(&cx.words::(), column.collapsed.is_none()); let _ = cx.header_part(edge, CHEVRON, slot).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); self.chevron_declared = true; } @@ -386,13 +394,12 @@ impl Component for FloatingGroup<'_> { /// The double arrow, over the title row's surface. fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let Some(column) = self.column.filter(|_| self.chevron_declared) else { return }; - let expanded = column.collapsed.is_none(); - paint_chevron(ui, column.edge, expanded, cx.flow.is_rtl(), chevron_name(&cx.words::(), expanded)); + paint_chevron(ui, column.edge, column.arrow, column.collapsed.is_none(), cx.flow.is_rtl(), &cx.words::()); } fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { if let Some(column) = self.column.filter(|_| self.chevron_declared) { - describe_chevron(access, &chevron_name(&cx.words::(), column.collapsed.is_none())); + describe_chevron(access, &column.arrow.name(&cx.words::(), column.collapsed.is_none())); } } diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 4500ca4e8..b08691473 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -2,7 +2,7 @@ use super::divider::{self, Divider, Drag}; use super::dock_column::{ - BarRecord, CHEVRON, ColumnBar, bar_slots, chevron_name, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, + BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, }; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_group_drag}; use crate::buttons::IconButton; @@ -419,7 +419,7 @@ impl Component for IconicColumn<'_, P> { self.bar_rect = plan.bar; if self.bar == ColumnBar::Own { let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); - let name = chevron_name(&cx.words::(), false); + let name = ColumnArrow::Collapse.name(&cx.words::(), false); let _ = cx.header_part(chevron_edge(self.edge), CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); } for (at, (_, _, cell)) in plan.cells.iter().enumerate() { @@ -525,7 +525,7 @@ impl Component for IconicColumn<'_, P> { ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); if self.bar == ColumnBar::Own { ui.draw().surface(self.bar_rect, SurfaceKind::Background, Corners::None); - paint_chevron(ui, self.edge, false, cx.flow.is_rtl(), chevron_name(&cx.words::(), false)); + paint_chevron(ui, self.edge, ColumnArrow::Collapse, false, cx.flow.is_rtl(), &cx.words::()); } let flat = self.flat(); for (at, (group, panel)) in flat.iter().enumerate() { @@ -562,7 +562,7 @@ impl Component for IconicColumn<'_, P> { } divider::describe(access, EDGE, 0, &self.edge_divider(cx.rect, &sizes.column), words.resize.as_str(), sizes.column.step); if self.bar == ColumnBar::Own { - describe_chevron(access, &chevron_name(&words, false)); + describe_chevron(access, &ColumnArrow::Collapse.name(&words, false)); } } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 2fdcc16d8..8d94f81a7 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -56,7 +56,7 @@ mod flyout; mod iconic; pub use dock_column::{ - ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, stepped, + ColumnArrow, ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds, }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; diff --git a/crates/ui-panels/src/docking/words.rs b/crates/ui-panels/src/docking/words.rs index 5db5e2781..71ba1ffd1 100644 --- a/crates/ui-panels/src/docking/words.rs +++ b/crates/ui-panels/src/docking/words.rs @@ -14,6 +14,10 @@ craft_ui::words! { move_column: template "dockColumn.move" = "Move panel column"; collapse_column: "dockColumn.collapse" = "Collapse column to icons"; expand_column: "dockColumn.expand" = "Expand column"; + /// The double arrow of a stepped column at one step, which widens it to two. + two_steps: "dockColumn.twoSteps" = "Show in two columns"; + /// The double arrow of a stepped column at more than one step, which narrows it to one. + one_step: "dockColumn.oneStep" = "Show in one column"; move_window: "floatingGroup.move" = "Move panel window"; close_window: "floatingGroup.close" = "Close panel window"; /// The tooltip and accessible name of the panel-menu button. diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index bc63bc405..efdd50105 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -11,16 +11,17 @@ use crate::docking::stack::{StackSection, StackSections, section_heights}; use crate::docking::tree::FrameRules; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ - ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, - DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, IconicColumn, - IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths, frame, move_actions, stepped, + ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, + DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, + IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths, frame, + move_actions, stepped, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, Commands as _, focus_within}; use crate::runtime::drag; use crate::runtime::env::{Env, Label, RevealEdge, ShellCx, ShellEntry}; use crate::runtime::memory::Remember as _; -use crate::runtime::windows::WindowHost; +use crate::runtime::windows::{ResizeEdge, WindowHost}; use crate::sections::HeaderAction; use craft_behavior::dock::{ Action, Column, DockEdge, DockError, Group, Layout, Location, Node, PanelPlace, Permissions, SplitSize, Workspace, node_at, @@ -944,16 +945,20 @@ impl Pass<'_, P> { Some(height) } - /// What a click on the double arrow of `column`, whose first panel is `first`, asks for when it reports - /// `iconic`: an expanded stepped column whose panels do not collapse switches between one and two steps; any - /// other column collapses to icons or expands. - fn arrow(&self, column: &Column

, first: &P, iconic: bool) -> Action

{ + /// What the double arrow of `column` does ([`ColumnArrow::of`]): it names the arrow and decides what a click asks + /// for. + fn arrow_of(&self, column: &Column

) -> ColumnArrow { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); - let collapses = column.panels().all(|panel| scene.permissions(panel).collapses); - match stepped(column, &spec) { - Some((_, steps)) if !collapses && !column.iconic => Action::set_column_steps(first.clone(), if steps == 1 { 2 } else { 1 }), - _ => Action::set_iconic(first.clone(), iconic), + ColumnArrow::of(column, &spec, column.panels().all(|panel| scene.permissions(panel).collapses)) + } + + /// What a click on the double arrow of `column`, whose first panel is `first`, asks for when it reports + /// `iconic`: the steps it switches to, or the collapse or expansion of the column. + fn arrow(&self, column: &Column

, first: &P, iconic: bool) -> Action

{ + match self.arrow_of(column).switched_steps() { + Some(steps) => Action::set_column_steps(first.clone(), steps), + None => Action::set_iconic(first.clone(), iconic), } } @@ -981,6 +986,7 @@ impl Pass<'_, P> { let output = DockColumn::new(name, dock, column, &spec) .edge(edge) .bar(bar) + .arrow(self.arrow_of(column)) .within(within) .auto_collapse(scene.auto_collapse) .show_groups_at(ui, cell, |group, rect, ui, body| { @@ -1050,7 +1056,8 @@ impl Pass<'_, P> { /// /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or - /// bottom the fewest whose content fits the height, and the window keeps its place. + /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps + /// its right edge. fn windows(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, open: &Option

, started: Option<&Layout

>) -> Option<(P, PlacementChange)> { let scene = self.scene; let ctx = ui.ctx().clone(); @@ -1097,7 +1104,8 @@ impl Pass<'_, P> { WindowColumn::fitted(edge, Vec2::new(width, content)) } else { WindowColumn::expanded(edge) - }; + } + .arrow(self.arrow_of(&window.column)); let mut group = FloatingGroup::new(spec.label, opening.rect) .limits(scene.spec(&anchor).limits) .sized(Sizing::Fill) @@ -1151,17 +1159,28 @@ impl Pass<'_, P> { && let Some((grid, steps)) = stepped(&window.column, &spec_of) { let column = &window.column; - let to = if (change.rect.width() - fitted.x).abs() > 0.5 { - grid.steps_within(change.rect.width()) - } else { + // A grip on the top or bottom edge sets the steps by height, any other grip by width; keyboard Size + // mode, which names no grip, by the side it changed. + let by_height = match change.kind { + PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), + _ => (change.rect.width() - fitted.x).abs() <= 0.5, + }; + let to = if by_height { let room = change.rect.height() - scene.sizes.strip; grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) + } else { + grid.steps_within(change.rect.width()) }; if to != steps { self.report.actions.push(Action::set_column_steps(anchor.clone(), to)); } - // The window keeps its place; its steps set its size. - change.rect = Rect::from_min_size(change.rect.min, opening.rect.size()); + // The window keeps its place and its steps set its size. A grip on the left keeps the right edge + // where it is, so the window grows or shrinks to the left. + let left = match change.kind { + PlacementKind::Size(ResizeEdge::Left | ResizeEdge::TopLeft | ResizeEdge::BottomLeft) => change.rect.right() - grid.width(to), + _ => change.rect.left(), + }; + change.rect = Rect::from_min_size(Pos2::new(left, change.rect.top()), opening.rect.size()); } if change.phase == GesturePhase::Commit { self.report.events.push(DockEvent::FloatPlaced { panel: anchor.clone(), rect: change.rect }); diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index f5d4e3071..470562297 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -1,13 +1,13 @@ //! Dock columns: room sharing between groups, and a dock side's total width shared between its columns. use craft_behavior::Axis; -use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; +use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; use craft_ui::contract::{Bind, BodyCx, Role, Show as _, SizeLimits}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, GroupSize, PanelSpec, group_heights}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; -use egui::{Rect, Ui, Vec2}; +use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -164,7 +164,7 @@ impl DockPanels for Tools { } /// A docked stepped column is only as tall as its content, not the dock's height; the double arrow of a column that -/// does not collapse switches it between one and two steps. +/// does not collapse switches it between one and two steps, and is named for the steps it switches to. #[trial] fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_and_two_steps() { let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1)]); @@ -191,14 +191,38 @@ fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_an }, other => panic!("{other:?}"), }; - for expected in [2, 1] { + for (name, expected) in [("Show in two columns", 2), ("Show in one column", 1)] { let tree = fixture.tree(); let arrow = fixture .by_role(Role::BUTTON) .into_iter() - .find(|button| craft_ui::testing::access::name(tree, button.node) == Some("Collapse column to icons")) - .expect("the column bar shows its double arrow"); + .find(|button| craft_ui::testing::access::name(tree, button.node) == Some(name)) + .expect("the column bar shows its double arrow, named for the steps it switches to"); fixture.click(&arrow).settle(); assert_eq!(steps(&workspace.borrow()), Some(expected), "the double arrow switches the steps"); } } + +/// A drag of a floating stepped window's left edge widens it in whole steps to the left: its right edge stays. +#[trial] +fn a_floating_stepped_windows_left_edge_drag_keeps_its_right_edge() { + let at = Rect::from_min_size(Pos2::new(200.0, 80.0), Vec2::new(100.0, 100.0)); + let window = Floating::new(Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1), at); + let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(None, vec![window])))); + let held = Rc::clone(&workspace); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = held.borrow().clone(); + DockArea::new("Floating tools", Bind::bound(&mut workspace), &mut Tools, DockConfig::default()).show(ui); + *held.borrow_mut() = workspace; + }); + fixture.settle(); + let shown = |fixture: &Fixture| fixture.by_role(Role::TAB_PANEL).first().map(|group| group.rect).expect("the window shows its group"); + let before = shown(&fixture); + // The left grip straddles the window's left edge, which is its rect's. + fixture.drag_at(Pos2::new(at.left(), before.center().y), Vec2::new(-1.5 * grid().step, 0.0)).settle(); + let after = shown(&fixture); + let steps = workspace.borrow().layout.floating[0].column.steps; + assert!(steps.is_some_and(|steps| steps > 1), "the drag widened the window by whole steps: {steps:?}"); + assert!((after.right() - before.right()).abs() <= 1.5, "the right edge stays: {before:?}, then {after:?}"); + assert!(after.left() < before.left(), "the window grew to the left: {before:?}, then {after:?}"); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 1b544ef66..869775470 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -103,7 +103,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A column collapsed to icons takes drops as an expanded column does: its edges (a new column beside it, docked only), the seams between its icon groups, the top of the first group and the bottom of the last (a new group above or below), and each icon group's cells (join its tabs). The column's state wins: a panel dropped into a collapsed column shows as an icon, one dropped into an expanded column shows expanded. - Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides. - A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to the edge of the float area nearer it; a move keeps the edge it began with, and a collapsed window's move ends with its strip where it was dropped (`WindowColumn::anchored`). -- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit; a drag of a floating window's top or bottom the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. +- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. - A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. diff --git a/migration/api-map/docking-and-panes.toml b/migration/api-map/docking-and-panes.toml index c8448e2d4..314c7c139 100644 --- a/migration/api-map/docking-and-panes.toml +++ b/migration/api-map/docking-and-panes.toml @@ -637,6 +637,13 @@ new = "craft_ui::docking::DockColumn" status = "replaced" note = "A column of a side dock: the column bar over the stacked groups. Replaces the hand-rolled column bar, collapse button and group stacking of the dock renderer." +[[type]] +name = "ColumnArrow" +old = "" +new = "craft_ui::docking::ColumnArrow" +status = "replaced" +note = "What a column's double arrow does, which names it and sets where it points: `Collapse`, or `Steps(n)` for a stepped column whose panels do not collapse, which switches between one and two steps. `ColumnArrow::of(&Column

, spec, collapses)`; `DockColumn::arrow` and `WindowColumn::arrow` take it. Replaces `ToolRail`'s column toggle." + [[type]] name = "IconicColumn" old = "" From a4d50040092b81c1b497e9e570c2e96b09b6d9e0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 04:15:48 +0000 Subject: [PATCH 17/18] Dock: a floating window keeps the edge its collapsed strip was dropped near; icons float collapsed under the pointer; top grips keep the bottom edge; a column that cannot collapse offers no collapse --- crates/behavior/src/dock/action.rs | 16 ++- crates/behavior/src/dock/edit.rs | 13 ++- crates/behavior/src/dock/groups.rs | 14 ++- crates/behavior/src/dock/inner.rs | 9 +- crates/behavior/src/dock/layout.rs | 2 +- crates/behavior/src/dock/node.rs | 43 +++++--- crates/behavior/src/dock/windows.rs | 2 +- crates/behavior/src/dock/workspace.rs | 2 +- crates/behavior/tests/dock_apply.rs | 39 +++++++- crates/ui-panels/src/docking/dock_column.rs | 55 +++++++---- .../ui-panels/src/docking/dock_column/bar.rs | 30 +++--- crates/ui-panels/src/docking/drop.rs | 76 +++++++++++--- crates/ui-panels/src/docking/floating.rs | 47 +++++---- crates/ui-panels/src/docking/group.rs | 16 ++- crates/ui-panels/src/docking/iconic.rs | 11 ++- crates/ui-panels/src/docking/mod.rs | 6 +- crates/ui-panels/src/docking/targets.rs | 6 +- crates/ui-patterns/src/patterns/dock/area.rs | 99 ++++++++++++------- .../ui-patterns/tests/it/docking/columns.rs | 32 ++++-- .../tests/it/docking/floating_area.rs | 64 +++++++++--- docs/ui-docking.md | 6 +- migration/api-map/docking-and-panes.toml | 4 +- 22 files changed, 421 insertions(+), 171 deletions(-) diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index fe4b8ff55..8075b7bf4 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -6,7 +6,7 @@ use crate::placement::Placement; use super::{ DockSide, - groups::{GroupLocation, Target}, + groups::{DockEdge, GroupLocation, Target}, policy::Permissions, split::SplitSize, }; @@ -161,6 +161,11 @@ pub enum Action

{ /// The window rect in logical points. Saved as `[x, y, width, height]`. #[serde(with = "crate::dock::rect_serde")] rect: Rect, + /// The window's [`Floating::edge`](super::Floating::edge): the edge the area decided from where a collapsed + /// window's strip was dropped. `None` (any move of an expanded window, and a sender without the float area) + /// leaves the edge to the area, nearer `rect`. + #[serde(default, skip_serializing_if = "Option::is_none")] + edge: Option, }, /// Path from the root: false is the first child, true the second. #[non_exhaustive] @@ -370,9 +375,14 @@ impl

Action

{ Self::OpenAt { panel, anchor, placement } } - /// Builds [`Action::MoveFloating`]. + /// Builds [`Action::MoveFloating`] with no edge: the area takes the edge nearer `rect`. pub fn move_floating(panel: P, rect: Rect) -> Self { - Self::MoveFloating { panel, rect } + Self::MoveFloating { panel, rect, edge: None } + } + + /// Builds [`Action::MoveFloating`] with the window's edge. + pub fn move_floating_with_edge(panel: P, rect: Rect, edge: Option) -> Self { + Self::MoveFloating { panel, rect, edge } } /// Builds [`Action::ResizeSplit`]. diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index bceb449b5..8d116bd79 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -325,7 +325,11 @@ impl Layout

{ } Layout { root: self.root.as_ref().map(node), - floating: self.floating.iter().map(|w| Floating { column: column_shape(&w.column), rect: Rect::ZERO, native: None, ..w.clone() }).collect(), + floating: self + .floating + .iter() + .map(|w| Floating { column: column_shape(&w.column), rect: Rect::ZERO, native: None, edge: None, ..w.clone() }) + .collect(), } } @@ -503,13 +507,14 @@ impl Layout

{ return Err(DockError::MissingPanel); } match to { - Target::Float { rect } => { + Target::Float { rect, edge } => { if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } - // A window's width is its rect's. + // A window's width is its rect's; only a collapsed column keeps to an edge of its own. let window = Floating::new(Column { width: None, ..moving.column }, rect); - self.floating.push(Floating { id: moving.id.unwrap_or(window.id), ..window }); + let edge = edge.filter(|_| window.column.iconic); + self.floating.push(Floating { id: moving.id.unwrap_or(window.id), edge, ..window }); Ok(()) } Target::NewDock { side } => { diff --git a/crates/behavior/src/dock/groups.rs b/crates/behavior/src/dock/groups.rs index 8738b920b..a05570c53 100644 --- a/crates/behavior/src/dock/groups.rs +++ b/crates/behavior/src/dock/groups.rs @@ -184,6 +184,11 @@ pub enum Target

{ /// `[x, y, width, height]`. #[serde(with = "crate::dock::rect_serde")] rect: Rect, + /// The new window's [`Floating::edge`](super::Floating::edge) when its column is collapsed: the edge the area + /// decided from where the strip was dropped. `None` (and any expanded column) leaves the edge to the area, + /// nearer `rect`. + #[serde(default, skip_serializing_if = "Option::is_none")] + edge: Option, }, } @@ -361,8 +366,13 @@ impl

Target

{ Self::NewDock { side } } - /// Builds [`Target::Float`]. + /// Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. pub fn float(rect: Rect) -> Self { - Self::Float { rect } + Self::Float { rect, edge: None } + } + + /// Builds [`Target::Float`] with the edge a collapsed window keeps to. + pub fn float_with_edge(rect: Rect, edge: Option) -> Self { + Self::Float { rect, edge } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index 129e1c595..bb620b8f5 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -50,7 +50,7 @@ impl Layout

{ // A panel the layout does not hold opens in the new window. let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None }); let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) }; - self.insert_moving(moving, Target::Float { rect }, canvas) + self.insert_moving(moving, Target::Float { rect, edge: None }, canvas) } Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel), Action::Activate { panel } => { @@ -91,12 +91,13 @@ impl Layout

{ } self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas) } - Action::MoveFloating { panel, rect } => { + Action::MoveFloating { panel, rect, edge } => { if !valid_rect(rect) { return Err(DockError::InvalidGeometry); } let window = self.floating.iter_mut().find(|g| g.contains(&panel)).ok_or(DockError::MissingPanel)?; window.rect = rect; + window.edge = edge; Ok(()) } Action::ResizeSplit { path, size } => { @@ -194,6 +195,10 @@ impl Layout

{ } Action::SetIconic { panel, iconic } => { self.column_of(&panel)?.iconic = iconic; + // A floating column that collapses hangs from the edge nearer its window, which the area takes. + if iconic && let Some(window) = self.floating.iter_mut().find(|window| window.contains(&panel)) { + window.edge = None; + } Ok(()) } Action::ResizeColumn { panel, width } => { diff --git a/crates/behavior/src/dock/layout.rs b/crates/behavior/src/dock/layout.rs index d4102cac4..ec3d68d10 100644 --- a/crates/behavior/src/dock/layout.rs +++ b/crates/behavior/src/dock/layout.rs @@ -301,7 +301,7 @@ impl Layout

{ 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. - proposed.insert_moving(moving(), Target::Float { rect }, &|_| false)?; + proposed.insert_moving(moving(), Target::Float { rect, edge: None }, &|_| false)?; } else if let Some(anchor) = &location.anchor && matches!(location.placement, DockPlacement::Group { .. } | DockPlacement::Column { .. }) { diff --git a/crates/behavior/src/dock/node.rs b/crates/behavior/src/dock/node.rs index f835a15fe..b9b2f68cc 100644 --- a/crates/behavior/src/dock/node.rs +++ b/crates/behavior/src/dock/node.rs @@ -88,11 +88,17 @@ pub struct Floating

{ /// Where the window is on the desktop while it is in its own OS window: the record app windows keep too, placed /// with [`place`](crate::placement::place). pub native: Option, + /// The edge of the float area, in reading order, the window keeps to, as the area decided it from where the strip + /// of the collapsed column was dropped ([`Action::MoveFloating`](super::Action::MoveFloating), + /// [`Target::Float`](super::Target::Float)): the collapsed column shows against that edge of `rect`, and the + /// title row's double arrow sits at that end. `None`: the edge nearer `rect`, which the area takes. Collapsing + /// the column clears it, so the strip hangs from the edge the expanded window showed. + pub edge: Option, } impl PartialEq for Floating

{ fn eq(&self, other: &Self) -> bool { - self.column == other.column && self.rect == other.rect && self.native == other.native + self.column == other.column && self.rect == other.rect && self.native == other.native && self.edge == other.edge } } @@ -138,7 +144,7 @@ impl

Floating

{ /// a layout once and keep it, or give its windows ids with [`Self::with_id`]. A layout /// built anew each frame without them opens new OS windows each frame. pub fn new(column: Column

, rect: Rect) -> Self { - Self { id: fresh_window_id(), column, rect, native: None } + Self { id: fresh_window_id(), column, rect, native: None, edge: None } } /// A window with one group. Each call makes a new window, as [`Self::new`] does. @@ -188,7 +194,7 @@ impl

Floating

{ /// | v1 `{panels, active, rect}` | one window, one group | /// | v2 `{groups, rect}` | one window of those groups | /// | v3 `{root, rect, native, minimized}` | a window per part the tree's top splits side by side, each at its share of `rect`; each part's leaves in reading order become its groups (an accordion entry a group, minimized when its section was closed); `minimized` minimizes every group | -/// | v4 `{column, rect, native}` | one window | +/// | v4 `{column, rect, native, edge}` | one window | /// /// The first window of a saved one keeps its id; the others get fresh ones. pub(super) mod floating_serde { @@ -196,7 +202,7 @@ pub(super) mod floating_serde { use serde::de::IgnoredAny; use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use super::{Column, Floating, Group, Node, fresh_window_id}; + use super::{Column, DockEdge, Floating, Group, Node, fresh_window_id}; use crate::dock::limits::MAX_NODES; use crate::dock::rect_serde::{from_array, to_array}; use crate::dock::split::SplitSize; @@ -218,6 +224,8 @@ pub(super) mod floating_serde { rect: [f32; 4], #[serde(skip_serializing_if = "Option::is_none")] native: Option<&'a Placement>, + #[serde(skip_serializing_if = "Option::is_none")] + edge: Option, } /// One expanded column holding one group with no state of its own: what v1 can hold. @@ -235,10 +243,11 @@ pub(super) mod floating_serde { impl Serialize for Floating

{ fn serialize(&self, serializer: S) -> Result { match self.column.groups.as_slice() { - [group] if self.native.is_none() && plain(&self.column, group) => { + [group] if self.native.is_none() && self.edge.is_none() && plain(&self.column, group) => { V1 { id: self.id, panels: &group.panels, active: group.active, rect: to_array(self.rect) }.serialize(serializer) } - _ => V4 { id: self.id, column: &self.column, rect: to_array(self.rect), native: self.native.as_ref() }.serialize(serializer), + _ => V4 { id: self.id, column: &self.column, rect: to_array(self.rect), native: self.native.as_ref(), edge: self.edge } + .serialize(serializer), } } } @@ -257,6 +266,7 @@ pub(super) mod floating_serde { rect: Option<[f32; 4]>, native: Option, minimized: bool, + edge: Option, } /// A saved value, or nothing in its place when it does not parse. @@ -281,7 +291,7 @@ pub(super) mod floating_serde { use serde::de::{MapAccess, Visitor}; use std::marker::PhantomData; - const FIELDS: &[&str] = &["id", "column", "root", "groups", "panels", "active", "rect", "native", "minimized"]; + const FIELDS: &[&str] = &["id", "column", "root", "groups", "panels", "active", "rect", "native", "minimized", "edge"]; struct V

(PhantomData

); impl<'de, P: Deserialize<'de>> Visitor<'de> for V

{ @@ -292,8 +302,18 @@ pub(super) mod floating_serde { } fn visit_map>(self, mut map: A) -> Result, A::Error> { - let mut repr = - Repr { id: None, column: None, root: None, groups: None, panels: None, active: 0, rect: None, native: None, minimized: false }; + let mut repr = Repr { + id: None, + column: None, + root: None, + groups: None, + panels: None, + active: 0, + rect: None, + native: None, + minimized: false, + edge: None, + }; while let Some(key) = map.next_key::()? { match key.as_str() { "id" => repr.id = Some(map.next_value()?), @@ -305,6 +325,7 @@ pub(super) mod floating_serde { "rect" => repr.rect = Some(map.next_value()?), "native" => repr.native = map.next_value::>>()?.and_then(Parsed::value), "minimized" => repr.minimized = map.next_value()?, + "edge" => repr.edge = map.next_value()?, _ => { map.next_value::()?; } @@ -321,7 +342,7 @@ pub(super) mod floating_serde { impl

Repr

{ /// The windows the saved window becomes, first to last. fn into_windows(self) -> Result>, E> { - let Repr { id, column, root, groups, panels, active, rect, native, minimized } = self; + let Repr { id, column, root, groups, panels, active, rect, native, minimized, edge } = self; let rect = from_array(rect.ok_or_else(|| E::missing_field("rect"))?); let columns = match (column, root, groups, panels) { (Some(column), None, None, None) => vec![(column, rect)], @@ -349,7 +370,7 @@ pub(super) mod floating_serde { let mut id = Some(id.unwrap_or_else(fresh_window_id)); Ok(columns .into_iter() - .map(|(column, rect)| Floating { id: id.take().unwrap_or_else(fresh_window_id), column, rect, native: native.clone() }) + .map(|(column, rect)| Floating { id: id.take().unwrap_or_else(fresh_window_id), column, rect, native: native.clone(), edge }) .collect()) } } diff --git a/crates/behavior/src/dock/windows.rs b/crates/behavior/src/dock/windows.rs index 51afda822..47246507b 100644 --- a/crates/behavior/src/dock/windows.rs +++ b/crates/behavior/src/dock/windows.rs @@ -263,7 +263,7 @@ impl DocumentWindows { let rect = *rect; match layout.floating.iter().find(|w| w.contains(&panel)) { Some(window) if window.rect == rect => {} - Some(_) => actions.push(Action::MoveFloating { panel, rect }), + Some(_) => actions.push(Action::move_floating(panel, rect)), None => { if !layout.contains(&panel) { actions.push(Action::Open { panel: panel_of(group.id), anchor: None }); diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 112ed9c24..167ff20dc 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -362,7 +362,7 @@ impl Workspace

{ let to = match place { PanelPlace::Dock { .. } => Target::At { anchor, placement: DockPlacement::Column { after: false } }, PanelPlace::Floating { window, .. } => match self.layout.floating.get(window) { - Some(window) => Target::Float { rect: window.rect }, + Some(window) => Target::Float { rect: window.rect, edge: window.edge }, None => continue, }, PanelPlace::Node(_) => Target::At { anchor, placement: DockPlacement::Split(DockSide::Start) }, diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index b7f769b9b..3ed8fc9c9 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -218,6 +218,35 @@ fn column_of(layout: &Layout, panel: u32) -> &Column { layout.column(&layout.place(&panel).unwrap()).unwrap() } +/// A floating window's edge: a save without one loads none, so the area takes the edge nearer the rect as before; a +/// move or a float of a collapsed column that sets one keeps and saves it; collapsing the column clears it; an +/// expanded column floated with one keeps none. +#[test] +fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleared_by_collapsing() { + let saved = r#"{"root": {"Tabs": {"panels": [1], "active": 0}}, "floating": [{"id": 5, "panels": [6], "active": 0, "rect": [100.0, 100.0, 300.0, 400.0]}]}"#; + let mut layout: Layout = serde_json::from_str(saved).unwrap(); + assert_eq!(layout.floating[0].edge, None, "a save without an edge keeps to the edge nearer its rect"); + + layout.apply(Action::set_iconic(6, true)).unwrap(); + layout.apply(Action::move_floating_with_edge(6, window(), Some(DockEdge::End))).unwrap(); + assert_eq!(layout.floating[0].edge, Some(DockEdge::End), "a collapsed window's move sets its edge"); + let back: Layout = serde_json::from_str(&serde_json::to_string(&layout).unwrap()).unwrap(); + assert_eq!(back, layout, "the edge is saved"); + layout.apply(Action::set_iconic(6, false)).unwrap(); + assert_eq!(layout.floating[0].edge, Some(DockEdge::End), "expanding keeps the edge the strip hung from"); + layout.apply(Action::set_iconic(6, true)).unwrap(); + assert_eq!(layout.floating[0].edge, None, "collapsing hangs the strip from the edge nearer the window"); + + let mut moved = columns(); + moved.apply(Action::move_group(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap(); + let floated = moved.floating.iter().find(|window| window.contains(&3)).unwrap(); + assert_eq!(floated.edge, Some(DockEdge::End), "a collapsed column floats at the edge its strip was dropped near"); + let mut moved = columns(); + moved.apply(Action::move_group(2, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap(); + let floated = moved.floating.iter().find(|window| window.contains(&2)).unwrap(); + assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect"); +} + /// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a /// column float in its state; groups joining a column, docked or floating, take that column's state. #[test] @@ -229,8 +258,11 @@ fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides layout.apply(Action::set_iconic(6, false)).unwrap(); assert_eq!(layout.panel_state(&6), PanelState::Front); - for action in [Action::move_column(3, Target::float(window())), Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] - { + for action in [ + Action::move_column(3, Target::float(window())), + Action::move_group(3, Target::float(window())), + Action::move_panel(3, Target::float(window())), + ] { let mut moved = columns(); moved.apply(action.clone()).unwrap(); assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons"); @@ -301,7 +333,8 @@ fn a_panel_that_does_not_collapse_keeps_its_column_expanded() { fn a_panel_that_shares_no_column_moves_only_to_a_column_of_its_own() { let alone = |p: &u32| if *p == 2 { Permissions::ALL.shares_column(false) } else { Permissions::ALL }; let layout = columns(); - let joins = [DockPlacement::tab(None), DockPlacement::Split(DockSide::Center), DockPlacement::group(true, None), DockPlacement::group(false, Some(80.0))]; + let joins = + [DockPlacement::tab(None), DockPlacement::Split(DockSide::Center), DockPlacement::group(true, None), DockPlacement::group(false, Some(80.0))]; for placement in joins { for (panel, anchor) in [(2, 3), (3, 2), (2, 6), (6, 2)] { let mut moved = layout.clone(); diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 9bbe8b4d2..ad747f9a6 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -30,7 +30,7 @@ mod sizing; use bar::panel_names; -pub(super) use bar::{BarRecord, CHEVRON, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar}; +pub(super) use bar::{BarRecord, CHEVRON, bar_band, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar}; use sizing::group_sizes; pub use sizing::{GroupSize, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; @@ -70,31 +70,39 @@ pub enum ColumnArrow { Collapse, /// Switches a stepped column ([`stepped`]) between one and two steps. Holds the steps it shows. Steps(u16), + /// Nothing: the column neither collapses nor has steps. It shows no double arrow, and its menu offers no + /// collapse. + Fixed, } impl ColumnArrow { - /// The arrow of `column`: an expanded stepped column whose panels do not collapse (`collapses` false) switches - /// steps; any other column collapses or expands. + /// The arrow of `column`: an expanded column whose panels do not collapse (`collapses` false) switches steps + /// when it is stepped and has none otherwise; any other column collapses or expands. pub fn of

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, collapses: bool) -> Self { - match stepped(column, spec) { - Some((_, steps)) if !collapses && !column.iconic => ColumnArrow::Steps(steps), - _ => ColumnArrow::Collapse, + if collapses || column.iconic { + return ColumnArrow::Collapse; + } + stepped(column, spec).map_or(ColumnArrow::Fixed, |(_, steps)| ColumnArrow::Steps(steps)) + } + + /// The steps a click gives a stepped column: two from one, else one. `None` for any other arrow. + pub fn switched_steps(self) -> Option { + match self { + ColumnArrow::Steps(steps) => Some(if steps == 1 { 2 } else { 1 }), + ColumnArrow::Collapse | ColumnArrow::Fixed => None, } } - /// The steps a click gives a stepped column: two from one, else one. `None` for an arrow that collapses. - pub fn switched_steps(self) -> Option { - match self { - ColumnArrow::Collapse => None, - ColumnArrow::Steps(steps) => Some(if steps == 1 { 2 } else { 1 }), - } + /// Whether the column shows a double arrow. + pub(super) fn shown(self) -> bool { + self != ColumnArrow::Fixed } /// Whether a click sends the column towards the edge it keeps to: collapsing the `expanded` column, or narrowing a /// stepped one. pub(super) fn towards_edge(self, expanded: bool) -> bool { match self { - ColumnArrow::Collapse => expanded, + ColumnArrow::Collapse | ColumnArrow::Fixed => expanded, ColumnArrow::Steps(steps) => steps > 1, } } @@ -102,8 +110,8 @@ impl ColumnArrow { /// The arrow's name: what a click on it does to the `expanded` or collapsed column. pub(super) fn name(self, words: &DockWords, expanded: bool) -> Label { let word = match self { - ColumnArrow::Collapse if expanded => &words.collapse_column, - ColumnArrow::Collapse => &words.expand_column, + ColumnArrow::Collapse | ColumnArrow::Fixed if expanded => &words.collapse_column, + ColumnArrow::Collapse | ColumnArrow::Fixed => &words.expand_column, ColumnArrow::Steps(1) => &words.two_steps, ColumnArrow::Steps(_) => &words.one_step, }; @@ -236,7 +244,7 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { at: Option, mut view: impl FnMut(&Group

, Rect, &mut Ui, &mut BodyCx<'_>) + 'a, ) -> DockColumnOutput

{ - let (column, spec, auto_collapse, edge, own) = (self.column, self.spec, self.auto_collapse, self.edge, self.bar); + let (column, spec, auto_collapse, edge, own, arrow) = (self.column, self.spec, self.auto_collapse, self.edge, self.bar, self.arrow); let mut bar = BarRecord::default(); let shown = &mut bar; let body = move |ui: &mut Ui, body: &mut BodyCx<'_>| { @@ -252,7 +260,8 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { if own == ColumnBar::Own && let Some(grip) = column_grip(column, spec, body) { - *shown = show_bar(ui, body, plan.bar, true, auto_collapse, edge, grip); + let band = bar_band(ui, plan.bar, edge); + *shown = show_bar(ui, body, band, true, auto_collapse, arrow, grip); } for (group, rect) in column.groups.iter().zip(&plan.groups) { view(group, *rect, ui, body); @@ -393,7 +402,7 @@ impl Component for DockColumn<'_, P> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let sizes = cx.style.sizes; let plan = column_plan(self.column, self.spec, rect, self.bar, &sizes, |_, _| None); - if self.bar == ColumnBar::Own { + if self.bar == ColumnBar::Own && self.arrow.shown() { let (chevron, _) = bar_slots(plan.bar, self.edge, cx.flow.is_rtl()); let name = self.arrow.name(&cx.words::(), true); let _ = cx.part(CHEVRON, chevron).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(name); @@ -412,7 +421,7 @@ impl Component for DockColumn<'_, P> { let sizes = cx.style.sizes; let (rect, rtl, ctx) = (cx.rect, cx.flow.is_rtl(), cx.core.ctx.clone()); let own = self.bar == ColumnBar::Own; - self.collapse = own && cx.part_activated(CHEVRON).is_some(); + self.collapse = own && self.arrow.shown() && cx.part_activated(CHEVRON).is_some(); let Some(base) = self.laid.take() else { return }; let mut plan = column_plan(self.column, self.spec, rect, self.bar, &sizes, |key, divider| divider::pointer(cx, DIVIDER, key, divider)); let dividers = base.dividers(rect, sizes.reach); @@ -449,7 +458,9 @@ impl Component for DockColumn<'_, P> { ui.draw().surface(cx.rect, SurfaceKind::Panel, Corners::All); if self.bar == ColumnBar::Own { ui.draw().surface(plan.bar, SurfaceKind::Background, Corners::None); - paint_chevron(ui, self.edge, self.arrow, true, cx.flow.is_rtl(), &cx.words::()); + if self.arrow.shown() { + paint_chevron(ui, self.edge, self.arrow, true, cx.flow.is_rtl(), &cx.words::()); + } } } @@ -482,7 +493,9 @@ impl Component for DockColumn<'_, P> { if self.bar == ColumnBar::Own { let edge = self.edge_divider(cx.rect, &sizes); divider::describe(access, EDGE, 0, &edge, words.resize.as_str(), sizes.step); - describe_chevron(access, &self.arrow.name(&words, true)); + if self.arrow.shown() { + describe_chevron(access, &self.arrow.name(&words, true)); + } } } diff --git a/crates/ui-panels/src/docking/dock_column/bar.rs b/crates/ui-panels/src/docking/dock_column/bar.rs index ac4976c02..7a76c4b41 100644 --- a/crates/ui-panels/src/docking/dock_column/bar.rs +++ b/crates/ui-panels/src/docking/dock_column/bar.rs @@ -70,23 +70,27 @@ pub(in crate::docking) fn describe_chevron(access: &mut Access, name: &Label) { access.node(CHEVRON, Role::BUTTON).name = Name::Text(name.as_str().to_owned()); } -/// Shows the band of the column bar `bar` and the column menu: a drag on `grip` moves the column, a double click -/// collapses or expands it, and a context request opens the column menu. The chevron at the bar's outer end is the -/// column's own part. Returns what the user did. +/// The band of the column bar `bar` of a column that keeps to `edge`: the bar beside the chevron's slot. +pub(in crate::docking) fn bar_band(ui: &Ui, bar: Rect, edge: DockEdge) -> Rect { + bar_slots(bar, edge, crate::runtime::env::Env::of(ui).direction.is_rtl()).1 +} + +/// Shows `band`, the band of a column bar ([`bar_band`]), and the column menu: a drag on `grip` moves the column, a double click +/// collapses or expands it, and a context request opens the column menu, which offers the collapse only where the +/// column's double arrow (`arrow`) collapses it. The chevron at the bar's outer end is the column's own part. Returns +/// what the user did. pub(in crate::docking) fn show_bar( ui: &mut Ui, body: &mut BodyCx<'_>, - bar: Rect, + band: Rect, expanded: bool, auto_collapse: bool, - edge: DockEdge, + arrow: ColumnArrow, grip: GroupGrip

, ) -> BarRecord { let words = body.words::(); let menu_words = body.words::(); - let rtl = crate::runtime::env::Env::of(ui).direction.is_rtl(); let toggle = ColumnArrow::Collapse.name(&words, expanded); - let (_, band) = bar_slots(bar, edge, rtl); let mut record = BarRecord::default(); if band.width() <= 0.0 { return record; @@ -95,13 +99,11 @@ pub(in crate::docking) fn show_bar( if held.double_pressed { record.iconic = Some(expanded); } - let rows = vec![ - PanelRow::Item(crate::contract::Entry::new(GroupItem::CollapseToIcons, toggle)), - PanelRow::Item( - crate::contract::Entry::new(GroupItem::AutoCollapse, Label::from(menu_words.panel_auto_collapse.as_str().to_owned())) - .checked(auto_collapse), - ), - ]; + let collapse = (arrow == ColumnArrow::Collapse).then(|| PanelRow::Item(crate::contract::Entry::new(GroupItem::CollapseToIcons, toggle))); + let auto = PanelRow::Item( + crate::contract::Entry::new(GroupItem::AutoCollapse, Label::from(menu_words.panel_auto_collapse.as_str().to_owned())).checked(auto_collapse), + ); + let rows: Vec<_> = collapse.into_iter().chain([auto]).collect(); let picked = Menu::new(Label::from(words.panels.as_str().to_owned())) .opened_by(&held.response, Trigger::Context) .show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked); diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 6ca845a26..4bd9beafb 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -4,9 +4,9 @@ //! the dock model's [`Action`], naming groups by an anchor panel. [`DockDropTarget`] runs the same resolution inside //! `DropTarget::accept`, refuses what the model would refuse, so the drag session arbitrates between docks and //! windows, and returns the mark the ghost paints. Every drag of a group, a window or a column starts through -//! [`start_group_drag`]. +//! [`start_group_drag`], or [`start_icon_drag`] out of a collapsed column. -use super::{DockSpot, DockTargets, FloatSpace, GroupDrag, PanelDrag, PanelKey}; +use super::{DockSpot, DockTargets, FloatSpace, GroupDrag, PanelDrag, PanelKey, WindowColumn}; use crate::contract::{Component, Cx, DropMark, DropOperation, DropTarget, Pointer as _}; use crate::runtime::drag::{self, DragPreview}; use crate::runtime::env::{AppValues, EnvValue, EnvView, Label}; @@ -49,6 +49,11 @@ pub trait DockDrag

{ fn source(&self) -> Option { None } + /// The size of the icons of a collapsed column the drag started on, whose float lands collapsed with its strip + /// under the pointer; `None` for any other drag. + fn strip(&self) -> Option { + None + } } impl DockDrag

for PanelDrag { @@ -69,6 +74,10 @@ impl DockDrag

for GroupDrag

{ fn source(&self) -> Option { self.source } + + fn strip(&self) -> Option { + self.strip + } } /// What a drop does and what the ghost paints for it. @@ -214,15 +223,40 @@ fn spot_action( /// The action that floats `unit` in a window under `at`, inside the area of `space`, at [`FloatSpace::size_of`] with /// `source` the size the unit had where the drag started, and the outline the ghost paints for it. The pointer sits in /// the middle of the window's title row. -pub fn float_drop(unit: &DragUnit

, space: &FloatSpace

, at: Pos2, source: Option) -> DockDropped

{ +/// +/// A unit dragged out of a collapsed column (`strip`, the size of the icons the drag started on) floats collapsed: +/// its strip, under the title row, lands with the pointer in the middle of the title row above it, the window keeps +/// to the edge of the area nearer the strip, and its rect shows the strip there ([`WindowColumn::around_strip`]); +/// the outline is the strip's. `rtl` is the layout direction. +pub fn float_drop( + unit: &DragUnit

, + space: &FloatSpace

, + at: Pos2, + source: Option, + strip: Option, + rtl: bool, +) -> DockDropped

{ let size = space.size_of(unit, source).min(space.area.size()); - let min = (at - Vec2::new(size.x * 0.5, space.title_row * 0.5)).min(space.area.max - size).max(space.area.min); - let rect = Rect::from_min_size(min, size); - let action = match unit { - DragUnit::Panel(panel) => Action::float(panel.clone(), rect), - _ => to_target(unit, Target::float(rect)), + let under = |size: Vec2| { + let min = (at - Vec2::new(size.x * 0.5, space.title_row * 0.5)).min(space.area.max - size).max(space.area.min); + Rect::from_min_size(min, size) }; - DockDropped { action, mark: DropMark::Into(rect) } + let (rect, edge, mark) = match strip.filter(|_| !matches!(unit, DragUnit::Window(_))) { + Some(strip) => { + let shown = under((strip + Vec2::new(0.0, space.title_row)).min(space.area.size())); + let (rect, edge) = WindowColumn::around_strip(shown, size, space.area, rtl); + (rect, Some(edge), shown) + } + None => { + let rect = under(size); + (rect, None, rect) + } + }; + let action = match unit { + DragUnit::Panel(panel) if edge.is_none() => Action::float(panel.clone(), rect), + _ => to_target(unit, Target::float_with_edge(rect, edge)), + }; + DockDropped { action, mark: DropMark::Into(mark) } } /// The action a release of `drag` at `at` makes in the dock `dock`, by the spots of the previous pass; `None` where @@ -282,7 +316,7 @@ impl DockDropTarget<'_, P> { let unit = drag.unit(self.layout)?; let window = matches!(unit, DragUnit::Window(_)); if pointer::frame(self.ctx).mods.cmd { - return if window { None } else { self.float(&unit, at, drag.source()) }; + return if window { None } else { self.float(&unit, at, drag.source(), drag.strip()) }; } if window && !self.title_bar_docks { return None; @@ -299,13 +333,13 @@ impl DockDropTarget<'_, P> { if window || !self.float_on_empty { return None; } - self.float(&unit, at, drag.source()) + self.float(&unit, at, drag.source(), drag.strip()) } /// The unit floated under `at`, when it may float and the model takes it; `source` is its size where the drag - /// started. - fn float(&self, unit: &DragUnit

, at: Pos2, source: Option) -> Option> { - let floated = float_drop(unit, self.space?, at, source); + /// started, `strip` the size of the icons it started on ([`float_drop`]). + fn float(&self, unit: &DragUnit

, at: Pos2, source: Option, strip: Option) -> Option> { + let floated = float_drop(unit, self.space?, at, source, strip, self.rtl); ((self.permissions)(unit.lead()).floatable && takes(self.layout, &floated.action, self.permissions)).then_some(floated) } } @@ -388,7 +422,19 @@ where None => DragPreview::None, }; let started = started(&cx.env); - cx.start_drag(GroupDrag { unit, active, source, started }, preview); + cx.start_drag(GroupDrag { unit, active, source, strip: None, started }, preview); +} + +/// Starts the drag of `unit` out of a collapsed column, from its icons of size `strip`, whose shown panel is +/// `active`: the ghost is a frame of that size with `label`, and a float of the unit lands collapsed with its strip +/// under the pointer ([`float_drop`]). +pub fn start_icon_drag(cx: &mut Cx<'_, C>, unit: DragUnit

, active: PanelKey, strip: Vec2, label: Label) +where + P: Clone + Send + Sync + 'static, + C: Component, +{ + let started = started(&cx.env); + cx.start_drag(GroupDrag { unit, active, source: None, strip: Some(strip), started }, DragPreview::frame(strip, Some(label))); } /// Ends a running tab or group drag that started on `shown`'s dock under another revision: another arrangement diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index bbbfd5857..38a7c7fe2 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -49,7 +49,8 @@ pub struct FloatingGroupStyle { #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct WindowColumn { - /// The edge of the float area, in reading order, that the window keeps to: the one nearer the window. + /// The edge of the float area, in reading order, that the window keeps to: the dock model's `Floating::edge`, + /// else the one nearer the window. pub edge: DockEdge, /// The size of the collapsed column under the title row; `None` while the column is expanded. pub collapsed: Option, @@ -91,23 +92,29 @@ impl WindowColumn { if at_left != rtl { DockEdge::Start } else { DockEdge::End } } - /// The rect a collapsed window keeps when a move that showed it against `edge` ends at `rect`, so its strip - /// stays where it was dropped once the window keeps to the edge nearer it again: `rect` while that edge is still - /// `edge`; else `rect` shifted so the strip, against the other edge, is where it was, when the other edge is the - /// nearer one of the shifted rect. A strip dropped near the middle of `bounds`, where neither holds, keeps - /// `rect`. An expanded window keeps `rect`. - pub fn anchored(self, rect: Rect, bounds: Rect, rtl: bool) -> Rect { - let Some(size) = self.collapsed else { return rect }; - if Self::nearer_edge(rect, bounds, rtl) == self.edge { - return rect; - } - let at_left = |edge: DockEdge| (edge == DockEdge::Start) != rtl; - let strip = if at_left(self.edge) { rect.left() } else { rect.right() - size.x }; - let other = if self.edge == DockEdge::Start { DockEdge::End } else { DockEdge::Start }; - let left = if at_left(other) { strip } else { strip + size.x - rect.width() }; - let shifted = Rect::from_min_size(Pos2::new(left, rect.top()), rect.size()); - if Self::nearer_edge(shifted, bounds, rtl) == other { shifted } else { rect } + /// Where a window whose move ends at `rect` keeps to, and the rect it keeps: for a collapsed window, the edge of + /// `bounds` nearer its strip as it was dropped, shown against [`Self::edge`], and the rect that shows the strip + /// at the same place against that edge ([`Self::around_strip`]); an expanded window keeps `rect`, and the edge + /// nearer it (`None`). + pub fn dropped(self, rect: Rect, bounds: Rect, rtl: bool) -> (Rect, Option) { + let Some(size) = self.collapsed else { return (rect, None) }; + let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; + let (rect, edge) = Self::around_strip(Rect::from_min_size(Pos2::new(left, rect.top()), size), rect.size(), bounds, rtl); + (rect, Some(edge)) } + + /// The edge of `bounds` nearer the strip of a collapsed column at `strip`, whose top is its window's, and the + /// window rect of `size` that shows the strip at `strip` against that edge. + pub fn around_strip(strip: Rect, size: Vec2, bounds: Rect, rtl: bool) -> (Rect, DockEdge) { + let edge = Self::nearer_edge(strip, bounds, rtl); + let left = if at_left(edge, rtl) { strip.left() } else { strip.right() - size.x }; + (Rect::from_min_size(Pos2::new(left, strip.top()), size), edge) + } +} + +/// Whether `edge`, in reading order, is the left one of the screen. +fn at_left(edge: DockEdge, rtl: bool) -> bool { + (edge == DockEdge::Start) != rtl } /// What a floating group reports in a pass. @@ -343,14 +350,14 @@ impl<'a> FloatingGroup<'a> { fn collapsed_rect(&self) -> Option { let column = self.column?; let size = column.collapsed? + Vec2::new(0.0, self.header); - let at_left = (column.edge == DockEdge::Start) != self.rtl; - let left = if at_left { self.rect.left() } else { self.rect.right() - size.x }; + let left = if at_left(column.edge, self.rtl) { self.rect.left() } else { self.rect.right() - size.x }; Some(Rect::from_min_size(Pos2::new(left, self.rect.top()), size)) } /// The double arrow's square at the end of the title row the window keeps to. fn chevron_edge(&self) -> Option { - self.column.map(|column| if column.edge == DockEdge::End { HeaderEdge::End } else { HeaderEdge::Start }) + let column = self.column.filter(|column| column.arrow.shown())?; + Some(if column.edge == DockEdge::End { HeaderEdge::End } else { HeaderEdge::Start }) } } diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index d0e886a3d..14e855c33 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -2,7 +2,7 @@ //! button, over the body of the active panel. The band and the button are the group's own parts. use super::commands::DockCommands; -use super::drop::{self, DragUnit, start_group_drag}; +use super::drop::{self, DragUnit, start_group_drag, start_icon_drag}; use super::targets::{DockSizes, DockSpot, DockTargets, ZoneRule}; use super::words::DockWords; use super::{PanelDrag, PanelKey, PanelTitle}; @@ -68,6 +68,10 @@ pub struct GroupGrip { /// A drag on the grip drags the unit. #[prop] movable: bool, + /// The grip is a collapsed column's: its drag is an icon drag ([`start_icon_drag`]) whose strip is the ghost's + /// extent, so a float of the unit lands collapsed under the pointer. + #[prop] + icons: bool, double: bool, started: bool, } @@ -75,7 +79,7 @@ pub struct GroupGrip { impl GroupGrip

{ /// The grip of `unit`, whose shown panel is `active`. pub fn new(unit: DragUnit

, active: PanelKey) -> Self { - GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, double: false, started: false } + GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, icons: false, double: false, started: false } } } @@ -102,9 +106,11 @@ impl Component for GroupGrip

{ fn update(&mut self, cx: &mut Cx<'_, Self>) { self.double = cx.press().double_pressed(); if self.movable && matches!(cx.press().phase, PressPhase::DragStart { .. }) { - // The ghost's extent is the group's own. - let source = self.ghost.as_ref().map(|(size, _)| *size); - start_group_drag(cx, self.unit.clone(), self.active, source, self.ghost.clone()); + match self.ghost.clone() { + Some((strip, label)) if self.icons => start_icon_drag(cx, self.unit.clone(), self.active, strip, label), + // The ghost's extent is the group's own. + ghost => start_group_drag(cx, self.unit.clone(), self.active, ghost.as_ref().map(|(size, _)| *size), ghost), + } self.started = true; } } diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index b08691473..8e375d9d3 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -2,9 +2,9 @@ use super::divider::{self, Divider, Drag}; use super::dock_column::{ - BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, + BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, }; -use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_group_drag}; +use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; use crate::contract::{ @@ -463,7 +463,7 @@ impl Component for IconicColumn<'_, P> { { let shown = lead.active_panel().unwrap_or(anchor); let label = Label::from((self.spec)(shown).label.as_str().to_owned()); - start_group_drag(cx, DragUnit::Group(anchor.clone()), PanelKey::of(shown), None, Some((extent.size(), label))); + start_icon_drag(cx, DragUnit::Group(anchor.clone()), PanelKey::of(shown), extent.size(), label); began = true; } } @@ -473,7 +473,7 @@ impl Component for IconicColumn<'_, P> { && let Some(panel) = self.panel(*group, *panel) { let label = Label::from((self.spec)(panel).label.as_str().to_owned()); - start_group_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), None, Some((cell.size(), label))); + start_icon_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), cell.size(), label); began = true; } } @@ -699,7 +699,8 @@ impl Container for IconicColumn<'_, P> { return; } if let Some(grip) = column_grip(self.column, self.spec, cx) { - self.record = show_bar(ui, cx, self.bar_rect, false, self.auto_collapse, self.edge, grip); + let band = bar_band(ui, self.bar_rect, self.edge); + self.record = show_bar(ui, cx, band, false, self.auto_collapse, ColumnArrow::Collapse, grip.icons(true)); } } } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 8d94f81a7..f04de479f 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -32,7 +32,7 @@ pub mod native; pub use config::{DockConfig, DockSides}; #[doc(hidden)] pub use drop::{Arrangement, end_replaced_drags}; -pub use drop::{DockDrag, DockDropTarget, DockDropped, DragUnit, float_drop, resolve_drop, start_group_drag}; +pub use drop::{DockDrag, DockDropTarget, DockDropped, DragUnit, float_drop, resolve_drop, start_group_drag, start_icon_drag}; pub use event::{DockEvent, FloatSpace, HidePanels}; pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook}; @@ -56,8 +56,8 @@ mod flyout; mod iconic; pub use dock_column::{ - ColumnArrow, ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, stepped, - width_bounds, + ColumnArrow, ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, + stepped, width_bounds, }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes}; diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 294ba3563..0e17258d2 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -434,7 +434,8 @@ impl DockTargets

{ } /// What a drag of a whole group, window or column carries, beside `PanelDrag` for one tab. Every such drag starts -/// through [`start_group_drag`](super::start_group_drag), so the type is `non_exhaustive` and only the crate builds it. +/// through [`start_group_drag`](super::start_group_drag) or [`start_icon_drag`](super::start_icon_drag), so the type +/// is `non_exhaustive` and only the crate builds it. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct GroupDrag

{ @@ -443,6 +444,9 @@ pub struct GroupDrag

{ /// The size of the group, window or column where the drag started, which a float of it takes; `None` where /// that size is not the unit's own (an iconic column's cells). pub source: Option, + /// The size of the icons the drag started on, for a unit dragged out of a collapsed column + /// ([`start_icon_drag`](super::start_icon_drag)): a float of it lands collapsed, its strip under the pointer. + pub strip: Option, /// The panel the unit shows, for the drag's preview. pub active: PanelKey, /// The arrangement the drag started on, when it started in a dock area. diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index efdd50105..6858d28e1 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -582,12 +582,22 @@ fn show_area( let moved = if floating { pass.windows(ui, body, &open, started) } else { None }; let mut report = pass.report; let label: Arc = Arc::from(body.words::().move_window.as_str()); - if let Some((anchor, change)) = moved - && let Some(event) = window_edit(ctx, current, rights, &mut memory.moving, &anchor, &change, label) + if let Some((anchor, change, edge)) = moved + && let Some(event) = window_edit( + ctx, + current, + rights, + &mut memory.moving, + change.phase, + Action::move_floating_with_edge(anchor.clone(), change.rect, edge), + label, + ) { - let rect_in = |layout: &Layout

| layout.floating.iter().find(|window| window.contains(&anchor)).map(|window| window.rect); - if let Some(rect) = event.landed().and_then(|landed| rect_in(&landed.layout)).filter(|rect| Some(*rect) != rect_in(¤t.layout)) { - geometry.push(Action::move_floating(anchor.clone(), rect)); + let place_in = |layout: &Layout

| layout.floating.iter().find(|window| window.contains(&anchor)).map(|window| (window.rect, window.edge)); + if let Some((rect, edge)) = + event.landed().and_then(|landed| place_in(&landed.layout)).filter(|place| Some(*place) != place_in(¤t.layout)) + { + geometry.push(Action::move_floating_with_edge(anchor.clone(), rect, edge)); } edit.push(event); } @@ -873,7 +883,9 @@ impl Pass<'_, P> { && scene.permissions(panel).floatable && (scene.config.float_on_empty_drop || !ui.ctx().content_rect().contains(*pointer)) }); - let torn = torn.map(|(panel, pointer)| float_drop(&DragUnit::Panel(panel.clone()), scene.space, pointer, Some(fitted(ui, panel))).action); + let torn = torn.map(|(panel, pointer)| { + float_drop(&DragUnit::Panel(panel.clone()), scene.space, pointer, Some(fitted(ui, panel)), None, scene.rtl).action + }); if let Some(panel) = output.picked.and_then(|key| scene.panel(key)) { self.report.actions.push(Action::activate(panel.clone())); self.report.picked = Some(panel.clone()); @@ -954,11 +966,15 @@ impl Pass<'_, P> { } /// What a click on the double arrow of `column`, whose first panel is `first`, asks for when it reports - /// `iconic`: the steps it switches to, or the collapse or expansion of the column. - fn arrow(&self, column: &Column

, first: &P, iconic: bool) -> Action

{ - match self.arrow_of(column).switched_steps() { - Some(steps) => Action::set_column_steps(first.clone(), steps), - None => Action::set_iconic(first.clone(), iconic), + /// `iconic`: the steps it switches to, or the collapse or expansion of the column; nothing for a column with no + /// double arrow, whose bar's double click reports the same. + fn arrow(&self, column: &Column

, first: &P, iconic: bool) -> Option> { + match self.arrow_of(column) { + ColumnArrow::Fixed => None, + arrow => Some(match arrow.switched_steps() { + Some(steps) => Action::set_column_steps(first.clone(), steps), + None => Action::set_iconic(first.clone(), iconic), + }), } } @@ -1002,7 +1018,7 @@ impl Pass<'_, P> { let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { return }; if let Some(iconic) = work.iconic { let action = self.arrow(column, first, iconic); - self.report.actions.push(action); + self.report.actions.extend(action); } if let Some(item) = work.picked { self.pick(first, item); @@ -1047,18 +1063,25 @@ impl Pass<'_, P> { /// its panels allow one. A window takes the drops over it on its own layer, from the spots its column registers in /// its own registry. `open` is the open flyout, which a collapsed window's icons share with the docks'. `started` /// is the layout a running move or resize of a window began on. Returns the move or resize of a window in the app - /// window this pass, which the area reports as a workspace edit. + /// window this pass, with the edge the window keeps to after it, which the area reports as a workspace edit. /// - /// A window keeps to the edge of the float area nearer it: its title row's double arrow sits at that end, and its - /// collapsed column shows against that edge of its rect. A move or resize keeps the edge the window had when it - /// began, so nothing jumps while the window crosses the middle; a collapsed window's move ends with the rect - /// that keeps its strip where it was dropped ([`WindowColumn::anchored`]). + /// A window keeps to its edge of the float area (`Floating::edge`, else the one nearer it): its title row's + /// double arrow sits at that end, and its collapsed column shows against that edge of its rect. A move or resize + /// keeps the edge the window had when it began, so nothing jumps while the window crosses the middle. A collapsed + /// window's move ends at the edge nearer the strip where it was dropped, with the rect that shows the strip there + /// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect. /// /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps /// its right edge. - fn windows(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, open: &Option

, started: Option<&Layout

>) -> Option<(P, PlacementChange)> { + fn windows( + &mut self, + ui: &mut Ui, + body: &mut BodyCx<'_>, + open: &Option

, + started: Option<&Layout

>, + ) -> Option<(P, PlacementChange, Option)> { let scene = self.scene; let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); @@ -1093,9 +1116,9 @@ impl Pass<'_, P> { let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated), &active); let mut commands = Vec::new(); let spec = scene.spec(&active); - let began = - started.and_then(|layout| layout.floating.iter().find(|began| began.id == window.id)).map_or(opening.rect, |began| began.rect); - let edge = WindowColumn::nearer_edge(began, scene.bounds, scene.rtl); + let began = started.and_then(|layout| layout.floating.iter().find(|began| began.id == window.id)); + let (began_rect, began_edge) = began.map_or((opening.rect, window.edge), |began| (began.rect, began.edge)); + let edge = began_edge.unwrap_or_else(|| WindowColumn::nearer_edge(began_rect, scene.bounds, scene.rtl)); let width = scene.sizes.expanded_width(&window.column, &spec_of); let shape = if window.column.iconic { let size = Vec2::new(scene.sizes.width(&window.column, &spec_of), IconicSizes::of(&ctx).icons_height(&window.column)); @@ -1151,8 +1174,10 @@ impl Pass<'_, P> { self.report.actions.extend(native::reported(&ctx, window, viewport)); } } else if let Some(mut change) = output.placed { + // A collapsed window keeps the edge its move began with until the move ends where its strip was dropped. + let mut keeps = shape.collapsed.map(|_| edge); if change.phase == GesturePhase::Commit { - change.rect = shape.anchored(change.rect, scene.bounds, scene.rtl); + (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); } if !matches!(change.kind, PlacementKind::Move) && let Some(fitted) = shape.fitted @@ -1175,17 +1200,24 @@ impl Pass<'_, P> { self.report.actions.push(Action::set_column_steps(anchor.clone(), to)); } // The window keeps its place and its steps set its size. A grip on the left keeps the right edge - // where it is, so the window grows or shrinks to the left. + // where it is, and one on the top the bottom edge, so the window grows or shrinks that way. let left = match change.kind { PlacementKind::Size(ResizeEdge::Left | ResizeEdge::TopLeft | ResizeEdge::BottomLeft) => change.rect.right() - grid.width(to), _ => change.rect.left(), }; - change.rect = Rect::from_min_size(Pos2::new(left, change.rect.top()), opening.rect.size()); + let top = match change.kind { + PlacementKind::Size(ResizeEdge::Top | ResizeEdge::TopLeft | ResizeEdge::TopRight) => { + let content = self.stepped_height(ui, body, column, grid.width(to), true).unwrap_or(0.0); + change.rect.bottom() - scene.sizes.strip - content + } + _ => change.rect.top(), + }; + change.rect = Rect::from_min_size(Pos2::new(left, top), opening.rect.size()); } if change.phase == GesturePhase::Commit { self.report.events.push(DockEvent::FloatPlaced { panel: anchor.clone(), rect: change.rect }); } - moved = Some((anchor.clone(), change)); + moved = Some((anchor.clone(), change, keeps)); } match output.action { // The OS close of a native window arrives here as well, also where the title row offers no Close. @@ -1211,7 +1243,7 @@ impl Pass<'_, P> { // The title row is the column's bar: its double arrow collapses or expands the column. if let Some(iconic) = output.iconic { let action = self.arrow(&window.column, &anchor, iconic); - self.report.actions.push(action); + self.report.actions.extend(action); } } moved @@ -1238,29 +1270,30 @@ fn split_changes

(from: &Node

, to: &Node

) -> Vec<(Vec, SplitSize)> out } -/// The workspace edit of a floating window's move or resize: the gesture runs from the window's `Begin` to its -/// `Commit`, so one drag is one undo step. `moving` holds the gesture and the workspace it began on; `rights` are the -/// panels' permissions with the lock applied, which refuse the move of a locked workspace. +/// The workspace edit of a floating window's move or resize, the step `phase` of a gesture that `action` +/// (`Action::MoveFloating`) places the window by: the gesture runs from the window's `Begin` to its `Commit`, so one +/// drag is one undo step. `moving` holds the gesture and the workspace it began on; `rights` are the panels' +/// permissions with the lock applied, which refuse the move of a locked workspace. fn window_edit( ctx: &Context, current: &Workspace

, rights: &HashMap, moving: &mut Option>, - anchor: &P, - change: &PlacementChange, + phase: GesturePhase, + action: Action

, label: Arc, ) -> Option>> { let moved = || { let mut next = current.clone(); let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL); - next.apply(Action::move_floating(anchor.clone(), change.rect), false, policy).ok().map(|_| next) + next.apply(action.clone(), false, policy).ok().map(|_| next) }; let begin = |moving: &mut Option>| { let id = crate::runtime::edit::next_gesture_id(ctx); *moving = Some(Moving { id, before: current.clone() }); EditEvent::begin(id, Mixed::Same(current.clone()), Arc::clone(&label), None) }; - match change.phase { + match phase { GesturePhase::Begin => Some(begin(moving)), GesturePhase::Update => match moving.as_ref() { Some(held) => Some(EditEvent::update(held.id, moved()?)), diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 470562297..d335a4bd6 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -203,10 +203,8 @@ fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_an } } -/// A drag of a floating stepped window's left edge widens it in whole steps to the left: its right edge stays. -#[trial] -fn a_floating_stepped_windows_left_edge_drag_keeps_its_right_edge() { - let at = Rect::from_min_size(Pos2::new(200.0, 80.0), Vec2::new(100.0, 100.0)); +/// A dock area showing only a floating window at `at` with the toolbar in a column of one step. +fn floating_tools(at: Rect) -> (Fixture, Rc>>) { let window = Floating::new(Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1), at); let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(None, vec![window])))); let held = Rc::clone(&workspace); @@ -216,13 +214,33 @@ fn a_floating_stepped_windows_left_edge_drag_keeps_its_right_edge() { *held.borrow_mut() = workspace; }); fixture.settle(); - let shown = |fixture: &Fixture| fixture.by_role(Role::TAB_PANEL).first().map(|group| group.rect).expect("the window shows its group"); - let before = shown(&fixture); + (fixture, workspace) +} + +/// The rect of the floating toolbar's group. +fn shown_tools(fixture: &Fixture) -> Rect { + fixture.by_role(Role::TAB_PANEL).first().map(|group| group.rect).expect("the window shows its group") +} + +/// A floating stepped window keeps the edge opposite the grip a drag holds: a drag of its left edge widens it in +/// whole steps to the left with its right edge where it was, and a drag of its top edge keeps its bottom edge. +#[trial] +fn a_floating_stepped_windows_left_and_top_edge_drags_keep_the_opposite_edge() { + let at = Rect::from_min_size(Pos2::new(200.0, 80.0), Vec2::new(100.0, 100.0)); + let (mut fixture, workspace) = floating_tools(at); + let before = shown_tools(&fixture); // The left grip straddles the window's left edge, which is its rect's. fixture.drag_at(Pos2::new(at.left(), before.center().y), Vec2::new(-1.5 * grid().step, 0.0)).settle(); - let after = shown(&fixture); + let after = shown_tools(&fixture); let steps = workspace.borrow().layout.floating[0].column.steps; assert!(steps.is_some_and(|steps| steps > 1), "the drag widened the window by whole steps: {steps:?}"); assert!((after.right() - before.right()).abs() <= 1.5, "the right edge stays: {before:?}, then {after:?}"); assert!(after.left() < before.left(), "the window grew to the left: {before:?}, then {after:?}"); + + // Raised by its top edge, the content still fits one step: the window keeps its size and its bottom edge. + let (mut fixture, _) = floating_tools(at); + let before = shown_tools(&fixture); + fixture.drag_at(Pos2::new(before.center().x, at.top()), Vec2::new(0.0, -30.0)).settle(); + let after = shown_tools(&fixture); + assert!((after.bottom() - before.bottom()).abs() <= 1.5, "the bottom edge stays: {before:?}, then {after:?}"); } diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index c0e27cb9e..0e4fde61a 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -1,7 +1,7 @@ //! Floating windows of a `DockArea`: a drop over a window lands on it. use craft_behavior::Axis; -use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, SplitSize, Workspace}; +use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; use craft_ui::contract::{Bind, BodyCx, Role, Show as _, ShowContainer as _}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockPanels, GroupDrag, PanelSpec, request_actions}; @@ -327,21 +327,57 @@ fn button_rect(bed: &Bed, name: &str) -> Option { } /// A collapsed window keeps to the edge it kept when its move began: dragged across the middle of the float area, -/// its strip stays under the pointer, and it stays where it is dropped. +/// its strip stays under the pointer, and it stays where it is dropped. So does a strip dropped in the middle band, +/// where the strip is nearer one edge and its window's expanded rect the other. #[trial] fn a_collapsed_window_dragged_across_the_middle_keeps_its_strip_under_the_pointer() { - let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); - let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); - // The title row's band, clear of the double arrow at the end the window keeps to. - let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); - let by = Vec2::new(-250.0, 0.0); - bed.fixture.drag_hold_at(band, by); - let held = button_rect(&bed, &title(WINDOW)).expect("the icon shows while the window moves"); - assert!((held.left() - (icon.left() + by.x)).abs() <= SLACK, "the strip follows the pointer across the middle: {icon:?}, then {held:?}"); - bed.fixture.release_at(band + by).settle(); - let dropped = button_rect(&bed, &title(WINDOW)).expect("the icon shows after the move"); - assert!((dropped.left() - held.left()).abs() <= SLACK, "the strip stays where it was dropped: {held:?}, then {dropped:?}"); - assert!(bed.workspace.borrow().layout.floating[0].column.iconic, "the window stays collapsed"); + // Across the middle; then to the strip's centre just past the middle of the 400-point room, on the end side, + // while the expanded rect hanging from it reaches past the middle to the start side. + for middle in [None, Some(210.0)] { + let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); + let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); + let by = Vec2::new(middle.map_or(-250.0, |x: f32| x - icon.center().x), 0.0); + // The title row's band, clear of the double arrow at the end the window keeps to. + let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); + bed.fixture.drag_hold_at(band, by); + let held = button_rect(&bed, &title(WINDOW)).expect("the icon shows while the window moves"); + assert!((held.left() - (icon.left() + by.x)).abs() <= SLACK, "by {by:?}: the strip follows the pointer: {icon:?}, then {held:?}"); + bed.fixture.release_at(band + by).settle(); + bed.fixture.idle(3); + let dropped = button_rect(&bed, &title(WINDOW)).expect("the icon shows after the move"); + assert!((dropped.left() - held.left()).abs() <= SLACK, "by {by:?}: the strip stays where it was dropped: {held:?}, then {dropped:?}"); + let window = bed.workspace.borrow().layout.floating[0].clone(); + assert!(window.column.iconic && window.edge.is_some(), "by {by:?}: the window stays collapsed and keeps its edge: {window:?}"); + } +} + +/// An icon dragged out of a docked collapsed column and floated in the middle band of the float area floats +/// collapsed, its strip under the pointer, and stays there. +#[trial] +fn an_icon_floated_in_the_middle_band_lands_collapsed_under_the_pointer() { + let mut column = Column::new(vec![Group::new(vec![WINDOW], 0)]); + column.iconic = true; + let root = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![DOCKED], 0), Node::dock(DockEdge::End, vec![column])); + let mut bed = bed(Layout::new(Some(root), Vec::new()), |_| Permissions::ALL); + let icon = button_rect(&bed, &title(WINDOW)).expect("the docked collapsed column shows its icon"); + // Just past the middle of the 400-point room: the strip is nearer the end edge, a window of the float width + // around it the start edge. + let at = Pos2::new(210.0, 150.0); + press_and_move(&mut bed.fixture, icon.center(), at - icon.center()); + // The key that floats goes down while the pointer still moves, so the drop target marks the float. + bed.fixture.hold(Modifiers::COMMAND); + bed.fixture.frame(vec![moved(at)]); + bed.fixture.frame(vec![release(at)]); + bed.fixture.hold(Modifiers::NONE); + bed.fixture.settle(); + let window = bed.workspace.borrow().layout.floating.first().cloned(); + let window = window.unwrap_or_else(|| panic!("the icon floats: {:?}", bed.actions.borrow())); + assert!(window.column.iconic && window.edge.is_some(), "it floats collapsed, keeping to the edge its strip was dropped near: {window:?}"); + let floated = button_rect(&bed, &title(WINDOW)).expect("the floating window shows its icon"); + assert!(floated.x_range().contains(at.x), "the strip lands under the pointer: {floated:?}, released at {at:?}"); + bed.fixture.idle(3); + let settled = button_rect(&bed, &title(WINDOW)).expect("the icon still shows"); + assert!((settled.left() - floated.left()).abs() <= SLACK, "the strip stays: {floated:?}, then {settled:?}"); } /// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 869775470..c4b63328e 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -102,8 +102,8 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A tab drag carries a `PanelDrag`; a group or column drag carries a `GroupDrag`. Groups and columns register `DockSpot`s in `DockTargets`, and `resolve_drop` maps the spot under the pointer to an `Action`. - A column collapsed to icons takes drops as an expanded column does: its edges (a new column beside it, docked only), the seams between its icon groups, the top of the first group and the bottom of the last (a new group above or below), and each icon group's cells (join its tabs). The column's state wins: a panel dropped into a collapsed column shows as an icon, one dropped into an expanded column shows expanded. - Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides. -- A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to the edge of the float area nearer it; a move keeps the edge it began with, and a collapsed window's move ends with its strip where it was dropped (`WindowColumn::anchored`). -- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. +- A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to its edge of the float area: `Floating::edge`, else the one nearer its rect. A move keeps the edge it began with. A collapsed window's move ends at the edge nearer its strip where it was dropped, with the rect that shows the strip there (`WindowColumn::dropped`), and the area records that edge (`Action::MoveFloating`'s `edge`); a unit dragged out of a collapsed column (`start_icon_drag`) floats collapsed the same way, its strip under the pointer (`Target::Float`'s `edge`). Collapsing a floating column and moving an expanded window clear the edge. A column that neither collapses nor has steps shows no double arrow and offers no collapse in its menu (`ColumnArrow::Fixed`). +- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. - A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. @@ -122,7 +122,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Floating and native windows -A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. A collapsed window shows its icons against the float area's edge nearer it, and keeps its expanded size for when it expands. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the window host runs that move (`runtime::windows::keeps_app_drag`). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). +A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. A collapsed window shows its icons against the edge of the float area it keeps to, and keeps its expanded size for when it expands. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the window host runs that move (`runtime::windows::keeps_app_drag`). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). A panel or group floated out of the dock (a drag, the Float command, a tab torn out of the window) opens at the width it had docked and at the height its group measures at in a floating window's room (`Proposal::Size`), at most `size.float.height`: content that fills its body opens at that height, other content at its own. A column opens at its docked size, at most that height. The area measures once, where the float starts: for a drag in the pass it starts, which adds the size to the drag's payload (`runtime::drag::amend`). A panel's own `PanelSpec` float size wins, and a window that already floats keeps its size. diff --git a/migration/api-map/docking-and-panes.toml b/migration/api-map/docking-and-panes.toml index 314c7c139..aceeba9ae 100644 --- a/migration/api-map/docking-and-panes.toml +++ b/migration/api-map/docking-and-panes.toml @@ -599,7 +599,7 @@ name = "GroupGrip" old = "" new = "craft_ui::docking::GroupGrip" status = "replaced" -note = "The legacy drag bar of a tab group; a double click minimizes the group and a drag starts through `start_group_drag` with a `DragUnit`, carrying a `GroupDrag`." +note = "The legacy drag bar of a tab group; a double click minimizes the group and a drag starts through `start_group_drag` with a `DragUnit`, carrying a `GroupDrag`. `GroupGrip::icons(true)`, the bar of a collapsed column, starts it through `start_icon_drag`, so a float of the unit lands collapsed under the pointer." [[type]] name = "section_heights" @@ -642,7 +642,7 @@ name = "ColumnArrow" old = "" new = "craft_ui::docking::ColumnArrow" status = "replaced" -note = "What a column's double arrow does, which names it and sets where it points: `Collapse`, or `Steps(n)` for a stepped column whose panels do not collapse, which switches between one and two steps. `ColumnArrow::of(&Column

, spec, collapses)`; `DockColumn::arrow` and `WindowColumn::arrow` take it. Replaces `ToolRail`'s column toggle." +note = "What a column's double arrow does, which names it and sets where it points: `Collapse`; `Steps(n)` for a stepped column whose panels do not collapse, which switches between one and two steps; `Fixed` for a column that neither collapses nor has steps, which shows no double arrow and no collapse row in its menu. `ColumnArrow::of(&Column

, spec, collapses)`; `DockColumn::arrow` and `WindowColumn::arrow` take it. Replaces `ToolRail`'s column toggle." [[type]] name = "IconicColumn" From 1536ecd9c21cf145aaa4b283bb5961bbcf9424b8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 04:26:50 +0000 Subject: [PATCH 18/18] Dock: Shift+Tab keeps the panels the host's Except names, docked and floating; Dock Panel joins the first group that takes the unit; one title row height for floating windows - hide::shown reads ShellCx::panels_hidden: the host's Except stays, any other hide hides every panel; a hidden dock (Tab) hides every panel. The columns no longer skip themselves on the shell's dock visibility. - DockTo::Docked tries the dock columns' groups, then the docked tree's, as tabs, and takes the first the model takes under the permissions (drop::takes), so a toolbar's group is passed over. - DockSizes::title_row is FloatingGroup's title row height; the window commands' source, stepped window heights and FloatSpace::title_row use it. - Trials: hidden.rs, dock_back.rs, and the window group under the area's title row in floating_area.rs. --- crates/ui-panels/src/docking/commands/dock.rs | 20 +++-- crates/ui-panels/src/docking/dock_column.rs | 6 +- crates/ui-panels/src/docking/drop.rs | 2 +- crates/ui-panels/src/docking/event.rs | 8 +- crates/ui-panels/src/docking/floating.rs | 9 +- crates/ui-panels/src/docking/iconic.rs | 2 +- crates/ui-panels/src/docking/targets.rs | 4 + crates/ui-patterns/src/patterns/dock/area.rs | 6 +- crates/ui-patterns/src/patterns/dock/hide.rs | 16 ++-- .../ui-patterns/tests/it/docking/dock_back.rs | 44 ++++++++++ .../tests/it/docking/floating_area.rs | 29 ++++++- crates/ui-patterns/tests/it/docking/hidden.rs | 85 +++++++++++++++++++ crates/ui-patterns/tests/it/docking/mod.rs | 2 + docs/ui-docking.md | 2 +- 14 files changed, 205 insertions(+), 30 deletions(-) create mode 100644 crates/ui-patterns/tests/it/docking/dock_back.rs create mode 100644 crates/ui-patterns/tests/it/docking/hidden.rs diff --git a/crates/ui-panels/src/docking/commands/dock.rs b/crates/ui-panels/src/docking/commands/dock.rs index 81fef5765..1287eb3da 100644 --- a/crates/ui-panels/src/docking/commands/dock.rs +++ b/crates/ui-panels/src/docking/commands/dock.rs @@ -1,6 +1,6 @@ //! The panel commands of a docked or floating panel and the dock actions they turn into. -use crate::docking::drop::{beside, members, moving_panels, to_target}; +use crate::docking::drop::{beside, members, moving_panels, takes, to_target}; use crate::docking::{DockEvent, DragUnit, FloatSpace}; use crate::runtime::commands::CommandState; use craft_behavior::DockSide; @@ -20,7 +20,7 @@ pub enum DockCommands { /// Float the panel's tab group into its own frame. #[command(label = "Float Tab Group")] FloatGroup, - /// Dock the floating panel: back where it was docked, else as a tab of the first docked panel. + /// Dock the floating panel: back where it was docked, else as a tab of the first docked group that takes it. #[command(label = "Dock Panel")] DockPanel, /// Ask for a group to move the panel to; the host lists [`Layout::move_targets`] and calls [`move_actions`]. @@ -146,7 +146,9 @@ pub enum DockTo

{ Edge(DockSide), /// As a new last column of the dock on this window edge, or in a new dock there. Dock(DockEdge), - /// Back to the docked layout: a tab of the first docked panel outside the unit. Nothing for a docked unit. + /// Back to the docked layout: tabs of the first group outside the unit that takes them, as its rights and the + /// unit's allow ([`Permissions::accepts_tabs`], [`Permissions::shares_column`]); dock columns come before the + /// docked tree. Nothing for a docked unit. Docked, } @@ -260,10 +262,14 @@ pub fn move_actions(scene: &DockScene<'_, P>, unit: &DragU } let panels = layout.panels(); let free = || panels.iter().copied().filter(|p| !moved.contains(p)); - let docked = free().find(|p| matches!(layout.place(p), Some(PanelPlace::Dock { .. }))); - let framed = || free().find(|p| matches!(layout.place(p), Some(PanelPlace::Node(_)))); - let anchor = docked.or_else(framed).cloned().ok_or(DockError::MissingTarget)?; - one(beside(unit, anchor, DockPlacement::tab(None))) + let docked = free().filter(|p| matches!(layout.place(p), Some(PanelPlace::Dock { .. }))); + let framed = free().filter(|p| matches!(layout.place(p), Some(PanelPlace::Node(_)))); + let mut joins = docked.chain(framed).map(|anchor| beside(unit, anchor.clone(), DockPlacement::tab(None))).peekable(); + if joins.peek().is_none() { + return Err(DockError::MissingTarget); + } + let permissions = |p: &P| scene.policy(p); + joins.find(|action| takes(layout, action, &permissions)).map_or(Err(DockError::NotAllowed), one) } } } diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index ad747f9a6..7ac1e5752 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -166,7 +166,7 @@ pub struct DockColumnStyle { /// them by pointer or with the arrow keys. /// /// The column registers the drop bands of its two edges (`DockSpot::column`) and of the seams between its groups -/// (`DockSpot::seam`) with the dock `dock` every pass. A dock hidden by the shell shows nothing. +/// (`DockSpot::seam`) with the dock `dock` every pass. /// /// In a floating window ([`ColumnBar::Window`]) the window's title row is the column's bar and the window's edges /// size it: the column shows its groups and their dividers only, and registers its seams. @@ -248,10 +248,6 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { let mut bar = BarRecord::default(); let shown = &mut bar; let body = move |ui: &mut Ui, body: &mut BodyCx<'_>| { - // A floating window shows where the area shows it; the shell hides docks only. - if own == ColumnBar::Own && body.shell().is_some_and(|shell| !shell.dock_visible()) { - return; - } let Some(sizes) = body.style::>().map(|style| style.sizes) else { return }; // The bar and the groups at the heights this pass's drag leaves them, in the measuring run and the real // run alike: the same plan `parts` lays out, so the dividers sit at the seams. diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 4bd9beafb..abfa15fcb 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -147,7 +147,7 @@ pub(crate) fn to_target(unit: &DragUnit

, target: Target

) -> Acti /// Whether the model takes `action` and changes the arrangement by it: a dry run on a copy, so no mark shows for a /// drop that `Layout::apply_with_permissions` would refuse or that moves nothing. -fn takes(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> bool { +pub(crate) fn takes(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> bool { let mut copy = layout.clone(); copy.apply_with_permissions(action.clone(), permissions).is_ok() && !copy.same_arrangement(layout) } diff --git a/crates/ui-panels/src/docking/event.rs b/crates/ui-panels/src/docking/event.rs index 88c3ce351..367fff306 100644 --- a/crates/ui-panels/src/docking/event.rs +++ b/crates/ui-panels/src/docking/event.rs @@ -39,7 +39,9 @@ pub enum DockEvent

{ }, } -/// Which panels the host hides. Protected panels always stay. +/// Which panels the host hides. Protected panels always stay. While the shell hides the panels and keeps the tools +/// (Shift+Tab), the panels `Except` names stay and every other panel hides; while it hides the dock (Tab), every panel +/// hides. #[non_exhaustive] pub enum HidePanels<'a, P> { /// Hides none. @@ -67,7 +69,7 @@ pub struct FloatSpace

{ pub area: Rect, /// Room between the area's top-left corner and a unit a command floats. pub inset: f32, - /// The height of a floating window's title row (`DockSizes::bar`), which a drop keeps under the pointer. + /// The height of a floating window's title row (`DockSizes::title_row`), which a drop keeps under the pointer. pub title_row: f32, /// The size a unit floats at when neither its panel nor where it came from gives one. Its height is also the /// most a panel, group or column floats at. @@ -85,7 +87,7 @@ impl FloatSpace

{ FloatSpace { area, inset: sizes.cascade_inset, - title_row: sizes.bar, + title_row: sizes.title_row, default_size: sizes.float_size, panels: Vec::new(), side_edge_zones: false, diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 38a7c7fe2..815f84358 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -22,7 +22,7 @@ use crate::runtime::env::{Env, Label}; use crate::runtime::overlay::CloseReason; use crate::runtime::windows::WindowSpec; use crate::sections::{HeaderAction, HeaderStrength, MenuRows, TitleRow}; -use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, StyleCx, SurfaceKind, UiTokens}; use craft_behavior::dock::DockEdge; use craft_behavior::{GesturePhase, Metrics, Sense}; use craft_ui_widgets::popover::WholeWindow; @@ -33,6 +33,11 @@ use std::hash::Hash; #[cfg(feature = "testing")] mod stories; +/// The height of a floating group's title row: a strong `TitleRow`, which is as tall as a panel header. +pub(crate) fn title_row(tokens: &UiTokens) -> f32 { + tokens.size.panel_header +} + /// The actions a floating group's title row shows unless `actions` says otherwise. const ACTIONS: [HeaderAction; 3] = [HeaderAction::Menu, HeaderAction::Float, HeaderAction::Close]; @@ -304,7 +309,7 @@ impl<'a> FloatingGroup<'a> { /// Shows the group; `body` fills the area under the title row unless the group is minimized. pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { let env = Env::of(ui); - let header = env.tokens.size.panel_header; + let header = title_row(&env.tokens); (self.header, self.rtl) = (header, env.direction.is_rtl()); let mount = self.mount(header); self.props = self.props.mount(mount); diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 8e375d9d3..70b9f5cd4 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -695,7 +695,7 @@ impl Container for IconicColumn<'_, P> { /// The column bar, over the icons. What the user did on it is read in `finish`. fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { - if self.bar == ColumnBar::Window || cx.shell().is_some_and(|shell| !shell.dock_visible()) { + if self.bar == ColumnBar::Window { return; } if let Some(grip) = column_grip(self.column, self.spec, cx) { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 0e17258d2..44a86f34f 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -47,6 +47,9 @@ pub struct DockSizes { pub strip: f32, /// The height of a column bar (a small control). pub bar: f32, + /// The height of a floating window's title row, which is the bar of the column the window holds: every height of + /// a window's body or content is the window's height less this. + pub title_row: f32, /// The least body size of a column's group and the least width of an expanded column (the panel header height). pub least: f32, /// How thick a divider is across its boundary (the least hit size). @@ -84,6 +87,7 @@ impl DockSizes { least_pane: size.pane.least, strip: size.panel_header, bar: size.control.sm, + title_row: super::floating::title_row(cx.tokens), least: size.panel_header, reach: size.hit.target, step: cx.control().gap, diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 6858d28e1..d975f6f37 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1191,7 +1191,7 @@ impl Pass<'_, P> { _ => (change.rect.width() - fitted.x).abs() <= 0.5, }; let to = if by_height { - let room = change.rect.height() - scene.sizes.strip; + let room = change.rect.height() - scene.sizes.title_row; grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) } else { grid.steps_within(change.rect.width()) @@ -1208,7 +1208,7 @@ impl Pass<'_, P> { let top = match change.kind { PlacementKind::Size(ResizeEdge::Top | ResizeEdge::TopLeft | ResizeEdge::TopRight) => { let content = self.stepped_height(ui, body, column, grid.width(to), true).unwrap_or(0.0); - change.rect.bottom() - scene.sizes.strip - content + change.rect.bottom() - scene.sizes.title_row - content } _ => change.rect.top(), }; @@ -1236,7 +1236,7 @@ impl Pass<'_, P> { self.pick(&active, item); } // The window's commands run from its body, below the title row. - let body = opening.rect.size() - Vec2::new(0.0, scene.sizes.bar); + let body = opening.rect.size() - Vec2::new(0.0, scene.sizes.title_row); for command in commands { self.run(&active, command, Some(body)); } diff --git a/crates/ui-patterns/src/patterns/dock/hide.rs b/crates/ui-patterns/src/patterns/dock/hide.rs index f518e3d7d..e6ca0e421 100644 --- a/crates/ui-patterns/src/patterns/dock/hide.rs +++ b/crates/ui-patterns/src/patterns/dock/hide.rs @@ -11,13 +11,15 @@ use std::hash::Hash; pub(super) struct Shown<'a, P: Clone> { /// The pruned layout with its write-back map. pub(super) view: FrameView<'a, P>, - /// Floating windows show: the shell shows them and the panels are not hidden. + /// Floating windows show: the shell shows them, or it hides the panels and the view keeps what the host names. pub(super) floating: bool, } /// `layout` with the host's `hide`, the shell's panel visibility and the frame of `maximized` applied. Protected -/// panels always stay, so a canvas shows while the dock is hidden. Size edits made on the view go back through -/// `FrameView::write_back`. +/// panels always stay, so a canvas shows while the dock is hidden. While the shell hides the panels and keeps the +/// tools (Shift+Tab), the panels the host's `HidePanels::Except` names stay, docked or floating, and every other panel +/// hides; while the shell hides the dock (Tab, body-only mode), every panel hides. Size edits made on the view go back +/// through `FrameView::write_back`. pub(super) fn shown<'a, P: Clone + Eq + Hash>( layout: &'a Layout

, maximized: Option<&P>, @@ -25,8 +27,10 @@ pub(super) fn shown<'a, P: Clone + Eq + Hash>( shell: Option<&ShellCx>, protected: &dyn Fn(&P) -> bool, ) -> Shown<'a, P> { - let dock_hidden = shell.is_some_and(|shell| !shell.dock_visible()); - let hide = if dock_hidden { HidePanels::All } else { hide }; - let floating = shell.is_none_or(|shell| shell.floating_visible()); + let (hide, floating) = match shell { + None => (hide, true), + Some(shell) if shell.panels_hidden() => (if let HidePanels::Except(keep) = hide { HidePanels::Except(keep) } else { HidePanels::All }, true), + Some(shell) => (if shell.dock_visible() { hide } else { HidePanels::All }, shell.floating_visible()), + }; Shown { view: maximize(layout, maximized, hide, protected), floating } } diff --git a/crates/ui-patterns/tests/it/docking/dock_back.rs b/crates/ui-patterns/tests/it/docking/dock_back.rs new file mode 100644 index 000000000..cad0462e1 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/dock_back.rs @@ -0,0 +1,44 @@ +//! Dock Panel with no docked place recorded: the floating unit joins the first docked group that takes it. + +use craft_behavior::Axis; +use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize}; +use craft_ui::docking::{DockScene, DockTo, DragUnit, FloatSpace, move_actions}; +use craft_ui::testing::trial; +use egui::{Pos2, Rect}; + +const CANVAS: usize = 1; +const TOOLBAR: usize = 2; +const LAYERS: usize = 3; +const FLOATED: usize = 4; + +fn rights(panel: &usize) -> Permissions { + match *panel { + CANVAS => Permissions::PROTECTED, + TOOLBAR => Permissions::ALL.accepts_tabs(false).accepts_splits(false).collapses(false).shares_column(false), + _ => Permissions::ALL, + } +} + +/// The toolbar alone in the start dock's only column, the canvas, Layers in the end dock, and a floating panel. +fn layout() -> Layout { + let start = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![TOOLBAR], 0)])]); + let end = Node::dock(DockEdge::End, vec![Column::new(vec![Group::new(vec![LAYERS], 0)])]); + let root = Node::split(Axis::X, SplitSize::Ratio(0.2), start, Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![CANVAS], 0), end)); + let window = Rect::from_min_size(Pos2::new(100.0, 100.0), egui::vec2(200.0, 150.0)); + Layout::new(Some(root), vec![Floating::single(vec![FLOATED], 0, window)]) +} + +#[trial] +fn a_floating_panel_docks_into_the_first_group_that_takes_tabs_and_shares_its_column() { + let mut layout = layout(); + let space = FloatSpace::new(Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0)), &super::sizes(4.0, 60.0, 20.0)); + let actions = { + let scene = DockScene::new(&layout, &space, false, &rights); + move_actions(&scene, &DragUnit::Panel(FLOATED), DockTo::Docked).expect("a docked group takes the panel") + }; + layout.apply_all(actions, rights).expect("the model takes the move"); + let group_of = |panel: usize| layout.place(&panel).and_then(|place| layout.group(&place)).map(|group| group.panels.clone()); + assert!(group_of(FLOATED).is_some_and(|panels| panels.contains(&LAYERS)), "the panel joins Layers' tabs, past the toolbar's group"); + assert_eq!(group_of(TOOLBAR), Some(vec![TOOLBAR]), "the toolbar keeps its group to itself"); + assert!(layout.floating.is_empty(), "the window closes with its only panel"); +} diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 0e4fde61a..0781a0708 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -67,6 +67,8 @@ struct Bed { second: Rc>, /// The tallest a floated panel opens (`FloatSpace::default_size`), as the area reported it. float_height: Rc>, + /// The height of a floating window's title row (`FloatSpace::title_row`), as the area reported it. + title_row: Rc>, } fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { @@ -74,7 +76,9 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { let actions: Rc>>> = Rc::default(); let second = Rc::new(Cell::new(false)); let float_height = Rc::new(Cell::new(0.0)); + let title_row = Rc::new(Cell::new(0.0)); let (held, seen_actions, shows_second, seen_height) = (Rc::clone(&workspace), Rc::clone(&actions), Rc::clone(&second), Rc::clone(&float_height)); + let seen_title_row = Rc::clone(&title_row); let mut other = Workspace::new(Layout::new(Some(Node::tabs(vec![SECOND], 0)), Vec::new())); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); @@ -84,13 +88,14 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { seen_actions.borrow_mut().extend(out.actions); if let Some(space) = out.float_space { seen_height.set(space.default_size.y); + seen_title_row.set(space.title_row); } if shows_second.get() { DockArea::new("Second dock", Bind::bound(&mut other), &mut panels, DockConfig::default()).show(ui); } }); fixture.settle(); - Bed { fixture, workspace, actions, second, float_height } + Bed { fixture, workspace, actions, second, float_height, title_row } } /// A point on the floating window's title row. @@ -230,6 +235,28 @@ fn a_floating_windows_drag_bar_shows_no_title() { assert_eq!(named, 1, "only the tab names the panel: {:?}", bed.fixture.texts()); } +/// The title row the area keeps a dropped window's under the pointer and adds to a floated unit's height is the +/// one the window draws: the window's group starts right under it. +#[trial] +fn a_floating_windows_group_starts_under_the_title_row_the_area_sizes_windows_by() { + let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let group = bed + .fixture + .by_role(Role::TAB_PANEL) + .into_iter() + .find(|group| WINDOW_AT.expand(SLACK).contains_rect(group.rect)) + .expect("the window shows its group") + .rect; + let title_row = bed.title_row.get(); + assert!(title_row > 0.0, "the area reported its float space"); + assert!( + (group.top() - WINDOW_AT.top() - title_row).abs() <= SLACK, + "the group starts at {} in a window from {} with a title row of {title_row}", + group.top(), + WINDOW_AT.top() + ); +} + /// A tab dragged out of the window floats at the width its group had where it was docked, not a default size. #[trial] fn a_floated_panel_fits_its_content_up_to_the_float_height() { diff --git a/crates/ui-patterns/tests/it/docking/hidden.rs b/crates/ui-patterns/tests/it/docking/hidden.rs new file mode 100644 index 000000000..dcc2cfc09 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/hidden.rs @@ -0,0 +1,85 @@ +//! What a dock area shows while the shell hides the panels and keeps the tools (Shift+Tab) or hides the dock (Tab). + +use craft_behavior::Axis; +use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx}; +use craft_ui::docking::{DockConfig, DockPanels, HidePanels, PanelSpec}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::env::{BodyMode, ShellCx, ShellEntry, WindowKey}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::collections::BTreeSet; +use std::rc::Rc; + +const CANVAS: usize = 1; +/// Docked, and named by the host's `HidePanels::Except`. +const TOOLBAR: usize = 2; +const LAYERS: usize = 3; +/// Floating, and named by the host's `HidePanels::Except`. +const PALETTE: usize = 4; +const NAVIGATOR: usize = 5; + +/// Records the panels whose bodies ran. +struct Panels { + shown: Rc>>, +} + +impl DockPanels for Panels { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn permissions(&self, panel: &usize) -> Permissions { + if *panel == CANVAS { Permissions::PROTECTED } else { Permissions::ALL } + } + + fn body(&mut self, panel: &usize, _: &mut Ui, _: &mut BodyCx<'_>) { + self.shown.borrow_mut().insert(*panel); + } +} + +/// The toolbar in a start dock, the canvas, Layers in an end dock, and two floating windows. +fn layout() -> Layout { + let start = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![TOOLBAR], 0)])]); + let end = Node::dock(DockEdge::End, vec![Column::new(vec![Group::new(vec![LAYERS], 0)])]); + let root = Node::split(Axis::X, SplitSize::Ratio(0.2), start, Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![CANVAS], 0), end)); + let window = |panel: usize, x: f32| Floating::single(vec![panel], 0, Rect::from_min_size(Pos2::new(x, 60.0), Vec2::new(120.0, 120.0))); + Layout::new(Some(root), vec![window(PALETTE, 90.0), window(NAVIGATOR, 220.0)]) +} + +/// The panels the area shows under `shell`, with the host keeping the toolbar and the palette when `keeps`. +fn shown_under(shell: ShellCx, keeps: bool) -> BTreeSet { + let shown: Rc>> = Rc::default(); + let seen = Rc::clone(&shown); + let mut fixture = Fixture::new(move |ui| { + seen.borrow_mut().clear(); + let mut workspace = Workspace::new(layout()); + let mut panels = Panels { shown: Rc::clone(&seen) }; + let keep = |panel: &usize| *panel == TOOLBAR || *panel == PALETTE; + let mut area = DockArea::new("Hidden dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()); + if keeps { + area = area.hide(HidePanels::Except(&keep)); + } + area.show(ui); + }); + fixture.root_value(ShellEntry(Some(shell))).settle(); + shown.take() +} + +#[trial] +fn shift_tab_keeps_the_panels_the_host_names_docked_and_floating_and_tab_hides_them_all() { + let room = Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0)); + let normal = ShellCx::detached(WindowKey::main(), BodyMode::Normal, room); + let all = BTreeSet::from([CANVAS, TOOLBAR, LAYERS, PALETTE, NAVIGATOR]); + assert_eq!(shown_under(normal.clone(), false), all, "every panel shows while nothing hides them"); + let shift_tab = normal.with_panels_hidden(true); + assert_eq!( + shown_under(shift_tab.clone(), true), + BTreeSet::from([CANVAS, TOOLBAR, PALETTE]), + "Shift+Tab keeps the canvas and what the host names, docked and floating" + ); + assert_eq!(shown_under(shift_tab, false), BTreeSet::from([CANVAS]), "Shift+Tab with nothing named keeps the canvas only"); + let tab = ShellCx::detached(WindowKey::main(), BodyMode::Only, room); + assert_eq!(shown_under(tab, true), BTreeSet::from([CANVAS]), "Tab keeps the canvas only, whatever the host names"); +} diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 9c195ac25..61631da3e 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -16,8 +16,10 @@ mod drop_session; mod floating; mod floating_area; +mod hidden; mod columns; +mod dock_back; mod group_view; mod workspace_dialogs; diff --git a/docs/ui-docking.md b/docs/ui-docking.md index c4b63328e..c0fb12b27 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -65,7 +65,7 @@ The binding decides who applies the edits. With `Bind::bound` the area writes ev A panel body, or code a body calls, changes the workspace during the pass with `docking::request_actions(ctx, actions)`, never by writing the workspace the area shows. The running area takes them unapplied and returns them in `DockAreaOutput::requested`, in order, for the host to apply after `actions` in the same frame. With no area over that panel type running, `request_actions` hands the actions back for the caller to apply. -Props: `hide` (`HidePanels::None`, `All` or `Except`), `maximized`, `auto_collapse`, `locked`, and `flyout`, which binds the open flyout to the host's value (the area keeps it otherwise). A hidden panel keeps its place for restore. +Props: `hide` (`HidePanels::None`, `All` or `Except`), `maximized`, `auto_collapse`, `locked`, and `flyout`, which binds the open flyout to the host's value (the area keeps it otherwise). A hidden panel keeps its place for restore. Inside an `AppShell`, the shell's hiding wins over `hide`: while it hides the panels and keeps the tools (Shift+Tab, `ShellCx::panels_hidden`), only the panels an `Except` names stay, docked or floating (a toolbar); while it hides the dock (Tab), no panel shows. Protected panels always show. A panel in a column collapsed to icons shows in its flyout (`Layout::opens_in_flyout`). The host opens and closes it by writing the `flyout` binding, not the layout: `WindowMenuRows` checks such a panel's row while its flyout is open (`WindowMenuRows::flyout`) and reports a pick in `WindowMenuRowsOutput::flyout`.