diff --git a/crates/ui-contract/src/contract/ghost.rs b/crates/ui-contract/src/contract/ghost.rs index 08c027b89..7a30d1267 100644 --- a/crates/ui-contract/src/contract/ghost.rs +++ b/crates/ui-contract/src/contract/ghost.rs @@ -150,18 +150,24 @@ fn paint_drag_badge(draw: &Draw<'_>, env: &Env, at: Pos2, text: &str) { } /// The drop mark: bands of the drop rule on a halo of the panel surface one thin stroke wide, so the mark reads over -/// any content. An area mark is the same band along the inside of its rect. +/// any content. An area mark is the same band along the inside of its rect; a region is also washed with the rule's +/// colour, so the area the payload takes reads as one piece, and carries its line band. fn paint_mark(painter: &egui::Painter, env: &Env, mark: DropMark) { let look = rule_look(&env.tokens, RuleKind::DropMark); let ppp = painter.ctx().pixels_per_point(); let width = look.width.points(ppp); let halo = RuleWidth::Points(env.tokens.stroke.thin).points(ppp); + let outline = |rect: Rect| { + let inside = rect.shrink(width / 2.0 + halo); + let corners = [inside.left_top(), inside.right_top(), inside.right_bottom(), inside.left_bottom()]; + (0..corners.len()).map(move |at| (corners[at], corners[(at + 1) % corners.len()])) + }; let segments: Vec<(Pos2, Pos2)> = match mark { DropMark::Line { from, to } => vec![(from, to)], - DropMark::Into(rect) | DropMark::Split(rect) => { - let inside = rect.shrink(width / 2.0 + halo); - let corners = [inside.left_top(), inside.right_top(), inside.right_bottom(), inside.left_bottom()]; - (0..corners.len()).map(|at| (corners[at], corners[(at + 1) % corners.len()])).collect() + DropMark::Into(rect) => outline(rect).collect(), + DropMark::Region { area, line } => { + painter.rect_filled(area, CornerRadius::ZERO, look.color.gamma_multiply(craft_theme::Opacity::WASH)); + outline(area).chain(line.map(|[from, to]| (from, to))).collect() } }; let band = |(from, to): (Pos2, Pos2), half: f32| Rect::from_two_pos(from, to).expand(half); diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index cc0bd10ae..01f86fa21 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -60,8 +60,14 @@ pub enum DropMark { }, /// The payload goes into this rect. Into(Rect), - /// This rect is split, the payload taking one side. - Split(Rect), + /// The payload will occupy this area once dropped, such as the rect a docked panel takes beside a group. + #[non_exhaustive] + Region { + /// The rect the payload takes. + area: Rect, + /// Where in it the payload goes in, such as the tab position of a panel joining a group. + line: Option<[Pos2; 2]>, + }, } impl DropMark { @@ -70,13 +76,23 @@ impl DropMark { DropMark::Line { from, to } } + /// The payload will occupy `area`. + pub const fn region(area: Rect) -> Self { + DropMark::Region { area, line: None } + } + + /// The payload will occupy `area` and goes in at the line from `from` to `to`. + pub const fn region_at(area: Rect, from: Pos2, to: Pos2) -> Self { + DropMark::Region { area, line: Some([from, to]) } + } + /// The mark with every point passed through `map`. pub(crate) fn mapped(self, map: impl Fn(Pos2) -> Pos2) -> Self { let rect = |rect: Rect| Rect::from_two_pos(map(rect.min), map(rect.max)); match self { DropMark::Line { from, to } => DropMark::Line { from: map(from), to: map(to) }, DropMark::Into(target) => DropMark::Into(rect(target)), - DropMark::Split(target) => DropMark::Split(rect(target)), + DropMark::Region { area, line } => DropMark::Region { area: rect(area), line: line.map(|line| line.map(&map)) }, } } } diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 7ac1e5752..3206baa71 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_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}; +pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; const DIVIDER: PartKey = PartKey::new("divider"); const EDGE: PartKey = PartKey::new("edge"); @@ -293,10 +293,16 @@ impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { } } +/// Where the groups of `column` sit in `rect`, the column's rect with its bar `bar`, as the column lays them out while +/// no divider between them is dragged. +pub fn group_rects

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, rect: Rect, bar: ColumnBar, sizes: &DockSizes) -> Vec { + column_plan(column, spec, rect, bar, sizes, |_, _| None).groups +} + /// 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). A /// column in a floating window has an empty bar on top. -fn column_plan( +fn column_plan

