diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index e5d94a6f3..d420f42cb 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -672,7 +672,7 @@ impl ShapeHooks for BodyHooks<'_> { if (band || matches!(props.mount, Mount::Viewport { .. } | Mount::Window { .. })) && let Some(viewport) = os_window(props, cx.core.memory.ctx(), cx.core.id, &cx.core.env) { - self.window_os(viewport, cx); + self.window_os(viewport, props, cx); self.window_movable(viewport, cx); } self.pane_drag(props, cx); diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 9fd863124..ffe88ce16 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -97,6 +97,7 @@ pub(super) struct WindowMode { restore: Placement, began: Option, moving: Option, + sizing: Option, /// The index in `GRIPS` of the grip a drag holds, from its `DragStart` to its release: `move_parts` keeps it /// declared when the drag flips the layer to a side whose placement holds its edge, so the drag keeps its result. held: Option, @@ -126,6 +127,20 @@ struct WindowMove { begun: bool, } +/// A resize of a viewport mount's OS window that its caller sizes ([`Resize::by_caller`](crate::contract::overlay::Resize::by_caller)), +/// which the app runs, from its Begin to its Commit or Cancel. Rects are the window's outer rect in desktop points. +#[derive(Clone, Copy, PartialEq)] +struct WindowSize { + /// The index in `GRIPS` of the grip the drag holds. + grip: usize, + /// The pressed point in desktop points. + pressed: Pos2, + /// Where the window was when the resize began; a cancel reports it again. + start: Rect, + /// The rect the resize reported last. + at: Rect, +} + /// The outer rect of a viewport mount's OS window as the container last learnt it: the window's placement, which the /// container keeps as a layer keeps its own. #[derive(Clone, Default)] @@ -334,7 +349,14 @@ impl BodyHooks<'_> { if mode.kind == Some(kind) { mode = WindowMode::default(); } else { - mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), moving: None, held: None }; + mode = WindowMode { + kind: Some(kind), + restore: current.clone(), + began: Some(current.rect_over(rect)), + moving: None, + sizing: None, + held: None, + }; self.reports.push(step(current.rect_over(rect), GesturePhase::Begin)); } } @@ -392,7 +414,7 @@ impl BodyHooks<'_> { // A band that moves the window below starts the OS move of the window the layer is shown in. if overlay.moves_window { let viewport = pass::current_viewport(&cx.core.ctx); - self.window_os(viewport, cx); + self.window_os(viewport, props, cx); return; } let id = cx.core.id; @@ -452,9 +474,18 @@ impl BodyHooks<'_> { } /// A press on the move band or a grip of a container in an OS window starts the OS move or resize; the band of a - /// window whose move the app runs starts that move instead ([`Self::window_move`]). Where the platform answers the - /// hit test (`answered_by_platform`), the parts stand for its sink only. - pub(super) fn window_os(&mut self, viewport: ViewportId, cx: &mut Cx<'_, C>) { + /// window whose move the app runs starts that move instead ([`Self::window_move`]), and a grip of a window its + /// caller sizes that resize ([`Self::window_resize`]). Where the platform answers the hit test + /// (`answered_by_platform`), the parts it takes stand for its sink only; the grips of a window its caller sizes + /// are never its. + pub(super) fn window_os(&mut self, viewport: ViewportId, props: &ContainerProps, cx: &mut Cx<'_, C>) { + let by_caller = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller); + if by_caller { + let limits = overlay_of(props).map(|overlay| Limits::new(overlay, window_min(props, cx.style.metrics().min_size))); + if let Some(limits) = limits { + self.window_resize(viewport, &limits, cx); + } + } if answered_by_platform(&cx.core.ctx, viewport) { return; } @@ -469,12 +500,68 @@ impl BodyHooks<'_> { windows::act(&cx.core.ctx, viewport, WindowAction::StartMove); } for (index, (dx, dy, _)) in GRIPS.into_iter().enumerate() { - if started((GRIP, Some(index as u64))) { + if !by_caller && started((GRIP, Some(index as u64))) { windows::act(&cx.core.ctx, viewport, WindowAction::StartResize(edge_of(dx, dy))); } } } + /// The resize of an OS window its caller sizes: a drag of a grip moves the edges the grip holds by the pointer's + /// travel since the press, within `limits`, and each step is reported through `placement_changed` as a layer's + /// resize is, from Begin to Commit or Cancel. The app sends the window no size: the caller places the size it + /// makes of the steps. The press holds the pointer, so its moves arrive while it is outside the window. A pointer + /// move of this pass is relative to where the window reports itself now, as in [`Self::window_move`]. + fn window_resize(&mut self, viewport: ViewportId, limits: &Limits, cx: &mut Cx<'_, C>) { + let ctx = cx.core.ctx.clone(); + let Some(facts) = windows::WindowHost::of(&ctx).facts(viewport) else { return }; + let outer = facts.outer.unwrap_or(facts.inner); + let phase = |index: usize| cx.core.results.get(&(GRIP, Some(index as u64))).map(|result| result.press.phase); + let change = |rect: Rect, phase: GesturePhase, grip: usize| { + let (dx, dy, _) = GRIPS[grip]; + PlacementChange { rect, phase, pointer: None, kind: PlacementKind::Size(edge_of(dx, dy)) } + }; + let resized = |sizing: &WindowSize, desktop: Pos2| { + let (dx, dy, _) = GRIPS[sizing.grip]; + limits.resized(sizing.start, dx, dy, desktop - sizing.pressed) + }; + let Some(mut sizing) = self.mode.sizing else { + let started = (0..GRIPS.len()).find_map(|index| match phase(index)? { + PressPhase::DragStart { start, pos, .. } => Some((index, start.origin, pos)), + _ => None, + }); + let Some((grip, origin, pos)) = started else { return }; + let sizing = WindowSize { grip, pressed: facts.inner.min + origin.to_vec2(), start: outer, at: outer }; + self.reports.push(change(outer, GesturePhase::Begin, grip)); + let at = resized(&sizing, facts.inner.min + pos.to_vec2()); + self.reports.push(change(at, GesturePhase::Update, grip)); + self.mode.sizing = Some(WindowSize { at, ..sizing }); + self.mode.held = Some(grip); + return; + }; + let ended = match phase(sizing.grip) { + Some(PressPhase::Cancel { .. }) => Some(GesturePhase::Cancel), + Some(PressPhase::Down { .. } | PressPhase::Drag { .. } | PressPhase::Held { .. } | PressPhase::DragStart { .. }) => None, + // A release, or a press that ended in a pass the container did not run. + _ => Some(GesturePhase::Commit), + }; + if let Some(ended) = ended { + let rect = if ended == GesturePhase::Cancel { sizing.start } else { sizing.at }; + self.reports.push(change(rect, ended, sizing.grip)); + self.mode.sizing = None; + self.mode.held = None; + return; + } + let moved = pointer::pass_pointer(&ctx) + .events + .iter() + .rev() + .find_map(|event| if let PointerEvent::Moved { at, .. } = event { Some(*at) } else { None }); + let Some(at) = moved.map(|at| resized(&sizing, facts.inner.min + at.to_vec2())).filter(|at| *at != sizing.at) else { return }; + sizing.at = at; + self.reports.push(change(at, GesturePhase::Update, sizing.grip)); + self.mode.sizing = Some(sizing); + } + /// The move of an OS window whose app runs it ([`windows::keeps_app_drag`]): a drag of the move band keeps the /// pressed point under the pointer, and each step is reported through `placement_changed` as a layer's move is, /// from Begin to Commit or Cancel. Where the platform tracks the OS's moves ([`Caps::OS_MOVES_TRACKED`]) the OS @@ -577,11 +664,15 @@ impl BodyHooks<'_> { let now = facts.outer.unwrap_or(facts.inner); let placed = &mut cx.core.memory.shown::(sub(sub(cx.core.id, "body"), "window_placed")).0; let before = placed.replace(now); - if self.mode.moving.is_some() { + if self.mode.moving.is_some() || self.mode.sizing.is_some() { return; } let Some(before) = before.filter(|before| *before != now) else { return }; let kind = resized_edge(before, now).map_or(PlacementKind::Move, PlacementKind::Size); + // The size of a window its caller sizes is the caller's own: the window reports only its moves. + if matches!(kind, PlacementKind::Size(_)) && overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller) { + return; + } self.reports.push(PlacementChange { rect: now, phase: GesturePhase::Commit, pointer: None, kind }); } @@ -635,6 +726,7 @@ impl BodyHooks<'_> { return; } let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.direction().is_rtl())); + let caller_sizes = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller); for (index, (dx, dy, cursor)) in GRIPS.into_iter().enumerate() { if held != Some(index) && !grip_stands(edges, pinned, dx, dy) { continue; @@ -654,7 +746,8 @@ impl BodyHooks<'_> { .cursor(cursor) .pointer_only(reason) .over(); - if let Some(hit) = exclusive(WindowHit::Resize(edge_of(dx, dy))) { + // The grips of a window its caller sizes are the app's (`window_resize`), never the platform's. + if let Some(hit) = exclusive(WindowHit::Resize(edge_of(dx, dy))).filter(|_| !caller_sizes) { part.exclusive(hit); } } diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 0abbea9a6..4d95b6d35 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -369,8 +369,9 @@ impl Host for ViewportHost { spec: &spec, limits: (Some(self.overlay.size_limits.min), self.overlay.size_limits.max), position: placed.map(|rect| rect.min), - // The full-window overlay has no grips (it covers the window), but its OS window is one the user sizes. - resizable: full_window || self.overlay.resize.edges != ResizeEdges::NONE, + // The full-window overlay has no grips (it covers the window), but its OS window is one the user sizes. A + // window its caller sizes takes no resize from the OS: the app runs its grips. + resizable: full_window || (self.overlay.resize.edges != ResizeEdges::NONE && !self.overlay.resize.by_caller), }; let dismissed = &mut self.dismissed; windows::show_viewport(&ctx, &open, |ui| { diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index 700b14911..f8603e638 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -112,17 +112,21 @@ pub struct Resize { /// The edges whose grips resize the layer; a corner grip needs both its edges. A placement that holds an edge /// still keeps its grip away. pub edges: ResizeEdges, + /// The caller turns each resize into a size of its own (a window as large as its content in whole steps). In an + /// OS window the app runs the grips' drag, reports each step, and the OS offers no resize of its own; the window + /// takes the size the caller places. A layer resizes as any other and reports the same steps. + pub by_caller: bool, } impl Resize { /// The layer keeps its size. - pub const NONE: Resize = Resize { edges: ResizeEdges::NONE }; + pub const NONE: Resize = Resize { edges: ResizeEdges::NONE, by_caller: false }; /// Grips on every free edge and corner. - pub const GRIPS: Resize = Resize { edges: ResizeEdges::ALL }; + pub const GRIPS: Resize = Resize { edges: ResizeEdges::ALL, by_caller: false }; /// Grips on the given edges only. pub fn edges(edges: ResizeEdges) -> Resize { - Resize { edges } + Resize { edges, by_caller: false } } } diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 2dfc1b999..5f1f18842 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -319,6 +319,12 @@ impl Overlay { self } + /// The caller sizes the layer or OS window from the resizes its grips report ([`Resize::by_caller`]). + pub fn sized_by_caller(mut self) -> Overlay { + self.resize.by_caller = true; + self + } + /// Rank `Window` and no backdrop. pub fn modeless(mut self) -> Overlay { self.rank = Rank::Window; diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 54f178798..cc0bd10ae 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -399,12 +399,17 @@ fn source_viewport(ctx: &Context) -> Option { board(ctx, |board| board.session.as_ref().map(|session| session.viewport)) } +/// Whether the running session started in a window other than `viewport`. That window holds the pointer while its +/// button is down, so `viewport` gets no pointer events of its own and still holds the place it saw the pointer last. +pub(crate) fn runs_elsewhere(ctx: &Context, viewport: ViewportId) -> bool { + source_viewport(ctx).is_some_and(|source| source != viewport) +} + /// The pointer in `viewport` for a drag that started in another window: the desktop pointer mapped into this /// window, when it lies inside. `None` without a session, in the source window, or outside this window. #[doc(hidden)] pub fn cross_window_pointer(ctx: &Context, viewport: ViewportId) -> Option { - let source = source_viewport(ctx)?; - (source != viewport).then(|| WindowHost::of(ctx).pointer_in(viewport)).flatten() + runs_elsewhere(ctx, viewport).then(|| WindowHost::of(ctx).pointer_in(viewport)).flatten() } /// The running session's payload whose type is `payload` and the pointer in screen space. For files the OS drags, the diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index f94ead91c..a7048938c 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -163,8 +163,9 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { // Every pass reads its own input and the frame's latches, so a second pass of a frame builds the same // modifiers from its own (event-free) input and counts no press twice. let mods = with_latched(read.mods, latched); - // A drag that started in another window reaches this one through the desktop pointer (8.4). - if read.pos.is_none() { + // A drag that started in another window reaches this one through the desktop pointer (8.4), never at the place + // this window saw the pointer last: the source window holds the pointer, and the window may have had no exit. + if drag::runs_elsewhere(ctx, viewport) { read.pos = drag::cross_window_pointer(ctx, viewport); } let wheel = input::wheel_read(ctx, WHEEL_LINE_POINTS, WHEEL_PAGE_POINTS); diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index f3ec67e21..95f7f4ab5 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -235,7 +235,8 @@ pub(crate) fn set_input(ctx: &Context) { /// or resize [`act`] handed the OS, when the input brings no release of its own (where the OS sends one, a second /// would turn into a click), once the system tells the button is up, or where it does not tell, on the first input /// after the hand-off; and, where the OS resizes undecorated windows from their edges -/// ([`Caps::OS_RESIZES_UNDECORATED`]), a size change under a held primary press. While the OS runs a tracked move +/// ([`Caps::OS_RESIZES_UNDECORATED`]), a size change of a window the OS may resize under a held primary press (the +/// size of a window that is not resizable is the app's own). While the OS runs a tracked move /// ([`Caps::OS_MOVES_TRACKED`]) it sends no key events, so every window's modifiers are the system's command modifier /// alone. Reads only the raw input, the system's button and modifier state and the viewport's record. Returns whether /// it added an event. @@ -257,7 +258,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { input.events.push(egui::Event::ModifiersChanged(modifiers)); } let (released, handed_off) = PerViewport::::with(ctx, viewport, |record| { - let resized = matches!((record.last_inner_size, size), (Some(before), Some(now)) if before != now); + let resized = record.resizable != Some(false) && matches!((record.last_inner_size, size), (Some(before), Some(now)) if before != now); record.last_inner_size = size.or(record.last_inner_size); let handed_off = record.handoff.is_some_and(|handoff| handoff.released.is_none() && handoff.pass < pass) && held != Some(true); if handed_off { diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index fee1675aa..d6214bac6 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -167,7 +167,8 @@ impl Outcome for FloatingGroupOutput { /// collapsed size against that edge of the rect, its title row shows no actions (the band and the double arrow; /// a context request on the band opens the menu), the edges do not resize, and a move keeps the rect's size. A /// column its content sizes ([`WindowColumn::fitted`]) shows at that size at the rect's place; its resizes are -/// reported as the user makes them. +/// reported as the user makes them, and in an OS window the app runs them, so the window takes only the size the +/// host gives it. /// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag /// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release. /// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where @@ -332,7 +333,8 @@ impl<'a> FloatingGroup<'a> { overlay = if let Some(shown) = collapsed { overlay.placed(shown).size_limits(SizeLimits::new(shown.size(), shown.size())) } else if let Some(size) = self.column.and_then(|column| column.fitted) { - overlay.placed(Rect::from_min_size(self.rect.min, size + Vec2::new(0.0, header))) + // The host turns a resize into the column's steps, and the window takes the size they make. + overlay.placed(Rect::from_min_size(self.rect.min, size + Vec2::new(0.0, header))).sized_by_caller() } else if self.minimized { let width = self.rect.width(); overlay.placed_at(self.rect.min).size_limits(SizeLimits::new(Vec2::new(width, 0.0), Vec2::new(width, f32::INFINITY))) diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index 5289c6a57..a800b50f4 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -94,6 +94,21 @@ pub fn reported(ctx: &Context, window: &Floating

