diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index f567b938e..6533a5127 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -36,6 +36,7 @@ pub use scroll::{STRIP_BACK, STRIP_FORWARD}; #[cfg(feature = "suite")] pub(crate) use window::MOVE_BAND; use window::WindowMode; +pub use window::grip_band; pub(crate) use window::keep_inside; /// The scroll region's view in the last pass that showed it. diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 5f95a19e4..0f9f07641 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -13,7 +13,7 @@ use super::scroll::{ strips_of, view_within, }; use super::size::MeasureKey; -use super::window::{WindowMode, os_window, window_instance}; +use super::window::{WindowMode, os_window, top_band, window_instance}; use super::{BodyHooks, BodyView}; use crate::contract::cx::CxCore; use crate::contract::cx::{BodyCx, BodyOwner, RegionShare}; @@ -302,7 +302,7 @@ impl ShapeHooks for BodyHooks<'_> { self.overflow = self.wanted_width(props).map_or(0.0, |wanted| (wanted - room.max(0.0)).max(0.0)); let (header, end) = (self.measured_header.unwrap_or(Vec2::ZERO), self.measured_end.unwrap_or(Vec2::ZERO)); let height = self.regions_size(props, body, header, self.measured_footer, end).y; - Vec2::new(width, height) + 2.0 * self.pads(props, scx.tokens) + Vec2::new(width, height) + self.frame_size(props, scx.tokens, top_band(props, ui.ctx(), id, scx.tokens)) } /// The regions run once in an invisible sizing pass over the room, as `content` runs them, and the container takes @@ -439,8 +439,11 @@ impl ShapeHooks for BodyHooks<'_> { } let tokens = cx.tokens; let pad = self.pads(&props, tokens); - let inner = content.shrink2(pad); - let regions = self.regions(&props, inner, pad, self.room_size(rect, inner), rtl, self.measured_sizes(), !cx.ui.is_sizing_pass()); + let band = top_band(&props, cx.ui.ctx(), cx.id, tokens); + let inner = self.inner_rect(&props, tokens, content, band); + let regions = self + .regions(&props, inner, pad, self.room_size(rect, inner), rtl, self.measured_sizes(), !cx.ui.is_sizing_pass()) + .below(content.min.y + band); let (_, slots) = self.header_line(regions.header, pad_of(tokens, header.inset), parts, rtl); Some(std::rc::Rc::new(slots)) } @@ -451,9 +454,11 @@ impl ShapeHooks for BodyHooks<'_> { let rtl = pcx.flow.is_rtl(); let tokens = pcx.tokens; let pad = self.pads(&props, tokens); - let inner = pcx.content_rect.shrink2(pad); + let band = top_band(&props, &ctx, pcx.id, tokens); + let inner = self.inner_rect(&props, tokens, pcx.content_rect, band); let room = self.room_size(rect, inner); - let regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes(), !pcx.ui.is_sizing_pass()); + let regions = + self.regions(&props, inner, pad, room, rtl, self.measured_sizes(), !pcx.ui.is_sizing_pass()).below(pcx.content_rect.min.y + band); let scroll = scroll_of(&props); if self.open && scroll.is_some() { let at = regions.body; @@ -859,7 +864,7 @@ impl BodyHooks<'_> { fn end_measure_run(&mut self, at: &Measuring<'_, '_>, id: Id, key: MeasureKey, content: Option) -> Vec2 { let props = Arc::clone(&self.props); let ctx = at.ui.ctx(); - let pad = 2.0 * self.pads(&props, at.scx.tokens); + let pad = self.frame_size(&props, at.scx.tokens, top_band(&props, ctx, id, at.scx.tokens)); let record = |key: Id, took: Vec2| layout_memory::emit_record(ctx, key, layout_memory::Measured::new(self.room, took)); record(id, self.body_size.unwrap_or(Vec2::ZERO)); if let Some(first) = self.first_line { @@ -1070,12 +1075,13 @@ impl BodyHooks<'_> { let rtl = env.direction.is_rtl(); let scroll = scroll_of(props); let pad = self.pads(props, &env.tokens); - let inner = core.content_rect.shrink2(pad); + let band = top_band(props, &ctx, id, &env.tokens); + let inner = self.inner_rect(props, &env.tokens, core.content_rect, band); let room = self.room_size(rect, inner); // A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer, // and claims no room in a parent flow. let real = !ui.is_sizing_pass(); - let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes(), real); + let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes(), real).below(core.content_rect.min.y + band); let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_))); let band_slot = ui.painter().add(Shape::Noop); let window = window_instance(props, id).filter(|window| *window != id); @@ -1846,7 +1852,7 @@ impl BodyHooks<'_> { fn measure_plan(&mut self, at: &Measuring<'_, '_>, id: Id, scrolled_share: bool) -> MeasurePlan { let props = Arc::clone(&self.props); let ctx = at.ui.ctx().clone(); - let pad = 2.0 * self.pads(&props, at.scx.tokens); + let pad = self.frame_size(&props, at.scx.tokens, top_band(&props, &ctx, id, at.scx.tokens)); let vertical = scroll_of(&props).is_some_and(|scroll| scroll.vertical_on()); let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); // A record a run of this pass left serves as before; a kept one serves only while the inputs it was measured diff --git a/crates/ui-contract/src/contract/body/pane.rs b/crates/ui-contract/src/contract/body/pane.rs index 20a4d3bf0..b9468431e 100644 --- a/crates/ui-contract/src/contract/body/pane.rs +++ b/crates/ui-contract/src/contract/body/pane.rs @@ -42,6 +42,7 @@ impl BodyHooks<'_> { .sense(craft_behavior::Sense::DRAG) .priority(HitPriority::new(HitLevel::Edge, 0)) .cursor(cursor) + .exact_hit() .pointer_only("no command resizes a docked pane; its extent is the app's layout"); Some((edge, least)) } diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 001b98ca9..24c1ff5c3 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -153,6 +153,15 @@ pub(super) struct Regions { pub(super) rules: [Option<(Rect, RectSide)>; 4], } +impl Regions { + /// The regions with the header's band, which may spread over the padding, below `top`: the bottom of the band a + /// layer keeps clear for its top grip. + pub(super) fn below(mut self, top: f32) -> Regions { + self.header.min.y = self.header.min.y.max(top); + self + } +} + /// The sizes of the header, footer and end region that the regions are placed from (zero or `None` for a region the /// container lacks or that has not measured). #[derive(Clone, Copy)] diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index bf05efae3..1c0392f89 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -163,6 +163,20 @@ impl<'b> BodyHooks<'b> { super::regions::pad_vec(tokens, props.pad, self.pad_edges(props)) } + /// What the container's frame adds to its regions' size: the padding on each side, and on a layer that keeps + /// `band` clear above its header for its top grip (`window::top_band`), the part of the band the padding leaves. + pub(super) fn frame_size(&self, props: &ContainerProps, tokens: &crate::style::UiTokens, band: f32) -> Vec2 { + let pad = self.pads(props, tokens); + 2.0 * pad + Vec2::new(0.0, (band - pad.y).max(0.0)) + } + + /// The rect the regions lie in within `content`: inside the padding, and below `band` at the top. + pub(super) fn inner_rect(&self, props: &ContainerProps, tokens: &crate::style::UiTokens, content: Rect, band: f32) -> Rect { + let mut inner = content.shrink2(self.pads(props, tokens)); + inner.min.y = inner.min.y.max(content.min.y + band); + inner + } + /// Whether the container's body is laid out across the width it is offered: the container is given the width, /// passes it on, or is held across the width its column settled on. pub(super) fn wide(&self) -> bool { diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 903c9a297..7976228fe 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -13,7 +13,7 @@ use crate::runtime::env::{EnvView, ShellEntry}; use crate::runtime::memory::sub; use crate::runtime::windows::{self, ResizeEdge, WindowAction, WindowHit}; use crate::runtime::{keys, pointer}; -use crate::style::ComponentStyle as _; +use crate::style::{ComponentStyle as _, UiTokens}; use craft_behavior::{CursorIcon, GesturePhase, HitLevel, HitPriority, PartKey, PointerEvent, PressPhase}; use craft_host::target::{Caps, WindowChrome, WindowState}; use craft_keymap::{Chord, Key, Mods}; @@ -26,8 +26,9 @@ const GRIP: PartKey = PartKey::new("resize_grip"); /// Which move and resize parts of the body step stand for the OS window of `viewport` (16.3, 21.2): the one rule /// every move band and grip of an OS window reads. Both need a frame the app draws (the chrome is not `Native`). The /// band stands on a maximized window too, so its double click restores the window and a drag is the platform's (it -/// restores and moves); the grips stand only on a window that is neither maximized nor full screen. The parts stand -/// whether or not a hit-test sink is installed: the sink reads them as the window's exclusive parts. +/// restores and moves); the grips stand only on a window that is neither maximized nor full screen, nor one the OS +/// resizes from its own frame (`windows::os_resizes`: AppKit's edges, where app grips would contest its presses). The +/// parts stand whether or not a hit-test sink is installed: the sink reads them as the window's exclusive parts. #[derive(Clone, Copy)] struct WindowParts { band: bool, @@ -43,11 +44,37 @@ impl WindowParts { fn of(ctx: &Context, viewport: ViewportId) -> WindowParts { let window = windows::shell_of(ctx, viewport).window; let framed_by_app = window.chrome != WindowChrome::Native; - let sized_by_os = matches!(window.state, WindowState::Maximized | WindowState::Fullscreen); + let sized_by_os = matches!(window.state, WindowState::Maximized | WindowState::Fullscreen) || windows::os_resizes(ctx, viewport); WindowParts { band: framed_by_app && window.state != WindowState::Fullscreen, grips: framed_by_app && !sized_by_os } } } +/// The band a layer keeps clear at its top for its top grip, so that grip never lies over the header: the grip's +/// width ([`grip_band`]) on a layer whose header is on a line of its own and whose top grip or a top corner's stands, +/// or that the user moves: a floating window keeps the band while it has no top grip (collapsed, minimized), so its +/// header stays where it was. None elsewhere, nor on a layer whose band moves the window below it. The regions start +/// below the band, or below the padding where that is deeper. An OS window keeps none: its grips, the platform's or +/// the app's, lie over its title bar as an OS title bar's resize edge does. +pub(super) fn top_band(props: &ContainerProps, ctx: &Context, id: Id, tokens: &UiTokens) -> f32 { + let overlay = match &props.mount { + Mount::Layer(overlay) => overlay, + Mount::Viewport { fallback, .. } if !windows::mount_window(ctx, id) => fallback, + _ => return 0.0, + }; + if !props.header.is_some_and(|header| !header.inline) || overlay.moves_window { + return 0.0; + } + let pinned = Pinned::of(overlay, ctx, id, false); + let top = [(0, -1), (-1, -1), (1, -1)].into_iter().any(|(dx, dy)| grip_stands(overlay.resize.edges, pinned, dx, dy)); + if top || overlay.movable { grip_band(tokens) } else { 0.0 } +} + +/// The width of a window's edge grips, and of the band a layer keeps clear above its header for its top grip: +/// `size.handle.sm`. A corner grip reaches twice as far along each of its edges. +pub fn grip_band(tokens: &UiTokens) -> f32 { + tokens.tokens().size.handle.sm +} + /// Whether the platform answers the hit test of `viewport`'s undecorated window itself, as it does for a window whose /// hit-test sink is installed (`WindowHost::install_hit_sink`): it takes the move, edge and caption hits from the /// window's exclusive parts, so a press on the move band or a grip never reaches the app as a move. @@ -701,7 +728,6 @@ impl BodyHooks<'_> { /// drag holds (`WindowMode::held`), which stays declared until its release. pub(super) fn move_parts(props: &ContainerProps, regions: &Regions, rect: Rect, held: Option, pcx: &mut PartsCx<'_, C>) { let ctx = pcx.ui.ctx().clone(); - let handle = pcx.tokens.tokens().size.handle.sm; let reason = "the Move and Size commands of the window command set do the same"; let os = os_window(props, &ctx, pcx.id, &pcx.env); let stands = match (&props.mount, os) { @@ -723,46 +749,58 @@ impl BodyHooks<'_> { let band = move_band(props, regions, rect); if props.header.is_some() && movable && band.is_positive() { // The band lies under the line's own parts and children, like the reorder band, so they keep their presses. - let part = pcx - .part(MOVE_BAND, band) - .sense(craft_behavior::Sense::DRAG) - .cursor(CursorIcon::Grab) - .drag_cursor(CursorIcon::Grabbing) - .pointer_only(reason); + // On a window the OS frames (macOS `Inset`) it keeps the arrow, as an OS title bar does: the OS's resize + // areas cover its ends and top edge, and a cursor set over them fights the OS's. + let moved = os.or(moves_window.then(|| pass::current_viewport(&ctx))); + let os_bar = moved.is_some_and(|viewport| windows::shell_of(&ctx, viewport).window.chrome == WindowChrome::Inset); + let mut part = pcx.part(MOVE_BAND, band).sense(craft_behavior::Sense::DRAG).pointer_only(reason); + if !os_bar { + part = part.cursor(CursorIcon::Grab).drag_cursor(CursorIcon::Grabbing); + } if let Some(hit) = exclusive(WindowHit::Move).or(moves_window.then_some(WindowHit::Move)) { part.exclusive(hit); } } - // The grips of a layer straddle its edge; those of a window lie inside it, where the window has pixels. They - // stack above the body (`over`), so a root in the body never covers their inner half (8.3). - let (edges, inset) = match &props.mount { - Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => (overlay.resize.edges, 0.0), - Mount::Window { resize } => (resize.edges, handle / 2.0), - _ => (ResizeEdges::NONE, 0.0), + let edges = match &props.mount { + Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => overlay.resize.edges, + Mount::Window { resize } => resize.edges, + _ => ResizeEdges::NONE, }; if edges == ResizeEdges::NONE || !stands.grips { return; } + // Every grip lies inside the frame, where a window has pixels and a layer's own rect takes the pointer: an edge + // grip `handle` deep, a corner grip twice that along each of its edges, the edge grips between the corners. + // They stack above the body (`over`), so a root in the body never covers them (8.3), and each takes exactly its + // rect (`exact_hit`), as the platform's hit test does for an exclusive grip. The top corners of a layer that + // keeps a band over its header (`top_band`) are only as tall as the band, so no grip lies over the header. + let handle = grip_band(pcx.tokens); + let corner = 2.0 * handle; + let top = top_band(props, &ctx, pcx.id, pcx.tokens); 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; } - let along = |edge: i8, low: f32, high: f32| match edge { - -1 => (low - handle / 2.0 + inset, low + handle / 2.0 + inset), - 1 => (high - handle / 2.0 - inset, high + handle / 2.0 - inset), - _ => (low + handle / 2.0 + inset, high - handle / 2.0 - inset), + let span = |edge: i8, low: f32, high: f32, deep: f32| match edge { + -1 => (low, low + deep), + 1 => (high - deep, high), + _ => (low + corner, high - corner), }; - let (x0, x1) = along(dx, rect.min.x, rect.max.x); - let (y0, y1) = along(dy, rect.min.y, rect.max.y); - let level = if dx != 0 && dy != 0 { HitLevel::Handle } else { HitLevel::Edge }; + let at_corner = dx != 0 && dy != 0; + let deep = if at_corner { corner } else { handle }; + let tall = if at_corner && dy == -1 && top > 0.0 { top } else { deep }; + let (x0, x1) = span(dx, rect.min.x, rect.max.x, deep); + let (y0, y1) = span(dy, rect.min.y, rect.max.y, tall); + let level = if at_corner { HitLevel::Handle } else { HitLevel::Edge }; let part = pcx .part(GRIP.at(index as u64), Rect::from_min_max(Pos2::new(x0, y0), Pos2::new(x1, y1))) .sense(craft_behavior::Sense::DRAG) .priority(HitPriority::new(level, 0)) .cursor(cursor) .pointer_only(reason) + .exact_hit() .over(); // 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) { diff --git a/crates/ui-contract/src/contract/cx/parts.rs b/crates/ui-contract/src/contract/cx/parts.rs index 50b702c77..982aaf7d2 100644 --- a/crates/ui-contract/src/contract/cx/parts.rs +++ b/crates/ui-contract/src/contract/cx/parts.rs @@ -187,6 +187,14 @@ impl PartBuilder<'_> { self } + /// The part's hit area is its shape as declared, never grown to the pointer's target size (`size.hit.target`): a + /// frame's resize grip, whose band is sized as its reach and whose neighbours (a title row, the content) own every + /// point beside it. + pub fn exact_hit(self) -> Self { + self.decl.exact = true; + self + } + /// The part's look is the plain state layer: the paint step fills its rect with `StyleCx::state_layer` in the /// part's state, under the component's paint, with control corners. pub fn state_layer(self) -> Self { diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 71951fc8e..44dee4d71 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -53,6 +53,7 @@ pub use crate::runtime::pending::{Job, Pending, Progress}; #[doc(hidden)] pub use body::REORDER_BAND; #[doc(hidden)] +pub use body::grip_band; pub use body::pad_of; #[doc(hidden)] pub use body::{STRIP_BACK, STRIP_FORWARD}; diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index ab1bc0b6e..d9e8d7461 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -128,6 +128,8 @@ pub(crate) struct PartDecl { pub inactive: bool, /// The component holds a press on the part (`PartBuilder::held`). pub held: bool, + /// The hit area is the shape as declared, never grown to the pointer's target size (`PartBuilder::exact_hit`). + pub exact: bool, } impl PartDecl { @@ -144,12 +146,18 @@ impl PartDecl { flags: Flags::default(), inactive: false, held: false, + exact: false, } } fn part_ref(&self) -> PartRef { PartRef { key: self.key, index: self.index } } + + /// The least size across the part's hit area, given the pointer's target size `target`. + fn min_across(&self, target: f32) -> f32 { + if self.exact { 0.0 } else { target } + } } /// One member's registration for this pass. @@ -313,7 +321,7 @@ fn rotate(state: &mut ArenaState, pass_nr: u64) { } fn own_part_shape(part: &PartDecl, root: Id, position: u32, target: f32) -> Shape { - Shape::new(part.shape.clone(), part.sense, root, Some(part.part_ref()), part.priority, position).min_across(target) + Shape::new(part.shape.clone(), part.sense, root, Some(part.part_ref()), part.priority, position).min_across(part.min_across(target)) } /// The root's own parts but the `over` ones, at position 0. @@ -338,7 +346,9 @@ fn over_position(count: usize) -> u32 { } fn member_part_shape(member: &MemberDecl, part: &PartDecl, position: u32, target: f32) -> Shape { - Shape::new(part.shape.clone(), part.sense, member.id, Some(part.part_ref()), part.priority, position).local(member.local).min_across(target) + Shape::new(part.shape.clone(), part.sense, member.id, Some(part.part_ref()), part.priority, position) + .local(member.local) + .min_across(part.min_across(target)) } /// The member's root shape and its parts but the `over` ones, at its stack position. diff --git a/crates/ui-contract/src/runtime/cursor.rs b/crates/ui-contract/src/runtime/cursor.rs index f8496a45a..53becfc43 100644 --- a/crates/ui-contract/src/runtime/cursor.rs +++ b/crates/ui-contract/src/runtime/cursor.rs @@ -95,12 +95,16 @@ fn push(ctx: &Context, cursor: Cursor, priority: CursorPriority, region: Option< /// blocked cursor. A system cursor goes out through the viewport's output; a painted cursor hides the system one and /// is left for the overlay host, which paints it or hands it back as an image ([`show_image`]), except a badged /// system cursor, which keeps its base and has only the badge painted. The window's image from the last pass is -/// cleared: egui keeps it until it is replaced. +/// cleared: egui keeps it until it is replaced. Over the resize areas of a window the OS resizes from its own frame +/// the cursor is the default whatever was requested: the OS shows its resize cursor there, and any other fights it. pub(crate) fn end_pass(ctx: &Context) { let blocked = windows::blocking_modal(ctx).is_some(); - let won = PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + let viewport = pass::current_viewport(ctx); + let to_os = !blocked && over_os_resize_area(ctx, viewport); + let won = PerViewport::::with(ctx, viewport, |state| { let (won, region) = match pick_index(&state.requests) { _ if blocked => (Some(Cursor::System(CursorIcon::NotAllowed)), None), + _ if to_os => (Some(Cursor::System(CursorIcon::Default)), None), Some(at) => (state.requests.get(at).map(|(cursor, _)| cursor.clone()), state.regions.get(at).copied().flatten()), None => (None, None), }; @@ -122,6 +126,18 @@ pub(crate) fn end_pass(ctx: &Context) { } } +/// Whether the pointer lies in the resize areas of `viewport`'s window where the OS resizes it from its own frame +/// (`windows::os_resizes`). +fn over_os_resize_area(ctx: &Context, viewport: ViewportId) -> bool { + if !windows::os_resizes(ctx, viewport) { + return false; + } + let Some(hover) = crate::runtime::pointer::pass_pointer(ctx).hover else { return false }; + let content = pass::content_rect(ctx); + let at = hover - content.min; + craft_window::mac::in_resize_area([content.width(), content.height()], [at.x, at.y]) +} + /// The cursor the last pass of the running viewport settled on; `None` is the default arrow. pub fn current(ctx: &Context) -> Option { PerViewport::::with(ctx, pass::current_viewport(ctx), |state| state.record.clone()) diff --git a/crates/ui-contract/src/runtime/egui/pass.rs b/crates/ui-contract/src/runtime/egui/pass.rs index 5af857656..b7ac890ec 100644 --- a/crates/ui-contract/src/runtime/egui/pass.rs +++ b/crates/ui-contract/src/runtime/egui/pass.rs @@ -34,6 +34,11 @@ pub fn current_viewport(ctx: &Context) -> ViewportId { } } +/// The running pass's window content, in its own points: the rect the pass lays out in. +pub(crate) fn content_rect(ctx: &Context) -> egui::Rect { + ctx.content_rect() +} + /// The viewports egui reports for the running pass. pub(crate) fn live_viewports(ctx: &Context) -> Vec { ctx.input(|input| input.raw.viewports.keys().copied().collect()) diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index 5327cb917..a5d117b24 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -180,6 +180,14 @@ pub(crate) fn take_sent(ctx: &Context) -> Vec<(ViewportId, WindowAction)> { shared(ctx, |shared| std::mem::take(&mut shared.sent)) } +/// Whether the OS resizes `viewport`'s window from a frame of its own: it draws the frame (macOS `Inset`, a titled +/// window under the app's bar) and the window is resizable. A window its caller sizes opens not resizable, so the OS +/// leaves it to the app's grips. +pub(crate) fn os_resizes(ctx: &Context, viewport: ViewportId) -> bool { + let chrome = shell_of(ctx, viewport).window.chrome; + chrome == WindowChrome::Inset && PerViewport::::with(ctx, viewport, |record| record.resizable != Some(false)) +} + /// Whether the app runs the move of `viewport`'s window (`Overlay::moved_by_app`). pub(crate) fn app_moves(ctx: &Context, viewport: ViewportId) -> bool { PerViewport::::with(ctx, viewport, |record| record.moved_by_app) diff --git a/crates/ui-contract/tests/it/runtime/window_move.rs b/crates/ui-contract/tests/it/runtime/window_move.rs index 7fb2b94d9..d022b9b12 100644 --- a/crates/ui-contract/tests/it/runtime/window_move.rs +++ b/crates/ui-contract/tests/it/runtime/window_move.rs @@ -3,6 +3,7 @@ //! it is neither maximized nor full screen; a `Window` mount puts its grips on the window's edges; a double click on the //! move band is reported once. +use craft_behavior::{Cursor, CursorIcon}; use craft_host::target::{ShellInfo, WindowChrome, WindowInfo, WindowKind}; use craft_ui::contract::overlay::Resize; use craft_ui::contract::{ @@ -166,3 +167,21 @@ fn a_window_mounts_edges_resize_the_window_and_the_childs_press_keeps_its_click( assert_eq!(rig.seen.borrow().activations, 1, "the child under the edge keeps its click"); assert!(resizes(&sent).is_empty(), "and the click starts no resize: {sent:?}"); } + +/// Where the OS draws a resizable window's frame (macOS `Inset`), AppKit resizes the window from its edges: the app +/// registers no grips there, so a drag on an edge starts no resize of the app's, and over AppKit's resize areas the +/// cursor is the default, as the OS shows its own there. +#[trial] +fn where_appkit_resizes_a_window_the_app_registers_no_grips_and_leaves_the_cursor_to_it() { + let edge = pos2(1.0, ROOT.y / 2.0); + let (sent, _) = root_drag(WindowChrome::Inset, edge, vec2(20.0, 0.0)); + assert!(resizes(&sent).is_empty(), "AppKit resizes the window, the app's grips stand down: {sent:?}"); + let windows = root(WindowChrome::Inset); + let rig = Rig::new(Mount::window(Resize::GRIPS)); + for _ in 0..4 { + rig.frame(&windows, vec![], vec![]); + } + rig.frame(&windows, vec![moved(edge)], vec![]); + let cursor = craft_ui::runtime::cursor::current(&windows.ctx); + assert!(matches!(cursor, None | Some(Cursor::System(CursorIcon::Default))), "over AppKit's edge the cursor is left to the OS: {cursor:?}"); +} diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 44fe2eb95..4a94c1131 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -244,12 +244,12 @@ pub fn float_drop( ) -> DockDropped