( column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, rect: Rect, @@ -310,7 +316,7 @@ fn column_plan( } /// [`column_plan`] for a column whose `bar` and `body` rects are known. -fn body_plan( +fn body_plan

( column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, bar: Rect, diff --git a/crates/ui-panels/src/docking/dock_column/sizing.rs b/crates/ui-panels/src/docking/dock_column/sizing.rs index 879a7afce..31bdba43a 100644 --- a/crates/ui-panels/src/docking/dock_column/sizing.rs +++ b/crates/ui-panels/src/docking/dock_column/sizing.rs @@ -2,7 +2,8 @@ use crate::contract::SizeLimits; use crate::docking::{DockGrid, DockHeights, DockSizes, PanelSpec}; -use craft_behavior::dock::Column; +use craft_behavior::Flow; +use craft_behavior::dock::{Column, DockEdge}; use egui::{Pos2, Rect}; /// The width bounds of an expanded column: no narrower than `least` or the widest minimum of its panels, no wider @@ -29,6 +30,31 @@ pub fn fit_widths(columns: &[(f32, Option)], room: f32) -> Vec { scale_widths(&bounded, room) } +/// The cells of a dock's columns in the dock's `rect`, from its window edge `edge` inwards, each the dock's full +/// height: the columns' natural widths ([`DockSizes::natural`]) fitted into the dock's width ([`fit_widths`]). `flow` +/// is the flow of the area the dock is in, which mirrors the edges for right-to-left. +pub fn column_cells

( + columns: &[Column

], + rect: Rect, + edge: DockEdge, + flow: Flow, + sizes: &DockSizes, + spec: &dyn Fn(&P) -> PanelSpec, +) -> Vec { + let widths = fit_widths(&sizes.natural(columns, spec), rect.width()); + let reading = flow.to_physical(rect); + let start = edge == DockEdge::Start; + let mut cursor = if start { reading.left() } else { reading.right() }; + widths + .into_iter() + .map(|width| { + let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) }; + cursor = if start { span.1 } else { span.0 }; + flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())) + }) + .collect() +} + /// 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)> { diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index abfa15fcb..2936b673d 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -6,7 +6,7 @@ //! windows, and returns the mark the ghost paints. Every drag of a group, a window or a column starts through //! [`start_group_drag`], or [`start_icon_drag`] out of a collapsed column. -use super::{DockSpot, DockTargets, FloatSpace, GroupDrag, PanelDrag, PanelKey, WindowColumn}; +use super::{DockSpot, DockTargets, FloatSpace, GroupDrag, PanelDrag, PanelKey, Placing, WindowColumn, placed_rect}; use crate::contract::{Component, Cx, DropMark, DropOperation, DropTarget, Pointer as _}; use crate::runtime::drag::{self, DragPreview}; use crate::runtime::env::{AppValues, EnvValue, EnvView, Label}; @@ -145,23 +145,29 @@ 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. -pub(crate) fn takes(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> bool { +/// The layout after `action`, when the model takes it and it changes the arrangement: a dry run on a copy, so no mark +/// shows for a drop that `Layout::apply_with_permissions` would refuse or that moves nothing. +pub(crate) fn applied(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> Option> { let mut copy = layout.clone(); - copy.apply_with_permissions(action.clone(), permissions).is_ok() && !copy.same_arrangement(layout) + (copy.apply_with_permissions(action.clone(), permissions).is_ok() && !copy.same_arrangement(layout)).then_some(copy) } -/// The action a drop of `unit` on `spot` makes, or `None` when the unit cannot move there: the permissions refuse, -/// the destination is the unit itself, the spot has no placement, or the model refuses the action. +/// Whether the model takes `action` and changes the arrangement by it ([`applied`]). +pub(crate) fn takes(layout: &Layout

, action: &Action

, permissions: &dyn Fn(&P) -> Permissions) -> bool { + applied(layout, action, permissions).is_some() +} + +/// The action a drop of `unit` on `spot` makes and the layout after it, or `None` when the unit cannot move there: the +/// permissions refuse, the destination is the unit itself, the spot has no placement, or the model refuses the action. fn action_for( layout: &Layout

, spot: &DockSpot

, unit: &DragUnit

