diff --git a/crates/behavior/src/dock/arrange.rs b/crates/behavior/src/dock/arrange.rs index ec2bc27d85..7984ce4498 100644 --- a/crates/behavior/src/dock/arrange.rs +++ b/crates/behavior/src/dock/arrange.rs @@ -4,15 +4,16 @@ use emath::{Rect, vec2}; /// One Window › Arrange entry. The n-up entries split the document area into that many -/// cells and put one document group in each, and Tile one cell per document; the rest act on -/// windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). +/// cells and put one document group in each, and Tile All and Tile one cell per document; the +/// rest act on windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Arrangement { - /// Tiles every document window across the document area, side by side. + /// One cell per document across the document area, side by side, floating windows docked + /// first. TileAllVertically, - /// Tiles every document window across the document area, stacked. + /// One cell per document across the document area, stacked, floating windows docked first. TileAllHorizontally, /// Two cells, side by side. TwoUpVertical, diff --git a/crates/behavior/src/dock/windows.rs b/crates/behavior/src/dock/windows.rs index 47246507bc..64d3a81b54 100644 --- a/crates/behavior/src/dock/windows.rs +++ b/crates/behavior/src/dock/windows.rs @@ -33,7 +33,7 @@ pub struct DocumentWindows { /// The floating groups, each with its window rect. #[serde(with = "floating_serde")] pub floating: Vec<(DocumentGroup, Rect)>, - /// The n-up or Tile arrangement the document area shows: set by Window › Arrange, cleared by + /// The n-up, Tile All or Tile arrangement the document area shows: set by Window › Arrange, cleared by /// Consolidate and by floating a document. #[serde(default)] pub arrangement: Option, diff --git a/crates/ui-contract/src/contract/collection.rs b/crates/ui-contract/src/contract/collection.rs index 11417d5159..da36f5cb0c 100644 --- a/crates/ui-contract/src/contract/collection.rs +++ b/crates/ui-contract/src/contract/collection.rs @@ -13,7 +13,7 @@ pub use events::{ }; pub use props::{ ActivateOn, CollectionProps, DeleteTarget, DragPayload, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ReorderRule, RowHeight, RowPressed, - RowState, SelectMode, SpaceAction, + RowPreview, RowState, SelectMode, SpaceAction, }; pub(crate) use response::Gestures; pub(crate) use response::ItemsOut; diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index 2e2fd99e25..fc7416ed45 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -37,6 +37,23 @@ pub enum DeleteTarget { FocusOrHover, } +/// What a row drag shows while it runs. The text is the count word for the dragged items +/// (`CollectionProps::drag_count`), else the number of items for several and the item's text for one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum RowPreview { + /// The text in a badge by the pointer. + #[default] + Badge, + /// The text inside the region a drop would take, where the target marks one ([`DragPreview::Named`]); nothing + /// by the pointer. + /// + /// [`DragPreview::Named`]: crate::runtime::drag::DragPreview::Named + Named, + /// No preview: the dragged row shows alone. + None, +} + /// How the user may reorder items. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] @@ -246,11 +263,11 @@ pub struct CollectionProps { /// Map a row drag to the payloads that other drop targets take (8.4), one per type. A map starts row drags by /// itself, with or without a reorder rule. pub drag_payloads: Vec, - /// The count word the drag badge shows for the dragged items, one item included ("1 page", "3 pages"); `None` - /// shows the number of items for several and the item's text for one. + /// The count word a row drag's preview shows for the dragged items, one item included ("1 page", "3 pages"); + /// `None` shows the number of items for several and the item's text for one. pub drag_count: Option, - /// Whether a row drag shows its badge by the pointer. Off, the drag carries no preview. - pub drag_badge: bool, + /// What a row drag shows while it runs. + pub drag_preview: RowPreview, /// The collection takes the full height of its rows and owns no scroll, so it can sit inside a scrolling page: /// every row is built, the wheel and the keys that move past an end act on the page's scroll owner, and moving /// the lead scrolls the page to keep the row in view. For short collections only; a long one keeps its own @@ -369,7 +386,7 @@ impl CollectionProps { delete_target: DeleteTarget::Focus, drag_payloads: Vec::new(), drag_count: None, - drag_badge: true, + drag_preview: RowPreview::Badge, natural_height: false, min_rows: 0, max_rows: None, @@ -424,14 +441,14 @@ impl CollectionProps { self } - /// Whether a row drag shows its badge by the pointer (on by default). + /// What a row drag shows while it runs (a badge by the pointer by default). #[must_use] - pub const fn drag_badge(mut self, on: bool) -> Self { - self.drag_badge = on; + pub const fn drag_preview(mut self, preview: RowPreview) -> Self { + self.drag_preview = preview; self } - /// The drag badge reads `count` for the number of dragged items. + /// A row drag's preview reads `count` for the number of dragged items. #[must_use] pub const fn drag_count(mut self, count: Counted) -> Self { self.drag_count = Some(count); diff --git a/crates/ui-contract/src/contract/items/drag.rs b/crates/ui-contract/src/contract/items/drag.rs index dc7c0e161e..7a98c8f73d 100644 --- a/crates/ui-contract/src/contract/items/drag.rs +++ b/crates/ui-contract/src/contract/items/drag.rs @@ -10,7 +10,7 @@ use super::marquee::MarqueeDrag; use super::{ItemsHooks, Placement}; use crate::contract::collection::{ - CollectionEvent, CollectionProps, ColumnKind, ContextMenuRequest, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, + CollectionEvent, CollectionProps, ColumnKind, ContextMenuRequest, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, RowPreview, ToggleColumn, ToggleEdit, }; use crate::contract::reorder; @@ -25,6 +25,7 @@ use craft_behavior::{ }; use egui::{Pos2, Rect, Vec2}; use std::any::Any; +use std::borrow::Cow; /// Maps a point to layout coordinates once for every collection type. fn logical_point(layout: &dyn ItemLayout, rect: Rect, rtl: bool, at: Pos2) -> Pos2 { @@ -591,11 +592,15 @@ impl ItemsHooks<'_, '_, C> { let key = self.source.key(at); let keys = self.keys_at(&self.acted_on(at)); let count = keys.len() as u64; - let preview = match props.drag_count.filter(|_| props.drag_badge) { - Some(word) => DragPreview::Badge(Label::from(cx.env.counted(word, count))), - None if !props.drag_badge => DragPreview::None, - None if count > 1 => DragPreview::Badge(Label::from(count.to_string())), - None => self.source.text(at).map_or(DragPreview::None, |text| DragPreview::Badge(Label::from(text.into_owned()))), + let text = || match props.drag_count { + Some(word) => Some(cx.env.counted(word, count)), + None if count > 1 => Some(count.to_string()), + None => self.source.text(at).map(Cow::into_owned), + }; + let preview = match props.drag_preview { + RowPreview::Badge => text().map_or(DragPreview::None, |text| DragPreview::Badge(Label::from(text))), + RowPreview::Named => text().map_or(DragPreview::None, |text| DragPreview::Named(Label::from(text))), + _ => DragPreview::None, }; let drag = ListDrag::new(id, keys, key.clone()); let also: Vec<_> = props.drag_payloads.iter().filter_map(|map| map.of(&drag)).collect(); diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 03dd21d444..9ba2a3a73e 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -61,7 +61,7 @@ pub use collection::{ ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove, ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DeleteTarget, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest, HoverLead, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, - RowPressed, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, + RowPressed, RowPreview, RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, }; #[doc(hidden)] pub use container::InBar; diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 30dfc6f6af..357c3484ad 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -959,14 +959,26 @@ pub(crate) struct Ghost { pub mark: Option<(DropMark, Arc)>, } -/// The running session's ghost data. +/// The running session's ghost data for the running viewport. The mark paints in the window whose target registered +/// it, and also in the window the session moves, mapped to the same desktop place: that window lies over the mark, +/// which would otherwise show only through it. pub(crate) fn ghost(ctx: &Context) -> Option { let viewport = pass::current_viewport(ctx); - board(ctx, |board| { - board.session.as_ref().map(|session| Ghost { - preview: session.preview.clone(), - env: session.env.clone(), - mark: session.mark.as_ref().filter(|shown| shown.viewport == viewport).map(|shown| (shown.mark, shown.tokens.clone())), - }) - }) + let (preview, env, mark, moves_this) = board(ctx, |board| { + board + .session + .as_ref() + .map(|session| (session.preview.clone(), session.env.clone(), session.mark.clone(), session.moving.viewport == Some(viewport))) + })?; + let mark = mark.and_then(|shown| { + let offset = if shown.viewport == viewport { + Vec2::ZERO + } else if moves_this { + WindowHost::of(ctx).offset_between(shown.viewport, viewport)? + } else { + return None; + }; + Some((shown.mark.mapped(|point| point + offset), shown.tokens)) + }); + Some(Ghost { preview, env, mark }) } diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 0d747a7260..a6002db479 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -477,9 +477,20 @@ impl WindowHost { /// The desktop pointer in the coordinates of `viewport`, when it lies inside that window. pub fn pointer_in(&self, viewport: ViewportId) -> Option { let desktop = self.desktop_pointer()?; - let inner = PerViewport::::with(&self.ctx, viewport, |record| record.facts.and_then(|facts| facts.inner))?; + let inner = self.inner_on_desktop(viewport)?; inner.contains(desktop).then(|| Pos2::ZERO + (desktop - inner.min)) } + + /// What a point of `from`'s window adds to land at the same desktop place in `to`'s window, by the inner rects + /// the windows last reported, as [`Self::pointer_in`] maps the desktop pointer. + pub(crate) fn offset_between(&self, from: ViewportId, to: ViewportId) -> Option { + Some(self.inner_on_desktop(from)?.min - self.inner_on_desktop(to)?.min) + } + + /// The inner rect of `viewport`'s window on the desktop, as the window last reported it. + fn inner_on_desktop(&self, viewport: ViewportId) -> Option { + PerViewport::::with(&self.ctx, viewport, |record| record.facts.and_then(|facts| facts.inner)) + } } /// The frame of `viewport`'s window as its chrome and the caption buttons it was opened with tell it, for a window diff --git a/crates/ui-macros/src/props.rs b/crates/ui-macros/src/props.rs index ff8addf8db..005cce8e7f 100644 --- a/crates/ui-macros/src/props.rs +++ b/crates/ui-macros/src/props.rs @@ -194,8 +194,12 @@ const COLLECTION: &[Forwarded] = &[ ("marquee", "bool", "A drag on the background selects the rows it covers."), ("deletable", "bool", "Delete and Backspace at the lead report the items to delete."), ("delete_target", "$ui::contract::DeleteTarget", "Where a deletable collection takes Delete and Backspace."), - ("drag_count", "$ui::runtime::env::Counted", "The drag badge reads this count word for the dragged items, one included."), - ("drag_badge", "bool", "A row drag shows its badge by the pointer (default on); off, the dragged row shows alone."), + ("drag_count", "$ui::runtime::env::Counted", "A row drag's preview reads this count word for the dragged items, one included."), + ( + "drag_preview", + "$ui::contract::RowPreview", + "What a row drag shows: a badge by the pointer (default), its name inside the drop region, or nothing.", + ), ("natural_height", "bool", "The collection takes its full content height and owns no scroll: for a short collection inside a scrolling page."), ("min_rows", "u16", "The collection is at least this many rows tall; rows it does not have count the row height."), ("max_rows", "u16", "The collection shows at most this many rows and scrolls the rest, inside a scrolling body too."), diff --git a/crates/ui-panels/src/docking/commands/arrange.rs b/crates/ui-panels/src/docking/commands/arrange.rs index 0f02c7bb40..91829b958f 100644 --- a/crates/ui-panels/src/docking/commands/arrange.rs +++ b/crates/ui-panels/src/docking/commands/arrange.rs @@ -1,7 +1,7 @@ //! The Window › Arrange commands and how they place the document windows. use crate::runtime::commands::CommandState; -use craft_behavior::dock::{Arrangement, DocumentWindows, arrange_rects}; +use craft_behavior::dock::{Arrangement, DocumentWindows}; use craft_behavior::placement::cascade_rects; use egui::{Rect, Vec2}; use std::hash::Hash; @@ -11,10 +11,10 @@ use std::hash::Hash; #[command(prefix = "arrange")] #[non_exhaustive] pub enum ArrangeCommands { - /// Tile every document window across the document area, side by side. + /// Every document in its own cell of the document area, side by side, floating windows docked first. #[command(label = "Tile All Vertically")] TileAllVertically, - /// Tile every document window across the document area, stacked. + /// Every document in its own cell of the document area, stacked, floating windows docked first. #[command(label = "Tile All Horizontally")] TileAllHorizontally, /// Two document groups, side by side. @@ -154,7 +154,7 @@ impl ArrangeSpace { #[non_exhaustive] pub enum Arranged { /// The document windows changed: the host applies `DocumentWindows::to_actions`, and lays the docked groups out - /// with `arrange_rects` for an n-up or Tile arrangement. + /// with `arrange_rects` for an n-up, Tile All or Tile arrangement. Windows, /// Every document view takes the active view's zoom, location and rotation, as flagged. #[non_exhaustive] @@ -174,11 +174,7 @@ pub fn arrange(windows: &mut DocumentWindows, command: let ArrangeSpace { area, size, step, active } = space; let next_slot = |windows: &DocumentWindows| cascade_rects(*area, *size, windows.floating.len() + 1, *step).pop(); match arrangement { - Arrangement::TileAllVertically | Arrangement::TileAllHorizontally => { - windows.float_all(*area, *size, *step); - tile_floating(windows, arrangement, *area); - } - Arrangement::Tile => { + Arrangement::TileAllVertically | Arrangement::TileAllHorizontally | Arrangement::Tile => { windows.consolidate(active.as_ref()); let documents = windows.docked.first().map_or(0, |group| group.documents.len()); windows.split_into(documents); @@ -221,10 +217,3 @@ pub fn arrange(windows: &mut DocumentWindows, command: } Arranged::Windows } - -fn tile_floating(windows: &mut DocumentWindows, arrangement: Arrangement, area: Rect) { - let Some(rects) = arrange_rects(arrangement, area, windows.floating.len()) else { return }; - for ((_, rect), tiled) in windows.floating.iter_mut().zip(rects) { - *rect = tiled; - } -} diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 8376328a18..8aa8668a3b 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -299,8 +299,8 @@ where /// 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. 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 +/// region the unit takes once dropped, laid out in the room the dock registered ([`placed_rect`]); a tab insertion +/// marks the group it joins as shown now, with its tab line; 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 @@ -365,13 +365,20 @@ impl DockDropTarget<'_, P> { self.float(&unit, at, drag.source(), drag.strip(), drag.press()) } - /// 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. + /// The region a drop of `unit` on `spot` marks: for a tab join, the group it joins as shown now (production's + /// mark: the group under the pointer, not the size it grows to); else the rect the panels of `unit` take in + /// `after`, the layout once dropped. `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; + if let DockSpot::Tab { anchor, .. } = spot { + if on_unit(self.layout, spot, unit) { + return None; + } + let group = members(self.layout, anchor); + if let Some(rect) = DockTargets::

