From b35a0faee0307b868aa93533cab29093f098749b Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 16:57:13 +0000 Subject: [PATCH 1/7] Floating windows: production's bar height, grips and AppKit resize - The floating window's title row is one text row high (HeaderStrength::Bar, size.row.text: 18 pt compact), as production's 18 pt bar; the tab strip below keeps the panel header height. - A resizable or movable layer with a header keeps its top grip's band (contract::grip_band, size.handle.sm) clear above the header, so the top grip never lies over it; the regions start below the band or the padding, whichever is deeper. Dialogs keep their layout (their padding is deeper than the band). - Grips lie inside the frame for layers too; corners reach twice the edge width along each edge (12 pt), top corners of a banded layer only the band's height. - Where the OS resizes a window from its own frame (macOS Inset, resizable: windows::os_resizes) no app grips stand, the cursor over AppKit's resize areas is the default (craft_window::mac::in_resize_area) and the move band keeps the arrow, as an OS title bar does. - DockSizes::window_chrome (title row plus the band in the app window) sizes floating windows, stepped resizes, collapsed windows and float previews (FloatSpace::chrome). --- crates/ui-contract/src/contract/body.rs | 3 +- crates/ui-contract/src/contract/body/hooks.rs | 23 +++-- .../ui-contract/src/contract/body/regions.rs | 9 ++ crates/ui-contract/src/contract/body/size.rs | 14 +++ .../ui-contract/src/contract/body/window.rs | 84 +++++++++++----- crates/ui-contract/src/contract/mod.rs | 1 + crates/ui-contract/src/runtime/cursor.rs | 20 +++- crates/ui-contract/src/runtime/egui/pass.rs | 5 + crates/ui-contract/src/runtime/windows.rs | 8 ++ .../tests/it/runtime/window_move.rs | 19 ++++ crates/ui-panels/src/docking/drop.rs | 4 +- crates/ui-panels/src/docking/event.rs | 22 +++-- crates/ui-panels/src/docking/floating.rs | 52 +++++----- crates/ui-panels/src/docking/iconic/trials.rs | 6 +- crates/ui-panels/src/docking/native.rs | 9 +- crates/ui-panels/src/docking/targets.rs | 14 ++- crates/ui-panels/src/sections/title_row.rs | 3 + .../src/sections/title_row/stories.rs | 6 ++ crates/ui-patterns/src/patterns/dock/area.rs | 37 ++++--- .../tests/it/docking/floating_area.rs | 96 +++++++++++++++---- crates/window/src/mac.rs | 21 ++++ docs/ui-docking.md | 2 +- 22 files changed, 352 insertions(+), 106 deletions(-) diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index ab1d798f2..141d5ecec 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -33,9 +33,10 @@ pub use regions::pad_of; #[doc(hidden)] pub use reorder::REORDER_BAND; pub use scroll::{STRIP_BACK, STRIP_FORWARD}; -#[cfg(feature = "testing")] pub(crate) use window::MOVE_BAND; use window::WindowMode; +#[cfg(feature = "testing")] +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 5d0f8087d..5e01c03fe 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}; @@ -301,7 +301,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 @@ -437,8 +437,9 @@ 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()); + 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()).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)) } @@ -449,9 +450,10 @@ 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()); + let regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes()).below(pcx.content_rect.min.y + band); let scroll = scroll_of(&props); if self.open && scroll.is_some() { let at = regions.body; @@ -822,7 +824,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 { @@ -1027,9 +1029,10 @@ 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); - let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes()); + let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes()).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); // A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer, @@ -1795,7 +1798,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/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 208849286..07c652fa8 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -152,6 +152,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 70607efd8..b77410178 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -166,6 +166,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..a9e638f5e 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 cannot be resized (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,40 +749,50 @@ 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). 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) diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 92a9cba84..119958341 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -52,6 +52,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/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 736913aa5..f278192ab 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 e0e09415e..034daee21 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -34,9 +34,9 @@ use std::hash::Hash; #[cfg(feature = "testing")] 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 @@ -92,19 +92,19 @@ 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)) + pub fn kept(self, shown: Rect, rect: Rect, chrome: f32, rtl: bool) -> Rect { + self.shown(rect, chrome, rtl).map_or(shown, |at| rect.translate(shown.min - at.min)) } /// The edge of `bounds`, in reading order, nearer the window at `rect`: the start edge when the window's centre is @@ -234,8 +234,10 @@ 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, /// Starts the window-unit drag; set by `window_of`. @@ -280,6 +282,7 @@ impl<'a> FloatingGroup<'a> { chevron_declared: false, chevron: false, header: 0.0, + chrome: 0.0, rtl: false, placed: None, start_drag: None, @@ -329,21 +332,24 @@ 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)); + /// 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(); let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized && collapsed.is_none()).opacity(self.opacity).body_scroll(false); @@ -351,7 +357,7 @@ impl<'a> FloatingGroup<'a> { overlay.placed(shown).size_limits(SizeLimits::new(shown.size(), shown.size())) } 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 +380,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. @@ -487,7 +493,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()); @@ -500,7 +506,7 @@ impl Container for FloatingGroup<'_> { 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); + 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/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index 41455272b..06ca1292c 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -204,9 +204,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 +257,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() { 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 0698d501b..c04fdc4d7 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); diff --git a/crates/ui-panels/src/sections/title_row.rs b/crates/ui-panels/src/sections/title_row.rs index 9e8764d99..a71cfee4b 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 e69656d48..f7571cd8d 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 8c84717f3..739891bae 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()); @@ -544,7 +544,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 chrome = panels.spec_version().map(|version| chrome_key(layout, version, config, locked, auto_collapse)); let scene = Scene { dock: id, @@ -702,9 +702,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); @@ -1094,8 +1101,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 @@ -1107,7 +1115,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); @@ -1117,7 +1125,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()) @@ -1125,7 +1133,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(), @@ -1380,12 +1388,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. @@ -1406,8 +1416,7 @@ impl Pass<'_, P> { 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 { @@ -1433,7 +1442,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..11921e944 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -67,8 +67,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 +76,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 +88,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 +235,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 +247,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() { @@ -365,7 +429,7 @@ fn a_collapsed_window_dragged_across_the_middle_keeps_its_strip_under_the_pointe 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 = Pos2::new(icon.left() + 4.0, window_title().y); 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:?}"); @@ -426,13 +490,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 = Pos2::new(icon.left() + 4.0, window_title().y); 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/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/ui-docking.md b/docs/ui-docking.md index ae8016407..dfcfa9946 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -122,7 +122,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Floating and native windows -A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. A collapsed window shows its icons against the edge of the float area it keeps to, under a title row of the band and the double arrow alone (a context request on the band opens the window's menu), and keeps its expanded size for when it expands. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the app runs that move (`Overlay::moved_by_app`, which the group's mount carries, so the window is opened knowing it). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). +A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. The title row is one text row high (`HeaderStrength::Bar`). A window in the main window keeps a band above it for its top grip (`contract::grip_band`), so the grip never covers the row; an OS window keeps none, and on macOS AppKit resizes it from its own edges, with no app grips there (`DockSizes::window_chrome`). A collapsed window shows its icons against the edge of the float area it keeps to, under a title row of the band and the double arrow alone (a context request on the band opens the window's menu), and keeps its expanded size for when it expands. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the app runs that move (`Overlay::moved_by_app`, which the group's mount carries, so the window is opened knowing it). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). A panel or group floated out of the dock (a drag, the Float command, a tab torn out of the window) opens at the width it had docked and at the height its group measures at in a floating window's room (`Proposal::Size`), at most `size.float.height`: content that fills its body opens at that height, other content at its own. A column opens at its docked size, at most that height. The area measures once, where the float starts: for a drag in the pass it starts, which adds the size to the drag's payload (`runtime::drag::amend`). A panel's own `PanelSpec` float size wins, and a window that already floats keeps its size. From d73552cec796c111289d2240e222e5d924e9320d Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 17:06:56 +0000 Subject: [PATCH 2/7] Grips take exactly their rect: PartBuilder::exact_hit Sensing grows every part's hit area to the pointer's target size (size.hit.target, 8 pt), so a 6 pt grip reached 1 pt past its rect on each side: a press 1 pt into a floating window's title row started a top resize, and the top corners of a banded layer (6 pt tall) reached 8 pt. A part declared exact_hit keeps its declared shape as its hit area. Every window grip and the edge pane's grip declare it: a frame's grip band is sized as its reach, its neighbours own the points beside it, and the in-app hit area matches the platform's hit test for an exclusive grip. docs/contract-api.md regenerated. --- crates/ui-contract/src/contract/body/pane.rs | 1 + .../ui-contract/src/contract/body/window.rs | 6 +- crates/ui-contract/src/contract/cx/parts.rs | 8 + crates/ui-contract/src/primitives/sensing.rs | 14 +- docs/contract-api.md | 863 ++++++++++++++---- 5 files changed, 690 insertions(+), 202 deletions(-) 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/window.rs b/crates/ui-contract/src/contract/body/window.rs index a9e638f5e..d6ac190c4 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -771,8 +771,9 @@ impl BodyHooks<'_> { } // 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). 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. + // 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); @@ -799,6 +800,7 @@ impl BodyHooks<'_> { .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/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 7cce1927b..01b1186c6 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. @@ -311,7 +319,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. @@ -336,7 +344,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/docs/contract-api.md b/docs/contract-api.md index 006b1c940..2c13df76f 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -39,6 +39,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `pub fn map_vec(&self, v: Vec2) -> ScreenVec`. A document vector as the view draws it: stretched, turned, zoomed and mirrored. - `pub fn unmap_vec(&self, v: ScreenVec) -> Vec2`. The document vector a screen vector shows: the inverse of [`map_vec`](Self::map_vec). - `pub fn zoom_x(&self) -> f64`. Screen points per document unit along the document's x axis: `zoom × aspect`. + - `pub fn extent(&self, r: Rect) -> ScreenVec`. The screen size of the box that holds document rect `r` at the view's zoom, rotation, - `pub fn quad(&self, r: Rect) -> [Pos2; 4]`. The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1), - `pub fn visible(&self) -> Rect`. The document bounds of the screen rect: every document point the view can show. - `pub fn doc_len(&self, points: f32) -> f64`. A screen distance in document units along the document's y axis (divide by @@ -56,6 +57,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ColumnWidth`: re-export of `craft_behavior::columns::ColumnWidth`. - `craft_behavior::CommandFlags`: re-export of `craft_behavior::command::CommandFlags`. - `craft_behavior::ControlMetrics`: re-export of `craft_behavior::sizing::ControlMetrics`. +- `craft_behavior::CountMark`: re-export of `craft_behavior::cursor::CountMark`. - `craft_behavior::Cursor`: re-export of `craft_behavior::cursor::Cursor`. - `craft_behavior::CursorBadge`: re-export of `craft_behavior::cursor::CursorBadge`. - `craft_behavior::CursorIcon`: re-export of `craft_behavior::cursor::CursorIcon`. @@ -79,8 +81,10 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::Escaped`: re-export of `craft_behavior::typing::Escaped`. - `craft_behavior::Flow`: re-export of `craft_behavior::flow::Flow`. - `craft_behavior::FreeLayout`: re-export of `craft_behavior::item_layout::FreeLayout`. +- `craft_behavior::GESTURE_GAP`: re-export of `craft_behavior::wheel::GESTURE_GAP`. - `craft_behavior::Gesture`: re-export of `craft_behavior::value::Gesture`. - `craft_behavior::GestureId`: re-export of `craft_behavior::value::GestureId`. +- `craft_behavior::GestureNote`: re-export of `craft_behavior::value::GestureNote`. - `craft_behavior::GesturePhase`: re-export of `craft_behavior::value::GesturePhase`. - `craft_behavior::Granularity`: re-export of `craft_behavior::intent::Granularity`. - `craft_behavior::GridCursor`: re-export of `craft_behavior::grid::GridCursor`. @@ -123,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. @@ -142,6 +147,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::Outline`: re-export of `craft_behavior::item_source::Outline`. - `craft_behavior::OwnerClass`: re-export of `craft_behavior::focus::OwnerClass`. - `craft_behavior::PaintedCursor`: re-export of `craft_behavior::cursor::PaintedCursor`. +- `craft_behavior::ParseNote`: re-export of `craft_behavior::codec::ParseNote`. - `craft_behavior::PartKey`: re-export of `craft_behavior::part::PartKey`. - `craft_behavior::PartRef`: re-export of `craft_behavior::part::PartRef`. - `craft_behavior::PassInput`: re-export of `craft_behavior::press::PassInput`. @@ -156,6 +162,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::Playback`: re-export of `craft_behavior::motion::Playback`. - `craft_behavior::PointerButton`: re-export of `craft_behavior::press::PointerButton`. - `craft_behavior::PointerEvent`: re-export of `craft_behavior::press::PointerEvent`. +- `craft_behavior::PointerGlyph`: re-export of `craft_behavior::cursor::PointerGlyph`. - `craft_behavior::PointerKind`: re-export of `craft_behavior::press::PointerKind`. - `craft_behavior::PointerSample`: re-export of `craft_behavior::press::PointerSample`. - `craft_behavior::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and @@ -167,6 +174,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::PressStart`: re-export of `craft_behavior::press::PressStart`. - `craft_behavior::PressState`: re-export of `craft_behavior::press::PressState`. - `craft_behavior::PressStep`: re-export of `craft_behavior::press::PressStep`. +- `craft_behavior::Preview`: re-export of `craft_behavior::value::Preview`. - `craft_behavior::Proposal`: re-export of `craft_behavior::sizing::Proposal`. - `craft_behavior::Reader`: re-export of `craft_behavior::quantity::Reader`. - `craft_behavior::ResolveFor`: re-export of `craft_behavior::hit::ResolveFor`. @@ -206,14 +214,15 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::SizeHint`: re-export of `craft_behavior::item_source::SizeHint`. - `craft_behavior::SizeTween`: re-export of `craft_behavior::layout_memory::SizeTween`. - `craft_behavior::SpanLayout`: re-export of `craft_behavior::item_layout::SpanLayout`. +- `craft_behavior::SurroundingUnit`: re-export of `craft_behavior::editor::SurroundingUnit`. - `craft_behavior::TextPos`: re-export of `craft_behavior::intent::TextPos`. - `craft_behavior::Ticks`: `pub enum Ticks { Decimal { whole: bool }, Custom(fn(f64) -> (f64, u32)) }`. How a ruler divides its unit at a zoom. - `pub const fn decimal(whole: bool) -> Self`. PhotoCraft's decimal steps; `whole` keeps the step a whole number of units without 2.5. - `craft_behavior::TileLayout`: re-export of `craft_behavior::item_layout::TileLayout`. - `craft_behavior::TypeAhead`: `pub struct TypeAhead`. Typed letters of the last second as one prefix. - `pub const fn new() -> Self`. An empty buffer. - - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix. - - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>) -> Option`. The entry a prefix picks: the first match from the position after `from` (from `from` itself when the + - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, + - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one - `craft_behavior::Typed`: re-export of `craft_behavior::typing::Typed`. - `craft_behavior::TypingRun`: re-export of `craft_behavior::typing::TypingRun`. - `craft_behavior::Validity`: re-export of `craft_behavior::value::Validity`. @@ -228,9 +237,11 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `pub const fn new(key: K, center: Point, zoom: f64) -> Self`. The view of `key` centred on `center` at `zoom`. - `craft_behavior::Wheel`: re-export of `craft_behavior::wheel::Wheel`. - `craft_behavior::WheelFocus`: re-export of `craft_behavior::wheel::WheelFocus`. +- `craft_behavior::WheelGesture`: re-export of `craft_behavior::wheel::WheelGesture`. - `craft_behavior::WheelNotch`: re-export of `craft_behavior::wheel::WheelNotch`. - `craft_behavior::WheelPhase`: re-export of `craft_behavior::wheel::WheelPhase`. - `craft_behavior::WheelRoom`: re-export of `craft_behavior::wheel::WheelRoom`. +- `craft_behavior::WheelSource`: re-export of `craft_behavior::wheel::WheelSource`. - `craft_behavior::WheelTaker`: re-export of `craft_behavior::wheel::WheelTaker`. - `craft_behavior::WheelUnit`: re-export of `craft_behavior::wheel::WheelUnit`. - `craft_behavior::Winner`: re-export of `craft_behavior::hit::Winner`. @@ -249,8 +260,10 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::resolve_flags`: re-export of `craft_behavior::command::resolve_flags`. - `craft_behavior::resolve_mapped`: re-export of `craft_behavior::hit::resolve_mapped`. - `craft_behavior::role_violations`: re-export of `craft_behavior::role_rule::role_violations`. +- `craft_behavior::same_in_f32`: re-export of `craft_behavior::value::same_in_f32`. +- `craft_behavior::same_in_f32_at`: re-export of `craft_behavior::value::same_in_f32_at`. - `craft_behavior::sub_row_cells`: re-export of `craft_behavior::columns::sub_row_cells`. -- `craft_behavior::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel event to the new value of a single-value control: one `notch` per event, up for positive scroll. +- `craft_behavior::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries - `craft_behavior::wrap_value`: re-export of `craft_behavior::value_drag::wrap_value`. ## `craft_behavior::anchor` @@ -289,6 +302,7 @@ The transform a canvas body is shown through, and the canvas view with its zoom - `pub fn map_vec(&self, v: Vec2) -> ScreenVec`. A document vector as the view draws it: stretched, turned, zoomed and mirrored. - `pub fn unmap_vec(&self, v: ScreenVec) -> Vec2`. The document vector a screen vector shows: the inverse of [`map_vec`](Self::map_vec). - `pub fn zoom_x(&self) -> f64`. Screen points per document unit along the document's x axis: `zoom × aspect`. + - `pub fn extent(&self, r: Rect) -> ScreenVec`. The screen size of the box that holds document rect `r` at the view's zoom, rotation, - `pub fn quad(&self, r: Rect) -> [Pos2; 4]`. The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1), - `pub fn visible(&self) -> Rect`. The document bounds of the screen rect: every document point the view can show. - `pub fn doc_len(&self, points: f32) -> f64`. A screen distance in document units along the document's y axis (divide by @@ -337,6 +351,7 @@ Zoom rules as pure functions on a [`CanvasView`]: Photoshop's zoom range and Zoo - `craft_behavior::canvas::zoom::step`: `pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32) -> bool`. View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next ladder rung - `craft_behavior::canvas::zoom::wheel_anchor`: `pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2`. Where a wheel or pinch zoom anchors for a pointer at `screen`: the pointer over the document, - `craft_behavior::canvas::zoom::with_device`: `pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32) -> CanvasView`. `view` at `device` zoom (1 = 100 %), clamped to the zoom range of a document of `size`, with its centre kept. +- `craft_behavior::canvas::zoom::wrapped_canvas`: `pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> ScreenVec`. The window-canvas size at which the zoomed document fits: the canvas size less the view's ## `craft_behavior::codec` @@ -348,7 +363,7 @@ Zoom rules as pure functions on a [`CanvasView`]: Photoshop's zoom range and Zoo - `const DRAFTS_ARE_VALUES: bool`. Every draft is a value (plain text): a draft applies as typed and never rejects. - `fn format(&self, v: &Self::Value) -> String`. The text of `v`. - `fn parse(&self, text: &str, start: &Self::Value) -> Result`. The value of `text`; `start` is the value when editing began, for relative input. - - `fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, Option), NotAValue>`. The value of `text` and the tag of the unit it named (`Reader::read_tagged`); the default names none. + - `fn parse_tagged(&self, text: &str, start: &Self::Value) -> Result<(Self::Value, ParseNote), NotAValue>`. The value of `text` and what the parse learned beside it (`Reader::read_tagged`); the default notes nothing. - `fn applies_as_typed(&self, _text: &str) -> bool`. Whether `text` applies as soon as it is typed rather than on commit. - `fn filter(&self, _c: char) -> bool`. Whether the codec takes `c` as typed. - `fn normalise(&self, _text: &str, v: &Self::Value) -> String`. The text the field shows after committing `v`, which was parsed from `text`. @@ -358,11 +373,13 @@ Zoom rules as pure functions on a [`CanvasView`]: Photoshop's zoom range and Zoo - `craft_behavior::codec::NumberCodec`: `pub struct NumberCodec`. An optional number: empty text is `None`; anything else reads through a [`Reader`]. - `pub fn new(reader: Reader, decimals: usize) -> Self`. A codec reading with `reader` and writing at most `decimals` decimal places. - `pub fn fixed(mut self) -> Self`. The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown + - `pub fn zoom_typing(mut self) -> Self`. The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the - `pub fn at_most(mut self, decimals: usize) -> Self`. The same codec writing at most `decimals` decimal places. - `pub fn or_parse(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self`. The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the - `pub fn widest(&self, range: &RangeInclusive) -> String`. The widest text the codec writes for a number in `range`: the longest of each end and the number one place of - `pub fn decimals(&self) -> usize`. The most decimal places the codec writes. - `pub fn reader(&self) -> &Reader`. The reader the codec parses with. +- `craft_behavior::codec::ParseNote`: `pub struct ParseNote { pub unit: Option, pub held: Option, pub cut: bool }`. What a parse learned beside the value. - `craft_behavior::codec::PlainText`: `pub struct PlainText`. Plain text: every draft is a value. - `craft_behavior::codec::decimals_for_step`: `pub fn decimals_for_step(step: f64) -> usize`. The decimal places a step needs to be written exactly: 2 for 0.25, 3 for 0.001, 0 for a whole step. A step with @@ -398,14 +415,15 @@ The pure rules of command routing (spec 11.3): which state a command resolves to Cursor requests as plain data and the rule that picks the winner (8.5). +- `craft_behavior::cursor::CountMark`: `pub enum CountMark { Add, Move, Delete }`. The kind of a [`CursorBadge::Count`] mark. - `craft_behavior::cursor::Cursor`: `pub enum Cursor { System(CursorIcon), Painted(PaintedCursor) }`. What a cursor request names. -- `craft_behavior::cursor::CursorBadge`: `pub enum CursorBadge { Add, Subtract, Intersect, Copy, NotAllowed, Scissors, Close }`. A mark beside a painted cursor. +- `craft_behavior::cursor::CursorBadge`: `pub enum CursorBadge { Add, Subtract, Intersect, Copy, NotAllowed, Scissors, Close, Move, Arrow, Target, Continue, Count(CountMark), Corner }`. A mark beside a painted cursor. - `craft_behavior::cursor::CursorIcon`: `pub enum CursorIcon { Default, None, ContextMenu, Help, PointingHand, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, AllScroll, ResizeHorizontal, ResizeNeSw, ResizeNwSe, ResizeVertical, ResizeColumn, ResizeEast, ResizeSouthEast, ResizeSouth, ResizeSouthWest, ResizeWest, ResizeNorthWest, ResizeNorth, ResizeNorthEast, ZoomIn, ZoomOut }`. A system cursor: craft-behavior's copy of egui's set, converted by `runtime::egui::output`. - `craft_behavior::cursor::CursorPriority`: `pub enum CursorPriority { Default, Tool, Hover, Part, DropTarget, Drag }`. Who asks, in ascending order of precedence. - `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 }, 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. @@ -415,8 +433,15 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `pub const fn turn(toward: Vec2) -> Self`. The rotate pointer bent toward screen direction `toward`. - `pub const fn distort(dir: Vec2) -> Self`. The free-distort pointer along screen direction `dir`. - `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. +- `craft_behavior::cursor::PointerGlyph`: `pub enum PointerGlyph { Crosshair, Arrow }`. The pointer of a [`PaintedCursor::PointerTool`]. - `craft_behavior::cursor::pick`: `pub fn pick(requests: &[(Cursor, CursorPriority)]) -> Option<&Cursor>`. The winning request: the highest priority, the later request on a tie. +- `craft_behavior::cursor::pick_index`: `pub fn pick_index(requests: &[(Cursor, CursorPriority)]) -> Option`. The index of the winning request ([`pick`]). ## `craft_behavior::digit_keys` @@ -453,16 +478,16 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `craft_behavior::dock::DockSide`: `pub enum DockSide { Start, End, Top, Bottom, Center }`. The side of a group a dropped panel docks on, in reading order: `Start` is the left half in a left-to-right - `pub const fn axis(self) -> Option`. The axis the side splits along; `None` for `Center`. - `pub fn area(self, group: Rect) -> Rect`. The part of `group` a panel docked on this side takes: the half on that side, or the whole group. -- `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect }, ResizeSplit { path: Vec, size: SplitSize }, ResizeWindowSplit { panel: P, path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

} }`. Groups, columns and floating windows are named by a panel they contain. +- `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

} }`. Groups, columns and floating windows are named by a panel they contain. - `pub fn move_beside(panel: P, anchor: P, placement: DockPlacement

) -> Self`. Builds [`Action::Move`]. - `pub fn float(panel: P, rect: Rect) -> Self`. Builds [`Action::Float`]. - `pub fn close(panel: P) -> Self`. Builds [`Action::Close`]. - `pub fn activate(panel: P) -> Self`. Builds [`Action::Activate`]. - `pub fn open(panel: P, anchor: Option

) -> Self`. Builds [`Action::Open`]. - `pub fn open_at(panel: P, anchor: P, placement: DockPlacement

) -> Self`. Builds [`Action::OpenAt`]. - - `pub fn move_floating(panel: P, rect: Rect) -> Self`. Builds [`Action::MoveFloating`]. + - `pub fn move_floating(panel: P, rect: Rect) -> Self`. Builds [`Action::MoveFloating`] with no edge: the area takes the edge nearer `rect`. + - `pub fn move_floating_with_edge(panel: P, rect: Rect, edge: Option) -> Self`. Builds [`Action::MoveFloating`] with the window's edge. - `pub fn resize_split(path: Vec, size: SplitSize) -> Self`. Builds [`Action::ResizeSplit`]. - - `pub fn resize_window_split(panel: P, path: Vec, size: SplitSize) -> Self`. Builds [`Action::ResizeWindowSplit`]. - `pub fn set_stack_open(panel: P, open: bool) -> Self`. Builds [`Action::SetStackOpen`]. - `pub fn resize_stack(panel: P, height: Option) -> Self`. Builds [`Action::ResizeStack`]. - `pub fn move_group(panel: P, to: Target

) -> Self`. Builds [`Action::MoveGroup`]. @@ -475,6 +500,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn set_minimized(panel: P, minimized: bool) -> Self`. Builds [`Action::SetMinimized`]. - `pub fn set_iconic(panel: P, iconic: bool) -> Self`. Builds [`Action::SetIconic`]. - `pub fn resize_column(panel: P, width: f32) -> Self`. Builds [`Action::ResizeColumn`]. + - `pub fn set_column_steps(panel: P, steps: u16) -> Self`. Builds [`Action::SetColumnSteps`]. - `pub fn resize_group(panel: P, height: Option) -> Self`. Builds [`Action::ResizeGroup`]. - `pub fn resize_flyout_width(panel: P, width: Option) -> Self`. Builds [`Action::ResizeFlyoutWidth`]. - `pub fn move_flyout_top(panel: P, offset: Option) -> Self`. Builds [`Action::MoveFlyoutTop`]. @@ -484,39 +510,45 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `craft_behavior::dock::Arrangement`: `pub enum Arrangement { TileAllVertically, TileAllHorizontally, TwoUpVertical, TwoUpHorizontal, ThreeUpVertical, ThreeUpHorizontal, ThreeUpStacked, FourUp, SixUp, ConsolidateAllToTabs, Cascade, Tile, FloatInWindow, FloatAllInWindows, NewWindowForDocument, MatchZoom, MatchLocation, MatchRotation, MatchAll }`. One Window › Arrange entry. The n-up entries split the document area into that many - `pub fn group_count(self, documents: usize) -> Option`. How many document groups an n-up or tile arrangement wants, `None` for the window and - `pub fn enabled(self, documents: usize, groups: usize, floating: usize) -> bool`. Whether the entry is enabled with `documents` open and `floating` floating windows: -- `craft_behavior::dock::Column`: `pub struct Column

{ pub groups: Vec>, pub width: Option, pub iconic: bool, pub iconic_width: Option }`. One column of a dock: groups from top to bottom. +- `craft_behavior::dock::Column`: `pub struct Column

{ pub groups: Vec>, pub width: Option, pub iconic: bool, pub iconic_width: Option, pub steps: Option }`. One column of groups from top to bottom: a column of a dock, or the whole of a floating window. - `pub fn new(groups: Vec>) -> Self`. A column of `groups`, expanded at the theme's column width until the user resizes it. - `pub fn with_width(mut self, width: f32) -> Self`. The column resized to `width` points. -- `craft_behavior::dock::ColumnLocation`: `pub struct ColumnLocation { pub side: DockEdge, pub width: Option, pub iconic: bool, pub iconic_width: Option }`. The column a closed panel's group was in. - - `pub const fn new(side: DockEdge, width: Option, iconic: bool, iconic_width: Option) -> Self`. A column location on `side`, `width` points wide when expanded (the theme's column width for `None`). + - `pub fn with_iconic(mut self, iconic: bool) -> Self`. The column collapsed to icons, or expanded. + - `pub fn with_steps(mut self, steps: u16) -> Self`. The column `steps` content columns wide ([`Self::steps`]). + - `pub fn panels(&self) -> impl Iterator`. Every panel of the column, top group first. +- `craft_behavior::dock::ColumnLocation`: `pub struct ColumnLocation { pub side: Option, pub width: Option, pub iconic: bool, pub iconic_width: Option, pub steps: Option }`. The column a closed panel's group was in. + - `pub const fn new(side: Option, width: Option, iconic: bool, iconic_width: Option) -> Self`. A column location on `side` (`None` for a floating window's column), `width` points wide when expanded (the + - `pub const fn with_steps(mut self, steps: Option) -> Self`. The location with the column `steps` content columns wide ([`Column::steps`]). - `craft_behavior::dock::DockEdge`: `pub enum DockEdge { Start, End }`. The window edge a [`Node::Dock`] sits on, in reading order so right-to-left interfaces - `craft_behavior::dock::DockError`: `pub enum DockError { LimitExceeded, DuplicatePanel, MissingPanel, MissingTarget, InvalidSelection, InvalidGeometry, InvalidPlacement, NotAllowed, UnsupportedVersion }`. Why a layout edit or load was refused. The layout is unchanged when an edit fails. - `craft_behavior::dock::DockPlacement`: `pub enum DockPlacement

{ Tab { before: Option

}, Split(DockSide), SplitSized { zone: DockSide, size: SplitSize, outer: SplitSize }, Group { below: bool, height: Option }, Column { after: bool }, Edge(DockSide) }`. Where a moved panel goes relative to an anchor panel. - `pub fn tab(before: Option

) -> Self`. Builds [`DockPlacement::Tab`]. - `pub fn group(below: bool, height: Option) -> Self`. Builds [`DockPlacement::Group`]. - `pub fn column(after: bool) -> Self`. Builds [`DockPlacement::Column`]. - - `pub fn allowed_by(&self, anchor: Permissions, floating: bool) -> bool`. Whether the anchor's permissions take this placement: tabs need `accepts_tabs`, side + - `pub fn allowed_by(&self, anchor: Permissions) -> bool`. Whether the anchor's permissions take this placement: tabs need `accepts_tabs` and `shares_column`, a group - `craft_behavior::dock::DocumentGroup`: `pub struct DocumentGroup { pub id: u64, pub documents: Vec, pub shown: Option }`. A document group: the documents in one tab strip, one of them shown. - `pub fn new(id: u64, documents: Vec) -> Self`. A group with id `id` holding `documents`, none shown. -- `craft_behavior::dock::DocumentWindows`: `pub struct DocumentWindows { pub docked: Vec>, pub floating: Vec<(DocumentGroup, Rect)> }`. The document windows of the app: the tabbed groups in the canvas area and the floating ones. +- `craft_behavior::dock::DocumentWindows`: `pub struct DocumentWindows { pub docked: Vec>, pub floating: Vec<(DocumentGroup, Rect)>, pub arrangement: Option }`. The document windows of the app: the tabbed groups in the canvas area and the floating ones. Saved with each - `pub fn float(&mut self, document: &D, rect: Rect) -> Option`. Float `document` from its group into a new window at `rect`. A document alone in a - `pub fn float_all(&mut self, area: Rect, size: Vec2, step: f32)`. Every document into its own floating window, cascaded from `area`'s top left. A floating - `pub fn consolidate(&mut self, active: Option<&D>)`. Every document back into one docked group, the active one shown. A document in several - `pub fn split_into(&mut self, n: usize)`. Split the docked documents into `n` groups for an n-up arrangement, in order. The first - `pub fn new_window_for(&mut self, document: &D, rect: Rect) -> u64`. A second view of `document`: the same document id in a new window; the app keeps one + - `pub fn close_window(&mut self, id: u64) -> bool`. Closes floating window `id`. Its documents return to the first docked group, or to a new docked group when + - `pub fn add_document(&mut self, document: &D)`. Adds `document` to the first docked group, or to a new docked group when there is none. A document a group - `pub fn to_actions(&self, layout: &Layout

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The -- `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub root: Node

, pub rect: Rect, pub native: Option, pub minimized: bool }`. A floating window: a tree of groups like the docked layout's, without docks. - - `pub fn new(root: Node

, rect: Rect) -> Self`. A window holding `root`. Each call makes a new window, with a fresh [`Self::id`]: build +- `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column + - `pub fn new(column: Column

, rect: Rect) -> Self`. A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build - `pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self`. A window with one group. Each call makes a new window, as [`Self::new`] does. - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id`, for a layout the app builds in code, such as a default layout: - - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, in tree order. - - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. Groups stacked top to bottom, as a v1 layout stored them: each group over a vertical - - `pub fn groups(&self) -> Vec> where P: Clone,`. The window's groups, first to last. + - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, top group first. + - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, + - `pub fn groups(&self) -> &[Group

]`. The window's groups, top to bottom. - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such -- `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a dock column. +- `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a column, docked or floating. - `pub fn new(panels: Vec

, active: usize) -> Self`. A group of `panels` with tab `active` selected, expanded and with no preferred height or flyout geometry. - `pub fn active_panel(&self) -> Option<&P>`. The selected panel, or `None` when `active` is out of range. -- `craft_behavior::dock::GroupLocation`: `pub struct GroupLocation { pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option, pub column: Option }`. The group a closed panel was in, when that group was in a dock. +- `craft_behavior::dock::GroupLocation`: `pub struct GroupLocation { pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option, pub column: Option }`. The group a closed panel was in, when that group was in a column, docked or floating. - `pub const fn new(minimized: bool, height: Option, column: Option) -> Self`. A group location with the given state and column. - `pub const fn with_flyout_width(mut self, width: Option) -> Self`. The location with the group's flyout `width` points wide. - `pub const fn with_flyout_offset(mut self, offset: Option) -> Self`. The location with the group's flyout top `offset` points from its icons' top. @@ -527,7 +559,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. - `pub fn can_step_group(&self, panel: &P, up: bool, permissions: impl Fn(&P) -> Permissions) -> bool`. Whether [`Action::StepGroup`] would move `panel`'s group, for enabling a menu item. - `pub fn location(&self, panel: &P) -> Result, DockError>`. Capture a panel's nearest surviving group/split neighbor before hiding it. - - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. + - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. In a column, docked or floating, - `pub fn restore(&mut self, panel: P, location: &Location

) -> Result<(), DockError>`. Restore an absent panel at a captured location. Missing anchors are reported without - `pub fn open_at_edge(&mut self, panel: P) -> Result<(), DockError>`. Open an absent panel as a frame at the outer edge of the docked area, taking most of it: - `craft_behavior::dock::Location`: `pub struct Location

{ pub floating: Option, pub anchor: Option

, pub placement: DockPlacement

, pub size: Option, pub stack: Option<(bool, Option)>, pub sibling: Vec

, pub group: Option }`. A closed panel's former placement. Applications may retain this beside visibility flags. @@ -541,30 +573,35 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn split(axis: Axis, size: SplitSize, first: Node

, second: Node

) -> Self`. Two children along `axis`, sharing the room by `size`. - `pub fn stack(entries: Vec>) -> Self`. Builds [`Node::Stack`]. - `pub fn dock(side: DockEdge, columns: Vec>) -> Self`. Builds [`Node::Dock`]. -- `craft_behavior::dock::PanelPlace`: `pub enum PanelPlace { Node(Vec), Dock { path: Vec, column: usize, group: usize }, Floating { window: usize, path: Vec } }`. Where a panel is. Paths lead from the root: false is a split's first child, true its second. - - `pub fn tree_path(&self) -> Option<(Option, &[bool])>`. The tree (`None` for the docked layout, else a floating window) and the path of a +- `craft_behavior::dock::PanelPlace`: `pub enum PanelPlace { Node(Vec), Dock { path: Vec, column: usize, group: usize }, Floating { window: usize, group: usize } }`. Where a panel is. Paths lead from the root: false is a split's first child, true its second. + - `pub fn tree_path(&self) -> Option<&[bool]>`. The path of a `Tabs` or `Stack` node of the docked tree; `None` for a group of a column. + - `pub fn group_index(&self) -> Option`. The group's index in its column; `None` for a `Tabs` or `Stack` node of the docked tree. - `craft_behavior::dock::PanelState`: `pub enum PanelState { Hidden, Open, Front }`. What the Window menu shows for a panel. The model does not track the z-order of floating -- `craft_behavior::dock::Permissions`: `pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, pub accepts_tabs: bool, pub accepts_splits: bool }`. What may happen to a panel. [`Layout::apply_with_permissions`] enforces these for every - - `pub const ALL: Self`. Every right: the panel moves, floats, closes and takes tabs and splits. +- `craft_behavior::dock::Permissions`: `pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, pub accepts_tabs: bool, pub accepts_splits: bool, pub collapses: bool, pub shares_column: bool, pub docks_outside_columns: bool }`. What may happen to a panel. `Layout::apply_with_permissions` enforces these for every + - `pub const ALL: Self`. Every right: the panel moves, floats, closes, takes tabs and splits, collapses, shares its column and docks - `pub const PROTECTED: Self`. A document canvas: it stays docked and open, and takes neither tabs nor side splits. - `pub const fn movable(mut self, movable: bool) -> Self`. These permissions with [`Self::movable`] set to `movable`. - `pub const fn floatable(mut self, floatable: bool) -> Self`. These permissions with [`Self::floatable`] set to `floatable`. - `pub const fn closable(mut self, closable: bool) -> Self`. These permissions with [`Self::closable`] set to `closable`. - `pub const fn accepts_tabs(mut self, accepts_tabs: bool) -> Self`. These permissions with [`Self::accepts_tabs`] set to `accepts_tabs`. - `pub const fn accepts_splits(mut self, accepts_splits: bool) -> Self`. These permissions with [`Self::accepts_splits`] set to `accepts_splits`. + - `pub const fn collapses(mut self, collapses: bool) -> Self`. These permissions with [`Self::collapses`] set to `collapses`. + - `pub const fn shares_column(mut self, shares_column: bool) -> Self`. These permissions with [`Self::shares_column`] set to `shares_column`. + - `pub const fn docks_outside_columns(mut self, docks_outside_columns: bool) -> Self`. These permissions with [`Self::docks_outside_columns`] set to `docks_outside_columns`. - `pub fn is_protected(self) -> bool`. A canvas: it can neither move, close nor take tabs. `accepts_splits` and `floatable` - - `pub fn locked(self) -> Self`. Lock Workspace: nothing moves, floats or closes; tab and split drops keep their policy. + - `pub fn locked(self) -> Self`. Lock Workspace: nothing moves, floats or closes; tab and split drops and the column rights keep their policy. - `craft_behavior::dock::SIDE_ZONE_DEPTH_SHARE`: `pub const SIDE_ZONE_DEPTH_SHARE: f32`. The most of a body's smaller side that a [`ZoneSize::Depth`] zone reaches, so a body always keeps a middle. - `craft_behavior::dock::SIDE_ZONE_FRACTION`: `pub const SIDE_ZONE_FRACTION: f32`. Share of a body, from each edge, that means "beside" under [`ZoneSize::Fraction`]: of its width from the start - `craft_behavior::dock::SplitSize`: `pub enum SplitSize { Ratio(f32), FixedFirst(f32), FixedSecond(f32) }`. A transient sizing request. Applications may adapt their own persisted sizing enum. - `craft_behavior::dock::StackEntry`: `pub struct StackEntry

{ pub panel: P, pub open: bool, pub height: Option }`. One panel of a [`Node::Stack`] accordion. - `pub fn new(panel: P) -> Self`. An open accordion section for `panel` with no preferred height. -- `craft_behavior::dock::Target`: `pub enum Target

{ At { anchor: P, placement: DockPlacement

}, NewDock { side: DockEdge }, Float { rect: Rect } }`. Where a group, column or floating window goes. +- `craft_behavior::dock::Target`: `pub enum Target

{ At { anchor: P, placement: DockPlacement

}, NewDock { side: DockEdge }, Float { rect: Rect, edge: Option } }`. Where a group, column or floating window goes. - `pub fn at(anchor: P, placement: DockPlacement

) -> Self`. Builds [`Target::At`]. - `pub fn new_dock(side: DockEdge) -> Self`. Builds [`Target::NewDock`]. - - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`]. -- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. - - `pub const VERSION: u32`. The format version written to files. + - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. + - `pub fn float_with_edge(rect: Rect, edge: Option) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to. +- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)>, pub floated: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. + - `pub const VERSION: u32`. The format version written to files. Version 4 saves a floating window as one column; older floating - `pub fn revision(&self) -> u64`. The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else. - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next revision. - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. Closed panels record where they go back, so each one can be reopened @@ -604,17 +641,24 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn take_back(&mut self) -> Option`. Takes back the newest undo step without a redo entry, for an edit that was refused: `settled` returns to the - `pub fn can_undo(&self) -> bool`. An undo would change something. - `pub fn can_redo(&self) -> bool`. A redo would change something. + - `pub fn redo_len(&self) -> usize`. How many steps a redo can go forward. - `craft_behavior::edit_history::Step`: `pub enum Step { Undo, Redo }`. Which way [`EditHistory::step`] goes. ## `craft_behavior::editor` `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 }, 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. - `pub const fn select(anchor: TextPos, focus: TextPos) -> Self`. A `Select` of `anchor` to `focus`. - `pub const fn is_read_only_safe(&self) -> bool`. Whether the input changes no text: a read-only editor receives only these (18.4). +- `craft_behavior::editor::SurroundingUnit`: `pub enum SurroundingUnit { Chars, Bytes }`. What an input method counts the text around the caret in. + - `pub fn chars_before(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the end of `text`, the editor's text before the deletion. A character + - `pub fn chars_after(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the start of `text`, the editor's text after the deletion. A ## `craft_behavior::eviction` @@ -626,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) -> TabFit`. Fit tab widths into `available` points, shrinking the widest tabs first to a common cap. +- `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` @@ -687,6 +732,8 @@ Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, focus after removal, the E Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the +- `craft_behavior::geometry::AXIS_BAND_DEGREES`: re-export of `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`. +- `craft_behavior::geometry::AspectHold`: re-export of `craft_behavior::geometry::crop::AspectHold`. - `craft_behavior::geometry::BoxAllow`: re-export of `craft_behavior::geometry::quad::BoxAllow`. - `craft_behavior::geometry::BoxDrag`: re-export of `craft_behavior::geometry::quad::BoxDrag`. - `craft_behavior::geometry::BoxPart`: re-export of `craft_behavior::geometry::quad::BoxPart`. @@ -716,13 +763,16 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::SelectionOperation`: re-export of `craft_behavior::geometry::selection_op::SelectionOperation`. - `craft_behavior::geometry::SnapGesture`: re-export of `craft_behavior::geometry::snap::SnapGesture`. - `craft_behavior::geometry::SnapKind`: re-export of `craft_behavior::geometry::snap::SnapKind`. +- `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`. - `craft_behavior::geometry::TransformMode`: re-export of `craft_behavior::geometry::quad::TransformMode`. - `craft_behavior::geometry::across_axis`: re-export of `craft_behavior::geometry::snap::across_axis`. +- `craft_behavior::geometry::axis_or_diagonal`: re-export of `craft_behavior::geometry::lock::axis_or_diagonal`. - `craft_behavior::geometry::coordinate_across`: re-export of `craft_behavior::geometry::snap::coordinate_across`. - `craft_behavior::geometry::crop_view`: re-export of `craft_behavior::geometry::crop::crop_view`. - `craft_behavior::geometry::crop_view_about`: re-export of `craft_behavior::geometry::crop::crop_view_about`. @@ -732,15 +782,19 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::lock_direction`: re-export of `craft_behavior::geometry::lock::lock_direction`. - `craft_behavior::geometry::marquee_pixels`: re-export of `craft_behavior::geometry::marquee::marquee_pixels`. - `craft_behavior::geometry::motion_across`: re-export of `craft_behavior::geometry::snap::motion_across`. +- `craft_behavior::geometry::outside_pieces`: re-export of `craft_behavior::geometry::outside::outside_pieces`. +- `craft_behavior::geometry::polygon_step`: re-export of `craft_behavior::geometry::lock::polygon_step`. - `craft_behavior::geometry::round_to_direction`: re-export of `craft_behavior::geometry::lock::round_to_direction`. - `craft_behavior::geometry::screen_step`: re-export of `craft_behavior::geometry::crop::screen_step`. - `craft_behavior::geometry::square_pixels`: re-export of `craft_behavior::geometry::marquee::square_pixels`. +- `craft_behavior::geometry::turn_grid`: re-export of `craft_behavior::geometry::crop::turn_grid`. - `craft_behavior::geometry::turn_to_45`: re-export of `craft_behavior::geometry::lock::turn_to_45`. ## `craft_behavior::geometry::crop` The crop frame's pure geometry: the box, where a press lands on it, what each gesture makes of it, the +- `craft_behavior::geometry::crop::AspectHold`: `pub enum AspectHold { Free, Ratio(f64), Diagonal }`. What a resize holds about the frame's proportions. - `craft_behavior::geometry::crop::CropBox`: `pub struct CropBox { pub rect: Rect, pub angle: f64 }`. The crop frame: a document rect and the angle it is turned by about its centre. - `pub const fn new(rect: Rect, angle: f64) -> Self`. The frame `rect` turned `angle` degrees about its centre. - `pub const fn upright(rect: Rect) -> Self`. An unturned frame. @@ -757,10 +811,11 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `pub fn nudged(&self, part: BoxPart, by: Vec2, ratio: Option) -> Self`. The frame after an arrow key moves `part` by `by`, as a plain drag of the part would, with `ratio` held. - `pub fn crop_size(&self) -> Option<(f64, f64)>`. The size Enter would crop to: the frame's own width and height in whole document units, at least 1; `None` - `pub fn size_ok(&self) -> bool`. Whether both sides are at least one document unit. - - `pub fn resized(&self, part: BoxPart, by: Vec2, ratio: Option, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on - - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, ratio: Option, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the + - `pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on + - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the - `pub fn turned_to(&self, grab: f64, to: Point, step: Option, image: bool) -> Self`. The frame turned from this one's angle by the pointer's sweep about the centre, from direction `grab` - `pub fn within(self, bounds: Rect, resizing: bool, held: bool) -> Option`. The frame kept inside `bounds`: an unturned frame is cut to it; a turned one is moved by the least that + - `pub fn kept_inside(&self, bounds: Rect) -> Option`. The frame at its angle kept inside `bounds` (#10869, an image-mode turn): `self`, bit for bit, when its turned - `pub fn level_angle(a: Point, b: Point) -> Option`. The frame angle (degrees, clockwise on the page, in -45..=45) that makes the line from `a` to `b` level, or - `pub fn fitted(&self, canvas: Size, angle: f64) -> Option`. The largest frame with this one's proportions that fits a canvas of `canvas` at `angle` degrees, centred on - `craft_behavior::geometry::crop::CropGuide`: `pub enum CropGuide { Thirds, Grid, Diagonal, Triangle, GoldenRatio, GoldenSpiral }`. The composition guide drawn inside a crop frame, in Photoshop's menu order. @@ -782,6 +837,7 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `craft_behavior::geometry::crop::screen_step`: `pub fn screen_step(view: &CanvasView, by: Vec2) -> Vec2`. An arrow step `by` (screen points) as the document vector it is in `view`, at one document unit per point. - `craft_behavior::geometry::crop::snap_angle`: `pub fn snap_angle(deg: f64, step: f64) -> f64`. `deg` on the nearest multiple of `step` degrees, brought into (-180, 180]; a step that is not finite and positive - `craft_behavior::geometry::crop::turn`: `pub fn turn(p: Point, c: Point, deg: f64) -> Point`. `p` turned `deg` degrees clockwise on screen (y down) about `c`. +- `craft_behavior::geometry::crop::turn_grid`: `pub fn turn_grid(w: f64, h: f64, step: f64, visible: Rect) -> Vec>`. The lines of the grid a default-mode turn shows over a `w` by `h` frame (screen points), in the frame's unit square ## `craft_behavior::geometry::draft` @@ -795,12 +851,14 @@ An outline being drawn by a selection or freeform tool, and how it closes: [`Out - `pub const fn new(close: f64, same_point: f64) -> Self`. A reach closing within `close` screen points of the first vertex and treating a press - `craft_behavior::geometry::draft::OutlineDraft`: `pub struct OutlineDraft`. The pointer state machine of an outline being drawn, shared by every lasso. - `pub fn new(kind: DraftKind, reach: DraftReach) -> Self`. An empty draft following `kind`'s rules, closing within `reach`. + - `pub fn locking_shift_drags(mut self) -> Self`. This draft with ⇧ holding a freehand drag to one of eight directions (see [`DraftKind::Mixed`]). - `pub fn kind(&self) -> DraftKind`. The rules this draft follows. - `pub fn set_reach(&mut self, reach: DraftReach)`. Changes the close radii; an open outline keeps its points. - `pub fn for_document(&mut self, key: u64) -> Option`. Records `key` as the active document's. An open outline begun under another key is - `pub fn press(&mut self, at: DraftPoint, has_selection: bool) -> Option`. The primary button went down at `at`; `has_selection` is whether the document has a - `pub fn drag(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down. Freehand and Mixed: the point is added - - `pub fn hover(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button up: only the rubber band follows (hover moves + - `pub fn move_to(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down while the reposition key is held: the whole outline moves by the + - `pub fn hover(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button up: only the rubber band follows, to where a click would place the - `pub fn release(&mut self, at: DraftPoint) -> Option`. The primary button went up at `at`. Freehand: closes. Mixed: closes unless straight - `pub fn mods_changed(&mut self, mods: Mods) -> Option`. The held modifiers changed. Mixed only: ⌥ pressed after the press (or pressed again after - `pub fn retract(&mut self) -> Option`. Removes the last vertex while [`takes_retract`](Self::takes_retract); removing the only @@ -821,14 +879,17 @@ Plane geometry the canvas overlays share, in document or screen units: segment c ## `craft_behavior::geometry::lock` -Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`] and [`turn_to_45`]. +Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`], +- `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`: `pub const AXIS_BAND_DEGREES: f64`. How near an axis, in degrees, a ⇧ line or anchor drag must point to snap onto the axis rather than the diagonal - `craft_behavior::geometry::lock::Directions`: `pub enum Directions { Four, Eight }`. The directions ⇧ locks a move to. - `pub const fn count(self) -> u32`. How many evenly spaced directions: 4 or 8. - `craft_behavior::geometry::lock::LOCK_HYSTERESIS_DEGREES`: `pub const LOCK_HYSTERESIS_DEGREES: f64`. Extra angle in degrees the pointer must pass the half-way line between two directions by +- `craft_behavior::geometry::lock::axis_or_diagonal`: `pub fn axis_or_diagonal(from: Point, point: Point) -> Point`. Shift's rule for the Line tool and anchor drags: within [`AXIS_BAND_DEGREES`] of an axis, `point` moves onto the - `craft_behavior::geometry::lock::lock_direction`: `pub fn lock_direction(d: Vec2, previous: Option, directions: Directions) -> Vec2`. `d` locked to the nearest of `directions` evenly spaced directions (0° = right, document y +- `craft_behavior::geometry::lock::polygon_step`: `pub fn polygon_step(from: Point, point: Point) -> Point`. Shift's polygon vertex: `point` moved to the nearest of eight directions from `from`; an axis keeps the - `craft_behavior::geometry::lock::round_to_direction`: `pub fn round_to_direction(angle: f64, directions: Directions) -> f64`. `angle` (radians, 0 = right, document y down) rounded to the nearest of `directions` evenly -- `craft_behavior::geometry::lock::turn_to_45`: `pub fn turn_to_45(from: Point, point: Point) -> Point`. `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the one ⇧ rule for a line, a +- `craft_behavior::geometry::lock::turn_to_45`: `pub fn turn_to_45(from: Point, point: Point) -> Point`. `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle ## `craft_behavior::geometry::marquee` @@ -862,6 +923,7 @@ A move by drag: direction lock, stroke lock and snapping along a ray. - `pub fn follow(&mut self, at: Point, mods: Mods, zoom: f64) -> Option`. The pointer moved to `at` (document units) with `mods` at `zoom` screen points per - `pub fn release(mut self, at: Point, mods: Mods, zoom: f64) -> MoveValue`. The release at `at`: the same lock as [`follow`](Self::follow) applies, so a release where - `pub fn value(&self) -> MoveValue`. The value of the last [`follow`](Self::follow): the offset and whether it copies. + - `pub fn left_press(&self) -> bool`. Whether the pointer, at a [`follow`](Self::follow), has been half a document unit or more from the press on - `pub fn locked(&self) -> Option`. The direction ⇧ holds the offset to, as the last locked offset; `None` while the move is free. - `craft_behavior::geometry::move_gesture::MoveValue`: `pub struct MoveValue { pub delta: Vec2, pub copy: bool }`. The value of a move drag. - `pub fn changed(&self) -> bool`. Whether the drag changes anything: an offset or a copy. A press and release without @@ -871,25 +933,34 @@ A move by drag: direction lock, stroke lock and snapping along a ray. - `pub fn locked(&self) -> bool`. Whether a direction is locked. - `pub fn reset(&mut self)`. Forget the lock (the stroke ended). +## `craft_behavior::geometry::outside` + +The canvas outside a convex hole, as convex pieces. + +- `craft_behavior::geometry::outside::outside_pieces`: `pub fn outside_pieces(canvas: [Point; 4], hole: &[Point]) -> Vec>`. Convex pieces that cover the canvas quad outside the convex `hole` exactly once: the canvas clipped by each + ## `craft_behavior::geometry::quad` Box geometry of transform boxes: where the box goes when a part of it is dragged, and the -- `craft_behavior::geometry::quad::BoxAllow`: `pub struct BoxAllow { pub rotate: bool, pub skew: bool, pub distort: bool }`. What the box's content allows. PhotoCraft: editable type refuses distort and perspective +- `craft_behavior::geometry::quad::BoxAllow`: `pub struct BoxAllow { pub rotate: bool, pub skew: bool, pub distort: bool, pub warp: bool }`. What the box's content allows. PhotoCraft: editable type refuses distort and perspective - `pub const fn new(rotate: bool, skew: bool, distort: bool) -> Self`. What the content allows: turning, skewing and distorting. + - `pub const fn with_warp(mut self, warp: bool) -> Self`. Whether the content allows warping. - `craft_behavior::geometry::quad::BoxDrag`: `pub enum BoxDrag { Move, Pivot, Rotate, Scale, Distort, Perspective, Skew, SlideCorner }`. What a drag of a box part does ([`BoxRules::drag_kind`]). - `craft_behavior::geometry::quad::BoxPart`: `pub enum BoxPart { Corner(u8), Edge(u8), Pivot, Inside, Outside }`. A part of a box under the pointer or picked from the keyboard. Edge `k` joins corners `k` and - `pub const fn index(self) -> u64`. The number a part is keyed by in a canvas control's part keys: 0 inside or outside, 1 to 4 the corners, 5 to - `pub const fn from_index(index: u64) -> Option`. The part keyed by `index`: the inverse of [`index`](Self::index), with 0 the inside. -- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64 }`. How drags change a box. +- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64 }`. How drags change a box. - `pub fn in_mode(mode: TransformMode) -> BoxRules`. The rules of `mode` with the default scale rule, a linked aspect, everything allowed and - `pub fn with_scale(mut self, scale: ScaleRule) -> BoxRules`. The rules with `scale` as the plain corner and edge drag rule. - `pub fn with_aspect_linked(mut self, linked: bool) -> BoxRules`. The rules with the options bar's aspect link on or off. - `pub fn with_allow(mut self, allow: BoxAllow) -> BoxRules`. The rules with `allow` as what the content permits. + - `pub fn with_min_side(mut self, side: f64) -> BoxRules`. The rules with `side` as the minimum side of a scaled box, in document units. - `pub fn effective_mode(&self) -> TransformMode`. The mode drags follow: a mode the content refuses scales as Free Transform does. - `pub fn allows(&self, part: BoxPart) -> bool`. Whether a drag of `part` changes the box: in Distort only the corners, the inside and the - `pub fn drag_kind(&self, part: BoxPart, mods: Mods) -> Option`. What a drag of `part` with `mods` held (as the host has them, before - `craft_behavior::geometry::quad::BoxState`: `pub struct BoxState { pub quad: [Point; 4], pub pivot: Point }`. A transform box: its four corners clockwise from the top left (as the box was before any + - `pub fn origin_of_pivot(&self, rect: Rect) -> Point`. The reference point's place within the box, carried to `rect`: the pivot through the - `pub const fn new(quad: [Point; 4], pivot: Point) -> Self`. A box with the corners `quad`, clockwise from the top left, and the reference point `pivot`. - `pub fn from_rect(r: Rect) -> Self`. The box of `r`, the reference point at its centre. - `pub fn moved(&self, by: Vec2) -> Self`. The box and its reference point moved by `by`. @@ -905,6 +976,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub fn scaled_about_pivot(&self, kx: f64, ky: f64) -> Self`. Scaled by `kx` and `ky` along the box's own axes about the reference point. A negative - `pub fn turned_about_pivot(&self, radians: f64) -> Self`. Turned by `radians` about the reference point. - `craft_behavior::geometry::quad::Homography`: `pub struct Homography`. A projective map of the plane: the unit square onto a box, so a box scales along its own axes + - `pub fn apply_in_front(&self, p: Point, within: Rect) -> Option`. [`Homography::apply`] for a point on the front side of the horizon, the side most of - `pub fn from_rows(rows: [[f64; 3]; 3]) -> Homography`. The map with these rows of (x, y, w) coefficients, applied to (x, y, 1). - `pub fn row(&self, i: usize) -> [f64; 3]`. Row `i` (0 to 2) of the matrix: the coefficients of x, y and the constant. - `pub fn unit_to_quad(q: [Point; 4]) -> Option`. The map taking (0, 0), (1, 0), (1, 1), (0, 1) to `q`'s corners; `None` for a degenerate @@ -913,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 }`. 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 @@ -939,19 +1011,32 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub const fn rect(at_press: Rect) -> Self`. A moving rectangle that was `at_press` when the gesture began. - `pub const fn axis(along: Axis) -> Self`. Only the coordinate across the lines that run `along` snaps: x for `Axis::Y`. - `craft_behavior::geometry::snap::SnapKind`: `pub enum SnapKind { Guide, Grid, Bounds, Center, LayerEdge, LayerCenter, Selection }`. What a target is, so an app can filter (Snap To › Guides only) and the lines can be drawn in + - `pub const fn is_smart(self) -> bool`. Whether the target's lines draw in the smart-guide colour: `LayerEdge`, `LayerCenter` and `Center`. +- `craft_behavior::geometry::snap::SnapKinds`: `pub struct SnapKinds`. A set of [`SnapKind`]s, a bit per kind: the kind filter a gesture passes to its snapping. + - `pub const ALL: SnapKinds`. Every kind. + - `pub const fn only(kind: SnapKind) -> Self`. The set of `kind` alone. + - `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. - `pub fn new() -> Self`. No targets. - `pub fn add(&mut self, target: SnapTarget)`. Add one target. + - `pub fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind)`. Add a rectangle's four edges as `edge` targets and its two centre lines as `center` - `pub fn with_document(self, options: &SnapOptions, bounds: Rect, guides: impl IntoIterator, grid: Option<(Point, Vec2)>,) -> Self`. Guides as full-height targets, grid lines of `spacing` from `origin` over `bounds`, the - `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 - `pub fn snap_rect(&self, rect: Rect, tolerance: f64) -> (Vec2, Vec)`. The offset that moves `rect` so its nearest edge or centre meets a target on each axis, + - `pub fn snap_rect_of(&self, rect: Rect, tolerance: f64, kinds: SnapKinds) -> (Vec2, Vec)`. [`snap_rect`](Self::snap_rect) to the targets of a kind in `kinds` only (moving a selection skips the selection's - `craft_behavior::geometry::snap::across_axis`: `pub const fn across_axis(along: Axis) -> Axis`. The axis across `along`: a line running along `Axis::Y` (vertical) is placed on `Axis::X`. - `craft_behavior::geometry::snap::coordinate_across`: `pub const fn coordinate_across(along: Axis, p: Point) -> f64`. The coordinate of `p` a line running `along` an axis is placed by: x for a line along `Axis::Y`. - `craft_behavior::geometry::snap::motion_across`: `pub fn motion_across(along: Axis) -> Vec2`. The document direction a line running `along` an axis moves in: x for a line along `Axis::Y`. A screen caller @@ -972,6 +1057,7 @@ The `Grid` cursor: columns resolved from last pass's measurements, and the cell - `pub fn region(&self) -> Rect`. The rect the next child measures and is placed in: from its column's start edge and its row's top, as large - `pub fn fill_room(&self) -> Vec2`. The room the next child fills when it fills its width: its column's width, which for a `Content` column is the - `pub fn in_content_column(&self) -> bool`. Whether the next child goes in a `Content` column. + - `pub fn column(&self) -> usize`. The column the next child goes in. - `pub fn widen(&mut self, size: Vec2)`. The cell last placed measured `size` after all: its column and row record that, and a `Content` column offers - `pub fn measured(&self) -> &GridMeasure`. What this pass measured. - `craft_behavior::grid::GridMeasure`: `pub struct GridMeasure { pub columns: Vec, pub rows: Vec, pub least: Vec }`. What a `Grid` pass measured: the widest child per column and the tallest per row, and the least each column @@ -987,10 +1073,11 @@ Hit shapes, their priority and the arena's resolve rule (8.3). - `craft_behavior::hit::HitPriority`: `pub struct HitPriority { pub level: HitLevel, pub sub: u8 }`. A part's rank among the shapes of its stack position: a node editor ranks port above wire above node body. - `pub const fn new(level: HitLevel, sub: u8) -> Self`. A priority at `level` and `sub`. - `pub const BODY: HitPriority`. The priority of a component body. -- `craft_behavior::hit::HitShape`: `pub enum HitShape { Rect(Rect), Circle { center: Pos2, radius: f32 }, Segment { a: Pos2, b: Pos2 }, Polyline { points: Vec, closed: bool }, Polygon(Vec), OutsidePolygon { within: Rect, polygon: Vec } }`. The geometry a part registers: the shape painted is the shape hit. +- `craft_behavior::hit::HitShape`: `pub enum HitShape { Rect(Rect), Circle { center: Pos2, radius: f32 }, Segment { a: Pos2, b: Pos2 }, Polyline { points: Vec, closed: bool, reach: f32 }, Polygon(Vec), OutsidePolygon { within: Rect, polygon: Vec } }`. The geometry a part registers: the shape painted is the shape hit. - `pub const fn circle(center: Pos2, radius: f32) -> Self`. A disc. - `pub const fn segment(a: Pos2, b: Pos2) -> Self`. A line segment. - - `pub fn polyline(points: Vec, closed: bool) -> Self`. A chain of segments, closed when `closed`. + - `pub fn polyline(points: Vec, closed: bool) -> Self`. A chain of segments, closed when `closed`, hit within [`LINE_REACH`]. + - `pub fn polyline_within(points: Vec, closed: bool, reach: f32) -> Self`. A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from - `pub fn outside_polygon(within: Rect, polygon: Vec) -> Self`. The part of `within` outside `polygon`. - `pub fn bounds(&self) -> Rect`. The smallest rectangle around the shape. - `pub fn hit(&self, point: Pos2) -> bool`. Whether `point` hits the shape. @@ -1000,6 +1087,7 @@ Hit shapes, their priority and the arena's resolve rule (8.3). - `pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self`. A shape of `owner` at stack `position`. - `pub const fn min_across(mut self, across: f32) -> Self`. The hit area is at least `across` points wide and high. - `pub const fn local(mut self, local: bool) -> Self`. The shape lies in the body layer's space. + - `pub fn hits(&self, point: Pos2) -> bool`. Whether `point` lies in the hit area: the shape grown to be at least its `min_across` wide and high. The - `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool }`. The shape that won a resolution. - `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last - `craft_behavior::hit::resolve_mapped`: `pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFor, to_local: impl Fn(Pos2) -> Pos2) -> Option>`. [`resolve`] where shapes with `local` set are tested at `to_local(point)`. @@ -1018,7 +1106,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`. @@ -1045,6 +1133,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. @@ -1222,6 +1311,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. @@ -1253,8 +1343,8 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `craft_behavior::nav::StepResult`: `pub enum StepResult { Set(f64), Ignored }`. What a single-value move does. - `craft_behavior::nav::TypeAhead`: `pub struct TypeAhead`. Typed letters of the last second as one prefix. - `pub const fn new() -> Self`. An empty buffer. - - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix. - - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>) -> Option`. The entry a prefix picks: the first match from the position after `from` (from `from` itself when the + - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, + - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one - `craft_behavior::nav::ValueAxes`: `pub enum ValueAxes { Horizontal, Vertical, Both }`. The axes a single-value control reads moves on. - `craft_behavior::nav::ValueSteps`: `pub struct ValueSteps { pub value: f64, pub min: f64, pub max: f64, pub small: f64, pub large: f64, pub fine: f64, pub notch: f64 }`. The value and steps of a single-value control. - `pub const fn new(value: f64, min: f64, max: f64, small: f64, large: f64) -> Self`. Steps over `min..=max` from `value`. The fine step is `small / LARGE_STEPS` and a wheel notch is `small`. @@ -1265,7 +1355,7 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `craft_behavior::nav::step`: `pub fn step(shape: NavShape, outline: &dyn NavOutline, state: &mut NavState, mv: NavMove, mods: MoveMods) -> NavStep`. Steps the lead of a navigation of `shape` over `outline` by `mv`. `mods.extend` keeps the anchor at the - `craft_behavior::nav::step_until_changed`: `pub fn step_until_changed(from: T, step: impl Fn(T) -> T, same: impl Fn(T) -> bool) -> T`. The value `step` reaches from `from`, stepped again while a step still moves it and `same` says the value is the - `craft_behavior::nav::step_value`: `pub fn step_value(steps: &ValueSteps, axes: ValueAxes, mv: NavMove, mods: MoveMods) -> StepResult`. Maps a move to the new value of a slider, dial, rating, resize handle or colour pad. `Forward`, `Up` and -- `craft_behavior::nav::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel event to the new value of a single-value control: one `notch` per event, up for positive scroll. +- `craft_behavior::nav::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries ## `craft_behavior::one_press` @@ -1326,6 +1416,7 @@ Where windows go on the desktop: where a saved window opens ([`place`]), which m - `pub fn new(size: [f32; 2], scale: f32) -> Self`. A window of `size` points, position unknown, on a monitor of `scale`, not maximized. - `pub fn repaired(&self) -> Option`. The record with out-of-range numbers repaired, or `None` when its size is no size. - `pub fn position(&self) -> Option<[f32; 2]>`. The outer top-left corner in desktop points at the saved scale, where the position is known. +- `craft_behavior::placement::capped`: `pub fn capped(size: Vec2, monitor: &Monitor, frame: Vec2, min: Vec2) -> Vec2`. `size` at least `min` and at most the monitor's usable area less `frame`; the cap wins over the minimum. - `craft_behavior::placement::cascade`: `pub fn cascade(previous: Rect, size: Vec2, bounds: Rect, step: f32) -> Rect`. Where a window of `size` opens after the one at `previous`: one `step` right and down. An axis on which that - `craft_behavior::placement::cascade_rects`: `pub fn cascade_rects(area: Rect, size: Vec2, n: usize, step: f32) -> Vec`. `n` windows of `size` in a cascade inside `area`: the first at its top left, each next one [`cascade`]d from the - `craft_behavior::placement::monitor_of`: `pub fn monitor_of(monitors: &[Monitor], window_px: Rect) -> Option<&Monitor>`. The monitor the window at `window_px` (desktop pixels) is on: the one showing most of it or, when none shows it, @@ -1345,7 +1436,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn delta(mut self, delta: Vec2) -> Self`. The pointer movement of the pass. - `pub const fn cancel(mut self, cancel: Option) -> Self`. A reason the captured press ends now. - `craft_behavior::press::PointerButton`: `pub enum PointerButton { Primary, Secondary, Middle, Extra1, Extra2 }`. A pointer button. -- `craft_behavior::press::PointerEvent`: `pub enum PointerEvent { Moved(Pos2), Pressed { button: PointerButton, pos: Pos2, time: f64, clicks: u32 }, Released { button: PointerButton, pos: Pos2 }, Gone }`. A button event of one pass, in the order it arrived. The press lifecycle follows the primary button and the +- `craft_behavior::press::PointerEvent`: `pub enum PointerEvent { Moved { at: Pos2, sample: Option }, Pressed { button: PointerButton, pos: Pos2, time: f64, clicks: u32 }, Released { button: PointerButton, pos: Pos2 }, Gone }`. A button event of one pass, in the order it arrived. The press lifecycle follows the primary button and the + - `pub const fn moved(at: Pos2, sample: Option) -> Self`. The pointer moved to `at`, with the pen's reading for the move when the runtime has one. - `pub const fn pressed(pos: Pos2, time: f64, clicks: u32) -> Self`. The primary button going down at `pos`, `time`, as the `clicks`th press in a row. - `pub const fn released(pos: Pos2) -> Self`. The primary button going up at `pos`. - `pub const fn pressed_by(button: PointerButton, pos: Pos2, time: f64, clicks: u32) -> Self`. `button` going down at `pos`, `time`, as the `clicks`th press in a row. @@ -1353,7 +1445,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `craft_behavior::press::PointerKind`: `pub enum PointerKind { Mouse, Pen, Touch }`. What kind of device the pointer is. - `craft_behavior::press::PointerSample`: `pub struct PointerSample { pub pressure: f32, pub tilt: [f32; 2], pub rotation: f32, pub eraser: bool }`. Pressure and tilt of the current contact. - `pub const fn new(pressure: f32) -> Self`. A sample with no tilt or rotation. -- `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed }`. Why a captured press ended without a release. + - `pub fn sanitized(self) -> Self`. The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value +- `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed, Host }`. Why a captured press ended without a release. - `craft_behavior::press::PressMachine`: `pub struct PressMachine`. The press lifecycle of one root: the press winner it picked, kept until release or cancel. - `pub const fn new() -> Self`. A machine with no press. - `pub fn target(&self) -> Option`. The target of the open press. @@ -1361,7 +1454,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn dragging(&self) -> bool`. Whether a drag holds the pointer. - `pub fn release_held(&self) -> bool`. Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` -- `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. +- `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart, pos: Pos2 }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. - `pub const fn is_press(&self) -> bool`. A press is in progress or just ended: not `Idle` or `Hover`. - `pub const fn start(&self) -> Option`. The press the phase belongs to. - `pub const fn button_down(&self) -> bool`. Whether the button is down: `Down`, `Held`, `DragStart` or `Drag`. @@ -1378,7 +1471,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn captured(mut self, captured: bool) -> Self`. Whether a drag holds the pointer. - `pub const fn double_pressed(&self) -> bool`. Whether the phase is the `Down` of the second press of a double click: true once, false while the button is - `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option }`. What one pass did to the press. -- `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32)>, pos: Pos2, time: f64, slop: f32) -> u32`. The click count of a press at `pos` and `time`, given the previous press `(pos, time, clicks)`: one more when +- `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32`. The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, ## `craft_behavior::quantity` @@ -1428,6 +1521,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` @@ -1497,7 +1591,7 @@ Selection models: what a collection's selection holds and how a change applies t The library's sense set, for a root or a part. -- `craft_behavior::sense::Sense`: `pub struct Sense: u16 (flag set)`. What a root or a part senses. The egui adapter maps the root's sense to egui's. +- `craft_behavior::sense::Sense`: `pub struct Sense: u32 (flag set)`. What a root or a part senses. The egui adapter maps the root's sense to egui's. - `pub const PRESS: Sense`. The bits that make a shape a press candidate. - `pub const WHEELS: Sense`. The bits that make a shape register a wheel taker. - `pub const fn takes_press(self) -> bool`. Whether a press can start on a shape with this sense. @@ -1539,9 +1633,10 @@ The library's sense set, for a root or a part. - `pub fn codec(&self) -> &C`. The codec. - `pub fn shown(&self, run: &EditRun, value: &C::Value) -> String`. The text to show: the draft, else the value's text. - `pub fn open(&self, run: &mut EditRun, start: &C::Value)`. Opens the run on `start` when none is open. - - `pub fn edit(&self, run: &mut EditRun, start: &C::Value, text: &str) -> Typed`. The draft is now `text`: characters the codec refuses and characters past the limit drop out. + - `pub fn edit(&self, run: &mut EditRun, start: &C::Value, text: &str) -> (Typed, bool)`. The draft is now `text`: characters the codec refuses and characters past the limit drop out. The `bool` + - `pub fn rewrite(&self, run: &mut EditRun) -> bool`. Replaces the draft with the codec's normal form of the value it reads (`Codec::normalise`, as a commit - `pub fn commit(&self, run: &mut EditRun) -> Ended`. Commits the draft: a value closes the run, a draft that is no value keeps it open. - - `pub fn commit_tagged(&self, run: &mut EditRun) -> (Ended, Option)`. [`commit`](Self::commit), with the tag of the unit the committed text named (`Codec::parse_tagged`). + - `pub fn commit_tagged(&self, run: &mut EditRun) -> (Ended, ParseNote)`. [`commit`](Self::commit), with the note of the committed text (`Codec::parse_tagged`); the default note for a - `pub fn cancel(&self, run: &mut EditRun) -> Option`. Closes the run without a commit and returns the value from before it; `None` when no run was open. - `pub fn escape(&self, run: &mut EditRun) -> Escaped`. Applies the escape rule. A codec that refuses the empty text keeps the cleared draft open under @@ -1550,7 +1645,7 @@ The library's sense set, for a root or a part. The value core of chapter 10: the bound every value type meets, `Mixed`, edit events and the list a pass's events - `craft_behavior::value::Applied`: `pub enum Applied { Changed, Unchanged, Restored }`. What applying an event did to a value. -- `craft_behavior::value::CancelReason`: `pub enum CancelReason { Refused, Dismissed, Escape, Blur, Removed, HostChanged, UndoDuringGesture }`. Why a gesture ended without a commit. +- `craft_behavior::value::CancelReason`: `pub enum CancelReason { Refused, Dismissed, Escape, Blur, Removed, HostChanged, UndoDuringGesture, Unchanged }`. Why a gesture ended without a commit. - `pub const fn document_moved(self) -> bool`. The document changed under the gesture, so the gesture's own edits stay and a revert would also take back the - `craft_behavior::value::EditEvent`: `pub enum EditEvent { Begin { id: GestureId, before: Mixed, label: Arc, doc_key: Option }, Update { id: GestureId, value: T }, Commit { id: GestureId, before: Mixed, after: T }, Cancel { id: GestureId, reason: CancelReason, before: Option> }, Set { before: Mixed, after: T, label: Arc, doc_key: Option } }`. One step of an edit. A pass raises several; [`EditEvents`] holds them in order. - `pub fn begin(id: GestureId, before: Mixed, label: Arc, doc_key: Option) -> Self`. A gesture began. @@ -1567,6 +1662,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub fn apply(&self, v: &mut T) -> Applied`. Applies the event to `v`: a proposal, commit or set writes its value, a cancel restores the value from before - `pub fn apply_mixed(&self, v: &mut Mixed) -> Applied`. Applies the event to a value that may be mixed: the written value is a concrete one. - `craft_behavior::value::EditEvents`: `pub struct EditEvents`. The edit events of one pass, in order. `push` folds what loses nothing, within one gesture: a later `Update`, + - `pub fn committed(&self) -> Option<&T>`. The value of the last `Commit` or `Set` in the events; `None` if there is none. - `pub fn new() -> Self`. No events. - `pub fn push(&mut self, event: EditEvent)`. Adds the next event of the pass, folding it with the one before when that loses nothing. - `pub fn is_empty(&self) -> bool`. No event happened. @@ -1581,20 +1677,27 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub fn map(self, f: impl Fn(T) -> U) -> EditEvents`. Maps the carried values of every event. - `pub fn filter_map(self, f: impl Fn(T) -> Option) -> EditEvents`. Maps the carried values of every event, dropping the events `f` has no value for. - `craft_behavior::value::EditPolicy`: `pub enum EditPolicy { WriteThrough, OnCommit }`. When a write-through source is written: on every proposal of a gesture or only on its commit. -- `craft_behavior::value::Gesture`: `pub struct Gesture { pub id: GestureId, pub before: Option>, pub proposal: Option, pub last_given: Option, pub emitted: Option, pub reported: Option, pub dead: bool, pub cancel_seen: u64, pub watched: bool }`. The running gesture of a value component, kept in shown memory under the component. Plain data; the pipeline +- `craft_behavior::value::Gesture`: `pub struct Gesture { pub id: GestureId, pub before: Option>, pub proposal: Option, pub last_given: Option, pub emitted: Option, pub reported: Option, pub dead: bool, pub cancel_seen: u64, pub watched: bool, pub wheel: bool, pub note: Option }`. The running gesture of a value component, kept in shown memory under the component. Plain data; the pipeline - `pub fn ended(&self, dead: bool) -> Gesture`. The gesture after it ended: no value, the id kept, and `dead` while the press that carried it is held. - `pub fn is_running(&self) -> bool`. A gesture is running. - `craft_behavior::value::GestureId`: `pub struct GestureId(pub u64)`. Names a gesture; ids grow in the order the gestures begin. - `pub const fn new(n: u64) -> GestureId`. The id numbered `n`. - `pub const fn next(self) -> GestureId`. The id of the gesture after this one. +- `craft_behavior::value::GestureNote`: `pub struct GestureNote`. A typed note a component sets on its running gesture for readers outside its pass, such as the guide a guides + - `pub fn new(note: N) -> Self`. A note holding `note`. + - `pub fn get(&self) -> Option<&N>`. The note, when it is an `N`. - `craft_behavior::value::GesturePhase`: `pub enum GesturePhase { Begin, Update, Commit, Cancel }`. Where a gesture stands in one pass. - `craft_behavior::value::Mixed`: `pub enum Mixed { Same(T), Mixed }`. A value that may differ across a multi-selection. - `pub const fn same(&self) -> Option<&T>`. The shared value, `None` while the items differ. - `pub const fn or<'a>(&'a self, start: &'a T) -> &'a T`. The shared value, or `start` while the items differ. - `pub fn each(values: [T; N]) -> [Mixed; N]`. Every part of `values` as a shared value: the per-part form of a composite value no part of which differs. - `pub fn parts(self) -> [Mixed; N]`. The per-part form of a composite value: a whole `Mixed` binding means every part differs. +- `craft_behavior::value::Preview`: `pub enum Preview { Unchanged, Shows(V), Ended }`. What one pass did to a live preview a component shows beside its value (the family under the pointer in a font + - `pub fn map(self, f: impl FnOnce(V) -> W) -> Preview`. The same change over the value `f` makes of the shown one. - `craft_behavior::value::Validity`: `pub enum Validity { Ok, Fix(T), Warn(M), Refuse(M), Error(M) }`. What a check says about a value. `M` is the message type: craft-ui exports the alias with its own `Message`. - `craft_behavior::value::Value`: `pub trait Value: Clone + PartialEq + Send + Sync + 'static`. What a bound value must be: cloneable, comparable and shareable across threads. +- `craft_behavior::value::same_in_f32`: `pub fn same_in_f32(proposed: f64, host: f64) -> bool`. Whether `host`, a number an app wrote back, is the proposal `proposed` as a host that keeps it in `f32` stores it: +- `craft_behavior::value::same_in_f32_at`: `pub fn same_in_f32_at(proposed: f64, host: f64, magnitude: f64) -> bool`. [`same_in_f32`] for a number the host computes in `f32` from terms as large as `magnitude`: a corner of a box it ## `craft_behavior::value_drag` @@ -1623,24 +1726,36 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub at: Option, pub zooms: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. + - `pub const fn touch_zoom(mut self, zoom: f32) -> Self`. The same gesture with the two-finger touch zoom factor `zoom`. + - `pub const fn rotation(mut self, radians: f32) -> Self`. The same gesture with rotation `radians`, clockwise on screen. + - `pub const fn touch_rotation(mut self, radians: f32) -> Self`. The same gesture with the two-finger touch rotation `radians`. + - `pub const fn source(mut self, source: WheelSource) -> Self`. The same gesture from `source`. - `pub const fn at(mut self, at: Pos2) -> Self`. The same gesture with the pointer at `at`. -- `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool }`. Who holds key focus, as the split reads it. +- `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool, pub by_position: bool }`. Who holds key focus, as the split reads it. - `pub const fn new(taker: Option) -> Self`. Focus on `taker`, or on nothing that takes the wheel. - `pub const fn app_field(mut self, on: bool) -> Self`. The same focus, in a text field the app drew itself when `on`. + - `pub const fn by_position(mut self, on: bool) -> Self`. The same focus, with the pointer over a layer that takes the wheel by position when `on` +- `craft_behavior::wheel::WheelGesture`: `pub struct WheelGesture { pub owner: Option, pub last: f64 }`. A wheel gesture: events closer than [`GESTURE_GAP`] seconds, or inside one device phase. `owner` is `None` while + - `pub fn runs(&self, now: f64) -> bool`. Whether an event at `now` continues the gesture: one is open, the device has not ended it and the gap since + - `pub fn end(&mut self, now: f64) -> Option`. Closes the gesture once `now - last` reaches [`GESTURE_GAP`], or at once after a device end, and returns the - `craft_behavior::wheel::WheelNotch`: `pub enum WheelNotch { Points(f32), ViewShare(f32) }`. The distance one wheel line scrolls a taker. - `pub const DEFAULT: WheelNotch`. The distance of a taker that states none. - `pub fn points(self, extent: f32) -> f32`. The notch in points, for a taker whose view is `extent` points along the axis. - `craft_behavior::wheel::WheelPhase`: `pub enum WheelPhase { Start, Move, End, Cancel }`. A wheel gesture's phase. - `craft_behavior::wheel::WheelRoom`: `pub struct WheelRoom { pub positive: Vec2, pub negative: Vec2 }`. The scroll left in a region, in points of wheel scroll: `positive` is what a wheel with positive `scroll` can - `pub const fn new(positive: Vec2, negative: Vec2) -> Self`. A room of `positive` and `negative` points. -- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option, pub zooms_view: bool, pub field: bool }`. A component that takes wheel input, as registered last pass. +- `craft_behavior::wheel::WheelSource`: `pub enum WheelSource { Unknown, Wheel, Trackpad, Momentum }`. The device a wheel event came from, where the system says (egui reports it on macOS only). + - `pub const fn fingers(self) -> bool`. Whether fingers drive the scroll: a trackpad or its momentum. +- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option, pub zooms_view: bool, pub field: bool, pub value: bool }`. A component that takes wheel input, as registered last pass. - `pub const fn new(owner: O, rect: Rect) -> Self`. A taker over `rect` that takes no axis yet. - `pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option`. The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll - `pub const fn zooms_view(mut self, on: bool) -> Self`. Whether it is a zoom zone (`WheelTaker::zooms_view`). - `pub const fn field(mut self, on: bool) -> Self`. Whether it is a value field (`WheelTaker::field`). + - `pub const fn value(mut self, on: bool) -> Self`. Whether it is a value control (`WheelTaker::value`). - `pub const fn horizontal(mut self, on: bool) -> Self`. Whether it takes horizontal scroll. - `pub const fn vertical(mut self, on: bool) -> Self`. Whether it takes vertical scroll. - `pub const fn zoom(mut self, on: bool) -> Self`. Whether it takes zoom. @@ -1650,12 +1765,13 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli - `pub const fn room(mut self, room: WheelRoom) -> Self`. The taker's scroll room: it passes a wheel on an axis it has no room left for to the next enclosing taker. - `pub fn points(&self, scroll: Vec2, unit: WheelUnit) -> Vec2`. `scroll`, given in `unit`s of the device, as points of this taker's view: a line is one notch, a page is - `craft_behavior::wheel::WheelUnit`: `pub enum WheelUnit { Point, Line, Page }`. How far one wheel event reaches. -- `craft_behavior::wheel::split`: `pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option) -> Vec<(O, Wheel)>`. The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes +- `craft_behavior::wheel::split`: `pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option, gesture: &mut WheelGesture, now: f64,) -> Vec<(O, Wheel)>`. The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes ## `craft_ui` The base of the craft UI library: runtime, style, fonts, primitives, the component contract, layout and the test +- `craft_ui::bind_tracked!`: `macro_rules! bind_tracked`. Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` - `craft_ui::testing_registered!`: `macro_rules! testing_registered`. Writes `pub fn registered()` for the invoking package: its library crate's registrations in the running binary. - `craft_ui::InstallError`: re-export of `craft_ui::runtime::install::InstallError`. - `craft_ui::InstallSpec`: re-export of `craft_ui::runtime::install::InstallSpec`. @@ -1675,16 +1791,19 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `const MEMBERS: bool`. Whether the items are members of the collection's run instead of runs of their own. Each visible item is then - `fn items(&self) -> &CollectionProps`. Plain data: selection mode, reorder, rename, columns. - `fn selection(&mut self) -> Option>`. The selection binding; `None` keeps it in session memory. + - `fn column_layout(&mut self) -> Option>`. The column arrangement binding; `None` keeps it in the header's own memory. The header starts each pass from - `fn cell_space<'s>(&'s self, space: CellSpace<'s, Self::Key>) -> CellSpace<'s, Self::Key>`. The grid a model of cells selects in (17.7). The item step passes the grid it knows, the source's rows and the - `fn reveal(&self) -> Option<&Self::Key>`. A one-shot request to scroll an item into view. - `fn item_layout(&self, source: &dyn ItemSource, width: f32, cx: &StyleCx<'_>) -> Self::ItemLayout`. The layout of `source` at `width`. - `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. - `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). @@ -1692,12 +1811,13 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn drops(&self) -> &[DropKind<'_, Self::Key>]`. What the collection takes from drags that did not start in it, in order: the first kind that takes the drag's - `fn edge_press(&self) -> Option<&EdgePress<'_, Self::Key>>`. The press on the line between two adjacent rows the collection takes, reported as - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): it reports - - `fn empty_height(&self, width: f32, ui: &Ui, _cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The + - `fn empty_height(&self, width: f32, ui: &Ui, cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The - `fn empty(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>)`. The empty state at the rect the item step placed. The default shows `CollectionProps::empty`. - `craft_ui::contract::Component`: `pub trait Component: Meta + Sized`. The core trait: every UI type is a `Component`. - `const ROLE: Role`. The AccessKit role. - `const ALT_ROLES: &'static [Role]`. Roles `access` may pick per instance. - `const INPUT: Input`. How input reaches the component. + - `const ESCAPE: EscapeEdit`. What Escape does to the running gesture. - `const OVERLAYS: bool`. Whether the component hosts popups: `false` skips the overlay bookkeeping of steps 9, 10, 12, 15 and 16. - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except @@ -1725,7 +1845,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn same_value(&self, proposed: &ValueOf, host: &ValueOf) -> bool`. Whether `host`, a value the app wrote back, is the value `proposed` as the component holds values: a host that - `fn scrub(&self) -> Option>>`. Lets a drag on the scrub's sources (the side label, the body, a part) change the value; the pipeline runs the - `fn scroll(&mut self) -> Option>`. The scroll offset's owner when the app drives scrolling; `None` keeps it in session memory. The app restores a - - `fn content_env(&self, _cx: &Cx<'_, Self>, _values: &mut crate::runtime::env::AppValues)`. App values for content the component does not build: its body or its items. Runs once, at step 13. + - `fn content_env(&self, _cx: &Cx<'_, Self>, _values: &mut crate::runtime::env::AppValues)`. App values for content the component does not build: its body or its items. Runs at step 13, and in a measuring run of the body before it. - `fn update(&mut self, _cx: &mut Cx<'_, Self>)`. After sensing, before paint: value maths, memory, popup triggers. - `fn overlay(&mut self, _ui: &mut OverlayUi<'_>, _cx: &mut Cx<'_, Self>)`. Anchored popups. Runs before flags and paint. - `fn flags(&self) -> Flags`. Value-driven flags (checked, open, invalid, busy). @@ -1734,6 +1854,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn paint_over(&mut self, _ui: &mut PaintUi<'_>, _cx: &Cx<'_, Self>)`. Content above the body or items. - `fn access(&self, _access: &mut Access, _cx: &Cx<'_, Self>)`. Value, range, relations, sub-nodes and custom actions beyond role, label and flags. - `fn value_text(&self, _cx: &Cx<'_, Self>) -> Option`. The shown value as the component words it ("40.0", "20 to 60"), which assistive technology reads and a viewer + - `fn word_value(&self, _value: &ValueOf, _cx: &Cx<'_, Self>) -> Option`. Words `value` as the control shows it ("40.0", "20 to 60"); `None` for a component that words no value. The - `fn finish(self, cx: Cx<'_, Self>) -> Self::Output`. Builds the output from the finished context. - `craft_ui::contract::Container`: `pub trait Container: Component + HasProps + Meta`. A component whose caller supplies a body. - `fn open(&mut self) -> Option>`. The open state's owner: the caller's binding. `None`: a session slot under the id. @@ -1741,11 +1862,13 @@ 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 - `craft_ui::contract::ContentPainter`: `pub trait ContentPainter: Component`. Implemented by the allowlisted components that paint content with a raw painter (a preview, a waveform). - `craft_ui::contract::DisabledLook`: `pub enum DisabledLook { States, Faded }`. How a component that is not enabled looks (`Component::DISABLED`). Either way it takes no input, its access node +- `craft_ui::contract::EscapeEdit`: `pub enum EscapeEdit { Cancel, Commit }`. What Escape does to a value component's running gesture (step 9). - `craft_ui::contract::HasProps`: `pub trait HasProps`. Written by the derive from a `#[container]` field, for containers and collections. - `fn props(&self, _: Internal) -> &ContainerProps`. - `craft_ui::contract::IdSource`: `pub enum IdSource { Auto, Salt(IdSalt), Id(Id) }`. Where an element's id comes from. @@ -1774,12 +1897,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`. @@ -1796,12 +1919,13 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn given(v: impl Into>) -> Self`. A value in; every edit comes out as an event. - `pub fn bound(v: &'a mut T) -> Self`. Edits write through to `v`. - `pub fn bound_mixed(v: &'a mut Mixed) -> Self`. Edits write through to a field that may be mixed; an edit makes it concrete. - - `pub fn kept() -> Self`. No caller value: the component keeps it in session memory under its id. + - `pub fn kept() -> Self`. No caller value: the component keeps it in session memory under its id. Until something is stored, it reads - `pub fn saved(mut self, key: SaveKey) -> Self where T: Savable,`. A kept value that is also saved across runs under `key`. The `Savable` bound sits here; the pipeline reaches - `pub fn policy(mut self, policy: EditPolicy) -> Self`. When a write-through source is written. - `pub fn check(mut self, check: impl Fn(&T) -> Validity + 'a) -> Self`. The check on a value: `Fix` replaces it; `Warn`, `Refuse` and `Error` set the component's state, and `Refuse` - - `pub fn reset(mut self, default: T) -> Self`. The value a reset gesture restores. + - `pub fn reset(mut self, default: T) -> Self`. The value a reset gesture restores, and the value a kept binding reads while nothing is stored. - `pub fn reborrowed(&mut self) -> Bind<'_, T>`. A binding with the same source, check, policy and reset that borrows this one, so a composite can hand its + - `pub fn value(&self) -> Option<&T>`. The one value the binding holds before this pass's edits; `None` for a mixed or kept binding. - `pub fn reborrow(&mut self) -> BindMut<'_, T>`. The binding as the pipeline reads and writes it. - `craft_ui::contract::BindMut`: `pub struct BindMut<'a, T>`. A reborrow of a [`Bind`] the pipeline reads at steps 4, 11, 15 and 17. `Component::bind` returns it, and returns the - `pub fn read(&self, cx: &mut impl StageAccess) -> Option>`. The binding's value for code that runs no pipeline step: a given or write-through value, or the kept value @@ -1809,6 +1933,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. @@ -1821,10 +1946,12 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it -- `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]> } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. +- `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. - `pub const fn row() -> Self`. Children side by side from the start edge, with no wrap. - `pub fn grid(columns: impl Into>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass. + - `pub fn fit(self, fit: GridFit) -> Self`. A `Grid` with `fit`; any other layout is unchanged. + - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. @@ -1833,9 +1960,10 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn new() -> Self`. A collapsible body that starts open, animated. - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. -- `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection(SelectionChange), LeadMoved { key: K, by: LeadSource }, Activate(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option

+ Send + Sync + 'static) -> Self`. A row drag carries `map` of it, for the drop targets of type `P`; a row the map gives `None` for does not drag @@ -1878,15 +2006,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

(&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 } } @@ -142,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. @@ -229,9 +245,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, } @@ -324,6 +340,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 { @@ -335,7 +353,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 } @@ -374,15 +392,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 }) } } @@ -408,6 +426,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), } } @@ -419,8 +442,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()); @@ -446,6 +469,7 @@ 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"); @@ -551,6 +575,13 @@ 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); } + 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. 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 }; diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index 06ca1292c..d540e9906 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; @@ -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 = |label: &str| fixture.by_label(label).expect("the panel's icon").rect; + let (brushes, layers, swatches) = (icon("Brushes"), icon("Layers"), icon("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()), ]; From ddd2e23f89aecf5e7a645843fd5219eef0d1681b Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 19:45:04 +0000 Subject: [PATCH 5/7] Collapsed floating windows resize their width A collapsed dock window's sides resize its width, and only its width, within the bounds of a docked collapsed column (DockSizes::iconic_bounds, the one rule both use), on macOS by AppKit and elsewhere by the window's own grips. FloatingGroupOutput::collapsed_width reports the width, which the area keeps as the column's iconic width through the docked column's own path (Action::ResizeIconic); names show from IconicSizes::labels as in a docked column. The height stays the icons', the expanded rect keeps its size and the window keeps its edge. The column in a window has no inner-edge divider: the window's sides size it, as for an expanded column. --- .../ui-contract/src/contract/body/window.rs | 2 +- crates/ui-panels/src/docking/floating.rs | 58 +++++++++++----- .../ui-panels/src/docking/floating/stories.rs | 21 ++++-- crates/ui-panels/src/docking/iconic.rs | 42 +++++++----- crates/ui-panels/src/docking/targets.rs | 13 ++-- crates/ui-patterns/src/patterns/dock/area.rs | 17 +++-- .../tests/it/docking/floating_area.rs | 66 +++++++++++++++++-- crates/ui-patterns/tests/it/docking/native.rs | 51 ++++++++++++++ docs/ui-docking.md | 2 +- 9 files changed, 221 insertions(+), 51 deletions(-) diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index d6ac190c4..7976228fe 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -51,7 +51,7 @@ impl WindowParts { /// 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 cannot be resized (collapsed, minimized), so its +/// 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. diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 034daee21..952ef2d55 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, @@ -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`]). @@ -102,9 +106,12 @@ impl WindowColumn { } /// 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`. + /// 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 { - self.shown(rect, chrome, rtl).map_or(shown, |at| rect.translate(shown.min - at.min)) + 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. @@ -240,6 +254,8 @@ pub struct FloatingGroup<'a> { 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. @@ -285,6 +301,7 @@ impl<'a> FloatingGroup<'a> { chrome: 0.0, rtl: false, placed: None, + collapsed_width: None, start_drag: None, take_drop: None, moving: false, @@ -350,11 +367,13 @@ impl<'a> FloatingGroup<'a> { 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(); - 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())) + 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, self.chrome))).sized_by_caller() @@ -460,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); @@ -505,7 +525,15 @@ 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. + // 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 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 b52dffc8f..d08285730 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -102,7 +102,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>, @@ -179,8 +180,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> { @@ -309,8 +310,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) } @@ -474,7 +475,9 @@ impl Component for IconicColumn<'_, P> { .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); } @@ -509,12 +512,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 @@ -582,10 +587,13 @@ impl Component for IconicColumn<'_, P> { 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. - 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)); + // 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>) { @@ -601,8 +609,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/targets.rs b/crates/ui-panels/src/docking/targets.rs index c04fdc4d7..bc50de89a 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -129,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-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 739891bae..d0b8680d6 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1281,7 +1281,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`]). /// @@ -1342,7 +1344,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 { @@ -1412,7 +1414,9 @@ 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)); } @@ -1422,7 +1426,7 @@ impl Pass<'_, P> { } 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. @@ -1434,6 +1438,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())); diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 11921e944..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}; @@ -428,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_title().y); + 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:?}"); @@ -471,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() { @@ -496,7 +554,7 @@ fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column() 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_title().y); + 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/docs/ui-docking.md b/docs/ui-docking.md index dfcfa9946..a6ab3fd4f 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -122,7 +122,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords ## Floating and native windows -A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. The title row is one text row high (`HeaderStrength::Bar`). A window in the main window keeps a band above it for its top grip (`contract::grip_band`), so the grip never covers the row; an OS window keeps none, and on macOS AppKit resizes it from its own edges, with no app grips there (`DockSizes::window_chrome`). A collapsed window shows its icons against the edge of the float area it keeps to, under a title row of the band and the double arrow alone (a context request on the band opens the window's menu), and keeps its expanded size for when it expands. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the app runs that move (`Overlay::moved_by_app`, which the group's mount carries, so the window is opened knowing it). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). +A floating window is a `Floating` in the layout: its one `column`, its `rect` in logical points in the app's viewport, and `native` and `monitor` while it is an OS window. `FloatingGroup` shows it, with the column inside drawn as a dock column is (`ColumnBar::Window`): the window's title row is the column's bar, whose double arrow, like a double click on the row, collapses the column to icons. The title row is one text row high (`HeaderStrength::Bar`). A window in the main window keeps a band above it for its top grip (`contract::grip_band`), so the grip never covers the row; an OS window keeps none, and on macOS AppKit resizes it from its own edges, with no app grips there (`DockSizes::window_chrome`). A collapsed window shows its icons against the edge of the float area it keeps to, under a title row of the band and the double arrow alone (a context request on the band opens the window's menu), and keeps its expanded size for when it expands. Its sides resize its width, and only its width, within the bounds of a docked collapsed column (`DockSizes::iconic_bounds`), on every platform and in the main window alike; names show beside the icons from `IconicSizes::labels`, and the width is the column's `iconic_width` (`Action::ResizeIconic`, `FloatingGroupOutput::collapsed_width`), kept across collapse and expand. With `DockConfig::native_windows` (on by default), every floating window opens in its own OS window (`docking::native`) where the window host opens OS windows and reports where they are (`WindowHost::positions_reported`; not on Wayland); a window never shown native yet opens over its place in the main window. Elsewhere, and for a panel with `allow_native` off, the window stays inside the main window. The OS close of a native window is its Close action: the window closes when every panel in it may close. Dragging a native window by its title row moves the whole window and docks it where it is released over a group of the main window, as a floating window inside the main window does: the app runs that move (`Overlay::moved_by_app`, which the group's mount carries, so the window is opened knowing it). On macOS the row's press hands the move to the OS, the app follows the system pointer and button (`Caps::OS_MOVES_TRACKED`), and a press that ends within the click distance is a click, which docks nothing; elsewhere the app moves the window, and Escape puts it back. The app sends an OS window its place only when the app changes it (an undo, a reloaded layout); the OS's own moves and resizes are recorded and never sent back. `window_kind` says whether an OS window is a document or a tool window. A tool window's title row is its only title bar, whatever frame the main window has (`craft_window::policy::tool_frame`). A panel or group floated out of the dock (a drag, the Float command, a tab torn out of the window) opens at the width it had docked and at the height its group measures at in a floating window's room (`Proposal::Size`), at most `size.float.height`: content that fills its body opens at that height, other content at its own. A column opens at its docked size, at most that height. The area measures once, where the float starts: for a drag in the pass it starts, which adds the size to the drag's payload (`runtime::drag::amend`). A panel's own `PanelSpec` float size wins, and a window that already floats keeps its size. From a45db600db635064a3e31c9259f8804164bc5f74 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 20:04:01 +0000 Subject: [PATCH 6/7] contract: MOVE_BAND's re-export stays testing-only --- crates/ui-contract/src/contract/body.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 3e76a1e93..078729881 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -33,6 +33,7 @@ pub use regions::pad_of; #[doc(hidden)] pub use reorder::REORDER_BAND; pub use scroll::{STRIP_BACK, STRIP_FORWARD}; +#[cfg(feature = "testing")] pub(crate) use window::MOVE_BAND; use window::WindowMode; pub use window::grip_band; From 6fea865c9a80bdfa6066afe3165df842181d63bc Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 20:31:09 +0000 Subject: [PATCH 7/7] Grip trial: the icon-rect closure is not named like an icon id --- crates/ui-panels/src/docking/iconic/trials.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index d540e9906..3b5519ee9 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -367,8 +367,8 @@ fn a_groups_grip_lies_above_its_icons_and_its_drag_moves_the_group() { 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 = |label: &str| fixture.by_label(label).expect("the panel's icon").rect; - let (brushes, layers, swatches) = (icon("Brushes"), icon("Layers"), icon("Swatches")); + 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");