, permissions: &dyn Fn(&P) -> Permissions, -) -> Option> { +) -> Option<(Action

, Layout

)> { let action = spot_action(layout, spot, unit, permissions)?; - takes(layout, &action, permissions).then_some(action) + let after = applied(layout, &action, permissions)?; + Some((action, after)) } fn spot_action( @@ -275,12 +281,15 @@ where { let unit = drag.unit(layout)?; let (spot, _) = DockTargets::

::resolve(ctx, dock, at)?; - action_for(layout, &spot, &unit, permissions) + action_for(layout, &spot, &unit, permissions).map(|(action, _)| action) } /// The drop target of one dock over one layout, for a tab drag ([`PanelDrag`]) and a group drag ([`GroupDrag`]). /// -/// It accepts a move only. A release over a spot docks the unit there. Ctrl or Cmd held at the release floats it +/// It accepts a move only. A release over a spot docks the unit there. With `placing`, the mark over a spot is the +/// region the unit takes once dropped, laid out in the room the dock registered ([`placed_rect`]), with the tab line +/// of a tab insertion; a reorder inside the unit's own group, and a drop whose panels get no rect of their own, mark +/// the spot ([`DockSpot::mark`]). Ctrl or Cmd held at the release floats it /// instead (Photoshop: the key prevents docking), and with `float_on_empty` a release that no spot takes floats it; /// both float it into `space` under the pointer. A floating window dragged by its title bar moves itself and never /// floats into another window. Fields are assigned by the dock after [`Self::new`]. @@ -299,12 +308,14 @@ pub struct DockDropTarget<'a, P> { pub float_on_empty: bool, /// A floating window dragged by its title bar docks on a spot (`DockConfig::title_bar_docks`). Off: it only moves. pub title_bar_docks: bool, + /// How the dock lays out its panels, for the region a drop gives them. Without it every mark is the spot's. + pub placing: Option>, } impl<'a, P> DockDropTarget<'a, P> { /// The target of `dock` over `layout`: it docks on spots and floats nothing until `space` is set. pub fn new(ctx: &'a Context, dock: Id, layout: &'a Layout

, permissions: &'a dyn Fn(&P) -> Permissions) -> Self { - DockDropTarget { ctx, dock, layout, permissions, rtl: false, space: None, float_on_empty: false, title_bar_docks: true } + DockDropTarget { ctx, dock, layout, permissions, rtl: false, space: None, float_on_empty: false, title_bar_docks: true, placing: None } } } @@ -322,8 +333,14 @@ impl DockDropTarget<'_, P> { return None; } if let Some((spot, applies)) = DockTargets::

::resolve(self.ctx, self.dock, at) { - if let Some(action) = action_for(self.layout, &spot, &unit, self.permissions) { - let mark = spot.mark(applies, self.rtl)?; + if let Some((action, after)) = action_for(self.layout, &spot, &unit, self.permissions) { + let mark = match self.region(&spot, &unit, &after) { + Some(area) => match spot.tab_line(applies, self.rtl) { + Some([from, to]) => DropMark::region_at(area, from, to), + None => DropMark::region(area), + }, + None => spot.mark(applies, self.rtl)?, + }; return Some(DockDropped { action, mark }); } if on_unit(self.layout, &spot, &unit) { @@ -336,6 +353,18 @@ impl DockDropTarget<'_, P> { self.float(&unit, at, drag.source(), drag.strip()) } + /// The rect the panels of `unit` take in `after`, the layout once dropped on `spot`; `None` without `placing` or + /// a registered room, for a reorder inside the unit's own group, which marks only its tab line, and where the + /// panels get no rect of their own. + fn region(&self, spot: &DockSpot

, unit: &DragUnit

, after: &Layout

) -> Option { + let placing = self.placing.as_ref()?; + if matches!(spot, DockSpot::Tab { .. }) && on_unit(self.layout, spot, unit) { + return None; + } + let room = DockTargets::

::room(self.ctx, self.dock)?; + placed_rect(after, &moving_panels(self.layout, unit), room, placing, self.rtl) + } + /// The unit floated under `at`, when it may float and the model takes it; `source` is its size where the drag /// started, `strip` the size of the icons it started on ([`float_drop`]). fn float(&self, unit: &DragUnit

, at: Pos2, source: Option, strip: Option) -> Option> { diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index f04de479f..dc680bb41 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -13,6 +13,7 @@ mod group; mod floating; mod panels; +mod placed; mod root; mod spec; mod splitter; @@ -40,6 +41,7 @@ pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, Windo pub use panels::{DockPanels, request_actions}; #[doc(hidden)] pub use panels::{close_requests, open_requests}; +pub use placed::{Placing, placed_rect, with_area_rules}; pub use root::{DockRoot, DockRootOutput, DockRootStyle}; pub use spec::{DockGrid, DockHeights, PanelSpec}; pub use splitter::{Splitter, SplitterStyle}; @@ -56,8 +58,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, column_cells, fit_widths, group_heights, + group_rects, 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/placed.rs b/crates/ui-panels/src/docking/placed.rs new file mode 100644 index 000000000..69535f020 --- /dev/null +++ b/crates/ui-panels/src/docking/placed.rs @@ -0,0 +1,122 @@ +//! Where a drop puts the panels it moves: the layout after the drop, pruned as the dock area shows it and laid out by +//! the functions the dock draws with, so a drop's mark is the rect the moved panels take once dropped. + +use super::frame::maximize; +use super::tree::{self, FrameRules}; +use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects, stepped}; +use craft_behavior::Flow; +use craft_behavior::dock::{Column, Layout, Node}; +use egui::Rect; +use std::hash::Hash; + +/// How a dock lays out its panels, which its drop target reads to mark where a drop puts them +/// (`DockDropTarget::placing`). +#[non_exhaustive] +pub struct Placing<'a, P> { + /// The dock's sizes. + pub sizes: DockSizes, + /// Each panel's spec: its limits, heights and whether it is a canvas. + pub spec: &'a dyn Fn(&P) -> PanelSpec, + /// The panels that always show, such as a canvas. + pub protected: &'a dyn Fn(&P) -> bool, + /// The panels the area hides, as the shell's visibility leaves them. + pub hide: HidePanels<'a, P>, + /// The panel whose frame the area shows maximized. + pub maximized: Option<&'a P>, + /// The floating window whose column the dock lays out, by its id; `None` for a dock area's docked tree. + pub window: Option, +} + +impl<'a, P> Placing<'a, P> { + /// The placing of a dock area's docked tree that hides nothing. + pub fn new(sizes: DockSizes, spec: &'a dyn Fn(&P) -> PanelSpec, protected: &'a dyn Fn(&P) -> bool) -> Self { + Placing { sizes, spec, protected, hide: HidePanels::None, maximized: None, window: None } + } + + /// The area hides `hide` and shows the frame of `maximized` alone. + #[must_use] + pub fn shown(mut self, hide: HidePanels<'a, P>, maximized: Option<&'a P>) -> Self { + self.hide = hide; + self.maximized = maximized; + self + } + + /// The placing of the floating window `window` instead of the docked tree. + #[must_use] + pub fn window(mut self, window: u64) -> Self { + self.window = Some(window); + self + } +} + +/// Runs `f` with the rules a dock area lays its docked tree out by: each panel's limits from `spec`, a dock as wide as +/// its columns' natural widths ([`DockSizes::natural`]), and no strip on a canvas alone in its group. +pub fn with_area_rules(sizes: &DockSizes, spec: &dyn Fn(&P) -> PanelSpec, f: impl FnOnce(FrameRules<'_, P>) -> R) -> R { + let limits = |panel: &P| spec(panel).limits; + let dock_width = |columns: &[Column

]| sizes.natural(columns, spec).iter().map(|(width, _)| *width).sum::(); + let stripless = |panel: &P| spec(panel).canvas; + f(FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless)) +} + +/// The rect the panels `moved` take in `layout`, the layout after a drop, laid out in `room` (the room the dock +/// registered, `DockTargets::room`) as the dock lays it out, pruned as the area shows it: the union of the rects of the +/// groups that hold them, or the cell of a dock column they make up alone. `None` where one of them lands where the +/// layout gives it no rect of its own: hidden, in a collapsed column (icons) or in a stepped column (sized by its +/// content as it shows). +pub fn placed_rect(layout: &Layout

