diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index 0fd6e4fb6..ae872ef90 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -526,10 +526,11 @@ impl Component for Guides<'_> { for guide in guides { let Some([a, b]) = place::segment(&space.view, guide.along, guide.position, guide.span, cx.rect) else { continue }; let color = if self.selected == Some(guide.key) { style.selected.egui() } else { guide.color.map_or(style.line.egui(), data_color) }; + let look = RuleLook { color, width: RuleWidth::Points(style.width) }; match guide.line { - GuideLine::Solid => painter.painter.extend(Rule::shapes(&RuleLook { color, width: RuleWidth::Points(style.width) }, a, b, ppp)), + GuideLine::Solid => painter.painter.extend(Rule::shapes(&look, a, b, ppp)), GuideLine::Dashed => painter.dashed(&[a, b], Dashes::new(style.dash, style.gap), StrokeWidth::Thin, color), - GuideLine::Dots => painter.dashed(&[a, b], Dashes::new(style.width, style.gap), StrokeWidth::Thin, color), + GuideLine::Dots => painter.painter.extend(Rule::dotted(&look, a, b, style.gap, ppp)), } if focused == Some(guide.key.get()) && (b - a).length() > 0.0 { painter.painter.extend(FocusRing::shapes(&style.focus, FocusKind::Halo, &footprint(&space, a, b, style.width), ppp)); diff --git a/crates/ui-canvas/src/canvas_controls/guides/stories.rs b/crates/ui-canvas/src/canvas_controls/guides/stories.rs index 02fdeb99c..e5a48c4dd 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/stories.rs @@ -26,12 +26,15 @@ fn on_guides_canvas(ui: &mut Ui, mut control: impl FnMut(&mut Ui, Rect, Id) -> G on_canvas_with(ui, room, Canvas::new("Document").id(canvas).view(view), Some(document), |ui, at| control(ui, at, canvas)) } +/// Every line a guide draws: solid, dotted and dashed, and a locked one. fn guides() -> Vec { + let mut dotted = Guide::new(GuideKey::new(2), Axis::X, 120.0); + dotted.line = GuideLine::Dots; let mut dashed = Guide::new(GuideKey::new(3), Axis::X, 280.0); dashed.line = GuideLine::Dashed; let mut locked = Guide::new(GuideKey::new(4), Axis::Y, 480.0); locked.locked = true; - vec![Guide::new(GuideKey::new(1), Axis::Y, 160.0), Guide::new(GuideKey::new(2), Axis::X, 120.0), dashed, locked] + vec![Guide::new(GuideKey::new(1), Axis::Y, 160.0), dotted, dashed, locked] } /// Drags the first guide across itself by twice the drag threshold. diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 972df0013..ae2716b40 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -495,6 +495,11 @@ impl<'a> Draw<'a> { self.painter.extend(super::rule::Rule::shapes(look, from, to, self.painter.pixels_per_point())); } + /// Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a grip's dotted line. + pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32) { + self.painter.extend(super::rule::Rule::dotted(look, from, to, gap, self.painter.pixels_per_point())); + } + /// Paints a surface of `kind` (tracks, plot wells). pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners) { let style = surface_style(self.env.tokens, kind); diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index 053c41e4c..d50fdbd9c 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -469,9 +469,6 @@ const MINOR_SHARE: f32 = 0.45; /// How many times a thinned grid doubles its step before it gives up. const MAX_DOUBLINGS: u32 = 32; -/// The radius of a dot, in screen points. -const DOT_RADIUS: f32 = 0.6; - /// What a grid does when its lines come closer than the minimum step. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] @@ -693,7 +690,7 @@ pub fn grid_lines_with(look: &GridLook, grid: &GridLines, ink: &GridInk, pixels_ match ink.stroke { GridStroke::Solid => shapes.extend(Rule::shapes(&RuleLook { color, width: look.width }, a, b, pixels_per_point)), GridStroke::Dashed => shapes.extend(dashed(&[a, b], Dashes::new(look.dash, look.gap), look.width.points(pixels_per_point), color)), - GridStroke::Dots => shapes.extend(Shape::dotted_line(&[a, b], color, look.gap, DOT_RADIUS)), + GridStroke::Dots => shapes.extend(Rule::dotted(&RuleLook { color, width: look.width }, a, b, look.gap, pixels_per_point)), } } } diff --git a/crates/ui-contract/src/primitives/rule.rs b/crates/ui-contract/src/primitives/rule.rs index 522edbb92..3cf908347 100644 --- a/crates/ui-contract/src/primitives/rule.rs +++ b/crates/ui-contract/src/primitives/rule.rs @@ -1,7 +1,7 @@ //! `Rule`: dividers, edges, grid lines and drop marks, with one pixel-snap rule. use crate::style::RuleLook; -use egui::{Pos2, Rect, Shape, Stroke}; +use egui::{Mesh, Pos2, Rect, Shape, Stroke, Vec2}; pub use crate::style::RuleKind; @@ -47,16 +47,20 @@ impl RectSide { } } +/// `v` (points) snapped for a line `physical` pixels wide: an odd width on a physical pixel centre, an even one on a +/// pixel edge. +fn snap(v: f32, physical: f32, pixels_per_point: f32) -> f32 { + let px = v * pixels_per_point; + let snapped = if physical % 2.0 == 1.0 { px.floor() + 0.5 } else { px.round() }; + snapped / pixels_per_point +} + impl Rule { /// The line from `from` to `to`, snapped across its direction: a line whose physical width is odd sits on a /// pixel centre, an even one on a pixel edge, and no line is thinner than one physical pixel. pub fn shapes(look: &RuleLook, from: Pos2, to: Pos2, pixels_per_point: f32) -> Vec { let physical = look.width.pixels(pixels_per_point); - let snap = |v: f32| { - let px = v * pixels_per_point; - let snapped = if physical % 2.0 == 1.0 { px.floor() + 0.5 } else { px.round() }; - snapped / pixels_per_point - }; + let snap = |v: f32| snap(v, physical, pixels_per_point); let (from, to) = if (from.y - to.y).abs() <= (from.x - to.x).abs() { (Pos2::new(from.x, snap(from.y)), Pos2::new(to.x, snap(to.y))) } else { @@ -65,6 +69,35 @@ impl Rule { vec![Shape::line_segment([from, to], Stroke::new(physical / pixels_per_point, look.color))] } + /// The dotted form of the line from `from` to `to`: square dots as wide as the line, `gap` points apart, the run + /// of whole dots centred between the ends (a grip, a dotted guide or grid line). The gap is whole physical pixels, + /// at least one, and each dot's centre is snapped on both axes by the rule `shapes` snaps across with, so every dot + /// covers whole physical pixels and dots on a level or upright line are evenly spaced. The dots are one mesh. + pub fn dotted(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, pixels_per_point: f32) -> Vec { + let ppp = pixels_per_point.max(f32::EPSILON); + let side = look.width.pixels(ppp); + let gap = (gap * ppp).round().max(1.0); + let length = (to - from).length() * ppp; + // The run leaves at least a physical pixel of the line free, so snapping, which moves a dot at most half a + // pixel, keeps every dot between the ends. + let count = ((length - 1.0 + gap) / (side + gap)).floor(); + if !count.is_finite() || count < 1.0 { + return Vec::new(); + } + let direction = (to - from).normalized(); + let first = (length - (count * side + (count - 1.0) * gap)) / 2.0 + side / 2.0; + let dot = Vec2::splat(side / ppp); + // One mesh of plain quads: a filled rect two pixels wide or less is tessellated as a line segment, whose ends + // the tessellator rounds inward, and a one-pixel dot drawn that way vanishes. + let mut mesh = Mesh::default(); + for i in 0..count as usize { + let centre = from + direction * ((first + i as f32 * (side + gap)) / ppp); + let centre = Pos2::new(snap(centre.x, side, ppp), snap(centre.y, side, ppp)); + mesh.add_colored_rect(Rect::from_center_size(centre, dot), look.color); + } + vec![Shape::mesh(mesh)] + } + /// The line along the `side` edge of `rect`, on the physical pixels just inside it: a row's bottom rule or a /// cell's gridline, which a line centred on the edge would put on the first pixel outside, under the next row's /// clip or the next cell's fill. diff --git a/crates/ui-contract/src/runtime/windows/native.rs b/crates/ui-contract/src/runtime/windows/native.rs index 9974910df..c426eb9cd 100644 --- a/crates/ui-contract/src/runtime/windows/native.rs +++ b/crates/ui-contract/src/runtime/windows/native.rs @@ -9,7 +9,7 @@ use super::spec::{Standing, WindowLevel}; use super::{HandOff, Record, SEARCH_EVERY, shared}; use crate::runtime::egui::{pass, viewports}; use crate::runtime::frame::{PerViewport, Stored}; -use craft_host::target::{Caps, DoubleClick, WindowState}; +use craft_host::target::{Caps, DoubleClick, Os, WindowState}; use craft_window::native::NativeWindow; use craft_window::policy::Frame; use egui::{Context, Pos2, Rect, Vec2, ViewportId}; @@ -49,7 +49,7 @@ pub enum WindowAction { StartResize(ResizeEdge), /// Moves the window's outer top-left corner to a desktop position in points. SetOuterPosition(Pos2), - /// Sizes the window's inner area in points. + /// Sizes the window's inner area in points; its outer top-left corner stays where it is known to be. SetInnerSize(Vec2), /// Restores a minimized window. Restore, @@ -138,7 +138,18 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { } WindowAction::SetInnerSize(size) => { viewports::command(ctx, viewport, egui::ViewportCommand::InnerSize(size)); - PerViewport::::with(ctx, viewport, |record| record.known = record.known.map(|known| Rect::from_min_size(known.min, size))); + let known = PerViewport::::with(ctx, viewport, |record| { + record.known = record.known.map(|known| Rect::from_min_size(known.min, size)); + record.known + }); + // AppKit keeps a window's bottom-left corner when its size changes (`setContentSize`), so a new height + // moves its top edge: the window goes back to the top-left corner its caller knows it at, which a position + // sent before the size has already set. + if base.os == Os::Mac + && let Some(known) = known + { + viewports::command(ctx, viewport, egui::ViewportCommand::OuterPosition(known.min)); + } } WindowAction::Restore => viewports::command(ctx, viewport, egui::ViewportCommand::Minimized(false)), WindowAction::SetMinInnerSize(size) => viewports::command(ctx, viewport, egui::ViewportCommand::MinInnerSize(size)), diff --git a/crates/ui-contract/tests/it/paint/painters.rs b/crates/ui-contract/tests/it/paint/painters.rs index a5ba01714..84b652ccb 100644 --- a/crates/ui-contract/tests/it/paint/painters.rs +++ b/crates/ui-contract/tests/it/paint/painters.rs @@ -130,6 +130,45 @@ fn an_edge_rule_lies_on_the_pixels_just_inside_its_side_at_any_scale() { } } +#[trial] +fn a_dotted_rule_is_whole_pixel_dots_at_one_pitch_between_its_ends() { + use craft_ui::primitives::Rule; + use craft_ui::style::{RuleLook, RuleWidth}; + use egui::{Color32, Rect, Shape}; + + let whole = |v: f32| (v - v.round()).abs() < EPS; + for ppp in [1.0, 1.5, 2.0] { + for width in [RuleWidth::Hairline, RuleWidth::Points(1.0), RuleWidth::Points(2.0)] { + let look = RuleLook { color: Color32::WHITE, width }; + // Ends off the pixel grid, level and upright. + for (from, to) in [(pos2(10.3, 20.6), pos2(41.1, 20.6)), (pos2(7.7, 3.2), pos2(7.7, 29.9))] { + let shapes = Rule::dotted(&look, from, to, 3.0, ppp); + let [Shape::Mesh(mesh)] = shapes.as_slice() else { panic!("the dots are one mesh") }; + let dots: Vec = + mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::>())).collect(); + assert!(dots.len() > 2, "{width:?} at {ppp}x: several dots"); + let level = from.y == to.y; + let across = width.points(ppp); + let span = if level { + Rect::from_two_pos(from, to).expand2(egui::vec2(0.0, across)) + } else { + Rect::from_two_pos(from, to).expand2(egui::vec2(across, 0.0)) + }; + for dot in &dots { + let px = *dot * ppp; + assert!([px.min.x, px.min.y, px.max.x, px.max.y].into_iter().all(whole), "{width:?} at {ppp}x: {px:?} is not whole pixels"); + assert!((dot.width() - dot.height()).abs() < EPS, "{width:?} at {ppp}x: a dot is square"); + assert!(span.expand(EPS).contains_rect(*dot), "{width:?} at {ppp}x: {dot:?} leaves the line {from:?}..{to:?}"); + } + let starts: Vec = dots.iter().map(|dot| if level { dot.min.x } else { dot.min.y }).collect(); + let pitch = starts[1] - starts[0]; + assert!(pitch > dots[0].width(), "{width:?} at {ppp}x: dots are apart"); + assert!(starts.windows(2).all(|w| (w[1] - w[0] - pitch).abs() < EPS), "{width:?} at {ppp}x: one pitch: {starts:?}"); + } + } + } +} + #[trial] fn ant_edges_are_whole_device_pixels_at_a_fractional_scale() { use craft_theme::{Contrast, Mode}; diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 6ab02daf3..3a850af21 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -13,15 +13,15 @@ use crate::contract::{ WordSetCx as _, }; use crate::menu::GroupItem; -use crate::primitives::{IconSpec, PaintShape, TextRun}; +use crate::primitives::{IconSpec, TextRun}; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind, UiTokens}; +use crate::style::{ComponentStyle, Corners, GlyphRole, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::overlay::Side; use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value}; use craft_theme::ControlSize; -use egui::{CornerRadius, Id, Pos2, Rect, Response, Ui, Vec2}; +use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; use std::fmt::Debug; use std::hash::Hash; @@ -54,11 +54,11 @@ pub struct IconicSizes { /// The column width, in rail widths, from which the cells show their panels' names: 96 points at the Compact size. const LABELS_IN_RAIL_WIDTHS: f32 = 2.4; -/// The length of a group's grip bar, in icon cell heights: half a cell, 15 points at the Compact size (18 at -/// Comfortable). That is several times the bar's thickness, so it reads as a handle and not as a dot, and in a -/// rail-wide column (40 points at Compact) it leaves more than a quarter of the width free on each side, so it does -/// not read as a rule between the groups. -const GRIP_BAR_IN_CELLS: f32 = 0.5; +/// The length of a group's grip line, in icon cell heights: half a cell, 15 points at the Compact size (18 at +/// Comfortable). That holds several dots, so it reads as a handle and not as a dot, and in a rail-wide column (40 +/// points at Compact) it leaves more than a quarter of the width free on each side, so it does not read as a rule +/// between the groups. +const GRIP_LINE_IN_CELLS: f32 = 0.5; impl IconicSizes { /// The sizes of the style context `cx`. @@ -149,22 +149,21 @@ pub struct IconicColumnStyle { name_open: StyleColor, /// The room between an icon and its name. name_gap: f32, - /// The ink of a group's grip bar. + /// The ink of a group's grip line. grip: StyleColor, - /// The ink of a group's grip bar while the pointer is over it or drags it. + /// The ink of a group's grip line while the pointer is over it or drags it. grip_active: StyleColor, - /// The grip bar's length across the group and its thickness. + /// The grip line's length across the group. grip_length: f32, - grip_thickness: f32, - /// The grip bar's corners: the theme's pill rounding. - grip_radius: CornerRadius, + /// The side of the grip line's dots, and the gap between two of them. + grip_dot: f32, } /// A column collapsed to icons: the column bar over icon groups, one cell per panel. A panel without an icon shows the /// first letter of its name in a box. A column widened past `IconicSizes::labels` shows each panel's name beside its /// icon, cut with an ellipsis to the cell; a click or drag on the name acts as one on the icon. A click or Enter on an icon /// opens the flyout of its panel beside the column, switches it to that panel or closes it; one flyout is open at a -/// time. A drag of an icon starts a move of its panel, a drag of the grip bar on top of a group a move of the group, a +/// time. A drag of an icon starts a move of its panel, a drag of the grip line on top of a group a move of the group, a /// drag of the bar beside its button a move of the column; each starts through the drag session, and a press outside /// the flyout closes it. Escape and a press /// outside close the flyout; with `auto_collapse` the focus leaving it does too. @@ -423,11 +422,12 @@ impl Component for IconicColumn<'_, P> { name: cx.color(colors.text.normal), name_open: cx.color(colors.accent.text), name_gap: cx.tokens.space.gap.item, - grip: cx.color(colors.text.muted), + // A handle that is found when looked for, as the references' faint grips: hairline dots one dot apart in + // the faint ink, the normal ink under the pointer. + grip: cx.color(colors.text.faint), grip_active: cx.color(colors.text.normal), - grip_length: cx.tokens.size.rail.button * GRIP_BAR_IN_CELLS, - grip_thickness: cx.tokens.stroke.thick, - grip_radius: UiTokens::corner(cx.tokens.shape.radius.pill), + grip_length: cx.tokens.size.rail.button * GRIP_LINE_IN_CELLS, + grip_dot: cx.tokens.stroke.thin, } } @@ -580,8 +580,9 @@ impl Component for IconicColumn<'_, P> { for (group, strip) in self.laid.as_ref().map_or(&[][..], |plan| &plan.grips[..]) { let part = cx.part(GRIP.at(*group as u64)); let ink = if part.hovered || part.pressed() { style.grip_active } else { style.grip }; - let bar = Rect::from_center_size(strip.center(), Vec2::new(style.grip_length.min(strip.width()), style.grip_thickness)); - ui.draw().fill(&PaintShape::Rect(bar, style.grip_radius), ink); + let half = Vec2::new(style.grip_length.min(strip.width()) / 2.0, 0.0); + let look = RuleLook { color: ink.egui(), width: RuleWidth::Points(style.grip_dot) }; + ui.draw().dotted_rule_with(&look, strip.center() - half, strip.center() + half, style.grip_dot); } // The edge's line lies on the column's inner edge; its handle stays inside the column. A floating window's // edges are the window's. diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index d31e9adf9..d41fd148f 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -20,7 +20,7 @@ use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release, secondary}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; -use craft_ui_test_kit::windows::{Out, Windows}; +use craft_ui_test_kit::windows::{AppKitWindow, Out, Windows}; use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; @@ -597,20 +597,36 @@ fn a_native_float_the_os_resizes_or_moves_gets_no_place_back() { assert_eq!(Vec2::from(recorded.normal.size), at.size(), "the model holds the OS's last size"); } -/// An app change of a native palette's place (an undo, a reloaded layout) moves and sizes its window, once. +/// An app change of a native palette's place (an undo, a reloaded layout) moves and sizes its window, once, and the +/// window lands at that place: on Linux by one move and one size; on macOS, where AppKit keeps a resized window's +/// bottom-left corner, the move goes out again after the size. #[trial] fn an_app_change_of_a_native_floats_place_moves_its_window_once() { - let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); - let to = Rect::from_min_size(Pos2::new(1100.0, 200.0), Vec2::new(320.0, 260.0)); - let mut placement = Placement::new(to.size().into(), 1.0); - placement.position_px = Some([to.min.x as i32, to.min.y as i32]); - Arc::make_mut(&mut dock.workspace).apply(Action::set_native(1, Some(placement)), false, |_| Permissions::ALL).expect("the model takes the place"); - let mut sent = Vec::new(); - for _ in 0..3 { - sent.extend(dock.frame(vec![]).1); + for os in [Os::Linux, Os::Mac] { + let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new())); + let to = Rect::from_min_size(Pos2::new(1100.0, 200.0), Vec2::new(320.0, 260.0)); + let mut placement = Placement::new(to.size().into(), 1.0); + placement.position_px = Some([to.min.x as i32, to.min.y as i32]); + Arc::make_mut(&mut dock.workspace) + .apply(Action::set_native(1, Some(placement)), false, |_| Permissions::ALL) + .expect("the model takes the place"); + let (mut at, mut window) = (FLOAT_AT, AppKitWindow::new(FLOAT_AT, None)); + let mut sent = Vec::new(); + for _ in 0..3 { + let commands = dock.frame(vec![]).1; + window.run(&commands); + at = if os == Os::Mac { window.rect } else { placed_by(&commands, at) }; + dock.windows.child_info(info(true, at)); + sent.push(placing(&commands).into_iter().cloned().collect::>()); + } + let expected = match os { + Os::Mac => vec![ViewportCommand::OuterPosition(to.min), ViewportCommand::InnerSize(to.size()), ViewportCommand::OuterPosition(to.min)], + _ => vec![ViewportCommand::OuterPosition(to.min), ViewportCommand::InnerSize(to.size())], + }; + assert_eq!(sent.concat(), expected, "{os:?}: one move and one size"); + assert_eq!(sent.iter().filter(|frame| !frame.is_empty()).count(), 1, "{os:?}: in one frame"); + assert_eq!(at, to, "{os:?}: the window lands at the place"); } - let placing = placing(&sent); - assert_eq!(placing, [&ViewportCommand::OuterPosition(to.min), &ViewportCommand::InnerSize(to.size())], "one move and one size"); } /// The size and place an OS window takes from `commands`, starting at `at`. @@ -629,25 +645,15 @@ fn placed_by(commands: &[ViewportCommand], at: Rect) -> Rect { fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); let expanded = FLOAT_AT.size(); - // The OS follows the window commands of each frame, and the window reports where it is. + // AppKit follows the window commands of each frame, within the largest size the previous frames left in force, + // and the window reports where it is. let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| { let mut sent = Vec::new(); for _ in 0..frames { - // The OS clamps a size to the maximum in force when it takes the command: the one the previous frames - // left, then each limit command of this frame in order. - let mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + let mut window = AppKitWindow::new(*at, dock.builder.as_ref().and_then(|builder| builder.max_inner_size)); let commands = dock.frame(vec![]).1; - for command in &commands { - match command { - ViewportCommand::MaxInnerSize(limit) => max = Some(*limit), - ViewportCommand::InnerSize(size) => { - let size = max.map_or(*size, |max| size.min(max)); - *at = Rect::from_min_size(at.min, size); - } - ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), - _ => {} - } - } + window.run(&commands); + *at = window.rect; dock.windows.child_info(info(true, *at)); sent.extend(commands); } @@ -674,7 +680,7 @@ fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands"); let sent = follow(&mut dock, &mut at, 3); assert!(sent.contains(&ViewportCommand::InnerSize(expanded)), "the window takes its expanded size back: {:?}", placing(&sent)); - assert_eq!(at.min, dropped.min, "it opens from the strip's place, against the start edge"); + assert_eq!(at.min, dropped.min, "it opens from the strip's place, against the start edge, at the strip's top"); assert_eq!(at.size(), expanded, "the OS window grows although the strip's limits capped it when the size was sent"); let max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); assert!(max.is_none_or(|max| max.x >= expanded.x && max.y >= expanded.y), "the OS lets it take that size: max {max:?}"); @@ -687,10 +693,12 @@ fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() { let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); let mut at = FLOAT_AT; - // The OS follows the window commands of each frame, and the window reports where it is. + // AppKit follows the window commands of each frame, and the window reports where it is. let follow = |dock: &mut NativeDock, at: &mut Rect, events: Vec| { + let mut window = AppKitWindow::new(*at, dock.builder.as_ref().and_then(|builder| builder.max_inner_size)); let commands = dock.frame(events).1; - *at = placed_by(&commands, *at); + window.run(&commands); + *at = window.rect; dock.windows.child_info(info(true, *at)); commands }; @@ -741,13 +749,19 @@ fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_he let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new())); let expanded = FLOAT_AT.size(); let mut at = FLOAT_AT; - // The OS follows the window commands of each frame, within the limits in force, and the window reports where it is. + // The OS follows the window commands of each frame, within the limits in force, and the window reports where it is: + // AppKit keeps a resized window's bottom-left corner, Windows its top-left corner. let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| { let mut sent = Vec::new(); for _ in 0..frames { let mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + let mut window = AppKitWindow::new(*at, max); let commands = dock.frame(vec![]).1; - for command in &commands { + if os == Os::Mac { + window.run(&commands); + *at = window.rect; + } + for command in commands.iter().filter(|_| os != Os::Mac) { match command { ViewportCommand::MaxInnerSize(limit) => max = Some(*limit), ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, max.map_or(*size, |max| size.min(max))), @@ -827,6 +841,165 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { assert_eq!(at.size(), FLOAT_AT.size(), "the OS window takes its expanded size"); } +/// The display scale of a MacBook's built-in display. +const RETINA: f32 = 2.0; + +/// A native palette on a Retina Mac whose window AppKit runs, after its first frames. +fn appkit_palette(system: &Arc) -> (NativeDock, AppKitWindow) { + let mut dock = NativeDock::on(Os::Mac, Arc::clone(system)); + dock.windows.root_info(scaled(true, MAIN_AT, RETINA)); + let mut window = AppKitWindow::new(FLOAT_AT, None); + dock.windows.child_info(scaled(true, window.rect, RETINA)); + for _ in 0..2 { + appkit_frame(&mut dock, &mut window, vec![]); + } + (dock, window) +} + +/// One frame with `child` events for the palette's window, whose commands AppKit runs; the window then reports where +/// it is. +fn appkit_frame(dock: &mut NativeDock, window: &mut AppKitWindow, child: Vec) -> (Vec>, Vec) { + let (actions, commands) = dock.frame(child); + window.run(&commands); + dock.windows.child_info(scaled(true, window.rect, RETINA)); + (actions, commands) +} + +/// A click at `at` in the palette's window, with the system pointer and button as macOS tells them, and the frames +/// after it. +fn appkit_click(dock: &mut NativeDock, system: &FakeSystem, window: &mut AppKitWindow, at: Pos2) -> Vec> { + let desktop = window.rect.min + at.to_vec2(); + system.set_pointer(Some([desktop.x, desktop.y])); + let mut actions = appkit_frame(dock, window, vec![moved(at)]).0; + system.set_primary_held(Some(true)); + actions.extend(appkit_frame(dock, window, vec![press(at)]).0); + system.set_primary_held(Some(false)); + actions.extend(appkit_frame(dock, window, vec![release(at)]).0); + for _ in 0..3 { + actions.extend(appkit_frame(dock, window, vec![]).0); + } + actions +} + +/// The rect of the palette's button whose name starts with `name`, in its window's points. +fn palette_button(dock: &NativeDock, name: &str) -> Rect { + let tree = dock.palette_tree.as_ref().expect("the palette ran a pass"); + tree.keys() + .into_iter() + .find(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key).is_some_and(|shown| shown.starts_with(name))) + .and_then(|key| tree.bounds_of(key)) + .unwrap_or_else(|| panic!("the palette shows a button named {name}…: {:?}", nodes(tree))) +} + +/// On a Retina Mac, clicks on the double arrow collapse a native palette to its strip of icons and expand it again, +/// as AppKit runs the window commands: the strip shows at the window's top against the edge the window keeps to, and +/// expanded, the window takes its size back at its place. +#[trial] +fn the_double_arrow_collapses_and_expands_a_native_palette_on_macos() { + let system = Arc::new(FakeSystem::new()); + let (mut dock, mut window) = appkit_palette(&system); + let collapse = palette_button(&dock, "Collapse").center(); + let actions = appkit_click(&mut dock, &system, &mut window, collapse); + let strip = window.rect; + assert!(dock.workspace.layout().floating[0].column.iconic, "the click collapses the column: {actions:?}"); + assert!(strip.width() < FLOAT_AT.width() && strip.height() < FLOAT_AT.height(), "the window shows the strip: {strip:?}"); + assert!((strip.max.x - FLOAT_AT.max.x).abs() <= 0.5, "the strip keeps to the window's end edge: {strip:?} from {FLOAT_AT:?}"); + assert!((strip.min.y - FLOAT_AT.min.y).abs() <= 0.5, "the strip keeps the window's top: {strip:?} from {FLOAT_AT:?}"); + + let expand = palette_button(&dock, "Expand").center(); + let actions = appkit_click(&mut dock, &system, &mut window, expand); + assert!(!dock.workspace.layout().floating[0].column.iconic, "the click expands the column: {actions:?}"); + assert_eq!(window.rect.size(), FLOAT_AT.size(), "the window takes its expanded size"); + assert!((window.rect.min - FLOAT_AT.min).length() <= 0.5, "at its place: {:?} from {FLOAT_AT:?}", window.rect); +} + +/// A native palette on a Retina Mac collapsed to icons by its double arrow. +fn collapsed_appkit_palette(system: &Arc) -> (NativeDock, AppKitWindow) { + let (mut dock, mut window) = appkit_palette(system); + let collapse = palette_button(&dock, "Collapse").center(); + appkit_click(&mut dock, system, &mut window, collapse); + assert!(dock.workspace.layout().floating[0].column.iconic, "the click collapses the column"); + (dock, window) +} + +/// Whether `actions` dock a window or a group of it. +fn docks(actions: &[Action]) -> bool { + actions.iter().any(|action| matches!(action, Action::MoveWindow { .. } | Action::MoveGroup { .. })) +} + +/// Drags the collapsed palette from `from`, a point of its window, until the system pointer is over the main window's +/// group, as macOS runs a drag: the press holds the pointer in the palette's window, and AppKit moves the window +/// itself when the press hands it the move. Returns the commands of the press's frame and whether anything docked. +fn appkit_drag_over_group(dock: &mut NativeDock, system: &FakeSystem, window: &mut AppKitWindow, from: Pos2) -> (Vec, bool) { + let pressed_at = window.rect.min + from.to_vec2(); + system.set_pointer(Some([pressed_at.x, pressed_at.y])); + system.set_primary_held(Some(true)); + appkit_frame(dock, window, vec![moved(from)]); + let (actions, pressed) = appkit_frame(dock, window, vec![press(from)]); + let mut docked = docks(&actions); + let handed = pressed.contains(&ViewportCommand::StartDrag); + let step = (OVER_GROUP - pressed_at) / 3.0; + for at in 1..=3 { + let pointer = pressed_at + step * at as f32; + system.set_pointer(Some([pointer.x, pointer.y])); + if handed { + // AppKit keeps the pressed point under the pointer and sends the app no pointer events. + window.rect = Rect::from_min_size(pointer - from.to_vec2(), window.rect.size()); + dock.windows.child_info(scaled(true, window.rect, RETINA)); + docked |= docks(&appkit_frame(dock, window, vec![]).0); + } else { + docked |= docks(&appkit_frame(dock, window, vec![moved(pointer - window.rect.min.to_vec2())]).0); + } + } + for _ in 0..2 { + docked |= docks(&appkit_frame(dock, window, vec![]).0); + } + (pressed, docked) +} + +/// On a Retina Mac a native palette collapsed to icons moves by its title row as an expanded one does: the press hands +/// the move to the OS, the system pointer over the main window's group marks it, and the button's release docks the +/// whole window there. +#[trial] +fn dragging_a_collapsed_native_palette_by_its_title_row_docks_it_on_macos() { + let system = Arc::new(FakeSystem::new()); + let (mut dock, mut window) = collapsed_appkit_palette(&system); + let arrow = palette_button(&dock, "Expand"); + // The band: the title row beside the double arrow, half way to the strip's other side. + let width = window.rect.width(); + let band = Pos2::new(if arrow.center().x > width / 2.0 { arrow.min.x / 2.0 } else { (arrow.max.x + width) / 2.0 }, arrow.center().y); + let (pressed, docked) = appkit_drag_over_group(&mut dock, &system, &mut window, band); + assert!(pressed.contains(&ViewportCommand::StartDrag), "the press hands the move to the OS: {pressed:?}"); + assert!(drag::mark(&dock.windows.ctx).is_some(), "the group under the system pointer shows the drop mark"); + assert!(!docked, "nothing docks while the system holds the button"); + system.set_primary_held(Some(false)); + let mut docked = false; + for _ in 0..3 { + docked |= docks(&appkit_frame(&mut dock, &mut window, vec![]).0); + } + assert!(docked, "the button's release docks the whole window"); +} + +/// On a Retina Mac the grip of a native palette's icon group, collapsed to icons, drags the group: over the main +/// window's group it shows the drop mark, and the release docks it there. +#[trial] +fn dragging_the_group_grip_of_a_collapsed_native_palette_docks_it_on_macos() { + let system = Arc::new(FakeSystem::new()); + let (mut dock, mut window) = collapsed_appkit_palette(&system); + let grip = palette_button(&dock, "Move").center(); + let (pressed, docked) = appkit_drag_over_group(&mut dock, &system, &mut window, grip); + assert!(!pressed.contains(&ViewportCommand::StartDrag), "the grip does not move the window: {pressed:?}"); + assert!(drag::mark(&dock.windows.ctx).is_some(), "the group under the pointer shows the drop mark"); + assert!(!docked, "nothing docks while the button is held"); + let release_at = OVER_GROUP - window.rect.min.to_vec2(); + system.set_primary_held(Some(false)); + let mut docked = docks(&appkit_frame(&mut dock, &mut window, vec![release(release_at)]).0); + for _ in 0..2 { + docked |= docks(&appkit_frame(&mut dock, &mut window, vec![]).0); + } + assert!(docked, "the release docks the group"); +} + /// Panels whose palette panel's body records, in each of its real runs, the viewport it runs in. #[derive(Default)] struct BodyProbe(Vec); diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index 01fd11af2..4c50cc229 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -198,6 +198,45 @@ fn keep_tree(output: &mut FullOutput, viewport: ViewportId) { TREES.with(|kept| kept.borrow_mut().push((viewport, tree))); } +/// An OS window as macOS runs egui's window commands on it through winit, in desktop points with y down: a position +/// moves the frame's top-left corner at its current size (`setFrameOrigin`); a size keeps the frame's bottom-left +/// corner (`setContentSize`), so a change of height moves the top edge; the largest size in force clamps the current +/// size the same way, and every size the window takes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AppKitWindow { + /// Where the window is. + pub rect: Rect, + max: Option, +} + +impl AppKitWindow { + /// A window at `rect` whose largest size is `max`, the limit the commands of earlier frames left in force. + pub fn new(rect: Rect, max: Option) -> Self { + AppKitWindow { rect, max } + } + + /// Runs `commands` in order. + pub fn run(&mut self, commands: &[ViewportCommand]) { + for command in commands { + match command { + ViewportCommand::OuterPosition(to) => self.rect = Rect::from_min_size(*to, self.rect.size()), + ViewportCommand::InnerSize(size) => self.content_size(*size), + ViewportCommand::MinInnerSize(least) => self.content_size(self.rect.size().max(*least)), + ViewportCommand::MaxInnerSize(most) => { + self.max = Some(*most); + self.content_size(self.rect.size()); + } + _ => {} + } + } + } + + fn content_size(&mut self, size: Vec2) { + let size = self.max.map_or(size, |max| size.min(max)); + self.rect = Rect::from_min_size(Pos2::new(self.rect.min.x, self.rect.max.y - size.y), size); + } +} + /// What a frame sent out. #[non_exhaustive] pub struct Out {