, viewport: Viewpor (!settled).then(|| Action::set_native(panel.clone(), Some(next))) } +/// Sends the native window shown in `viewport`, which the dock model records at `recorded` (its outer top-left +/// corner and inner size), to `rect` where it differs by more than rounding: the place the dock gives a window it +/// sizes itself (a column with steps). The window's next report is that place, which [`reported`] records. +#[doc(hidden)] +pub fn place(ctx: &Context, viewport: ViewportId, recorded: Rect, rect: Rect) { + let differs = |delta: Vec2| delta.x.abs() > SETTLED || delta.y.abs() > SETTLED; + let host = WindowHost::of(ctx); + if differs(rect.min - recorded.min) { + host.act(viewport, WindowAction::SetOuterPosition(rect.min)); + } + if differs(rect.size() - recorded.size()) { + host.act(viewport, WindowAction::SetInnerSize(rect.size())); + } +} + /// Raises the window of the native group that `output` reports on when the user began moving or resizing it this /// pass, so a palette comes to the front of the windows it overlaps. False when nothing was raised. pub(crate) fn raise(ctx: &Context, output: &FloatingGroupOutput) -> bool { diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index d975f6f37..1c48fefe3 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -942,6 +942,50 @@ impl Pass<'_, P> { } } + /// The steps a resize `change` of the floating window of the stepped `column`, whose first panel is `first`, sets, + /// and the window's rect at them: as wide as its steps and as tall as its title row and its content at that width. + /// `fitted` is the content's size under the title row before the change. A grip on the top or bottom edge sets the + /// steps by height (the fewest whose content fits), any other grip by width (the most that fit); keyboard Size + /// mode, which names no grip, by the side it changed. The window keeps its place: a grip on the left keeps the + /// right edge where it is and one on the top the bottom edge, so the window grows or shrinks that way. Reports + /// the steps when they change. `None` for a column without steps. + fn stepped_resize( + &mut self, + ui: &mut Ui, + body: &mut BodyCx<'_>, + column: &Column