, moved: &[P], room: Rect, placing: &Placing<'_, P>, rtl: bool) -> Option { + let view = maximize(layout, placing.maximized, placing.hide, placing.protected); + let layout: &Layout

= &view.layout; + let mut rects = Vec::new(); + match placing.window { + Some(id) => { + let window = layout.floating.iter().find(|window| window.id == id)?; + column_rects(&window.column, room, ColumnBar::Window, placing, moved, &mut rects)?; + } + None => { + let root = layout.root.as_ref()?; + let flow = Flow::new(room, rtl); + with_area_rules(&placing.sizes, placing.spec, |rules| { + for frame in tree::frames(root, room, &placing.sizes, &rules, rtl).groups { + match frame.node { + Node::Dock { side, columns } => { + for (column, cell) in columns.iter().zip(column_cells(columns, frame.rect, *side, flow, &placing.sizes, placing.spec)) { + column_rects(column, cell, ColumnBar::Own, placing, moved, &mut rects)?; + } + } + Node::Tabs { panels, .. } if panels.iter().any(|panel| moved.contains(panel)) => rects.push(frame.rect), + Node::Stack { entries, .. } if entries.iter().any(|entry| moved.contains(&entry.panel)) => rects.push(frame.rect), + _ => {} + } + } + Some(()) + })?; + } + } + rects.into_iter().reduce(Rect::union) +} + +/// Adds the rects the moved panels take in `column` at `cell` to `rects`: the cell when they make up the column, else +/// the rects of its groups that hold them. `None` when one lands in a collapsed or stepped column. +fn column_rects( + column: &Column

, + cell: Rect, + bar: ColumnBar, + placing: &Placing<'_, P>, + moved: &[P], + rects: &mut Vec, +) -> Option<()> { + let moves = |panel: &P| moved.contains(panel); + if !column.panels().any(moves) { + return Some(()); + } + if column.iconic || stepped(column, placing.spec).is_some() { + return None; + } + if column.panels().all(moves) { + rects.push(cell); + return Some(()); + } + let groups = column.groups.iter().zip(group_rects(column, placing.spec, cell, bar, &placing.sizes)); + rects.extend(groups.filter(|(group, _)| group.panels.iter().any(moves)).map(|(_, rect)| rect)); + Some(()) +} diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 44a86f34f..c84c396f0 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -8,8 +8,8 @@ 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; +use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; -use craft_behavior::{DockSide, Flow}; use egui::{Context, Id, Pos2, Rect, Vec2}; pub use craft_behavior::dock::{SIDE_ZONE_DEPTH_SHARE, SIDE_ZONE_FRACTION}; @@ -268,31 +268,40 @@ impl

DockSpot

