Merge pull request #3293 from aiongg/rc-dock-drag

Docking: one drop mark, the panel's name in the drop region, and Tile All in docked cells
This commit is contained in:
aiongg
2026-11-24 09:46:18 -05:00
committed by GitHub
19 changed files with 285 additions and 60 deletions
+5 -4
View File
@@ -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,
+1 -1
View File
@@ -33,7 +33,7 @@ pub struct DocumentWindows<D> {
/// The floating groups, each with its window rect.
#[serde(with = "floating_serde")]
pub floating: Vec<(DocumentGroup<D>, 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<Arrangement>,
@@ -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;
@@ -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<DragPayload>,
/// 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<Counted>,
/// 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);
+11 -6
View File
@@ -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<C: Collection> 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();
+1 -1
View File
@@ -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;
+20 -8
View File
@@ -959,14 +959,26 @@ pub(crate) struct Ghost {
pub mark: Option<(DropMark, Arc<UiTokens>)>,
}
/// 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<Ghost> {
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 })
}
+12 -1
View File
@@ -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<Pos2> {
let desktop = self.desktop_pointer()?;
let inner = PerViewport::<Record>::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<Vec2> {
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<Rect> {
PerViewport::<Record>::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
+6 -2
View File
@@ -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."),
@@ -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<D> ArrangeSpace<D> {
#[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<D: Clone + Eq + Hash>(windows: &mut DocumentWindows<D>, command:
let ArrangeSpace { area, size, step, active } = space;
let next_slot = |windows: &DocumentWindows<D>| 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<D: Clone + Eq + Hash>(windows: &mut DocumentWindows<D>, command:
}
Arranged::Windows
}
fn tile_floating<D: Clone + Eq + Hash>(windows: &mut DocumentWindows<D>, 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;
}
}
+14 -7
View File
@@ -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<P: Clone + Eq + Hash + Send + 'static> 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<P>, unit: &DragUnit<P>, after: &Layout<P>) -> Option<Rect> {
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::<P>::group_rect(self.ctx, self.dock, |panel| group.contains(panel)) {
return Some(rect);
}
}
let room = DockTargets::<P>::room(self.ctx, self.dock)?;
placed_rect(after, &moving_panels(self.layout, unit), room, placing, self.rtl)
+2
View File
@@ -778,6 +778,8 @@ fn tab_row<P: Clone + PartialEq + Debug + Hash + Send + Sync + 'static>(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<PanelKey>| Some(PanelDrag { panel: drag.grabbed, from, source: None, started: None }));
if row.wheel_selects {
+14
View File
@@ -573,6 +573,20 @@ impl<P: Clone + Send + 'static> DockTargets<P> {
pub fn resolve(ctx: &Context, dock: Id, at: Pos2) -> Option<(DockSpot<P>, 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<Rect> {
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
+42
View File
@@ -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<u32> {
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:?}"),
}
}
}
+1
View File
@@ -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;
@@ -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<Rect> = 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]
+48 -2
View File
@@ -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<ViewportId>,
/// The tree the palette window's pass produced in the last frame.
palette_tree: Option<AccessTree>,
/// The shapes the palette window's pass painted in the last frame.
palette_shapes: Vec<Shape>,
/// 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
+18
View File
@@ -36,6 +36,8 @@ thread_local! {
static COMMANDS: RefCell<Vec<(ViewportId, ViewportCommand)>> = const { RefCell::new(Vec::new()) };
/// The AccessKit tree each viewport's last pass produced, in pass order.
static TREES: RefCell<Vec<(ViewportId, AccessTree)>> = const { RefCell::new(Vec::new()) };
/// The shapes each pass of the frame painted, nested shapes flattened.
static SHAPES: RefCell<Vec<(ViewportId, Vec<egui::Shape>)>> = const { RefCell::new(Vec::new()) };
/// The time every pass of the frame runs at.
static NOW: Cell<f64> = 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<egui::Shape>) {
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<egui::Shape>)>,
}
/// 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())),
}
}
}
+1 -1
View File
@@ -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<D>, _, insert| {
// `insert` counts every tab; `keeps_fixed` takes the place among the tabs left without the dragged ones.