{ let size = space.size_of(unit, source).min(space.area.size()); let under = |size: Vec2| { - let min = (at - Vec2::new(size.x * 0.5, space.title_row * 0.5)).min(space.area.max - size).max(space.area.min); + let min = (at - Vec2::new(size.x * 0.5, space.chrome * 0.5)).min(space.area.max - size).max(space.area.min); Rect::from_min_size(min, size) }; let (rect, edge, mark) = match strip.filter(|_| !matches!(unit, DragUnit::Window(_))) { Some(strip) => { - let shown = under((strip + Vec2::new(0.0, space.title_row)).min(space.area.size())); + let shown = under((strip + Vec2::new(0.0, space.chrome)).min(space.area.size())); let (rect, edge) = WindowColumn::around_strip(shown, size, space.area, rtl); (rect, Some(edge), shown) } diff --git a/crates/ui-panels/src/docking/event.rs b/crates/ui-panels/src/docking/event.rs index 367fff306..5fdfe8bcc 100644 --- a/crates/ui-panels/src/docking/event.rs +++ b/crates/ui-panels/src/docking/event.rs @@ -69,8 +69,9 @@ pub struct FloatSpace

{ pub area: Rect, /// Room between the area's top-left corner and a unit a command floats. pub inset: f32, - /// The height of a floating window's title row (`DockSizes::title_row`), which a drop keeps under the pointer. - pub title_row: f32, + /// The height above a floated window's body (`DockSizes::window_chrome`): its title row, which a drop keeps under + /// the pointer, and the band over it where floats show in the app window. + pub chrome: f32, /// The size a unit floats at when neither its panel nor where it came from gives one. Its height is also the /// most a panel, group or column floats at. pub default_size: Vec2, @@ -87,13 +88,20 @@ impl FloatSpace

{ FloatSpace { area, inset: sizes.cascade_inset, - title_row: sizes.title_row, + chrome: sizes.window_chrome(true), default_size: sizes.float_size, panels: Vec::new(), side_edge_zones: false, } } + /// For an area whose floats open in OS windows (`on`), whose chrome is their title row alone. + #[must_use] + pub fn in_os_windows(mut self, sizes: &DockSizes, on: bool) -> Self { + self.chrome = sizes.window_chrome(!on); + self + } + /// For an area drawn with `DockConfig::side_edge_zones` when the area has not drawn yet (a headless run). #[must_use] pub fn with_side_edge_zones(mut self, on: bool) -> Self { @@ -120,7 +128,7 @@ impl FloatSpace

{ /// The size `unit` floats at: a panel's own float size, else the size it had where it came from (`source`), else /// the default. A window keeps its own size. A panel, group or column takes the source's width and its height - /// with the window's title row above it, at most the default height: the dock passes the height its content + /// with the window's chrome above it, at most the default height: the dock passes the height its content /// measures at in that room, so content that fills floats at the default height. pub fn size_of(&self, unit: &DragUnit

, source: Option) -> Vec2 { let own = match unit { @@ -129,15 +137,15 @@ impl FloatSpace

{ }; let framed = |size: Vec2| match unit { DragUnit::Window(_) => size, - _ => Vec2::new(size.x, (size.y + self.title_row).min(self.default_size.y)), + _ => Vec2::new(size.x, (size.y + self.chrome).min(self.default_size.y)), }; own.or(source.map(framed)).unwrap_or(self.default_size) } /// The height a panel, group or column's content is measured in for a float of it: the default height less the - /// window's title row. + /// window's chrome. pub fn content_room(&self) -> f32 { - (self.default_size.y - self.title_row).max(0.0) + (self.default_size.y - self.chrome).max(0.0) } fn find(sizes: &[(P, Vec2)], panel: &P) -> Option { diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 5c84635a8..1980e15bd 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -12,7 +12,7 @@ use super::drop::{DragUnit, start_group_drag}; use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; use crate::contract::SizeLimits; -use crate::contract::overlay::{PlacementChange, PlacementKind, Popup}; +use crate::contract::overlay::{PlacementChange, PlacementKind, Popup, ResizeEdges}; use crate::contract::{ Access, Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderEdge, HeaderParts, HeaderRegion, Inner, MeasureCx, Mount, NoValue, OsFiles, Outcome, Overlay, Pad, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, @@ -34,9 +34,9 @@ use std::hash::Hash; #[cfg(feature = "suite")] pub(crate) mod stories; -/// The height of a floating group's title row: a strong `TitleRow`, which is as tall as a panel header. +/// The height of a floating group's title row: a `TitleRow` of the `Bar` strength, one text row high. pub(crate) fn title_row(tokens: &UiTokens) -> f32 { - tokens.size.panel_header + tokens.size.row.text } /// The actions a floating group's title row shows unless `actions` says otherwise: Close alone, as a floating panel's @@ -61,6 +61,9 @@ pub struct WindowColumn { pub edge: DockEdge, /// The size of the collapsed column under the title row; `None` while the column is expanded. pub collapsed: Option, + /// The least and most width the sides of a collapsed column's window resize it to + /// ([`DockSizes::iconic_bounds`](super::DockSizes::iconic_bounds)); unbounded while the column is expanded. + pub widths: (f32, f32), /// The size of an expanded column whose content sets it (a column with steps) under the title row; `None` for a /// column the rect sizes. pub fitted: Option, @@ -71,19 +74,20 @@ pub struct WindowColumn { impl WindowColumn { /// An expanded column that keeps to `edge`. pub fn expanded(edge: DockEdge) -> Self { - WindowColumn { edge, collapsed: None, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } - /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. - pub fn collapsed(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: Some(size), fitted: None, arrow: ColumnArrow::Collapse } + /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. The window's sides resize its + /// width within `widths`, as a docked collapsed column's inner edge does; its height stays `size`'s. + pub fn collapsed(edge: DockEdge, size: Vec2, widths: (f32, f32)) -> Self { + WindowColumn { edge, collapsed: Some(size), widths, fitted: None, arrow: ColumnArrow::Collapse } } /// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at /// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's /// steps, and a move keeps the rect's size. pub fn fitted(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: None, fitted: Some(size), arrow: ColumnArrow::Collapse } + WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } } /// The column with the double arrow `arrow` ([`ColumnArrow::of`]). @@ -92,19 +96,22 @@ impl WindowColumn { self } - /// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under a title row - /// `header` tall, at the top of `rect` and against the edge the window keeps to. `None` while the column is - /// expanded. - pub fn shown(self, rect: Rect, header: f32, rtl: bool) -> Option { - let size = self.collapsed? + Vec2::new(0.0, header); + /// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under the window's + /// chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect` and against the edge the window keeps + /// to. `None` while the column is expanded. + pub fn shown(self, rect: Rect, chrome: f32, rtl: bool) -> Option { + let size = self.collapsed? + Vec2::new(0.0, chrome); let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; Some(Rect::from_min_size(Pos2::new(left, rect.top()), size)) } /// The rect a window that keeps `rect` keeps when it shows at `shown`: while collapsed, `rect` moved with the - /// collapsed column ([`Self::shown`]), so it keeps its expanded size; while expanded, `shown`. - pub fn kept(self, shown: Rect, rect: Rect, header: f32, rtl: bool) -> Rect { - self.shown(rect, header, rtl).map_or(shown, |at| rect.translate(shown.min - at.min)) + /// collapsed column ([`Self::shown`]) so that the column's side on the edge the window keeps to stays on that side + /// of `rect`, whatever width the column shows at; `rect` keeps its expanded size. While expanded, `shown`. + pub fn kept(self, shown: Rect, rect: Rect, chrome: f32, rtl: bool) -> Rect { + let Some(at) = self.shown(rect, chrome, rtl) else { return shown }; + let dx = if at_left(self.edge, rtl) { shown.left() - at.left() } else { shown.right() - at.right() }; + rect.translate(Vec2::new(dx, shown.top() - at.top())) } /// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is @@ -134,6 +141,9 @@ impl WindowColumn { } } +/// The widths of a column that is not collapsed: its window's limits are the panels'. +const UNBOUNDED: (f32, f32) = (0.0, f32::INFINITY); + /// Whether `edge`, in reading order, is the left one of the screen. fn at_left(edge: DockEdge, rtl: bool) -> bool { (edge == DockEdge::Start) != rtl @@ -157,6 +167,9 @@ pub struct FloatingGroupOutput { /// The user asked to collapse the window's column to icons (`true`) or expand it (`false`): a click on the double /// arrow, or a double click on the title band. Only a group with a [`WindowColumn`] reports it. pub iconic: Option, + /// The width the user gave the collapsed column of the window this pass, by a side of the window or the keyboard + /// Size mode: the host keeps it as the column's iconic width. The rect in `placed` stays the expanded one. + pub collapsed_width: Option, /// The files dropped on the group's window that no target there took. pub files: Vec, } @@ -182,7 +195,8 @@ impl Outcome for FloatingGroupOutput { /// - Column: a dock window holds one column ([`column`](FloatingGroup::column)); its title row is the column's bar, /// with the double arrow at the end the window keeps to. While the column is collapsed the group shows at the /// 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 +/// a context request on the band opens the menu), its sides resize its width within the column's widths (reported +/// in [`FloatingGroupOutput::collapsed_width`]) while its height stays the icons', and the rect keeps its 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, and in an OS window the app runs them, so the window takes only the size the /// host gives it. @@ -234,10 +248,14 @@ pub struct FloatingGroup<'a> { /// The double arrow was declared this pass, and whether it was clicked. chevron_declared: bool, chevron: bool, - /// The title row's height and the layout direction, read when the group shows. + /// The title row's height, the height above the body (`DockSizes::window_chrome`) and the layout direction, read + /// when the group shows. header: f32, + chrome: f32, rtl: bool, placed: Option, + /// The width a resize gave the collapsed column this pass. + collapsed_width: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, /// Takes the drops released on the group, on the group's own layer. @@ -280,8 +298,10 @@ impl<'a> FloatingGroup<'a> { chevron_declared: false, chevron: false, header: 0.0, + chrome: 0.0, rtl: false, placed: None, + collapsed_width: None, start_drag: None, take_drop: None, moving: false, @@ -329,29 +349,34 @@ impl<'a> FloatingGroup<'a> { pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { let env = Env::of(ui); let header = title_row(&env.tokens); - (self.header, self.rtl) = (header, env.direction.is_rtl()); - let mount = self.mount(header); + // A window in the app window keeps the band over its title row that a layer the user moves keeps for its top + // grip; an OS window's grips lie over its title row. + let band = if self.native.is_none() { crate::contract::grip_band(&env.tokens) } else { 0.0 }; + (self.header, self.chrome, self.rtl) = (header, header + band, env.direction.is_rtl()); + let mount = self.mount(); self.props = self.props.mount(mount); let minimized = self.minimized; let shown = self.show(ui, |ui, cx| (!minimized).then(|| body(ui, cx))); Inner { output: shown.output, inner: shown.inner.flatten(), settle: shown.settle } } - /// The layer or window the group shows in. `header` is the height of the title row. + /// The layer or window the group shows in. /// /// A minimized group, and one with `Sizing::Content`, is placed by its position and width; its height is its - /// content's, which is the title row alone while minimized. - fn mount(&self, header: f32) -> Mount { - // The frame's limits are the body's with the title row on top. - let frame = self.limits.around(Vec2::new(0.0, header)); - let collapsed = self.collapsed_rect(); - let mut overlay = - Overlay::floating().movable(true).resizable(!self.minimized && collapsed.is_none()).opacity(self.opacity).body_scroll(false); - overlay = if let Some(shown) = collapsed { - overlay.placed(shown).size_limits(SizeLimits::new(shown.size(), shown.size())) + /// content's, which is the chrome alone while minimized. + fn mount(&self) -> Mount { + // The frame's limits are the body's with the chrome on top. + let frame = self.limits.around(Vec2::new(0.0, self.chrome)); + let collapsed = self.collapsed_rect().zip(self.column.map(|column| column.widths)); + let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized).opacity(self.opacity).body_scroll(false); + overlay = if let Some((shown, (least, most))) = collapsed { + // The sides resize a collapsed column's width; its height is its icons'. + let height = shown.height(); + let edges = if self.minimized { ResizeEdges::NONE } else { ResizeEdges::LEFT.union(ResizeEdges::RIGHT) }; + overlay.placed(shown).resize_edges(edges).size_limits(SizeLimits::new(Vec2::new(least, height), Vec2::new(most.max(least), height))) } else if let Some(size) = self.column.and_then(|column| column.fitted) { // 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() + overlay.placed(Rect::from_min_size(self.rect.min, size + Vec2::new(0.0, self.chrome))).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))) @@ -374,10 +399,10 @@ impl<'a> FloatingGroup<'a> { } } - /// Where the group shows while its column is collapsed: the collapsed column under the title row, at the top of - /// the rect and against its edge the window keeps to. `None` while the column is expanded. + /// Where the group shows while its column is collapsed: the collapsed column under the chrome, at the top of the + /// rect and against its edge the window keeps to. `None` while the column is expanded. fn collapsed_rect(&self) -> Option { - self.column?.shown(self.rect, self.header, self.rtl) + self.column?.shown(self.rect, self.chrome, self.rtl) } /// The double arrow's square at the end of the title row the window keeps to. @@ -454,6 +479,7 @@ impl Component for FloatingGroup<'_> { action: self.taken, minimized_toggled: self.toggled && self.column.is_none(), iconic, + collapsed_width: self.collapsed_width, files: self.files, }; native::raise(&cx.core.ctx, &output); @@ -487,7 +513,7 @@ impl Container for FloatingGroup<'_> { // the band and the double arrow; the menu, which a context request on the band opens, keeps its rows. let collapsed = self.column.is_some_and(|column| column.collapsed.is_some()); let actions = if collapsed { &[][..] } else { &self.actions[..] }; - let shown = TitleRow::new("").strength(HeaderStrength::Strong).actions(actions.iter().copied()).show(ui); + let shown = TitleRow::new("").strength(HeaderStrength::Bar).actions(actions.iter().copied()).show(ui); self.taken = shown.action.or(self.taken); if let Some(rows) = self.menu.as_mut() { self.menu_opener = rows.hang(ui, &shown, cx.words::().panel_menu.clone()); @@ -499,8 +525,16 @@ impl Container for FloatingGroup<'_> { let mut change = *change; let fitted = self.column.is_some_and(|column| column.fitted.is_some()); if let Some(column) = self.column.filter(|column| column.collapsed.is_some()) { - // The collapsed window moves; the rect keeps its expanded size. - change.rect = column.kept(change.rect, self.rect, self.header, self.rtl); + // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. + let resized = match change.kind { + PlacementKind::Size(_) => true, + PlacementKind::Keyboard => self.collapsed_rect().is_some_and(|shown| change.rect.width() != shown.width()), + _ => false, + }; + if resized { + self.collapsed_width = Some(change.rect.width()); + } + change.rect = column.kept(change.rect, self.rect, self.chrome, self.rtl); } else if (fitted || self.sized == Sizing::Content) && change.kind == PlacementKind::Move { // A window its content sizes moves (a cancel too, which reports the rect from before the gesture); the // rect keeps the size the caller gave, not the one measured from the body. diff --git a/crates/ui-panels/src/docking/floating/stories.rs b/crates/ui-panels/src/docking/floating/stories.rs index 65f0cd780..24a6d07c8 100644 --- a/crates/ui-panels/src/docking/floating/stories.rs +++ b/crates/ui-panels/src/docking/floating/stories.rs @@ -14,10 +14,13 @@ const START: Rect = Rect { min: Pos2::new(40.0, 40.0), max: Pos2::new(280.0, 220 /// The icons a collapsed story column shows: three panels. const ICON_CELLS: f32 = 3.0; -/// The size of a collapsed column of `ICON_CELLS` icon cells. -fn icon_strip(ui: &Ui) -> Vec2 { +/// A collapsed column of `ICON_CELLS` icon cells, `width` wide when the user resized it, else the rail's width: it +/// resizes from the rail's width up to the width of the expanded story window. +fn icon_strip(ui: &Ui, edge: DockEdge, width: Option) -> WindowColumn { let sizes = IconicSizes::of(ui.ctx()); - Vec2::new(sizes.cell, sizes.cell * ICON_CELLS) + let widths = (sizes.column.iconic_least, START.width()); + let width = width.unwrap_or(widths.0).clamp(widths.0, widths.1); + WindowColumn::collapsed(edge, Vec2::new(width, sizes.cell * ICON_CELLS), widths) } #[story(FloatingGroup<'static>, covers = [Default], drive = Drive::Never)] @@ -42,7 +45,8 @@ fn floating_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn floating_dock_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rect = *data.value("rect", START); let collapsed = *data.value("collapsed", false); - let column = if collapsed { WindowColumn::collapsed(DockEdge::Start, icon_strip(ui)) } else { WindowColumn::expanded(DockEdge::Start) }; + let width = *data.value("width", None::); + let column = if collapsed { icon_strip(ui, DockEdge::Start, width) } else { WindowColumn::expanded(DockEdge::Start) }; let shown = FloatingGroup::new("Layers", rect).column(column).sized(crate::contract::Sizing::Fill).show_group(ui, |ui, _| { Button::new(if collapsed { "L" } else { "Add layer" }).show(ui); }); @@ -52,6 +56,9 @@ fn floating_dock_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { if let Some(iconic) = shown.output.iconic { *data.value("collapsed", false) = iconic; } + if let Some(width) = shown.output.collapsed_width { + *data.value("width", None::) = Some(width); + } shown.output.into() } @@ -59,12 +66,16 @@ fn floating_dock_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(FloatingGroup<'static>, covers = [Default], drive = Drive::Never)] fn floating_collapsed_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rect = *data.value("rect", START); - let column = WindowColumn::collapsed(DockEdge::End, icon_strip(ui)); + let width = *data.value("width", None::); + let column = icon_strip(ui, DockEdge::End, width); let shown = FloatingGroup::new("Layers", rect).column(column).sized(crate::contract::Sizing::Fill).show_group(ui, |ui, _| { Button::new("L").show(ui); }); if let Some(change) = shown.output.placed { *data.value("rect", START) = change.rect; } + if let Some(width) = shown.output.collapsed_width { + *data.value("width", None::) = Some(width); + } shown.output.into() } diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 1665e17a0..4971991ec 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -13,16 +13,15 @@ use crate::contract::{ WordSetCx as _, }; use crate::menu::GroupItem; -use crate::primitives::IconSpec; -use crate::primitives::TextRun; +use crate::primitives::{IconSpec, PaintShape, TextRun}; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind, UiTokens}; 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::{Id, Pos2, Rect, Response, Ui, Vec2}; +use egui::{CornerRadius, Id, Pos2, Rect, Response, Ui, Vec2}; use std::fmt::Debug; use std::hash::Hash; @@ -44,7 +43,7 @@ pub struct IconicSizes { pub column: DockSizes, /// The height of an icon cell (the rail button). pub cell: f32, - /// How far an icon group's drag band reaches into its first icon. + /// The height of the grip strip at the top of each icon group, above its first icon. pub grip: f32, /// The room between two icon groups. pub separator: f32, @@ -55,6 +54,12 @@ 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; + impl IconicSizes { /// The sizes of the style context `cx`. pub fn style(cx: &StyleCx<'_>) -> Self { @@ -62,7 +67,7 @@ impl IconicSizes { IconicSizes { column: DockSizes::style(cx), cell: size.rail.button, - grip: size.handle.sm, + grip: size.hit.target, separator: cx.tokens.space.gap.tight, labels: size.rail.width * LABELS_IN_RAIL_WIDTHS, } @@ -74,10 +79,12 @@ impl IconicSizes { StyleCx::with_root(ctx, IconicSizes::style) } - /// The height of the icons of `column` under its bar: a cell per panel and the room between every two groups. + /// The height of the icons of `column` under its bar: a grip strip per group, a cell per panel and the room between + /// every two groups. pub fn icons_height

(&self, column: &Column

) -> f32 { let cells: usize = column.groups.iter().map(|group| group.panels.len()).sum(); - cells as f32 * self.cell + column.groups.len().saturating_sub(1) as f32 * self.separator + let groups = column.groups.len(); + groups as f32 * self.grip + cells as f32 * self.cell + groups.saturating_sub(1) as f32 * self.separator } } @@ -94,7 +101,8 @@ pub struct IconicColumnOutput

{ pub iconic: Option, /// The dock row the user picked in the column menu. pub picked: Option, - /// The width the user gave the iconic column on its inner edge this pass. + /// The width the user gave a docked iconic column on its inner edge this pass. A floating window's sides set the + /// width of the column it holds (`FloatingGroupOutput::collapsed_width`). pub width: Option, /// The size the user gave the open flyout, with the top edge's offset from the icons when it moved. pub flyout: Option>, @@ -141,13 +149,22 @@ 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. + grip: StyleColor, + /// The ink of a group's grip bar while the pointer is over it or drags it. + grip_active: StyleColor, + /// The grip bar's length across the group and its thickness. + grip_length: f32, + grip_thickness: f32, + /// The grip bar's corners: the theme's pill rounding. + grip_radius: CornerRadius, } /// 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 band 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 bar 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. @@ -162,8 +179,8 @@ pub struct IconicColumnStyle { /// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in /// [`IconicColumnOutput::flyout`], which the host keeps in the group (`flyout_width`, `height`, `flyout_offset`). /// -/// In a floating window ([`ColumnBar::Window`]) the window's title row is the column's bar: the column shows its -/// icons under it and keeps the divider of its inner edge, which sets its width, and registers no edge bands. +/// In a floating window ([`ColumnBar::Window`]) the window's title row is the column's bar and the window's sides set +/// its width: the column shows its icons under it, with no divider on its inner edge, and registers no edge bands. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, overlay, probe(IconicColumn<'static, u8>))] pub struct IconicColumn<'a, P: Value + Hash + 'static> { @@ -224,9 +241,9 @@ struct Plan { cells: Vec<(usize, usize, Rect)>, /// The rest of each row in a wide column, where the panel's name shows; empty in a narrow column. names: Vec, - /// `(group, rect)` of each group's drag band. + /// `(group, rect)` of each group's grip strip, above its first icon. grips: Vec<(usize, Rect)>, - /// `(group, rect)` of the cells of each group. + /// `(group, rect)` of the whole of each group: its grip strip and its cells. groups: Vec<(usize, Rect)>, body: Rect, } @@ -287,8 +304,8 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { /// The panels of the column in order, each with its group. /// The divider on the column's inner edge: the width runs from the rail to the width the column expands to. fn edge_divider(&self, rect: Rect, sizes: &DockSizes) -> Divider { - let least = sizes.iconic_least; - let most = sizes.expanded_width(self.column, self.spec).max(least).min((self.within.width() - sizes.least_pane).max(rect.width())); + let (least, most) = sizes.iconic_bounds(self.column, self.spec); + let most = most.min((self.within.width() - sizes.least_pane).max(rect.width())); Divider::column_edge(rect, self.edge, (least, most), sizes.reach) } @@ -318,6 +335,8 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { y += sizes.separator; } let top = y; + let grip = Rect::from_min_max(Pos2::new(body.left(), top), Pos2::new(body.right(), top + sizes.grip)); + y = grip.bottom(); for panel in 0..group.panels.len() { let row = Rect::from_min_size(Pos2::new(body.left(), y), Vec2::new(body.width(), sizes.cell)); if wide { @@ -329,7 +348,7 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { } y += sizes.cell; } - grips.push((at, Rect::from_min_max(Pos2::new(body.left(), top), Pos2::new(body.right(), (top + sizes.grip).min(y))))); + grips.push((at, grip)); groups.push((at, Rect::from_min_max(Pos2::new(body.left(), top), Pos2::new(body.right(), y)))); } Plan { bar, cells, names, grips, groups, body } @@ -368,15 +387,15 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { sizes: &DockSizes, ) -> Option> { let (group_at, _) = *self.flat().get(at)?; - let icons = self.laid.as_ref()?.groups.iter().find(|(group, _)| *group == group_at)?.1; + let icons = self.laid.as_ref()?.cells.iter().find(|(group, _, _)| *group == group_at)?.2.top(); let group = self.flyout_group(at)?; let width = group.flyout_width.filter(|width| width.is_finite() && *width > 0.0).unwrap_or(expanded).max(least.x).min(bounds.width()); let fixed = group.height.is_some_and(|height| height.is_finite() && height > 0.0); let height = self.flyout_height(&group, sizes).max(least.y).min(bounds.height()); let offset = group.flyout_offset.filter(|offset| offset.is_finite()).unwrap_or(0.0); - let top = (icons.top() + offset).min(bounds.bottom() - height).max(bounds.top()); + let top = (icons + offset).min(bounds.bottom() - height).max(bounds.top()); let left = if right { column.right() } else { column.left() - width }; - Some(FlyoutPlan { group, top_left: Pos2::new(left, top), size: Vec2::new(width, height), fixed, icons_top: icons.top() }) + Some(FlyoutPlan { group, top_left: Pos2::new(left, top), size: Vec2::new(width, height), fixed, icons_top: icons }) } } @@ -402,6 +421,11 @@ 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), + 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), } } @@ -413,8 +437,8 @@ impl Component for IconicColumn<'_, P> { Some(self.open.reborrow()) } - /// The icon cells, each toggling the flyout of its panel, and the drag band of every group. The cells win the - /// top of the first icon over the band, which is declared first. + /// The icon cells, each toggling the flyout of its panel, and the grip strip of every group, which takes exactly its + /// rect so that it never reaches into the group's first icon. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let sizes = cx.style.sizes; let plan = self.plan(rect, &sizes, cx.flow.is_rtl()); @@ -440,11 +464,14 @@ impl Component for IconicColumn<'_, P> { for (group, grip) in &plan.grips { cx.part(GRIP.at(*group as u64), *grip) .sense(Sense::DRAG) + .exact_hit() .cursor(CursorIcon::Grab) .drag_cursor(CursorIcon::Grabbing) .pointer_only("Move Panel To in the panel menu moves the group's panels"); } - divider::declare(cx, rect, EDGE, 0, &self.edge_divider(rect, &sizes.column)); + if self.bar == ColumnBar::Own { + divider::declare(cx, rect, EDGE, 0, &self.edge_divider(rect, &sizes.column)); + } self.laid = Some(plan); } @@ -479,12 +506,14 @@ impl Component for IconicColumn<'_, P> { began = true; } } - let edge = self.edge_divider(rect, &sizes.column); - if let Some(Drag::To(coord)) = divider::pointer(cx, EDGE, 0, &edge) { - self.move_edge(rect, &edge, coord); - } - if let Some((_, coord)) = divider::keys(cx, EDGE, &[(0, edge)], sizes.column.step, sizes.column.jump) { - self.move_edge(rect, &edge, coord); + if self.bar == ColumnBar::Own { + let edge = self.edge_divider(rect, &sizes.column); + if let Some(Drag::To(coord)) = divider::pointer(cx, EDGE, 0, &edge) { + self.move_edge(rect, &edge, coord); + } + if let Some((_, coord)) = divider::keys(cx, EDGE, &[(0, edge)], sizes.column.step, sizes.column.jump) { + self.move_edge(rect, &edge, coord); + } } let handles: Vec<_> = (0..flat.len()).map(|at| popup.at(at)).collect(); // A toggle of an icon (click, Enter, Alt+Down) changed a popup this pass: the user chose. Otherwise the @@ -545,10 +574,20 @@ impl Component for IconicColumn<'_, P> { let cell = IconButton::new(icon).label(spec.label).selected(selected).size(ControlSize::Md).glyphs(GlyphRole::ToolRail); ui.face(CELL.at(at as u64), cell); } - // The edge's line lies on the column's inner edge; its handle stays inside the column. - let (rect, edge) = (cx.rect, self.edge_divider(cx.rect, &cx.style.sizes.column)); - let x = if cx.flow.is_rtl() { rect.right() - (edge.at - rect.left()) } else { edge.at }; - ui.face(EDGE.at(0), Splitter::new(Axis::X).boundary(x)); + let style = &cx.style; + 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); + } + // 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. + if self.bar == ColumnBar::Own { + let (rect, edge) = (cx.rect, self.edge_divider(cx.rect, &cx.style.sizes.column)); + let x = if cx.flow.is_rtl() { rect.right() - (edge.at - rect.left()) } else { edge.at }; + ui.face(EDGE.at(0), Splitter::new(Axis::X).boundary(x)); + } } fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { @@ -564,8 +603,8 @@ impl Component for IconicColumn<'_, P> { let name = words.move_group.fill(&[("name", (self.spec)(shown).label.as_str())]); access.node(GRIP.at(*group as u64), Role::BUTTON).name = Name::Text(name); } - divider::describe(access, EDGE, 0, &self.edge_divider(cx.rect, &sizes.column), words.resize.as_str(), sizes.column.step); if self.bar == ColumnBar::Own { + divider::describe(access, EDGE, 0, &self.edge_divider(cx.rect, &sizes.column), words.resize.as_str(), sizes.column.step); describe_chevron(access, &ColumnArrow::Collapse.name(&words, false)); } } diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index 41455272b..3b5519ee9 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -1,9 +1,14 @@ -//! Trials of `IconicColumn`: the letter of a panel without an icon, the names a wide column shows, and the resizes -//! of its flyouts. +//! Trials of `IconicColumn`: the letter of a panel without an icon, the names a wide column shows, the grips of its +//! groups, and the resizes of its flyouts. #![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] +use super::GRIP; use crate::contract::{Bind, Show as _, ShowContainer as _}; -use crate::docking::{DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutResize, GroupAt, GroupGrip, IconicColumn, PanelKey, PanelSpec}; +use crate::docking::{ + DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutResize, GroupAt, GroupDrag, GroupGrip, IconicColumn, PanelKey, PanelSpec, +}; +use crate::runtime::drag; +use crate::runtime::env::Direction; use crate::sections::Panel; use crate::style::StyleCx; use crate::testing::memory::global; @@ -204,9 +209,9 @@ impl Flyouts { StyleCx::with_root(self.fixture.ctx(), DockSizes::style) } - /// Half the side of a resize grip, which straddles the edge it moves. + /// How far a resize grip reaches in from the edge it moves. fn grip_reach(&self) -> f32 { - StyleCx::with_root(self.fixture.ctx(), |cx| cx.tokens.size.handle.sm) / 2.0 + StyleCx::with_root(self.fixture.ctx(), |cx| crate::contract::grip_band(cx.tokens)) } } @@ -257,7 +262,7 @@ fn flyout_top_edge_and_free_top_corner_grow_it_upward() { } } -/// The top grip is the standard one, straddling the edge: a press inside it resizes; a press below it reaches the +/// The top grip is the standard one, inside the edge: a press inside it resizes; a press below it reaches the /// tab strip and drags the group. #[trial] fn the_flyout_top_handle_is_a_band_that_leaves_the_strip_its_drags() { @@ -340,6 +345,51 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt } } +/// Each icon group's grip strip has its own room at the group's top: across the group, below the bar or the group +/// before it and above the group's first icon, overlapping no icon. A drag that starts on a grip moves its whole +/// group, as a drag on an icon moves its panel. +#[trial] +fn a_groups_grip_lies_above_its_icons_and_its_drag_moves_the_group() { + let overlap = |a: Rect, b: Rect| { + let both = a.intersect(b); + both.width() > 0.0 && both.height() > 0.0 + }; + for direction in [Direction::Ltr, Direction::Rtl] { + let mut fixture = Fixture::hosted(|ui| { + let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)]); + column.iconic = true; + let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)); + let output = IconicColumn::new("Panels", global("iconic column", "grips"), &column, Bind::kept(), &named) + .within(screen()) + .show_flyouts_at(ui, place, |_, _, _, _| None); + Some(output.into()) + }); + fixture.direction(direction).room(SCREEN).settle(); + let id = fixture.root_id().expect("the column shows"); + let grips = [0, 1].map(|group| fixture.part_rect(id, GRIP.at(group)).expect("each group has its grip")); + let icon_rect = |label: &str| fixture.by_label(label).expect("the panel's icon").rect; + let (brushes, layers, swatches) = (icon_rect("Brushes"), icon_rect("Layers"), icon_rect("Swatches")); + assert!(grips[0].top() > 0.0, "{direction:?}: the first grip is under the bar: {grips:?}"); + assert!(grips[0].bottom() <= brushes.top(), "{direction:?}: the first grip is above its group's first icon"); + assert!(layers.bottom() <= grips[1].top(), "{direction:?}: the second grip is below the first group"); + assert!(grips[1].bottom() <= swatches.top(), "{direction:?}: the second grip is above its group's first icon"); + for grip in grips { + assert!(grip.x_range().contains(brushes.center().x), "{direction:?}: the grip runs across the group: {grip:?}"); + for cell in [brushes, layers, swatches] { + assert!(!overlap(grip, cell), "{direction:?}: {grip:?} overlaps the icon {cell:?}"); + } + } + assert!(!overlap(grips[0], grips[1]), "{direction:?}: the grips overlap"); + + for (grip, anchor) in grips.into_iter().zip([1, 3]) { + fixture.drag_hold_at(grip.center(), Vec2::new(RAIL * 2.0, 0.0)); + let unit = drag::active::>(fixture.ctx()).map(|drag| drag.unit.clone()); + assert_eq!(unit, Some(DragUnit::Group(anchor)), "{direction:?}: a drag on the grip moves its group"); + fixture.release_at(grip.center() + Vec2::new(RAIL * 2.0, 0.0)).settle(); + } + } +} + /// The icon groups take drops as an expanded column's groups do: the middle of a group joins its tabs, the separator /// between two groups is the seam between them and wins there, the top of the first group stacks above it, and the /// bottom of the last group, down through the column's empty foot, stacks below it. @@ -349,22 +399,25 @@ fn icon_groups_take_the_drops_of_an_expanded_columns_groups() { let probes: Rc>> = Rc::default(); let found: Rc>>>> = Rc::default(); let (asked, seen) = (Rc::clone(&probes), Rc::clone(&found)); - let mut fixture = Fixture::new(move |ui| { + let mut fixture = Fixture::hosted(move |ui| { let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)]); column.iconic = true; let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)); - IconicColumn::new("Panels", dock, &column, Bind::kept(), &named).within(screen()).show_flyouts_at(ui, place, |_, _, _, _| None); + let output = IconicColumn::new("Panels", dock, &column, Bind::kept(), &named).within(screen()).show_flyouts_at(ui, place, |_, _, _, _| None); // The registry a drop reads is the previous pass's. *seen.borrow_mut() = asked.borrow().iter().map(|at| DockTargets::::resolve(ui.ctx(), dock, *at).map(|(spot, _)| spot)).collect(); + Some(output.into()) }); fixture.room(SCREEN).settle(); let rect_of = |label: &str| fixture.by_label(label).expect("the panel's icon").rect; let (brushes, layers, swatches) = (rect_of("Brushes"), rect_of("Layers"), rect_of("Swatches")); + let grip = |group: u64| fixture.root_id().and_then(|id| fixture.part_rect(id, GRIP.at(group))).expect("the group's grip"); + let (first, second) = (grip(0), grip(1)); let x = brushes.center().x; *probes.borrow_mut() = vec![ Pos2::new(x, brushes.bottom()), - Pos2::new(x, (layers.bottom() + swatches.top()) / 2.0), - Pos2::new(x, brushes.top() + 1.0), + Pos2::new(x, (layers.bottom() + second.top()) / 2.0), + Pos2::new(x, first.center().y), Pos2::new(x, swatches.center().y), Pos2::new(x, swatches.bottom() + 2.0 * swatches.height()), ]; diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index 6bb096ac1..568e3d011 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -35,8 +35,15 @@ pub struct Opening { /// them over the dock's window this pass (the rule the group's mount falls back to a layer by) and reports where they /// are, and every panel allows it. pub(crate) fn allowed(ctx: &Context, config: &DockConfig, specs: &[PanelSpec]) -> bool { + opens_os_windows(ctx, config) && specs.iter().all(|spec| spec.allow_native) +} + +/// Whether the dock opens its floating windows in OS windows: `config` asks for them, and the window host opens OS +/// windows and reports where they are. A panel may still keep to the app window (`PanelSpec::allow_native`). +#[doc(hidden)] +pub fn opens_os_windows(ctx: &Context, config: &DockConfig) -> bool { let host = WindowHost::of(ctx); - config.native_windows && host.opens_windows() && host.positions_reported() && specs.iter().all(|spec| spec.allow_native) + config.native_windows && host.opens_windows() && host.positions_reported() } /// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 358e6b0b5..7ab6ef704 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -51,9 +51,12 @@ pub struct DockSizes { pub strip: f32, /// The height of a column bar (a small control). pub bar: f32, - /// The height of a floating window's title row, which is the bar of the column the window holds: every height of - /// a window's body or content is the window's height less this. + /// The height of a floating window's title row, which is the bar of the column the window holds. pub title_row: f32, + /// The band a floating window in the app window keeps clear over its title row for its top grip + /// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's + /// height less its chrome ([`Self::window_chrome`]). + pub top_band: f32, /// The least body size of a column's group and the least width of an expanded column (the panel header height). pub least: f32, /// How thick a divider is across its boundary (the least hit size). @@ -93,6 +96,7 @@ impl DockSizes { strip: size.panel_header, bar: size.control.sm, title_row: super::floating::title_row(cx.tokens), + top_band: crate::contract::grip_band(cx.tokens), least: size.panel_header, reach: size.hit.target, step: cx.control().gap, @@ -102,6 +106,12 @@ impl DockSizes { } } + /// The height above a floating window's body: its title row and, for a window in the app window (`in_app`), the + /// band over it. + pub fn window_chrome(&self, in_app: bool) -> f32 { + self.title_row + if in_app { self.top_band } else { 0.0 } + } + /// The width bounds of an expanded column from the limits of its panels. pub fn width_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { let limits = column.groups.iter().flat_map(|group| group.panels.iter()).map(|panel| spec(panel).limits); @@ -119,13 +129,18 @@ impl DockSizes { column.width.unwrap_or(self.column).clamp(lo, hi) } + /// The width bounds of a column collapsed to icons, docked or floating: the rail width up to the width it expands + /// to. A docked column's inner edge and a floating window's sides resize it within them. + pub fn iconic_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { + (self.iconic_least, self.expanded_width(column, spec).max(self.iconic_least)) + } + /// The bounds [`width`](Self::width) keeps a column in: an expanded column's [`width_bounds`](Self::width_bounds); - /// a stepped one's width at one step up to its width at all its grid's columns; an iconic column's rail width up - /// to the width it expands to. + /// a stepped one's width at one step up to its width at all its grid's columns; an iconic column's + /// [`iconic_bounds`](Self::iconic_bounds). pub fn shown_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { if column.iconic { - // Widening an iconic column stops at the width it expands to. - (self.iconic_least, self.expanded_width(column, spec).max(self.iconic_least)) + self.iconic_bounds(column, spec) } else if let Some((grid, _)) = stepped(column, spec) { (grid.width(1), grid.width(grid.most)) } else { diff --git a/crates/ui-panels/src/sections/title_row.rs b/crates/ui-panels/src/sections/title_row.rs index dfbfd4a5a..6e5abb058 100644 --- a/crates/ui-panels/src/sections/title_row.rs +++ b/crates/ui-panels/src/sections/title_row.rs @@ -37,6 +37,8 @@ pub enum HeaderStrength { Heading, /// A quiet heading over a group of controls: label text, faint, as written, with no rule. Caption, + /// A window's drag bar: one text row high (`size.row.text`), with label text; its action parts shrink to the row. + Bar, } /// What a title row's action parts ask the container to do. @@ -339,6 +341,7 @@ impl Component for TitleRow<'_> { HeaderStrength::Section => (cx.tokens.size.panel_header, TypeRole::BodyStrong, text.normal), HeaderStrength::Heading => (cx.tokens.size.panel_header, TypeRole::Heading, text.normal), HeaderStrength::Caption => (cx.control().height, TypeRole::Label, text.faint), + HeaderStrength::Bar => (cx.tokens.size.row.text, TypeRole::Label, text.normal), }; let shade = key.tone.map_or_else(|| cx.color(shade), |tone| cx.tone_on_fill(tone)); let (ink, disabled) = (cx.ink(Ink::OnPanel), cx.color(text.disabled)); diff --git a/crates/ui-panels/src/sections/title_row/stories.rs b/crates/ui-panels/src/sections/title_row/stories.rs index 822ee8182..73b4a112d 100644 --- a/crates/ui-panels/src/sections/title_row/stories.rs +++ b/crates/ui-panels/src/sections/title_row/stories.rs @@ -56,3 +56,9 @@ fn title_row_with_icon_and_subtitle(ui: &mut Ui, _: &mut StoryData) -> StoryOutp fn title_row_caption(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { TitleRow::new("Preset details").strength(HeaderStrength::Caption).show(ui).edit.into() } + +#[story(TitleRow<'static>, covers = [], drive = Drive::Never)] +fn title_row_bar(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + // A floating window's drag bar: no title, the Close action at the end. + TitleRow::new("").strength(HeaderStrength::Bar).actions([HeaderAction::Close]).show(ui).edit.into() +} diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index fbe9bf9be..369cb3c9d 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -204,7 +204,7 @@ impl Drops<'_, P> { let sizes = *cx.style.sizes(); let shell = cx.env.get::().0; let bounds = shell.as_ref().map_or(cx.rect, ShellCx::float_bounds); - let space = float_space(bounds, &sizes, self.config, self.specs); + let space = float_space(&ctx, bounds, &sizes, self.config, self.specs); let spec = |panel: &P| spec_in(self.specs, panel); let protected = |panel: &P| (self.permissions)(panel).is_protected(); let (hide, _) = hide::resolved(self.hide, shell.as_ref()); @@ -538,7 +538,7 @@ fn show_area( let Shown { view, floating } = hide::shown(¤t.layout, maximized, hide, shell.as_ref(), &protected); let layout: &Layout

= &view.layout; let bounds = shell.as_ref().map_or(body.rect, ShellCx::float_bounds); - let space = float_space(bounds, &sizes, config, specs); + let space = float_space(ctx, bounds, &sizes, config, specs); let scene = Scene { dock: id, sizes, @@ -694,9 +694,16 @@ fn register_bands( } /// Where floats land in an area whose float bounds are `bounds`: each panel at its spec's float size, else the -/// default float size of `sizes`. -fn float_space(bounds: Rect, sizes: &DockSizes, config: &DockConfig, specs: &HashMap) -> FloatSpace

{ - let mut space = FloatSpace::new(bounds, sizes).with_side_edge_zones(config.side_edge_zones); +/// default float size of `sizes`, under the chrome of the windows the dock opens floats in. +fn float_space( + ctx: &Context, + bounds: Rect, + sizes: &DockSizes, + config: &DockConfig, + specs: &HashMap, +) -> FloatSpace

{ + let mut space = + FloatSpace::new(bounds, sizes).in_os_windows(sizes, native::opens_os_windows(ctx, config)).with_side_edge_zones(config.side_edge_zones); for (panel, spec) in specs { if let Some(size) = spec.float_size { space = space.with_panel_size(panel.clone(), size); @@ -1004,8 +1011,9 @@ 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 + /// and the window's rect at them: as wide as its steps and as tall as its chrome and its content at that width. + /// `fitted` is the content's size under the chrome before the change, `chrome` the height above the window's body + /// (`DockSizes::window_chrome`). 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 @@ -1017,7 +1025,7 @@ impl Pass<'_, P> { column: &Column

, first: &P, change: &PlacementChange, - fitted: Vec2, + (fitted, chrome): (Vec2, f32), ) -> Option { let scene = self.scene; let spec_of = |panel: &P| scene.spec(panel); @@ -1027,7 +1035,7 @@ impl Pass<'_, P> { _ => (change.rect.width() - fitted.x).abs() <= 0.5, }; let to = if by_height { - let room = change.rect.height() - scene.sizes.title_row; + let room = change.rect.height() - chrome; 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()) @@ -1035,7 +1043,7 @@ impl Pass<'_, P> { 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 size = Vec2::new(grid.width(to), chrome + 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(), @@ -1177,7 +1185,9 @@ impl Pass<'_, P> { /// double arrow sits at that end, and its collapsed column shows against that edge of its rect. A move or resize /// keeps the edge the window had when it began, so nothing jumps while the window crosses the middle. A collapsed /// window's move ends at the edge nearer the strip where it was dropped, with the rect that shows the strip there - /// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect. An OS window is measured + /// ([`WindowColumn::dropped`]); an expanded window's move leaves its edge to its rect. A collapsed window's sides + /// resize its column's width within [`DockSizes::iconic_bounds`] (`Action::ResizeIconic`, as a docked collapsed + /// column's inner edge does), and the window keeps its edge and its expanded rect's size. An OS window is measured /// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records /// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]). /// @@ -1238,7 +1248,7 @@ impl Pass<'_, P> { let width = scene.sizes.expanded_width(&window.column, &spec_of); let shape = if window.column.iconic { let size = Vec2::new(scene.sizes.width(&window.column, &spec_of), IconicSizes::of(&ctx).icons_height(&window.column)); - WindowColumn::collapsed(edge, size) + WindowColumn::collapsed(edge, size, scene.sizes.iconic_bounds(&window.column, &spec_of)) } else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) { WindowColumn::fitted(edge, Vec2::new(width, content)) } else { @@ -1284,12 +1294,14 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } + // The height above the window's body: the title row, and in the app window the band over it. + let chrome = scene.sizes.window_chrome(opening.spec.is_none()); // 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)); + .and_then(|(change, fitted)| self.stepped_resize(ui, body, &window.column, &anchor, &change, (fitted, chrome))); 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. @@ -1306,18 +1318,19 @@ impl Pass<'_, P> { && let Some(change) = output.placed.filter(|change| change.phase == GesturePhase::Commit) && let Some(rect) = native::in_app(&ctx, change.rect) { - let (rect, keeps) = shape.dropped(rect, scene.bounds, scene.rtl); + // A resize of a collapsed window keeps its edge; a move ends where its strip was dropped. + let (rect, keeps) = + if output.collapsed_width.is_some() { (rect, Some(edge)) } else { shape.dropped(rect, scene.bounds, scene.rtl) }; kept.edge = keeps.unwrap_or(kept.edge); self.report.actions.push(Action::move_floating_with_edge(anchor.clone(), rect, keeps)); } - let title_row = scene.sizes.title_row; - let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, title_row, scene.rtl)); + let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl)); self.report.actions.extend(reported); } } else if let Some(mut change) = output.placed { // A collapsed window keeps the edge its move began with until the move ends where its strip was dropped. let mut keeps = shape.collapsed.map(|_| edge); - if change.phase == GesturePhase::Commit { + if change.phase == GesturePhase::Commit && output.collapsed_width.is_none() { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); } // The window keeps the place of its steps; its size is the steps' own, whatever the rect keeps. @@ -1329,6 +1342,11 @@ impl Pass<'_, P> { } moved = Some((anchor.clone(), change, keeps)); } + // The sides of a collapsed window set its column's width, as a docked collapsed column's inner edge does. + if let Some(width) = output.collapsed_width { + let work = ColumnWork { iconic: None, picked: None, resized: Vec::new(), width: Some(width), flyout: None }; + self.column_work(&window.column, work); + } // The OS close of a native window arrives here as well, also where the title row offers no Close. if output.action == Some(HeaderAction::Close) && rights.iter().all(|rights| rights.closable) { self.report.actions.push(Action::close_window(anchor.clone())); @@ -1337,7 +1355,7 @@ impl Pass<'_, P> { self.pick(&active, item); } // The window's commands run from its body, below the title row. - let body = opening.rect.size() - Vec2::new(0.0, scene.sizes.title_row); + let body = opening.rect.size() - Vec2::new(0.0, chrome); for command in commands { self.run(&active, command, Some(body)); } diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 4ea3299d4..7fad2cfbe 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -4,11 +4,12 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; use craft_ui::contract::{Bind, BodyCx, Role, Show as _, ShowContainer as _}; use craft_ui::display::Text; -use craft_ui::docking::{DockConfig, DockPanels, GroupDrag, PanelSpec, request_actions}; +use craft_ui::docking::{DockConfig, DockPanels, GroupDrag, IconicSizes, PanelSpec, request_actions}; use craft_ui::layout_components::Stack; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag::{self, DropMark}; use craft_ui::testing::pointer::{moved, press, release, secondary}; +use craft_ui::testing::snapshot::layer_rects; use craft_ui::testing::{Fixture, trial}; use egui::{Modifiers, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -67,8 +68,8 @@ struct Bed { second: Rc>, /// The tallest a floated panel opens (`FloatSpace::default_size`), as the area reported it. float_height: Rc>, - /// The height of a floating window's title row (`FloatSpace::title_row`), as the area reported it. - title_row: Rc>, + /// The height above a floating window's body (`FloatSpace::chrome`), as the area reported it. + chrome: Rc>, } fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { @@ -76,9 +77,9 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { let actions: Rc>>> = Rc::default(); let second = Rc::new(Cell::new(false)); let float_height = Rc::new(Cell::new(0.0)); - let title_row = Rc::new(Cell::new(0.0)); + let chrome = Rc::new(Cell::new(0.0)); let (held, seen_actions, shows_second, seen_height) = (Rc::clone(&workspace), Rc::clone(&actions), Rc::clone(&second), Rc::clone(&float_height)); - let seen_title_row = Rc::clone(&title_row); + let seen_chrome = Rc::clone(&chrome); let mut other = Workspace::new(Layout::new(Some(Node::tabs(vec![SECOND], 0)), Vec::new())); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); @@ -88,14 +89,14 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { seen_actions.borrow_mut().extend(out.actions); if let Some(space) = out.float_space { seen_height.set(space.default_size.y); - seen_title_row.set(space.title_row); + seen_chrome.set(space.chrome); } if shows_second.get() { DockArea::new("Second dock", Bind::bound(&mut other), &mut panels, DockConfig::default()).show(ui); } }); fixture.settle(); - Bed { fixture, workspace, actions, second, float_height, title_row } + Bed { fixture, workspace, actions, second, float_height, chrome } } /// A point on the floating window's title row, on its band: clear of the actions and the double arrow at its end. @@ -235,10 +236,10 @@ fn a_floating_windows_drag_bar_shows_no_title() { assert_eq!(named, 1, "only the tab names the panel: {:?}", bed.fixture.texts()); } -/// The title row the area keeps a dropped window's under the pointer and adds to a floated unit's height is the -/// one the window draws: the window's group starts right under it. +/// The chrome the area keeps a dropped window's under the pointer and adds to a floated unit's height is the one the +/// window draws: the window's group starts right under it. #[trial] -fn a_floating_windows_group_starts_under_the_title_row_the_area_sizes_windows_by() { +fn a_floating_windows_group_starts_under_the_chrome_the_area_sizes_windows_by() { let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); let group = bed .fixture @@ -247,16 +248,80 @@ fn a_floating_windows_group_starts_under_the_title_row_the_area_sizes_windows_by .find(|group| WINDOW_AT.expand(SLACK).contains_rect(group.rect)) .expect("the window shows its group") .rect; - let title_row = bed.title_row.get(); - assert!(title_row > 0.0, "the area reported its float space"); + let chrome = bed.chrome.get(); + assert!(chrome > 0.0, "the area reported its float space"); assert!( - (group.top() - WINDOW_AT.top() - title_row).abs() <= SLACK, - "the group starts at {} in a window from {} with a title row of {title_row}", + (group.top() - WINDOW_AT.top() - chrome).abs() <= SLACK, + "the group starts at {} in a window from {} with a chrome of {chrome}", group.top(), WINDOW_AT.top() ); } +/// The window's rect while a press at `from` drags by `by`, before the release, which would dock a window moved over +/// the docked group. +fn dragged_from(from: Pos2, by: Vec2) -> Rect { + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + press_and_move(&mut bed.fixture, from, by); + bed.workspace.borrow().layout.floating[0].rect +} + +/// A floating window's title row is a drag bar, shorter than the panel header of the tab strip under it, as +/// production's 18 pt bar over its tabs was. +#[trial] +fn a_floating_windows_title_row_is_shorter_than_its_tab_strip() { + let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let in_window = |role| bed.fixture.by_role(role).into_iter().find(|node| WINDOW_AT.expand(SLACK).contains_rect(node.rect)).map(|node| node.rect); + let row = in_window(Role::HEADING).expect("the window shows its title row"); + let tab = in_window(Role::TAB).expect("the window shows its tab"); + assert!(row.height() < tab.height(), "the title row ({row:?}) is shorter than the tab strip ({tab:?})"); +} + +/// The grips of a floating window lie inside its frame and reach at least as far as production's: a corner 12 pt +/// along each of its edges, an edge 4 pt in from it. +#[trial] +fn a_floating_windows_corner_and_edge_grips_reach_as_far_in_as_productions() { + let corner = dragged_from(Pos2::new(WINDOW_AT.right() - 11.0, WINDOW_AT.bottom() - 11.0), Vec2::new(20.0, 20.0)); + assert!( + corner.width() > WINDOW_AT.width() + SLACK && corner.height() > WINDOW_AT.height() + SLACK && corner.min == WINDOW_AT.min, + "a press 11 pt in from the corner resizes from the corner: {corner:?}" + ); + let edge = dragged_from(Pos2::new(WINDOW_AT.left() + 3.5, WINDOW_AT.center().y), Vec2::new(-20.0, 0.0)); + assert!( + edge.width() > WINDOW_AT.width() + SLACK && (edge.height() - WINDOW_AT.height()).abs() <= SLACK && edge.right() == WINDOW_AT.right(), + "a press 3.5 pt in from the left edge resizes from that edge: {edge:?}" + ); +} + +/// The top grip never lies over the title row: a press just inside the row's top moves the window, at its size. +#[trial] +fn the_top_of_a_floating_windows_title_row_moves_it_and_never_resizes_it() { + let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let row = + bed.fixture.by_role(Role::HEADING).into_iter().find(|node| WINDOW_AT.expand(SLACK).contains_rect(node.rect)).expect("the title row").rect; + let by = Vec2::new(-30.0, 20.0); + let rect = dragged_from(Pos2::new(WINDOW_AT.min.x + 40.0, row.top() + 1.0), by); + assert!((rect.size() - WINDOW_AT.size()).length() <= SLACK, "the press on the row at {row:?} resizes nothing: {rect:?}"); + assert!((rect.min - (WINDOW_AT.min + by)).length() <= SLACK, "it moves the window: {rect:?}"); +} + +/// A click on the title row neither moves nor docks the window; a press-drag on it moves the window. A guard of +/// production's behaviour, which the move already had. +#[trial] +fn a_click_on_a_floating_windows_bar_neither_moves_nor_docks_it_and_a_drag_moves_it() { + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let at = window_title(); + bed.fixture.frame(vec![moved(at)]); + bed.fixture.frame(vec![press(at)]); + bed.fixture.frame(vec![release(at)]); + bed.fixture.settle(); + assert_eq!(bed.workspace.borrow().layout.floating.first().map(|window| window.rect), Some(WINDOW_AT), "a click moves nothing"); + assert_eq!(bed.workspace.borrow().layout.floating.len(), 1, "and docks nothing"); + let by = Vec2::new(-40.0, 30.0); + let rect = dragged_from(at, by); + assert!((rect.min - (WINDOW_AT.min + by)).length() <= SLACK, "a drag moves the window: {rect:?}"); +} + /// A tab dragged out of the window floats at the width its group had where it was docked, not a default size. #[trial] fn a_floated_panel_fits_its_content_up_to_the_float_height() { @@ -364,8 +429,7 @@ fn a_collapsed_window_dragged_across_the_middle_keeps_its_strip_under_the_pointe let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); let by = Vec2::new(middle.map_or(-250.0, |x: f32| x - icon.center().x), 0.0); - // The title row's band, clear of the double arrow at the end the window keeps to. - let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); + let band = strip_band(icon); bed.fixture.drag_hold_at(band, by); let held = button_rect(&bed, &title(WINDOW)).expect("the icon shows while the window moves"); assert!((held.left() - (icon.left() + by.x)).abs() <= SLACK, "by {by:?}: the strip follows the pointer: {icon:?}, then {held:?}"); @@ -407,6 +471,64 @@ fn an_icon_floated_in_the_middle_band_lands_collapsed_under_the_pointer() { assert!((settled.left() - floated.left()).abs() <= SLACK, "the strip stays: {floated:?}, then {settled:?}"); } +/// The rect of the collapsed window's layer: the smallest layer around its icon. +fn strip_window(bed: &Bed) -> Rect { + let icon = button_rect(bed, &title(WINDOW)).expect("the collapsed window shows its icon"); + let layers = layer_rects(bed.fixture.ctx()).into_iter().filter(|rect| rect.contains(icon.center())); + layers.min_by(|a, b| a.area().total_cmp(&b.area())).expect("the window's layer holds its icon") +} + +/// A point of a collapsed window's title band: the band's start, clear of the side grip (`size.handle.sm` deep) and +/// of the double arrow at the end the window keeps to. +fn strip_band(icon: Rect) -> Pos2 { + Pos2::new(icon.left() + 10.0, window_title().y) +} + +/// A collapsed window's sides resize its width, and only its width, as a docked collapsed column's inner edge does: +/// the column's iconic width follows, names show beside the icons from the docked column's labels width on, the +/// column stays as tall as its icons, and the expanded rect keeps its size. The width stays across expanding and +/// collapsing again. +#[trial] +fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_columns_step() { + let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); + let sizes = IconicSizes::of(bed.fixture.ctx()); + let height = sizes.icons_height(&bed.workspace.borrow().layout.floating[0].column); + let named = |bed: &Bed| bed.fixture.texts().iter().any(|run| run.text == title(WINDOW)); + let height = height + bed.chrome.get(); + let strip = strip_window(&bed); + assert!(!named(&bed), "a rail-wide strip shows no names"); + assert!((strip.height() - height).abs() <= SLACK, "the window is as tall as its icons and its chrome: {strip:?}, {height}"); + assert!((strip.right() - WINDOW_AT.right()).abs() <= SLACK, "the strip keeps to the end edge: {strip:?}"); + // The start side faces the room; a press just inside it holds the window's grip. + let mut side = Pos2::new(strip.left() + 2.0, strip.center().y); + for width in [sizes.labels - 10.0, sizes.labels + 20.0] { + let by = Vec2::new(strip_window(&bed).width() - width, 0.0); + press_and_move(&mut bed.fixture, side, by); + bed.fixture.frame(vec![release(side + by)]); + bed.fixture.settle(); + side += by; + let window = bed.workspace.borrow().layout.floating[0].clone(); + let shown = strip_window(&bed); + let kept = window.column.iconic_width; + assert!(window.column.iconic && kept.is_some_and(|kept| (kept - width).abs() <= SLACK), "{width}: the column keeps the width: {window:?}"); + assert!((shown.width() - width).abs() <= SLACK, "{width}: the strip shows at it: {shown:?}"); + assert!((shown.height() - height).abs() <= SLACK, "{width}: the height stays its icons' and its chrome's: {shown:?}"); + assert!( + (window.rect.min - WINDOW_AT.min).length() <= SLACK && window.rect.size() == WINDOW_AT.size(), + "{width}: the expanded rect stays: {window:?}" + ); + assert_eq!(named(&bed), width >= sizes.labels, "{width}: names show from the labels width ({}) on", sizes.labels); + } + let resized = strip_window(&bed); + for iconic in [false, true] { + bed.workspace.borrow_mut().apply(Action::set_iconic(WINDOW, iconic), false, |_| Permissions::ALL).expect("the column toggles"); + bed.fixture.settle(); + } + let again = strip_window(&bed); + assert!((again.width() - resized.width()).abs() <= SLACK, "collapsed again, the strip keeps its width: {resized:?}, then {again:?}"); + assert_eq!(bed.workspace.borrow().layout.floating[0].rect, WINDOW_AT, "the expanded rect is unchanged"); +} + /// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. #[trial] fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { @@ -426,13 +548,13 @@ fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { #[trial] fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column() { let mut bed = bed(with_window(None), |_| Permissions::ALL); - let band = Pos2::new(WINDOW_AT.left() + 40.0, WINDOW_AT.top() + 6.0); + let band = Pos2::new(WINDOW_AT.left() + 40.0, window_title().y); bed.fixture.click_at(band).click_at(band).settle(); let window = bed.workspace.borrow().layout.floating[0].clone(); assert!(window.column.iconic, "the band's double click collapsed the column: {:?}", bed.actions.borrow()); assert!(window.groups().iter().all(|group| !group.minimized), "no group minimized"); let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); - let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); + let band = strip_band(icon); bed.fixture.click_at(band).click_at(band).settle(); assert!(!bed.workspace.borrow().layout.floating[0].column.iconic, "a second double click expanded it: {:?}", bed.actions.borrow()); } diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 5e25fb2f1..681d42e1e 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -653,6 +653,57 @@ fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { assert!(max.is_none_or(|max| max.x >= expanded.x && max.y >= expanded.y), "the OS lets it take that size: max {max:?}"); } +/// On macOS a native palette collapsed to icons is a window AppKit resizes, in its width only: it opens resizable with +/// its height fixed to the strip's, the app stands no grips of its own at its sides, and a width the OS gives it is the +/// column's iconic width while the model keeps the expanded size; the app sends no size back. +#[trial] +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. + let follow = |dock: &mut NativeDock, at: &mut Rect, events: Vec| { + let commands = dock.frame(events).1; + *at = placed_by(&commands, *at); + dock.windows.child_info(info(true, *at)); + commands + }; + dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..3 { + follow(&mut dock, &mut at, vec![]); + } + let strip = at; + let builder = dock.builder.clone().expect("the palette's window opened"); + assert_eq!(builder.resizable, Some(true), "the collapsed window is resizable"); + let (least, most) = (builder.min_inner_size.expect("a least size"), builder.max_inner_size.expect("a most size")); + assert!(least.y == most.y && (least.y - strip.height()).abs() <= 0.5, "the height is fixed to the strip's: {least:?}..{most:?}, {strip:?}"); + assert!(least.x < most.x, "the width resizes: {least:?}..{most:?}"); + + // A press and drag at the strip's free side, in its title row, clear of the double arrow at the end it keeps to: + // no app grip stands there, so nothing asks the OS for a resize. + let end = strip.max.x >= FLOAT_AT.max.x - 1.0 && strip.min.x > FLOAT_AT.min.x + 1.0; + let side = Pos2::new(if end { 2.0 } else { strip.width() - 2.0 }, 4.0); + let mut sent = Vec::new(); + for events in [vec![moved(side)], vec![press(side)], vec![moved(side + Vec2::new(0.0, 1.0))], vec![release(side)], vec![]] { + sent.extend(follow(&mut dock, &mut at, events)); + } + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::BeginResize(_))), "the app stands no grip: {sent:?}"); + + // AppKit widens the window. + let width = strip.width() + 60.0; + at = Rect::from_min_size(at.min, Vec2::new(width, at.height())); + dock.windows.child_info(info(true, at)); + let mut sent = Vec::new(); + for _ in 0..3 { + sent.extend(follow(&mut dock, &mut at, vec![])); + } + let palette = &dock.workspace.layout.floating[0]; + assert!(palette.column.iconic_width.is_some_and(|kept| (kept - width).abs() <= 0.5), "the column keeps the width: {:?}", palette.column); + let recorded = palette.native.clone().expect("the model records the window"); + assert_eq!(Vec2::from(recorded.normal.size), FLOAT_AT.size(), "the model keeps the expanded size"); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::InnerSize(_))), "no size goes back: {sent:?}"); + assert_eq!(at.width(), width, "the window keeps the width the OS gave it"); +} + /// On a display at 125 % (Windows), a click on the double arrow of a native palette collapsed to icons expands its /// column, and the OS window takes its expanded size. #[trial] diff --git a/crates/window/src/mac.rs b/crates/window/src/mac.rs index 82ade46c6..e7d3f4b3b 100644 --- a/crates/window/src/mac.rs +++ b/crates/window/src/mac.rs @@ -21,6 +21,27 @@ use crate::policy::MacInset; +/// How far AppKit's corner resize area reaches into a titled, resizable window along each edge: AppKit takes a press +/// there before the content sees it and shows its resize cursor. Measured on macOS 26 as a 19 pt square at each +/// corner, about 15 pt of it inside a square-cornered window +/// (); there is no published +/// measurement for earlier releases. +pub const RESIZE_CORNER: f32 = 15.0; + +/// How far AppKit's edge resize area reaches into the content between the corners: a few points; most of it lies +/// outside the window. +pub const RESIZE_EDGE: f32 = 4.0; + +/// Whether `at`, in the coordinates of a window's content of `size` (points from its top-left corner), lies in +/// AppKit's resize areas: a [`RESIZE_CORNER`] square at each corner and a [`RESIZE_EDGE`] strip along each edge. +pub fn in_resize_area(size: [f32; 2], at: [f32; 2]) -> bool { + let [w, h] = size; + let [x, y] = at; + let inside = (0.0..=w).contains(&x) && (0.0..=h).contains(&y); + let near = |pos: f32, len: f32, reach: f32| pos <= reach || pos >= len - reach; + inside && ((near(x, w, RESIZE_CORNER) && near(y, h, RESIZE_CORNER)) || near(x, w, RESIZE_EDGE) || near(y, h, RESIZE_EDGE)) +} + /// The three buttons as AppKit laid them out, in points. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Lights { diff --git a/docs/contract-api.md b/docs/contract-api.md index 6e9dcaf0e..3bc202cac 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -127,6 +127,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `fn is_section(&self, at: usize) -> bool`. Whether the position is a section header, which a move skips. - `fn enabled(&self, at: usize) -> bool`. Whether the position can take the lead. - `fn row_len(&self, _row: usize) -> Option`. `RaggedGrid`: the number of positions in `row`; rows hold consecutive positions. `None` past the last row. + - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are - `fn columns(&self) -> usize`. `Cell`: the cells of every position (a row of a sheet). - `fn first_column(&self) -> Option`. `WrappedGrid`: the column of position 0 when the grid has blank cells before it (the leading days of a - `fn rect(&self, _at: usize) -> Option`. `Spatial`: where the position sits, in any one coordinate space. @@ -422,7 +423,7 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `craft_behavior::cursor::IconId`: `pub struct IconId`. An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui. - `pub const fn new(name: &'static str) -> Self`. The icon named `name`. - `pub fn name(&self) -> &str`. The name. -- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId }, Hidden }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush +- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId }, Hidden, IBeam }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush - `pub const CENTRE_ARM: f32`. The arm of the centre mark of a circle or an outline, in points. - `pub const fn circle(radius: f32) -> Self`. A circle of `radius` points, with no centre mark and no badge. - `pub fn outline(rings: Vec>) -> Self`. App shapes as closed rings, with no centre mark and no badge. @@ -434,6 +435,7 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `pub const fn skew(dir: Vec2) -> Self`. The skew pointer along screen direction `dir`. - `pub const fn type_on(path: bool) -> Self`. The type tool's pointer, over a path when `path`. - `pub const fn arrow(hollow: bool) -> Self`. An arrow with its tip on the hotspot, hollow when `hollow`. + - `pub const fn arrow_toward(dir: Vec2) -> Self`. A solid arrow turned about its hotspot to point along `dir`. - `pub const fn path_text(start: bool, end: bool) -> Self`. An I-beam across the path with a triangle toward each grabbable side. - `pub const fn pointer_tool(pointer: PointerGlyph, icon: IconId) -> Self`. `pointer` with the tool's icon below and right of it. - `pub const fn badged(base: CursorIcon, badge: CursorBadge) -> Self`. A system cursor with a mark. @@ -646,8 +648,9 @@ The dock model: the tree of splits over panel frames, the side of a group a drop `EditorInput`: the one ordered input stream the IME engine produces and an editor part reads (18.4). -- `craft_behavior::editor::EditorInput`: `pub enum EditorInput { Text(Arc), Move(NavMove, MoveMods), Delete { forward: bool, by: Granularity }, DeleteSurrounding { before: usize, after: usize, unit: SurroundingUnit }, Select { anchor: TextPos, focus: TextPos }, Preedit { text: Arc, cursor: Option> }, ImeCommit, Edit(EditCommand), Newline, Tab, Cancel }`. One input of an editor part. - - `pub const fn delete(forward: bool, by: Granularity) -> Self`. A `Delete` of `by`. +- `craft_behavior::editor::EditorInput`: `pub enum EditorInput { Text(Arc), Move(NavMove, MoveMods), Delete { forward: bool, by: Granularity, shift: bool }, DeleteSurrounding { before: usize, after: usize, unit: SurroundingUnit }, Select { anchor: TextPos, focus: TextPos }, Preedit { text: Arc, cursor: Option> }, ImeCommit, Edit(EditCommand), Newline, Tab, BackTab, Cancel }`. One input of an editor part. + - `pub const fn delete(forward: bool, by: Granularity) -> Self`. A `Delete` of `by`, without Shift. + - `pub const fn delete_with_shift(forward: bool, by: Granularity, shift: bool) -> Self`. A `Delete` of `by` with Shift held when `shift`. - `pub const fn delete_surrounding(before: usize, after: usize) -> Self`. A `DeleteSurrounding` of `before` and `after` characters. - `pub const fn delete_surrounding_bytes(before: usize, after: usize) -> Self`. A `DeleteSurrounding` of `before` and `after` bytes of UTF-8 text, as winit reports it. - `pub fn preedit(text: impl Into>, cursor: Option>) -> Self`. A `Preedit` of `text` with the IME's cursor. @@ -667,14 +670,15 @@ When a component's remembered state is due for eviction. The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and -- `craft_behavior::fit::Fit`: `pub struct Fit { pub shown: Vec, pub overflow: Vec }`. Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. -- `craft_behavior::fit::FitItem`: `pub struct FitItem { pub extent: f32, pub section: u16, pub keep: FitKeep }`. One item as the fit rule sees it: its extent along the strip, its section and whether it may overflow. +- `craft_behavior::fit::Fit`: `pub struct Fit { pub shown: Vec, pub overflow: Vec, pub short: Vec }`. Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. +- `craft_behavior::fit::FitItem`: `pub struct FitItem { pub extent: f32, pub section: u16, pub keep: FitKeep, pub short: Option }`. One item as the fit rule sees it: its extent along the strip, its section and whether it may overflow. - `pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self`. An item `extent` long in `section`. + - `pub const fn short(mut self, extent: f32) -> Self`. The item with a shorter form `extent` long, which it takes before any free item leaves. - `craft_behavior::fit::FitKeep`: `pub enum FitKeep { Free, Pinned, Menu }`. Whether an item may move into the overflow menu, or lives there. - `craft_behavior::fit::TabFit`: `pub struct TabFit { pub shown: Vec<(usize, f32)>, pub overflow: Vec, pub overflow_width: f32 }`. Tabs visible on a strip and tabs that need an overflow menu, all in original order. - `craft_behavior::fit::fit`: `pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32, keep_selected: bool) -> TabFit`. Fit tab widths into `available` points, shrinking the widest tabs first to a common cap. - `craft_behavior::fit::fit_items`: `pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit`. Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -- `craft_behavior::fit::fit_whole`: `pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit`. Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. +- `craft_behavior::fit::fit_whole`: `pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32, overflow_width: f32) -> TabFit`. Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. - `craft_behavior::fit::run_extent`: `pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) -> f64`. The length of the items marked in `shown`, with `gap` between neighbours of a section and `section_gap` between ## `craft_behavior::flow` @@ -762,6 +766,7 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::SnapKinds`: re-export of `craft_behavior::geometry::snap::SnapKinds`. - `craft_behavior::geometry::SnapLine`: re-export of `craft_behavior::geometry::snap::SnapLine`. - `craft_behavior::geometry::SnapOptions`: re-export of `craft_behavior::geometry::snap::SnapOptions`. +- `craft_behavior::geometry::SnapSuspend`: re-export of `craft_behavior::geometry::snap::SnapSuspend`. - `craft_behavior::geometry::SnapTarget`: re-export of `craft_behavior::geometry::snap::SnapTarget`. - `craft_behavior::geometry::SnapTargets`: re-export of `craft_behavior::geometry::snap::SnapTargets`. - `craft_behavior::geometry::StrokeLock`: re-export of `craft_behavior::geometry::move_gesture::StrokeLock`. @@ -980,7 +985,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::quad::Parts`: `pub struct Parts { pub w: f64, pub h: f64, pub angle: f64, pub skew_h: f64, pub skew_v: f64 }`. A box read as the options bar shows it: the starting rect scaled by `w` and `h`, skewed by - `pub const fn new(w: f64, h: f64, angle: f64, skew_h: f64, skew_v: f64) -> Self`. The readings: scale factors `w` and `h`, the `angle` in degrees and the two skews in degrees. - `craft_behavior::geometry::quad::SKEW_LIMIT`: `pub const SKEW_LIMIT: f64`. The skew fields' reach in degrees: a skew of ±90° would flatten the box (PhotoCraft's). -- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, Shape }`. What a plain corner or edge drag does. +- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, Shape, Corners }`. What a plain corner or edge drag does. - `craft_behavior::geometry::quad::TransformMode`: `pub enum TransformMode { Free, Rotate, Skew, Distort, Perspective }`. Edit › Transform's modes. - `craft_behavior::geometry::quad::bisector`: `pub fn bisector(screen: &BoxState, i: usize) -> emath::Vec2`. Corner `i` of `screen`'s unit bisector, pointing into the box; zero for a collapsed corner. The - `craft_behavior::geometry::quad::drag`: `pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState`. The box after dragging `part` from `from` to `to` (document points) with `mods` held, from the @@ -1013,7 +1018,9 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub fn without(self, kind: SnapKind) -> Self`. This set without `kind`. - `pub fn contains(self, kind: SnapKind) -> bool`. Whether `kind` is in this set. - `craft_behavior::geometry::snap::SnapLine`: `pub struct SnapLine { pub along: Axis, pub position: f64, pub kind: SnapKind, pub span: Option<(f64, f64)> }`. The line the UI draws for a snap that happened. -- `craft_behavior::geometry::snap::SnapOptions`: `pub struct SnapOptions { pub on: bool, pub guides: bool, pub grid: bool, pub layers: bool, pub document_bounds: bool, pub selection: bool, pub smart_guides: bool }`. View › Snap To and View › Show › Smart Guides, as the app stores them. +- `craft_behavior::geometry::snap::SnapOptions`: `pub struct SnapOptions { pub on: bool, pub guides: bool, pub grid: bool, pub layers: bool, pub document_bounds: bool, pub selection: bool, pub smart_guides: bool, pub suspend: SnapSuspend }`. View › Snap To and View › Show › Smart Guides, as the app stores them. +- `craft_behavior::geometry::snap::SnapSuspend`: `pub enum SnapSuspend { Control, Alt }`. The key that suspends snapping. + - `pub fn is_held(self, mods: Mods, os: Platform) -> bool`. Whether this key is held in `mods` on `os`: Control is the Control key without ⌘ on macOS and Ctrl - `craft_behavior::geometry::snap::SnapTarget`: `pub struct SnapTarget { pub along: Axis, pub position: f64, pub kind: SnapKind, pub span: Option<(f64, f64)> }`. One snap position on one axis. - `pub const fn new(along: Axis, position: f64, kind: SnapKind) -> Self`. A full-height line of `kind` running `along` an axis, at `position` across it: a line along `Axis::Y` - `craft_behavior::geometry::snap::SnapTargets`: `pub struct SnapTargets`. The snap targets of one gesture. @@ -1024,6 +1031,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub fn filtered(&self, keep: impl Fn(SnapKind) -> bool) -> SnapTargets`. Only the targets `keep` accepts (Snap To with one kind off). - `pub fn is_empty(&self) -> bool`. Whether there is no target. - `pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option`. The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of + - `pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option`. [`nearest_of`](Self::nearest_of) that also takes the query's extent `across` the other axis: a target with a - `pub fn nearest(&self, along: Axis, value: f64, tolerance: f64) -> Option`. The nearest target among the lines that run `along` an axis, within `tolerance` of `value` across them. - `pub fn snap_point(&self, point: Point, tolerance: f64) -> (Point, Vec)`. `point` snapped on each axis independently, with the lines to draw. - `pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec)`. [`snap_point`](Self::snap_point) to the targets of a kind in `kinds` only (a Distort corner snaps to guides @@ -1102,7 +1110,7 @@ Intents: a key, an AccessKit action or typed text turned into meaning (spec 9.2) - `pub const fn new(action: accesskit::Action, target: Option, data: Option) -> Self`. A request for `action` on `target`. - `craft_behavior::intent::EditCommand`: `pub enum EditCommand { Cut, Copy, Paste, SelectAll, Undo, Redo, Delete }`. An edit command a component lists in its `KeyUse` to receive it as `Intent::Edit`. - `craft_behavior::intent::Granularity`: `pub enum Granularity { Unit, Word, Line, Paragraph, Document }`. How far a move reaches. -- `craft_behavior::intent::Intent`: `pub enum Intent { Activate, Submit, SubmitForce, Cancel, Move(NavMove, MoveMods), Delete { forward: bool, by: Granularity, shift: bool }, Space, TogglePick, Digit(u8), Rename, ContextMenu, Reset, Text(Arc), Tab, Edit(EditCommand), SwitchPage { forward: bool }, MoveItem { front: bool, all_the_way: bool }, Open, Close, Access(AccessRequest) }`. What the runtime routes to a focused component. +- `craft_behavior::intent::Intent`: `pub enum Intent { Activate, Submit, SubmitForce, Cancel, Move(NavMove, MoveMods), Delete { forward: bool, by: Granularity, shift: bool }, Space, TogglePick, Digit(u8), Rename, ContextMenu, Reset, Text(Arc), Tab, BackTab, Edit(EditCommand), SwitchPage { forward: bool }, MoveItem { front: bool, all_the_way: bool }, Open, Close, Access(AccessRequest) }`. What the runtime routes to a focused component. - `pub const fn delete(forward: bool, by: Granularity) -> Intent`. `Delete` of `by`, forward or back. - `pub const fn switch_page(forward: bool) -> Intent`. `SwitchPage` to the next page when `forward`. - `pub const fn move_item(front: bool, all_the_way: bool) -> Intent`. `MoveItem` toward the front when `front`, all the way when `all_the_way`. @@ -1129,6 +1137,7 @@ Item geometry: where each item of a collection sits for a scroll offset and view - `fn hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item under `point`. - `fn nav(&self) -> NavShape`. How arrow keys move through the items. - `fn row_len(&self, _row: usize) -> Option`. `NavShape::RaggedGrid`: the number of items in `row`, rows holding consecutive items and a run of hidden items + - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows - `fn shown(&self, _at: usize) -> bool`. Whether item `at` takes a place in the layout; a hidden item (in a closed group) cannot take the lead. - `fn cells(&self, _at: usize, _offset: ScrollPos, _out: &mut Vec<(ColumnKey, Rect)>)`. The cells of item `at`, with their rects. - `fn grid(&self) -> Option<&GridView>`. Column virtualisation and sections of a sheet. @@ -1306,6 +1315,7 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `fn is_section(&self, at: usize) -> bool`. Whether the position is a section header, which a move skips. - `fn enabled(&self, at: usize) -> bool`. Whether the position can take the lead. - `fn row_len(&self, _row: usize) -> Option`. `RaggedGrid`: the number of positions in `row`; rows hold consecutive positions. `None` past the last row. + - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are - `fn columns(&self) -> usize`. `Cell`: the cells of every position (a row of a sheet). - `fn first_column(&self) -> Option`. `WrappedGrid`: the column of position 0 when the grid has blank cells before it (the leading days of a - `fn rect(&self, _at: usize) -> Option`. `Spatial`: where the position sits, in any one coordinate space. @@ -1515,6 +1525,7 @@ Scroll positions and the range a scroll part shows. - `craft_behavior::scroll::drag`: `pub fn drag(span: &ScrollSpan, track: f32, min_thumb: f32, delta: f32) -> Range`. The visible range after the thumb moved `delta` points along the track, kept inside the content range. - `craft_behavior::scroll::jump`: `pub fn jump(span: &ScrollSpan, mv: NavMove) -> Option>`. The visible range after a navigation move that scrolls: a page up or down, or to the start or the end of the - `craft_behavior::scroll::page`: `pub fn page(span: &ScrollSpan, toward_end: bool) -> Range`. The visible range one visible length further toward the end (or the start), kept inside the content range. +- `craft_behavior::scroll::shifted`: `pub fn shifted(span: &ScrollSpan, shift: f64) -> Range`. Moves the visible range by `shift` content units, keeping it within the scrollable range. - `craft_behavior::scroll::thumb`: `pub fn thumb(span: &ScrollSpan, track: f32, min_thumb: f32) -> (f32, f32)`. The thumb of `span` on a track `track` points long: its start along the track and its length, at least ## `craft_behavior::selection` @@ -1792,10 +1803,12 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn item_layout_from(&self, _previous: Option, source: &dyn ItemSource, width: f32, _item: Option, cx: &StyleCx<'_>,) -> Self::ItemLayout`. The layout of `source` at `width`, given the layout of the last pass. An implementor may reuse `previous` - `fn measures_items(&self) -> bool`. Whether the layout sizes its items from their own measure: the items step measures every item at its ideal - `fn dress_inputs(&self) -> u64`. What `dress` reads of the collection, hashed: a kept measure of the items serves only while it is the same. - - `fn ideal_width(&self, _item: Option, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of + - `fn ideal_width(&self, _item: Option, _rows: usize, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this - `fn rename_editor(&mut self, _ui: &mut Ui, _draft: Bind<'_, String>, _label: Rect, _name: &str) -> Option>`. The rename editor at `label`: the label rect the renaming item reports (`ItemOutput::label_rect`), else its row. + - `fn hosts_header(&self, _column: &ColumnKey) -> bool`. Whether the collection hosts a component in the header cell of `column`: the header then calls `header_cell` + - `fn header_cell(&mut self, _ui: &mut PaintUi<'_>, _column: &ColumnKey, _key: HostedKey, _rect: Rect)`. Hosts a component in the header cell of `column`, in `rect`, measured and shown under `key` (the column's index - `fn rename_draft(&self, _key: &Self::Key) -> Option`. The text the rename field of the item `key` opens with; `None` for the item's own text. - `fn can_rename(&self, _key: &Self::Key) -> bool`. Whether the item `key` may be renamed; a rename request on another item does nothing. - `fn can_drag(&self, _key: &Self::Key) -> bool`. Whether the item `key` may be dragged (reordered, moved in a free layout, or dragged to another collection). @@ -1854,6 +1867,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn header_parts(&self, _cx: &MeasureCx<'_, Self>) -> HeaderParts`. The room the container's own parts take at the edges of its header's line (a menu button, a drag band). The - `fn controls(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the header's trailing region. - `fn footer(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the footer region. + - `fn body_end(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the region under the body and above the footer, whatever the footer's place. - `fn end(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the end region, after the body. - `fn closed(&mut self, _why: CloseReason)`. The container closed, and why: a layer's dismissal rule, a close the body or footer asked for with - `fn placement_changed(&mut self, _change: &overlay::PlacementChange)`. The user moved or resized the container's layer: by the move band, a grip or the keyboard Move and Size @@ -1888,12 +1902,12 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::ShowCollection`: `pub trait ShowCollection: Collection + sealed::ShowCollection`. Shows a collection's items. - `fn show_items<'r>(self, ui: &mut Ui, source: &dyn ItemSource, item: &mut ItemFn<'r, Self>) -> Self::Output`. Shows the visible items of `source`, one `item` call each. - `craft_ui::contract::ShowContainer`: `pub trait ShowContainer: Container + sealed::ShowContainer`. Shows a container with its body. - - `fn show(self, ui: &mut Ui, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container in the flow of `ui`. - - `fn show_at(self, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect`, with no allocation: a frame over a split or a layer the parent places. - - `fn show_at_taking_room(self, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies - - `fn measure_in(&mut self, ui: &Ui, proposal: Proposal, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Vec2`. Measures the container with `body` without allocating: steps 1 to 5 under the id `show` would use next, with - - `fn show_with_tip(self, ui: &mut Ui, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner`. Shows the container with rich tooltip content. - - `fn show_at_with_tip(self, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui),) -> Inner`. Shows the container at `rect` with rich tooltip content. + - `fn show(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container in the flow of `ui`. + - `fn show_at(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect`, with no allocation: a frame over a split or a layer the parent places. + - `fn show_at_taking_room(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies + - `fn measure_in(&mut self, ui: &Ui, proposal: Proposal, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Vec2`. Measures the container with `body` without allocating: steps 1 to 5 under the id `show` would use next, with + - `fn show_with_tip(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner`. Shows the container with rich tooltip content. + - `fn show_at_with_tip(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui),) -> Inner`. Shows the container at `rect` with rich tooltip content. - `craft_ui::contract::ShowShape`: `pub trait ShowShape: sealed::ShowShape`. Which show trait applies, and the shape's default sense. - `const KIND: ShapeKind`. The shape as a value. - `const DEFAULT_SENSE: Sense`. Leaf `CLICK | FOCUS`; body empty; items `CLICK | DRAG | FOCUS | WHEEL | TAKE_FOCUS`. @@ -1928,6 +1942,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::BodyCx`: `pub struct BodyCx<'a> { pub id: Id, pub env: EnvView<'a>, pub resolved: &'a Resolved<'a>, pub rect: Rect, pub memory: &'a mut MemoryStage }`. What a body closure and the header, footer and empty hooks read: a view over the pipeline's memory stage - `pub fn open_url(&mut self, url: &str, new_tab: bool)`. Asks the platform to open `url`, in a new tab where the platform has tabs and `new_tab` is set: the opener - `pub fn take_pick_answer(&self, ticket: craft_host::PickId) -> Option`. The host file service's answer to the picker `ticket`, taken once. A measuring run gets none and leaves + - `pub fn is_exiting(&self) -> bool`. Whether the container has closed and its body only stays on screen while it fades out. `is_open` reads true - `pub fn field_message(&self) -> Option<(Message, craft_theme::variant::Tone)>`. The validity message of the first control in the container's label scope, recorded last frame, with the - `pub fn is_open(&self) -> bool`. Whether the body is open. - `pub fn open(&mut self) -> &mut bool`. The open state: a title row's disclosure binds to it, and step 15 writes a change to its owner. @@ -2000,15 +2015,17 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::ColumnAlign`: `pub enum ColumnAlign { Start, End }`. Where a column's content sits. - `craft_ui::contract::ColumnCommands`: `pub enum ColumnCommands { Resize, MoveLeft, MoveRight }`. The commands of a column header (17.1): resize works from the keyboard through them, and the header menu lists - `pub const ALL: [ColumnCommands; 3]`. Every header command, in menu order. -- `craft_ui::contract::ColumnEvent`: `pub enum ColumnEvent { Sort { key: ColumnKey, descending: bool }, Resized { key: ColumnKey, width: f32 }, Moved { key: ColumnKey, to: usize }, Shown { key: ColumnKey, shown: bool }, Unsorted, Reset }`. A change to the columns. +- `craft_ui::contract::ColumnEvent`: `pub enum ColumnEvent { Sort { key: ColumnKey, descending: bool }, Resized { key: ColumnKey, width: f32 }, Moved { key: ColumnKey, to: usize }, Shown { key: ColumnKey, shown: bool }, Unsorted, Reset, Removed { key: ColumnKey } }`. A change to the columns. - `craft_ui::contract::ColumnKey`: re-export of `craft_behavior::columns::ColumnKey`. - `craft_ui::contract::ColumnKind`: `pub enum ColumnKind { Content, Toggle(ToggleColumn) }`. What a column's cells are. +- `craft_ui::contract::ColumnRemove`: `pub struct ColumnRemove { pub name: Label, pub enabled: bool }`. The remove control of a column's header. - `craft_ui::contract::ColumnRequest`: `pub enum ColumnRequest { Shown(ColumnKey, bool), Reset, Command(crate::contract::ColumnCommands) }`. What a pick in the header menu asks of the header, given back with `Cx::column_request`. - `craft_ui::contract::ColumnSort`: `pub struct ColumnSort { pub key: ColumnKey, pub descending: bool }`. The column the rows are sorted by and the direction: the app's value, which it changes on `ColumnEvent::Sort`. - `pub const fn new(key: ColumnKey, descending: bool) -> Self`. Rows sorted by `key`, descending when `descending`. - `pub const fn ascending(key: ColumnKey) -> Self`. Rows sorted by `key`, ascending. - `pub const fn descending(key: ColumnKey) -> Self`. Rows sorted by `key`, descending. -- `craft_ui::contract::ColumnSpec`: `pub struct ColumnSpec { pub key: ColumnKey, pub header: Label, pub width: ColumnWidth, pub resizable: bool, pub sortable: bool, pub movable: bool, pub frozen: bool, pub kind: ColumnKind, pub align: ColumnAlign, pub tabular: bool, pub first_descending: bool, pub icon: Option, pub tip: Option