{ } } - /// What the drag ghost paints for a drop on this spot; `None` for [`DockSpot::Blocked`], which takes no drop. + /// What the drag ghost paints for a drop on this spot when the dock cannot say where the moved panels land + /// (`DockDropTarget::placing`); `None` for [`DockSpot::Blocked`], which takes no drop. /// - /// `rect` is the rect the spot applies to: the group's rect for [`DockSpot::Group`], whose side marks the half - /// of it a docked panel would take (mirrored under `rtl`); the rect it registered with (`DockTargets::register_in`, else its hit rect) for the others. A tab - /// insertion marks a line across the hit rect's start edge. A band (edge, seam, column, new dock) marks a line - /// along its middle. + /// `rect` is the rect the spot applies to: the group's rect for [`DockSpot::Group`]; the rect it registered with + /// (`DockTargets::register_in`, else its hit rect) for the others. A group's middle marks the group as the region + /// the panels join; a side of it marks a line along that edge of the group (mirrored under `rtl`). A tab insertion + /// marks a line across the hit rect's start edge. A band (edge, seam, column, new dock) marks a line along its + /// middle. pub fn mark(&self, rect: Rect, rtl: bool) -> Option { + let (start, end) = if rtl { (rect.right(), rect.left()) } else { (rect.left(), rect.right()) }; + let across = |x: f32| DropMark::line(Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom())); + let along = |y: f32| DropMark::line(Pos2::new(rect.left(), y), Pos2::new(rect.right(), y)); match self { DockSpot::Blocked => None, - DockSpot::Group { side: DockSide::Center, .. } => Some(DropMark::Into(rect)), - DockSpot::Group { side, .. } => Some(DropMark::Split(Flow::new(rect, rtl).to_physical(side.area(rect)))), - DockSpot::Tab { .. } => { - let x = if rtl { rect.right() } else { rect.left() }; - Some(DropMark::line(Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom()))) - } + DockSpot::Group { side, .. } => Some(match side { + DockSide::Start => across(start), + DockSide::End => across(end), + DockSide::Top => along(rect.top()), + DockSide::Bottom => along(rect.bottom()), + _ => DropMark::region(rect), + }), + DockSpot::Tab { .. } => self.tab_line(rect, rtl).map(|[from, to]| DropMark::line(from, to)), DockSpot::Edge(_) | DockSpot::Seam { .. } | DockSpot::Column { .. } | DockSpot::NewDock(_) => { let centre = rect.center(); - Some(if rect.width() <= rect.height() { - DropMark::line(Pos2::new(centre.x, rect.top()), Pos2::new(centre.x, rect.bottom())) - } else { - DropMark::line(Pos2::new(rect.left(), centre.y), Pos2::new(rect.right(), centre.y)) - }) + Some(if rect.width() <= rect.height() { across(centre.x) } else { along(centre.y) }) } } } + + /// The tab line of a [`DockSpot::Tab`] at `rect`, the rect it registered with: across its start edge. + pub(crate) fn tab_line(&self, rect: Rect, rtl: bool) -> Option<[Pos2; 2]> { + let x = if rtl { rect.right() } else { rect.left() }; + matches!(self, DockSpot::Tab { .. }).then(|| [Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom())]) + } } /// How a group's body divides into side zones. @@ -326,15 +335,17 @@ struct Target

{ applies: Rect, } -/// The spots of one dock in one pass with their hit rects. Spots are added back to front. +/// The spots of one dock in one pass with their hit rects, and the room the dock laid its panels out in. Spots are +/// added back to front. #[derive(Clone, Debug, PartialEq)] pub struct DockTargets

{ targets: Vec>, + room: Option, } impl

Default for DockTargets

{ fn default() -> Self { - DockTargets { targets: Vec::new() } + DockTargets { targets: Vec::new(), room: None } } } @@ -414,6 +425,21 @@ impl DockTargets

{ if !crate::runtime::measure::effect(ctx, "dock::register_target") { return; } + Self::with_dock(ctx, dock, |targets| targets.add(spot, hit, applies)); + } + + /// Registers `room`, the rect the dock `dock` lays its panels out in this pass: the docked tree's rect for a dock + /// area, the column's rect for a floating window. A drop's mark lays the panels out in it as they land + /// ([`placed_rect`](super::placed_rect)). + pub fn register_room(ctx: &Context, dock: Id, room: Rect) { + if !crate::runtime::measure::effect(ctx, "dock::register_room") { + return; + } + Self::with_dock(ctx, dock, |targets| targets.room = Some(room)); + } + + /// Runs `f` on the registry of `dock` in the running pass, made empty the first time. + fn with_dock(ctx: &Context, dock: Id, f: impl FnOnce(&mut DockTargets

)) { Self::with_pass(ctx, |pass| { let at = match pass.now.iter().position(|(id, _)| *id == dock) { Some(at) => at, @@ -422,10 +448,16 @@ impl DockTargets

{ pass.now.len() - 1 } }; - pass.now[at].1.add(spot, hit, applies); + f(&mut pass.now[at].1); }); } + /// The room the dock `dock` laid its panels out in the previous pass ([`Self::register_room`]); `None` outside a + /// pass and where the dock registered none. + pub fn room(ctx: &Context, dock: Id) -> Option { + Self::with_pass(ctx, |pass| pass.before.iter().find(|(id, _)| *id == dock).and_then(|(_, targets)| targets.room)).flatten() + } + /// The spot a drop at `at` lands on in the dock `dock`, by the spots of the previous pass, with the rect its /// mark applies to (`DockSpot::mark` takes it); `None` outside a pass. /// diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index dd311a833..7d27eb17c 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -8,13 +8,12 @@ use crate::contract::{ }; use crate::docking::SplitFramesCx as _; 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::{ 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, + IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, Placing, SplitArea, WindowColumn, actions, column_cells, dock_states, + frame, move_actions, stepped, with_area_rules, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, Commands as _, focus_within}; @@ -185,13 +184,16 @@ impl