, + first: &P, + change: &PlacementChange, + fitted: Vec2, + ) -> Option { + let scene = self.scene; + let spec_of = |panel: &P| scene.spec(panel); + let (grid, steps) = stepped(column, &spec_of)?; + let by_height = match change.kind { + PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), + _ => (change.rect.width() - fitted.x).abs() <= 0.5, + }; + let to = if by_height { + let room = change.rect.height() - scene.sizes.title_row; + grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) + } else { + grid.steps_within(change.rect.width()) + }; + if to != steps { + self.report.actions.push(Action::set_column_steps(first.clone(), to)); + } + let size = Vec2::new(grid.width(to), scene.sizes.title_row + self.stepped_height(ui, body, column, grid.width(to), true).unwrap_or(0.0)); + let left = match change.kind { + PlacementKind::Size(ResizeEdge::Left | ResizeEdge::TopLeft | ResizeEdge::BottomLeft) => change.rect.right() - size.x, + _ => change.rect.left(), + }; + let top = match change.kind { + PlacementKind::Size(ResizeEdge::Top | ResizeEdge::TopLeft | ResizeEdge::TopRight) => change.rect.bottom() - size.y, + _ => change.rect.top(), + }; + Some(Rect::from_min_size(Pos2::new(left, top), size)) + } + /// The height of the groups of an expanded stepped column ([`stepped`]) measured at `width`, the width of its /// steps: what the column shows under its bar. `None` for any other column. fn stepped_height(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, width: f32, in_window: bool) -> Option { @@ -1074,7 +1118,8 @@ impl Pass<'_, P> { /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps - /// its right edge. + /// its right edge. An OS window takes that rect at once ([`native::place`]); the app runs its grips, so the OS + /// sizes it no other way. fn windows( &mut self, ui: &mut Ui, @@ -1168,8 +1213,18 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } + // A resize of a window whose column has steps: the steps it sets, and the window's rect at them. + let resized = output + .placed + .filter(|change| !matches!(change.kind, PlacementKind::Move)) + .zip(shape.fitted) + .and_then(|(change, fitted)| self.stepped_resize(ui, body, &window.column, &anchor, &change, fitted)); if opening.spec.is_some() { if let Some(viewport) = WindowHost::of(&ctx).viewport_of(output.response.id) { + // The OS window takes the rect of its steps at once, so the place recorded below is that rect. + if let Some(rect) = resized { + native::place(&ctx, viewport, opening.rect, rect); + } self.report.windows.push((anchor.clone(), viewport)); self.report.actions.extend(native::reported(&ctx, window, viewport)); } @@ -1179,40 +1234,9 @@ impl Pass<'_, P> { if change.phase == GesturePhase::Commit { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); } - if !matches!(change.kind, PlacementKind::Move) - && let Some(fitted) = shape.fitted - && let Some((grid, steps)) = stepped(&window.column, &spec_of) - { - let column = &window.column; - // A grip on the top or bottom edge sets the steps by height, any other grip by width; keyboard Size - // mode, which names no grip, by the side it changed. - let by_height = match change.kind { - PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), - _ => (change.rect.width() - fitted.x).abs() <= 0.5, - }; - let to = if by_height { - let room = change.rect.height() - scene.sizes.title_row; - grid.steps_for_height(room, |width| self.stepped_height(ui, body, column, width, true).unwrap_or(0.0)) - } else { - grid.steps_within(change.rect.width()) - }; - if to != steps { - self.report.actions.push(Action::set_column_steps(anchor.clone(), to)); - } - // The window keeps its place and its steps set its size. A grip on the left keeps the right edge - // where it is, and one on the top the bottom edge, so the window grows or shrinks that way. - let left = match change.kind { - PlacementKind::Size(ResizeEdge::Left | ResizeEdge::TopLeft | ResizeEdge::BottomLeft) => change.rect.right() - grid.width(to), - _ => change.rect.left(), - }; - let top = match change.kind { - PlacementKind::Size(ResizeEdge::Top | ResizeEdge::TopLeft | ResizeEdge::TopRight) => { - let content = self.stepped_height(ui, body, column, grid.width(to), true).unwrap_or(0.0); - change.rect.bottom() - scene.sizes.title_row - content - } - _ => change.rect.top(), - }; - change.rect = Rect::from_min_size(Pos2::new(left, top), opening.rect.size()); + // The window keeps the place of its steps; its size is the steps' own, whatever the rect keeps. + if let Some(rect) = resized { + change.rect = Rect::from_min_size(rect.min, opening.rect.size()); } if change.phase == GesturePhase::Commit { self.report.events.push(DockEvent::FloatPlaced { panel: anchor.clone(), rect: change.rect }); diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 9820aa276..9e31e5d67 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -1,11 +1,12 @@ //! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and //! docking the whole window by dragging its title row. -use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, Workspace}; +use craft_behavior::dock::{Action, Column, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; -use craft_ui::contract::{Bind, BodyCx, ShowContainer as _}; -use craft_ui::docking::{DockConfig, DockPanels, PanelSpec}; +use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _}; +use craft_ui::display::Text; +use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec}; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; @@ -172,20 +173,56 @@ const ROW_AT: Pos2 = Pos2::new(150.0, 10.0); /// A desktop point over the middle of the main window's group. const OVER_GROUP: Pos2 = Pos2::new(550.0, 400.0); +/// The grid of the stepped palette's content, as a toolbar's. +fn tools_grid() -> DockGrid { + DockGrid::new(40.0, 32.0, 6) +} + +/// A palette whose content lays out in a grid (a toolbar): its column has steps and its window fits its content. +struct SteppedPalette; + +impl DockPanels for SteppedPalette { + fn spec(&self, panel: &u32) -> PanelSpec { + if *panel == 1 { PanelSpec::new(PALETTE_TITLE).grid(tools_grid()) } else { PanelSpec::new("Canvas") } + } + + fn permissions(&self, _: &u32) -> Permissions { + Permissions::ALL.collapses(false) + } + + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel == 1 { + Text::new("One").show(ui); + Text::new("Two").show(ui); + } + } +} + /// A dock of one docked group and one native palette. struct NativeDock { windows: Windows, workspace: Workspace, + stepped: bool, } impl NativeDock { fn on(os: Os, system: Arc) -> Self { + let palette = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + Self::with(os, system, palette, false) + } + + /// The dock with a stepped palette of one step ([`SteppedPalette`]). + fn stepped(os: Os, system: Arc) -> Self { + let column = Column::new(vec![Group::new(vec![1], 0)]).with_steps(1); + Self::with(os, system, Floating::new(column, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())), true) + } + + fn with(os: Os, system: Arc, palette: Floating, stepped: bool) -> Self { let shell = ShellInfo::default().os(os).caps(Caps::native(os)); let windows = Windows::with(InstallSpec::new(shell, system)); windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); - let palette = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); - let mut dock = NativeDock { windows, workspace: Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])) }; + let mut dock = NativeDock { windows, workspace: Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])), stepped }; for _ in 0..3 { dock.frame(vec![]); } @@ -194,12 +231,17 @@ impl NativeDock { /// One frame with `child` events for the palette's window: the dock's actions and the palette's window commands. fn frame(&mut self, child: Vec) -> (Vec>, Vec) { + self.frame_with(vec![], child) + } + + /// One frame with `root` events for the main window and `child` events for the palette's window. + fn frame_with(&mut self, root: Vec, child: Vec) -> (Vec>, Vec) { let mut actions = Vec::new(); let workspace = &mut self.workspace; - let out = self.windows.frame(vec![], child, |ui| { - actions.extend( - DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui).actions, - ); + let (mut palettes, mut stepped) = (Palettes(Permissions::ALL), SteppedPalette); + let panels: &mut dyn DockPanels = if self.stepped { &mut stepped } else { &mut palettes }; + let out = self.windows.frame(root, child, |ui| { + actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui).actions); }); let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); (actions, commands) @@ -303,6 +345,100 @@ fn dragging_a_native_palette_by_its_title_row_docks_it_where_the_os_moves_window assert!(docked, "the button's release docks the whole window"); } +/// A point near the main window's start edge, in its own coordinates: away from the middle of its group. +const STALE: Pos2 = Pos2::new(5.0, 300.0); + +/// The main window keeps the place it saw the pointer last when the palette over it takes the pointer, and may never +/// learn that the pointer left: AppKit sends no exit for a window of the app laid over it, and the press holds the +/// pointer in the palette's window. A drag of the palette resolves the main window's drops at the system pointer all +/// the same, never at that place. +#[trial] +fn a_palette_drag_resolves_the_main_windows_drops_at_the_system_pointer_not_where_it_saw_the_pointer_last() { + let system = Arc::new(FakeSystem::new()); + let mut dock = NativeDock::on(Os::Mac, system.clone()); + dock.frame_with(vec![moved(STALE)], vec![]); + let pressed_at = FLOAT_AT.min + ROW_AT.to_vec2(); + system.set_pointer(Some([pressed_at.x, pressed_at.y])); + system.set_primary_held(Some(true)); + dock.frame(vec![moved(ROW_AT)]); + dock.frame(vec![press(ROW_AT)]); + dock.frame(vec![]); + system.set_pointer(Some([OVER_GROUP.x, OVER_GROUP.y])); + let mut docked = false; + for _ in 0..3 { + docked |= docks_window(&dock.frame(vec![]).0); + } + let mark = drag::mark(&dock.windows.ctx); + assert!(matches!(mark, Some(DropMark::Into(_))), "the middle of the group under the system pointer is marked: {mark:?}"); + system.set_primary_held(Some(false)); + for _ in 0..3 { + docked |= docks_window(&dock.frame(vec![]).0); + } + assert!(docked, "the release docks the whole window"); +} + +/// The steps of the stepped palette's column. +fn palette_steps(dock: &NativeDock) -> Option { + dock.workspace.layout.floating[0].column.steps +} + +/// One frame of `dock` with `child` events, after which the palette's window is where the app sent it, as the OS +/// puts it: its commands, with `at` the window's rect. +fn placed_frame(dock: &mut NativeDock, child: Vec, at: &mut Rect) -> Vec { + let (_, commands) = dock.frame(child); + for command in &commands { + match command { + ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), + ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, *size), + _ => {} + } + } + dock.windows.child_info(info(true, *at)); + commands +} + +/// A native palette whose column has steps (a toolbar) is sized by the app, not the OS: a drag of its side sets whole +/// steps and the window takes their width at once, a drag of its left side keeps its right edge, and the OS is never +/// asked to resize it. The drag holds on where the OS resizes undecorated windows (Windows): a size change the app +/// makes under the held press ends no press. +#[trial] +fn a_native_stepped_palette_resizes_in_whole_steps_that_the_app_runs() { + let grid = tools_grid(); + for os in [Os::Mac, Os::Windows] { + let mut dock = NativeDock::stepped(os, Arc::new(FakeSystem::new())); + let mut at = FLOAT_AT; + let mut sent = Vec::new(); + for _ in 0..3 { + sent.extend(placed_frame(&mut dock, vec![], &mut at)); + } + assert_eq!(at.width(), grid.width(1), "{os:?}: the window is as wide as its one step"); + + // The right grip straddles the window's right edge. + let grip = Pos2::new(at.width() - 1.0, at.height() / 2.0); + for events in [vec![moved(grip)], vec![press(grip)], vec![moved(grip + Vec2::new(1.6 * grid.step, 0.0))], vec![]] { + sent.extend(placed_frame(&mut dock, events, &mut at)); + } + assert_eq!(palette_steps(&dock), Some(2), "{os:?}: a drag of 1.6 steps sets the whole step it reached"); + assert_eq!(at.width(), grid.width(2), "{os:?}: the window takes the width of its steps while the drag runs"); + let end = grip + Vec2::new(1.6 * grid.step, 0.0); + for events in [vec![release(end)], vec![], vec![]] { + sent.extend(placed_frame(&mut dock, events, &mut at)); + } + assert_eq!(palette_steps(&dock), Some(2), "{os:?}: the release keeps the steps"); + + let right = at.right(); + let grip = Pos2::new(1.0, at.height() / 2.0); + let end = grip - Vec2::new(1.6 * grid.step, 0.0); + for events in [vec![moved(grip)], vec![press(grip)], vec![moved(end)], vec![], vec![release(end)], vec![], vec![]] { + sent.extend(placed_frame(&mut dock, events, &mut at)); + } + assert_eq!(palette_steps(&dock), Some(3), "{os:?}: a drag of the left side sets whole steps too"); + assert_eq!(at.width(), grid.width(3), "{os:?}: the window takes the width of its steps"); + assert!((at.right() - right).abs() <= 0.5, "{os:?}: the right edge stays: {right} then {at:?}"); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::BeginResize(_))), "{os:?}: the OS never resizes the window"); + } +} + fn placing(commands: &[ViewportCommand]) -> Vec<&ViewportCommand> { commands.iter().filter(|command| matches!(command, ViewportCommand::OuterPosition(_) | ViewportCommand::InnerSize(_))).collect() }