::group_rect(self.ctx, self.dock, |panel| group.contains(panel)) { + return Some(rect); + } } let room = DockTargets::

::room(self.ctx, self.dock)?; placed_rect(after, &moving_panels(self.layout, unit), room, placing, self.rtl) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 16184feac5..a3ffef3dcf 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -778,6 +778,8 @@ fn tab_row(row: &mu .shown(active) .tear_off() .natural_height(true) + // Group, column and icon drags name what they move inside the drop region; a tab drag does the same. + .drag_preview(crate::contract::RowPreview::Named) .can_close(move |key: &PanelKey| panels.iter().any(|panel| &panel.key == key && closes(panel))) .drag_payload(move |drag: &ListDrag| Some(PanelDrag { panel: drag.grabbed, from, source: None, started: None })); if row.wheel_selects { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 467df4b572..c42db4747e 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -573,6 +573,20 @@ impl DockTargets

{ pub fn resolve(ctx: &Context, dock: Id, at: Pos2) -> Option<(DockSpot

, Rect)> { Self::with_pass(ctx, |pass| pass.before.iter().find(|(id, _)| *id == dock).and_then(|(_, targets)| targets.at(at))).flatten() } + + /// The rect of a group in the dock `dock` as the previous pass showed it, by the side spots it registered (a + /// [`DockSpot::Group`] applies to its group's rect); `in_group` tells the group's panels. `None` outside a pass + /// and for a group that registered no side spots, such as a minimized one. + pub(crate) fn group_rect(ctx: &Context, dock: Id, in_group: impl Fn(&P) -> bool) -> Option { + Self::with_pass(ctx, |pass| { + let (_, targets) = pass.before.iter().find(|(id, _)| *id == dock)?; + targets.targets.iter().find_map(|target| match &target.spot { + DockSpot::Group { anchor, .. } if in_group(anchor) => Some(target.applies), + _ => None, + }) + }) + .flatten() + } } /// The registrations of a pass. A settled memoized view's run record keeps each one to make it again and compares it diff --git a/crates/ui-panels/tests/it/arrange.rs b/crates/ui-panels/tests/it/arrange.rs new file mode 100644 index 0000000000..7390f91b4f --- /dev/null +++ b/crates/ui-panels/tests/it/arrange.rs @@ -0,0 +1,42 @@ +//! Window › Arrange over the document windows. + +use craft_behavior::dock::{Arrangement, DocumentGroup, DocumentWindows, arrange_rects}; +use craft_ui::docking::{ArrangeCommands, ArrangeSpace, Arranged, arrange}; +use craft_ui::testing::trial; +use egui::{Pos2, Rect, Vec2}; + +const AREA: Rect = Rect { min: Pos2::new(0.0, 40.0), max: Pos2::new(900.0, 640.0) }; + +/// Two documents docked in one group and a third in a floating window. +fn windows() -> DocumentWindows { + let mut windows = DocumentWindows::default(); + windows.docked = vec![DocumentGroup::new(0, vec![1, 2])]; + windows.floating = vec![(DocumentGroup::new(1, vec![3]), Rect::from_min_size(Pos2::new(50.0, 80.0), Vec2::new(300.0, 200.0)))]; + windows +} + +/// Tile All lays every document out in docked cells of the document area, as Tile does: no document is left in (or +/// moved into) a floating window, each gets its own group, and the cells run across or down the area. +#[trial] +fn tile_all_docks_every_document_in_its_own_cell_of_the_document_area() { + let space = ArrangeSpace::new(AREA, Vec2::new(400.0, 300.0), 24.0, Some(1)); + for (command, arrangement) in [ + (ArrangeCommands::TileAllVertically, Arrangement::TileAllVertically), + (ArrangeCommands::TileAllHorizontally, Arrangement::TileAllHorizontally), + ] { + let mut windows = windows(); + assert_eq!(arrange(&mut windows, command, &space), Arranged::Windows); + assert!(windows.floating.is_empty(), "{command:?} leaves no floating window: {:?}", windows.floating); + let groups: Vec<_> = windows.docked.iter().map(|group| group.documents.clone()).collect(); + assert_eq!(groups, [vec![1], vec![2], vec![3]], "{command:?} gives each document its own docked group"); + assert_eq!(windows.arrangement, Some(arrangement), "{command:?} is the arrangement the document area shows"); + let cells = arrange_rects(arrangement, AREA, groups.len()).expect("Tile All has cells for three documents"); + assert!(cells.iter().all(|cell| AREA.contains_rect(*cell)), "the cells lie in the document area: {cells:?}"); + let across = cells.windows(2).all(|pair| pair[1].left() >= pair[0].right() - 0.5); + let down = cells.windows(2).all(|pair| pair[1].top() >= pair[0].bottom() - 0.5); + match arrangement { + Arrangement::TileAllVertically => assert!(across, "Tile All Vertically puts the cells side by side: {cells:?}"), + _ => assert!(down, "Tile All Horizontally stacks the cells: {cells:?}"), + } + } +} diff --git a/crates/ui-panels/tests/it/main.rs b/crates/ui-panels/tests/it/main.rs index 70872c8f4c..83aaa72406 100644 --- a/crates/ui-panels/tests/it/main.rs +++ b/crates/ui-panels/tests/it/main.rs @@ -4,6 +4,7 @@ extern crate craft_ui_panels as craft_ui; pub(crate) mod access; +pub(crate) mod arrange; pub(crate) mod body; pub(crate) mod dialogs; pub(crate) mod dock_group; diff --git a/crates/ui-patterns/tests/it/docking/drop_preview.rs b/crates/ui-patterns/tests/it/docking/drop_preview.rs index 021ccf828e..412ef3e703 100644 --- a/crates/ui-patterns/tests/it/docking/drop_preview.rs +++ b/crates/ui-patterns/tests/it/docking/drop_preview.rs @@ -9,7 +9,7 @@ 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 egui::{Pos2, Rect, Shape, Ui, Vec2}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; @@ -93,6 +93,17 @@ fn drop_tab(bed: &mut Bed, panel: usize, to: Pos2) -> DropMark { mark } +/// Presses the tab of `panel` and drags it to `to`, holding the button there. +fn hold_tab_at(bed: &mut Bed, panel: usize, to: Pos2) { + 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()); +} + /// 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(); @@ -133,6 +144,51 @@ fn a_tab_joining_a_group_marks_the_group_and_its_tab_line_and_a_reorder_marks_th assert!(matches!(mark, DropMark::Line { .. }), "a reorder inside its own strip marks its line only: {mark:?}"); } +/// A tab that joins a group whose rect grows once its own group goes marks the group as it is under the pointer, as +/// production did, not the larger rect the group takes after the drop. +#[trial] +fn a_tab_joining_a_group_marks_the_group_as_shown_now_not_the_rect_it_grows_to() { + let mut bed = bed(); + let before = group_rect(&bed, 3); + let target = tab(&bed, 3); + let mark = drop_tab(&mut bed, 4, 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 after = group_rect(&bed, 4); + assert_eq!(after, group_rect(&bed, 3), "the tab joined the right group"); + assert!(after.height() > before.height() + SLACK, "the group grew once the top group went: {before:?} -> {after:?}"); + assert!(same(area, before), "the mark {area:?} is the group as it was under the pointer: {before:?}"); +} + +/// A tab drag names its panel inside the region a drop takes, at the region's top, as group drags do; no badge with +/// the name follows the pointer. +#[trial] +fn a_tab_drag_names_its_panel_inside_the_drop_region_and_not_by_the_pointer() { + let mut bed = bed(); + let own = tab(&bed, 2); + let right = group_rect(&bed, 3); + let to = Pos2::new(right.center().x, right.bottom() - right.height() * 0.2); + hold_tab_at(&mut bed, 2, to); + let Some(DropMark::Region { area, .. }) = drag::mark(bed.fixture.ctx()) else { panic!("the dock marks the region below the right group") }; + assert!(to.y > area.center().y, "the pointer {to:?} is in the region's lower half: {area:?}"); + let names: Vec = bed + .fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + Shape::Text(text) if text.galley.text() == "Panel 2" => Some(shape.visual_bounding_rect()), + _ => None, + }) + .filter(|rect| !own.intersects(*rect)) + .collect(); + assert!(!names.is_empty(), "the panel's name shows while it is dragged"); + for name in &names { + // The pointer is in the region's lower half, so a badge beside it would be too. + assert!(area.contains_rect(*name) && name.bottom() < area.center().y, "the name {name:?} sits at the top of the region {area:?}"); + } + bed.fixture.frame(vec![release(to)]); + bed.fixture.settle(); +} + /// A strip along the layout's top edge takes tab joins: the band there, where a drop adds a full-width row, reaches /// into the strip only near the edge. #[trial] diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index aa82dee486..81f0909430 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -25,7 +25,9 @@ use craft_ui::testing::trial; use craft_ui::testing::windows::{FakeSystem, HeldButtons}; use craft_ui::text::NumberField; use craft_ui_test_kit::windows::{AppKitWindow, FilesOver, Out, Windows}; -use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; +use egui::{ + Event, HoveredFile, Key, Modifiers, Pos2, Rect, Shape, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo, +}; use std::sync::Arc; /// The root window and the palette overlap; the palette is the larger. @@ -270,6 +272,8 @@ struct NativeDock { palette: Option, /// The tree the palette window's pass produced in the last frame. palette_tree: Option, + /// The shapes the palette window's pass painted in the last frame. + palette_shapes: Vec, /// Whether Auto-Collapse Iconic Panels is on in the frames of a collapsed palette. auto_collapse: bool, } @@ -293,7 +297,17 @@ impl NativeDock { windows.child_info(info(true, FLOAT_AT)); let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette]))); let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped }); - let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None, auto_collapse: false }; + let mut dock = NativeDock { + windows, + workspace, + stepped, + specs, + builder: None, + palette: None, + palette_tree: None, + palette_shapes: Vec::new(), + auto_collapse: false, + }; for _ in 0..3 { dock.frame(vec![]); } @@ -320,6 +334,7 @@ impl NativeDock { } let palette = self.palette; self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree); + self.palette_shapes = out.shapes.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, shapes)| shapes).unwrap_or_default(); for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { @@ -384,6 +399,37 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_app_moves_windo assert!(!docked, "a cancelled move docks nothing"); } +/// A palette moved by its title row over the main window's group lies over the mark the group shows: its own window +/// paints the mark too, at the same desktop place by the windows' inner rects, so the mark shows over the palette and +/// not only through its faded window. +#[trial] +fn a_native_palette_moved_over_a_drop_target_paints_the_mark_over_itself() { + let mut dock = NativeDock::on(Os::Linux, Arc::new(FakeSystem::new())); + let step = (OVER_GROUP - (FLOAT_AT.min + ROW_AT.to_vec2())) / 3.0; + for events in [vec![moved(ROW_AT)], vec![press(ROW_AT)]] { + dock.frame(events); + } + for _ in 0..3 { + dock.frame(vec![moved(ROW_AT + step)]); + } + dock.frame(vec![]); + let area = match drag::mark(&dock.windows.ctx) { + Some(DropMark::Region { area, .. } | DropMark::Into(area)) => area, + mark => panic!("the main window's group marks the region the palette takes: {mark:?}"), + }; + dock.frame(vec![]); + let palette = dock.palette.expect("the palette has its window"); + let inner = dock.windows.facts(palette).inner_rect.expect("the palette reports its inner rect"); + let mapped = area.translate(MAIN_AT.min - inner.min); + let shows = dock.palette_shapes.iter().any( + |shape| matches!(shape, Shape::Rect(rect) if (rect.rect.min - mapped.min).length() < 0.5 && (rect.rect.max - mapped.max).length() < 0.5), + ); + assert!(shows, "the palette's window paints the mark at {mapped:?}, where the main window's {area:?} lies under it"); + for events in [vec![key_press(Key::Escape, Modifiers::NONE)], vec![release(ROW_AT)], vec![]] { + dock.frame(events); + } +} + /// Where the app moves windows itself and the platform tells the system pointer (Windows): the window follows the /// system pointer, not the pass's pointer event, which can be an older sample than the window's current place (the /// window moves between passes). Measured from such an event the window lands a step behind the pointer each pass and diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index d54eafd75c..bbda539b5c 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -36,6 +36,8 @@ thread_local! { static COMMANDS: RefCell> = const { RefCell::new(Vec::new()) }; /// The AccessKit tree each viewport's last pass produced, in pass order. static TREES: RefCell> = const { RefCell::new(Vec::new()) }; + /// The shapes each pass of the frame painted, nested shapes flattened. + static SHAPES: RefCell)>> = const { RefCell::new(Vec::new()) }; /// The time every pass of the frame runs at. static NOW: Cell = const { Cell::new(0.0) }; /// Each child's builder as its window has it: a later builder patches it, and what changed goes to the window as @@ -205,6 +207,18 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { fn keep_tree(output: &mut FullOutput, viewport: ViewportId) { let tree = tree_of(output); TREES.with(|kept| kept.borrow_mut().push((viewport, tree))); + let mut shapes = Vec::new(); + for clipped in &output.shapes { + flatten(&clipped.shape, &mut shapes); + } + SHAPES.with(|kept| kept.borrow_mut().push((viewport, shapes))); +} + +fn flatten(shape: &egui::Shape, into: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten(shape, into)), + shape => into.push(shape.clone()), + } } /// An OS window as macOS runs egui's window commands on it through winit, in desktop points with y down: a position @@ -256,6 +270,8 @@ pub struct Out { /// The AccessKit tree each viewport's pass produced, in pass order: the children's first, as they run inside the /// root's pass. pub trees: Vec<(ViewportId, AccessTree)>, + /// The shapes each viewport's pass painted, nested shapes flattened, in the order of `trees`. + pub shapes: Vec<(ViewportId, Vec)>, } /// A context with the runtime installed whose child viewports are OS windows. @@ -343,6 +359,7 @@ impl Windows { root_dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); CHILD_FILES.with(|files| *files.borrow_mut() = child_files); TREES.with(|kept| kept.borrow_mut().clear()); + SHAPES.with(|kept| kept.borrow_mut().clear()); set_input(&self.ctx, FrameInput::new(self.root.borrow().clone())); let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, ROOT_SIZE)), @@ -373,6 +390,7 @@ impl Windows { commands: COMMANDS.with(|kept| std::mem::take(&mut *kept.borrow_mut())), builders, trees: TREES.with(|kept| std::mem::take(&mut *kept.borrow_mut())), + shapes: SHAPES.with(|kept| std::mem::take(&mut *kept.borrow_mut())), } } } diff --git a/crates/ui-widgets/src/tabs/document.rs b/crates/ui-widgets/src/tabs/document.rs index ae46d1c59c..5a8842e27d 100644 --- a/crates/ui-widgets/src/tabs/document.rs +++ b/crates/ui-widgets/src/tabs/document.rs @@ -300,7 +300,7 @@ impl<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Documen strip = strip .reorder(ReorderRule::new()) // The held tab is the preview; production shows no filename badge beside the pointer. - .drag_badge(false) + .drag_preview(crate::contract::RowPreview::None) .can_drag(move |key: &D| tabs.iter().find(|tab| &tab.id == key).is_none_or(|tab| tab.movable)) .accepts(move |drag: &ListDrag, _, insert| { // `insert` counts every tab; `keeps_fixed` takes the place among the tabs left without the dragged ones.