Default for AreaMemory

{ } } -/// What the root's drop taker reads: the dock, the layout it shows, the rights and where a floating drop lands. +/// What the root's drop taker reads: the dock, the layout it shows, the rights, where a floating drop lands and what +/// the host hides. struct Drops<'a, P> { dock: Id, layout: &'a Layout

, permissions: &'a dyn Fn(&P) -> Permissions, config: &'a DockConfig, specs: &'a HashMap, + hide: HidePanels<'a, P>, + maximized: Option<&'a P>, rtl: bool, } @@ -200,13 +202,18 @@ impl Drops<'_, P> { fn take(&self, cx: &mut Cx<'_, DockRoot<'_, DockDropped

>>) -> Option> { let ctx = cx.core.ctx.clone(); let sizes = *cx.style.sizes(); - let bounds = cx.env.get::().0.as_ref().map_or(cx.rect, ShellCx::float_bounds); + let shell = cx.env.get::().0; + let bounds = shell.as_ref().map_or(cx.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, self.config, self.specs); + let spec = |panel: &P| spec_in(self.specs, panel); + let protected = |panel: &P| (self.permissions)(panel).is_protected(); + let (hide, _) = hide::resolved(self.hide, shell.as_ref()); let mut target = DockDropTarget::new(&ctx, self.dock, self.layout, self.permissions); target.rtl = self.rtl; target.space = Some(&space); target.float_on_empty = self.config.float_on_empty_drop; target.title_bar_docks = self.config.title_bar_docks; + target.placing = Some(Placing::new(sizes, &spec, &protected).shown(hide, self.maximized)); cx.drop_target::, _>(&target).or_else(|| cx.drop_target::(&target)) } } @@ -242,9 +249,14 @@ struct Scene<'s, P> { floated: &'s [(P, Location

)], } +/// The spec of `panel` in `specs`, or an unnamed one. +fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec { + specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) +} + impl Scene<'_, P> { fn spec(&self, panel: &P) -> PanelSpec { - self.specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) + spec_in(self.specs, panel) } fn permissions(&self, panel: &P) -> Permissions { @@ -352,7 +364,16 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { .collect(); let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL); let specs: HashMap = current.layout.panels().into_iter().map(|panel| (panel.clone(), panels.spec(panel))).collect(); - let drops = Drops { dock: id, layout: ¤t.layout, permissions: &policy, config: &config, specs: &specs, rtl }; + let drops = Drops { + dock: id, + layout: ¤t.layout, + permissions: &policy, + config: &config, + specs: &specs, + hide, + maximized: maximized.as_ref(), + rtl, + }; let shows = Arrangement { dock: id, revision: current.revision() }; end_replaced_drags::

(&ctx, shows); let dropped: RefCell>> = RefCell::new(None); @@ -542,31 +563,30 @@ fn show_area( }; let spec_of = |panel: &P| scene.spec(panel); - let limits = |panel: &P| scene.spec(panel).limits; - let dock_width = |columns: &[Column

]| scene.sizes.natural(columns, &spec_of).iter().map(|(width, _)| *width).sum::(); - let stripless = |panel: &P| scene.spec(panel).canvas; - let rules = FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless); let label = Label::from(body.words::().panels.as_str().to_owned()); let mut leaves: Vec<(Vec, Rect)> = Vec::new(); - let area = SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| { - for (anchor, rect) in split.group_frames::

() { - let Some(place) = scene.layout.place(&anchor) else { continue }; - let Some(node) = scene.layout.node_of(&place) else { continue }; - if let PanelPlace::Node(path) = &place { + let area = with_area_rules(&scene.sizes, &spec_of, |rules| { + SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| { + DockTargets::

::register_room(ctx, id, split.rect); + for (anchor, rect) in split.group_frames::

() { + let Some(place) = scene.layout.place(&anchor) else { continue }; + let Some(node) = scene.layout.node_of(&place) else { continue }; + if let PanelPlace::Node(path) = &place { + leaves.push((path.clone(), rect)); + } + pass.leaf(ui, split, node, rect); + } + let flow = Flow::new(split.rect, rtl); + for (edge, rect) in split.dock_frames() { + let Some(path) = scene.layout.dock_path(edge) else { continue }; + let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue }; leaves.push((path.clone(), rect)); + if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed() && crate::runtime::measure::effect(ctx, "shell::reveal_rect")) { + shell.reveal_rect(if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); + } + pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); } - pass.leaf(ui, split, node, rect); - } - let flow = Flow::new(split.rect, rtl); - for (edge, rect) in split.dock_frames() { - let Some(path) = scene.layout.dock_path(edge) else { continue }; - let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue }; - leaves.push((path.clone(), rect)); - if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed() && crate::runtime::measure::effect(ctx, "shell::reveal_rect")) { - shell.reveal_rect(if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); - } - pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); - } + }) }); let mut edit = area.output.edit.events.map(|edited| { let mut next = current.clone(); @@ -922,14 +942,8 @@ impl Pass<'_, P> { fn dock(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, plan: DockPlan<'_, P>) { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); - let widths = fit_widths(&scene.sizes.natural(plan.columns, &spec), plan.rect.width()); - let reading = plan.flow.to_physical(plan.rect); - let start = plan.edge == DockEdge::Start; - let mut cursor = if start { reading.left() } else { reading.right() }; - 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 mut cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range())); + let cells = column_cells(plan.columns, plan.rect, plan.edge, plan.flow, &scene.sizes, &spec); + for (column, mut cell) in plan.columns.iter().zip(cells) { 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. @@ -1031,6 +1045,9 @@ impl Pass<'_, P> { let dock = self.dock; let ColumnAt { cell, edge, bar, within, open } = at; let in_window = bar == ColumnBar::Window; + if in_window { + DockTargets::

::register_room(ui.ctx(), dock, cell); + } 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) @@ -1132,6 +1149,7 @@ impl Pass<'_, P> { let scene = self.scene; let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); + let protected = |panel: &P| scene.permissions(panel).is_protected(); let spec_of = |panel: &P| scene.spec(panel); let mut moved = None; for window in &scene.layout.floating { @@ -1158,6 +1176,8 @@ impl Pass<'_, P> { target.space = Some(scene.space); target.float_on_empty = scene.config.float_on_empty_drop; target.title_bar_docks = scene.config.title_bar_docks; + // The scene's layout is the pruned view the windows show, so the placing hides nothing more. + target.placing = Some(Placing::new(scene.sizes, &spec_of, &protected).window(window.id)); // The window is an instance of the group scope: its menu's command rows reach it, and run on its active // panel through the same path as a docked group's. let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &policy).floated(scene.floated), &active); diff --git a/crates/ui-patterns/src/patterns/dock/hide.rs b/crates/ui-patterns/src/patterns/dock/hide.rs index e6ca0e421..7ea931261 100644 --- a/crates/ui-patterns/src/patterns/dock/hide.rs +++ b/crates/ui-patterns/src/patterns/dock/hide.rs @@ -27,10 +27,16 @@ pub(super) fn shown<'a, P: Clone + Eq + Hash>( shell: Option<&ShellCx>, protected: &dyn Fn(&P) -> bool, ) -> Shown<'a, P> { - let (hide, floating) = match shell { + let (hide, floating) = resolved(hide, shell); + Shown { view: maximize(layout, maximized, hide, protected), floating } +} + +/// The panels the area hides, the host's `hide` with the shell's panel visibility applied, and whether floating windows +/// show (see [`shown`]). +pub(super) fn resolved<'h, P>(hide: HidePanels<'h, P>, shell: Option<&ShellCx>) -> (HidePanels<'h, P>, bool) { + 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/drop_preview.rs b/crates/ui-patterns/tests/it/docking/drop_preview.rs new file mode 100644 index 000000000..b7e75b5d1 --- /dev/null +++ b/crates/ui-patterns/tests/it/docking/drop_preview.rs @@ -0,0 +1,128 @@ +//! A dock drop's mark is the region the dragged panel takes once dropped: the rect the area then gives its group. + +use craft_behavior::Axis; +use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_ui::contract::{Bind, BodyCx, Role}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec}; +use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::drag::{self, DropMark}; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +const ROOM: Vec2 = Vec2::new(800.0, 500.0); +const SLACK: f32 = 0.5; + +/// Each group's rect as the area last showed it, by the group's panels. +type Shown = Rc, Rect>>>; + +/// Records the rect of every group the area shows and leaves the group to the dock. +struct Panels { + shown: Shown, +} + +impl DockPanels for Panels { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} + + fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + if let GroupAt::Show(rect) = at { + self.shown.borrow_mut().insert(panels.to_vec(), rect); + } + None + } +} + +struct Bed { + fixture: Fixture, + workspace: Rc>>, + shown: Shown, +} + +/// `[1, 2]` beside `[3]`. +fn bed() -> Bed { + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![1, 2], 0), Node::tabs(vec![3], 0)); + let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); + let shown: Shown = Rc::default(); + let (held, seen) = (Rc::clone(&workspace), Rc::clone(&shown)); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = held.borrow().clone(); + let mut panels = Panels { shown: Rc::clone(&seen) }; + DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + *held.borrow_mut() = workspace; + }); + fixture.room(ROOM).settle(); + Bed { fixture, workspace, shown } +} + +fn tab(bed: &Bed, panel: usize) -> Rect { + let tree = bed.fixture.tree(); + let name = format!("Panel {panel}"); + bed.fixture + .by_role(Role::TAB) + .into_iter() + .find(|tab| craft_ui::testing::access::name(tree, tab.node) == Some(name.as_str())) + .map(|tab| tab.rect) + .unwrap_or_else(|| panic!("the tab of panel {panel} shows")) +} + +/// Drags the tab of `panel` to `to` and returns the mark shown there, then releases it. +fn drop_tab(bed: &mut Bed, panel: usize, to: Pos2) -> DropMark { + let from = tab(bed, panel).center(); + bed.fixture.frame(vec![moved(from)]); + bed.fixture.frame(vec![press(from)]); + for step in 1..=4 { + bed.fixture.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))]); + } + bed.fixture.frame(Vec::new()); + let mark = drag::mark(bed.fixture.ctx()).expect("the dock takes the drop"); + bed.fixture.frame(vec![release(to)]); + bed.fixture.settle(); + mark +} + +/// The rect the area shows the group of `panel` in. +fn group_rect(bed: &Bed, panel: usize) -> Rect { + let layout = bed.workspace.borrow().layout.clone(); + let place = layout.place(&panel).expect("the panel is docked"); + let Some(Node::Tabs { panels, .. }) = layout.node_of(&place) else { panic!("panel {panel} is in a tab group") }; + *bed.shown.borrow().get(panels).unwrap_or_else(|| panic!("the group {panels:?} was shown")) +} + +fn same(a: Rect, b: Rect) -> bool { + (a.min - b.min).length() <= SLACK && (a.max - b.max).length() <= SLACK +} + +#[trial] +fn a_tab_dropped_beside_a_group_marks_the_rect_its_group_takes() { + let mut bed = bed(); + let right = group_rect(&bed, 3); + // In the bottom third of the right group's body, clear of the layout's bottom edge band. + let to = Pos2::new(right.center().x, right.bottom() - right.height() * 0.2); + let mark = drop_tab(&mut bed, 2, to); + let DropMark::Region { area, line: None, .. } = mark else { panic!("a side drop marks a region without a line: {mark:?}") }; + let placed = group_rect(&bed, 2); + assert!(placed.top() > right.top(), "the tab went below the right group: {placed:?}"); + assert!(same(area, placed), "the mark {area:?} is the rect the dropped panel's group took: {placed:?}"); +} + +#[trial] +fn a_tab_joining_a_group_marks_the_group_and_its_tab_line_and_a_reorder_marks_the_line_only() { + let mut bed = bed(); + let target = tab(&bed, 3); + let mark = drop_tab(&mut bed, 2, Pos2::new(target.right() + 20.0, target.center().y)); + let DropMark::Region { area, line: Some(_), .. } = mark else { panic!("a tab join marks a region with its tab line: {mark:?}") }; + let joined = group_rect(&bed, 2); + assert_eq!(joined, group_rect(&bed, 3), "the tab joined the right group"); + assert!(same(area, joined), "the mark {area:?} is the rect of the group it joined: {joined:?}"); + + let after = tab(&bed, 2); + let mark = drop_tab(&mut bed, 3, Pos2::new(after.right() + 10.0, after.center().y)); + assert!(matches!(mark, DropMark::Line { .. }), "a reorder inside its own strip marks its line only: {mark:?}"); +} diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 0f335e877..4ea3299d4 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -133,7 +133,7 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { let mark = drag::mark(bed.fixture.ctx()).expect("the window takes the drop"); let points = match mark { DropMark::Line { from, to, .. } => vec![from, to], - DropMark::Into(rect) | DropMark::Split(rect) => vec![rect.center()], + DropMark::Into(rect) | DropMark::Region { area: rect, .. } => vec![rect.center()], _ => Vec::new(), }; assert!(!points.is_empty() && points.iter().all(|point| WINDOW_AT.expand(SLACK).contains(*point)), "the mark is the window's: {mark:?}"); @@ -481,7 +481,7 @@ fn a_drag_over_a_floating_window_joins_or_stacks_and_never_splits() { 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:?}"); + assert!(matches!(mark, DropMark::Region { .. }), "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); diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index 61631da3e..2243f997e 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -12,6 +12,7 @@ mod runs; mod split; mod drop; +mod drop_preview; mod drop_session; mod floating;