From fb45d473dfe85cd0c611b580bbf48c44a7671aa1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:42:39 +0000 Subject: [PATCH 01/24] Dock workspace: tabs closed together reopen together (photocraft#15545) When one apply_all batch closes several tabs of a group (Close Tab Group, or a preset that closes panels one at a time), each closed panel's Location records the set in closed_with. Reopening any of them restores the set in group order, each by its own record, with the requested one in front. A tab closed in a batch of its own stays closed: the set only counts members whose records name each other. --- crates/behavior/src/dock/action.rs | 7 +- crates/behavior/src/dock/inner.rs | 2 +- crates/behavior/src/dock/workspace.rs | 110 +++++++++++++++++++++----- crates/behavior/tests/dock_apply.rs | 36 +++++++++ 4 files changed, 133 insertions(+), 22 deletions(-) diff --git a/crates/behavior/src/dock/action.rs b/crates/behavior/src/dock/action.rs index 8075b7bf4..825e63292 100644 --- a/crates/behavior/src/dock/action.rs +++ b/crates/behavior/src/dock/action.rs @@ -93,6 +93,11 @@ pub struct Location

{ /// restoring creates a new group, column, dock or window for the panel. #[serde(default)] pub group: Option, + /// The panels of its group that closed in the same batch of actions, itself included, in group order; empty + /// when it closed alone. Reopening any of them brings back the others that are still hidden and were closed with + /// it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub closed_with: Vec

, } /// Groups, columns and floating windows are named by a panel they contain. @@ -340,7 +345,7 @@ pub enum Action

{ impl

Location

{ /// A location relative to `anchor` by `placement`, with no recorded sizes or siblings. pub fn new(anchor: Option

, placement: DockPlacement

) -> Self { - Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None } + Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None, closed_with: Vec::new() } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index bb620b8f5..93510d78a 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -554,7 +554,7 @@ pub(super) fn group_location(panels: &[P], panel: &P) -> Option(node: &Node

) -> Option<&P> { diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 5aba1f0b5..6f18bf113 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -12,7 +12,7 @@ use super::{ DockSide, action::{Action, DockPlacement, Location}, edit::tree_panels, - groups::{Column, DockEdge, PanelPlace, Target}, + groups::{Column, DockEdge, PanelPlace, Target, Unit}, layout::Layout, limits::MAX_PANELS, node::Node, @@ -163,7 +163,7 @@ impl

Workspace

{ impl Workspace

{ /// Check the version, the layout, that every hidden panel is hidden once and absent - /// from the layout, and that the floated records are bounded and one per panel. + /// from the layout and its record is bounded, and that the floated records are bounded and one per panel. pub fn validate(&self) -> Result<(), DockError> { if self.version > Self::VERSION { return Err(DockError::UnsupportedVersion); @@ -174,10 +174,13 @@ impl Workspace

{ } let visible: HashSet<&P> = self.layout.panels().into_iter().collect(); let mut seen = HashSet::new(); - for (panel, _) in &self.hidden { + for (panel, location) in &self.hidden { if visible.contains(panel) || !seen.insert(panel) { return Err(DockError::DuplicatePanel); } + if location.closed_with.len() > MAX_PANELS { + return Err(DockError::LimitExceeded); + } } if self.floated.len() > MAX_PANELS { return Err(DockError::LimitExceeded); @@ -211,8 +214,11 @@ impl Workspace

{ let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) }; let mut proposed = self.clone(); let mut all_closed = Vec::new(); + // The group of each panel as it closes, in closing order. + let mut closing_groups = Vec::new(); for action in actions { let closed = proposed.layout.closed_by(&action)?; + closing_groups.extend(closed.iter().map(|panel| proposed.layout.members(panel, Unit::Group).unwrap_or_else(|_| vec![panel.clone()]))); let locations = close_locations(&proposed.layout, &closed); let before = proposed.layout.clone(); // Opening a hidden panel puts it back where it was. @@ -240,6 +246,7 @@ impl Workspace

{ proposed.hidden.retain(|(p, _)| !visible.contains(p)); let mut seen = HashSet::new(); all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone())); + proposed.record_closed_together(&all_closed, &closing_groups); proposed.validate()?; let Workspace { layout, hidden, floated, .. } = proposed; (self.layout, self.hidden, self.floated) = (layout, hidden, floated); @@ -248,10 +255,11 @@ impl Workspace

{ } /// Show or hide one panel. Showing restores its recorded location, following the chain of - /// hidden anchors when its own anchor is hidden too; otherwise it opens as - /// [`Action::Open`] with `fallback` as the anchor, following `permissions`. The hidden - /// panels on that chain reopen beside it later, so a group or window closed one panel at a - /// time comes back as one. + /// hidden anchors when its own anchor is hidden too, and brings back the hidden panels of its + /// group that closed with it in one batch (Close Tab Group, a preset) as tabs of its group; + /// otherwise it opens as [`Action::Open`] with `fallback` as the anchor, following + /// `permissions`. The other hidden panels on that chain reopen beside it later, so a group or + /// window closed one panel at a time comes back as one. /// A shown panel becomes the active tab of its group. Hiding follows `permissions` and /// `locked`, as [`Self::apply`] does, so a protected canvas stays shown. pub fn set_visible( @@ -276,29 +284,91 @@ impl Workspace

{ self.apply_all([open, Action::Activate { panel }], locked, permissions).map(drop) } - /// Restore a hidden `panel` to its recorded place and make it the active tab. `Ok(false)` when the record - /// cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace stays - /// as it was and the caller opens the panel by the ordinary, checked path. + /// Restore a hidden `panel` to its recorded place, with the hidden panels closed with it, and make it the + /// active tab. The set is restored in group order, each panel by its own record, so the group comes back in + /// the order it had; a panel closed with it whose place refuses it stays hidden. `Ok(false)` when `panel`'s + /// record cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace + /// stays as it was and the caller opens the panel by the ordinary, checked path. fn reopen(&mut self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Result { - // The restore also rewrites the records of the hidden panels it passed, so it runs on a copy. + let mut restored = self.clone(); + for member in self.closed_together(panel) { + match restored.restored(&member, permissions) { + Some(next) => restored = next, + None if &member == panel => return Ok(false), + None => {} + } + } + restored.layout.apply(Action::Activate { panel: panel.clone() })?; + self.layout = restored.layout; + self.hidden = restored.hidden; + Ok(true) + } + + /// The workspace with the hidden `panel` restored to its recorded place, `None` when the record cannot be + /// restored or the place refuses the panel under `permissions`. The restore also rewrites the records of the + /// hidden panels it passed, so it runs on a copy. + fn restored(&self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Option { let mut trial = self.clone(); let mut layout = self.layout.clone(); - if trial.restore_from_hidden(&mut layout, panel).is_err() { - return Ok(false); - } + trial.restore_from_hidden(&mut layout, panel).ok()?; let allowed = layout .location(panel) .ok() .and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor)))) .unwrap_or(true); if !allowed || layout.breaks_columns_beyond(&self.layout, permissions) { - return Ok(false); + return None; + } + trial.layout = layout; + trial.hidden.retain(|(p, _)| p != panel); + Some(trial) + } + + /// The hidden `panel` and the hidden panels closed with it, in group order: those its record's + /// [`closed_with`](Location::closed_with) names whose own records name it back. A panel that closed again on + /// its own since names it no more. `[panel]` when it closed alone. + fn closed_together(&self, panel: &P) -> Vec

{ + let record = |p: &P| self.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location); + let mut seen = HashSet::new(); + let together: Vec

= record(panel) + .map(|location| &location.closed_with[..]) + .unwrap_or_default() + .iter() + .filter(|&p| p == panel || record(p).is_some_and(|location| location.closed_with.contains(panel))) + .filter(|&p| seen.insert(p)) + .cloned() + .collect(); + if together.len() > 1 && together.contains(panel) { together } else { vec![panel.clone()] } + } + + /// Records on the hidden panels `closed`, which this batch closed, the panels of their group that closed with + /// them. `groups` holds each closing panel's group as it closed, in closing order. The closed panels of one + /// group, or of groups that share one, form one set in the order the groups name them. + fn record_closed_together(&mut self, closed: &[P], groups: &[Vec

]) { + let closed: HashSet<&P> = closed.iter().collect(); + let mut sets: Vec> = Vec::new(); + for group in groups { + let members: Vec<&P> = group.iter().filter(|p| closed.contains(p)).collect(); + let (joined, rest): (Vec>, Vec>) = + std::mem::take(&mut sets).into_iter().partition(|set| set.iter().any(|p| members.contains(&p))); + let mut set: Vec

= joined.into_iter().flatten().collect(); + for panel in members { + if !set.contains(panel) { + set.push(panel.clone()); + } + } + sets = rest; + if !set.is_empty() { + sets.push(set); + } + } + for set in sets.into_iter().filter(|set| set.len() > 1) { + for (panel, location) in &mut self.hidden { + if set.contains(panel) { + location.closed_with.clone_from(&set); + } + } } - layout.apply(Action::Activate { panel: panel.clone() })?; - self.layout = layout; - self.hidden = trial.hidden; - self.hidden.retain(|(p, _)| p != panel); - Ok(true) } /// Update the floated records after an action that turned `before` into the current layout: drop the records of diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index c4461067d..b3bad10d0 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -188,6 +188,42 @@ fn opening_a_closed_floating_panel_restores_its_window_place() { assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]); } +/// The active tab of the dock or floating group holding `panel`. +fn front(layout: &Layout, panel: u32) -> u32 { + *layout.group(&layout.place(&panel).unwrap()).unwrap().active_panel().unwrap() +} + +/// Tabs closed in one batch (one at a time, as a preset does, or by Close Tab Group) come back together with whichever +/// of them reopens, in their order and with that one in front, after a save and a load; a tab closed in a batch of its +/// own stays closed. +#[test] +fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() { + let batches = [vec![Action::close(2), Action::close(3)], vec![Action::close(3), Action::close(2)], vec![Action::close_group(2)]]; + for batch in batches { + for open in [2, 3] { + let mut workspace = Workspace::new(docked()); + workspace.apply_all(batch.clone(), false, allow).unwrap(); + let saved = serde_json::to_string(&workspace).unwrap(); + let mut workspace: Workspace = serde_json::from_str(&saved).unwrap(); + workspace.apply(Action::open(open, None), false, allow).unwrap(); + let layout = workspace.layout(); + assert_eq!(group_members(layout, open), [2, 3], "{batch:?}, then {open} opens"); + assert_eq!(front(layout, open), open, "{batch:?}: the reopened tab is in front"); + assert_eq!(end_dock(layout)[0].groups[0].panels, [2, 3], "{batch:?}: back above 4 in its column"); + assert!(workspace.hidden().is_empty()); + } + } + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(3), false, allow).unwrap(); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(Action::open(2, None), false, allow).unwrap(); + assert_eq!(group_members(workspace.layout(), 2), [2]); + assert!(workspace.layout().place(&3).is_none(), "3 closed on its own stays closed"); + workspace.apply(Action::open(3, None), false, allow).unwrap(); + assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2"); +} + /// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first. #[test] fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { From 212617056557eff5463c0d6ca0ca3d5c20f3aa65 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:48:59 +0000 Subject: [PATCH 02/24] Overlay placement: a context menu that fits neither side covers its anchor (photocraft#15552) PlaceRequest gains covers_anchor. Below or above the anchor, an overlay with it that fits on neither side but fits the bounds keeps the preferred side and its height and slides over the anchor; only one taller than the bounds is capped. The overlay host sets it for a layer hanging from the pointer or from the rect a context request named, so placement's room and the first pass's content room are the cap within the bounds, and the menu shows every row without scroll strips. Dropdowns, menu-bar menus and submenus keep their rule. --- crates/behavior/src/overlay.rs | 40 ++++++++++++++-- .../ui-contract/src/contract/overlay/host.rs | 10 ++-- .../src/contract/overlay/opener.rs | 10 ++++ .../src/contract/overlay/placement.rs | 47 +++++++++++++------ crates/ui-widgets/tests/it/menu/overflow.rs | 41 +++++++++++++++- 5 files changed, 123 insertions(+), 25 deletions(-) diff --git a/crates/behavior/src/overlay.rs b/crates/behavior/src/overlay.rs index 84b75ee02..365078a3b 100644 --- a/crates/behavior/src/overlay.rs +++ b/crates/behavior/src/overlay.rs @@ -97,6 +97,10 @@ pub struct PlaceRequest { /// Beside the anchor, the overlay lines up with the anchor's other end when it runs past the bounds from the /// aligned end and fits from the other, instead of sliding: a submenu of a low row opens upward. pub flips_across: bool, + /// Below or above the anchor, an overlay that fits on neither side but fits the bounds keeps its height and slides + /// over the anchor from the preferred side; only one taller than the bounds is capped. For a context menu, whose + /// anchor is a point or a row. + pub covers_anchor: bool, } impl PlaceRequest { @@ -113,6 +117,7 @@ impl PlaceRequest { bounds, kept: None, flips_across: false, + covers_anchor: false, } } @@ -163,6 +168,12 @@ impl PlaceRequest { self.flips_across = on; self } + + /// Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds. + pub const fn covers_anchor(mut self, on: bool) -> Self { + self.covers_anchor = on; + self + } } /// Where `place` put the overlay. @@ -200,9 +211,10 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 { } /// Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to -/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Beside the anchor, a request that -/// flips across lines up with the anchor's other end when it runs past the bounds from the aligned end and fits from the -/// other. The rect is always finite and inside the bounds. +/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Below or above the anchor, a +/// request that covers its anchor and fits neither side keeps the preferred side and its height up to the bounds' and +/// slides over the anchor. Beside the anchor, a request that flips across lines up with the anchor's other end when it +/// runs past the bounds from the aligned end and fits from the other. The rect is always finite and inside the bounds. pub fn place(request: &PlaceRequest) -> Placement { let anchor = clean(request.anchor); let bounds = clean(request.bounds); @@ -213,12 +225,15 @@ pub fn place(request: &PlaceRequest) -> Placement { let need = if request.side.vertical() { wanted.y } else { wanted.x }; let preferred = room(anchor, bounds, request.side, rtl, gap); let other = room(anchor, bounds, request.side.flipped(), rtl, gap); + let covers = request.covers_anchor && request.side.vertical(); let side = match request.kept { Some(kept) => kept, None if preferred >= need || preferred >= other => request.side, + None if covers && other < need => request.side, None => request.side.flipped(), }; - let available = room(anchor, bounds, side, rtl, gap).max(0.0); + // Covering the anchor, the overlay may take the bounds' height: the shift inside them moves it over the anchor. + let available = if covers { bounds.height() } else { room(anchor, bounds, side, rtl, gap).max(0.0) }; let size = if side.vertical() { Vec2::new(wanted.x.min(bounds.width()), wanted.y.min(available).min(bounds.height())) } else { @@ -275,6 +290,20 @@ mod tests { assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside"); } + #[test] + fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() { + let point = rect(300.0, 400.0, 0.0, 0.0); + let request = PlaceRequest::new(point, Vec2::new(200.0, 450.0), BOUNDS).covers_anchor(true); + let placed = place(&request).rect; + assert_eq!(placed.height(), 450.0, "fits the bounds: its whole height"); + assert!(BOUNDS.contains_rect(placed) && placed.top() < point.top(), "slides up over the point: {placed:?}"); + assert_eq!(place(&request.size(Vec2::new(200.0, 700.0))).rect.height(), BOUNDS.height(), "taller than the bounds: capped"); + let above = place(&request.size(Vec2::new(200.0, 350.0))); + assert!(above.side == Side::Above && above.rect.bottom() == point.top(), "fits above: opens above the point: {above:?}"); + let without = place(&request.covers_anchor(false)); + assert!(without.side == Side::Above && without.rect.height() < 450.0, "without it: capped to the larger side: {without:?}"); + } + #[test] fn an_overlay_at_least_as_wide_as_its_anchor_takes_that_width_below_it_but_not_beside_it() { let field = rect(100.0, 100.0, 300.0, 24.0); @@ -298,7 +327,8 @@ mod tests { .side(side) .align(align) .rtl(i % 2 == 0) - .gap(if i == 1 { 4.0 } else { 0.0 }); + .gap(if i == 1 { 4.0 } else { 0.0 }) + .covers_anchor(align != Align::Start); let placed = place(&request).rect; assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}"); assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}"); diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index a37aa15b5..5d540cd9e 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -3,7 +3,7 @@ use super::dismissal::{dismissal, popup_dismissal}; use super::opener::{Opening, Trigger}; use super::place::{OverlayFit, Place}; -use super::placement::{anchor_rect, opened_overlay, placement}; +use super::placement::{anchor_rect, layer_covers_anchor, opened_overlay, placement}; use super::props::{Outside, Overlay}; use crate::runtime::access::{self}; use crate::runtime::egui::areas::{self, LayerSpec}; @@ -134,6 +134,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U if let Some((_, opening)) = &opened { memory.opening.get_or_insert(*opening); } + let covers = layer_covers_anchor(ctx, layer.overlay, memory.opening); let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), ..*layer }; let overlay = layer.overlay; let bounds = layer.region.map_or_else(|| areas::safe_rect(ctx), |region| region.intersect(areas::safe_rect(ctx))); @@ -155,7 +156,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U Some(size) => Some(egui::vec2(size.x.max(min_width), size.y)), None => areas::layer_rect(ctx, area).map(|rect| rect.size()), }; - let mut placed = placement(ctx, layer, size, bounds, anchor); + let mut placed = placement(ctx, layer, covers, size, bounds, anchor); let nudge = Nudge::of(ctx, layer, appears); if let Some(nudge) = &nudge { placed.at += nudge.offset(); @@ -275,6 +276,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut if let Some((_, opening)) = &opened { memory.opening.get_or_insert(*opening); } + let covers = layer_covers_anchor(ctx, layer.overlay, memory.opening); // The popup window lies outside any region of the opener: the work area is its room. let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer }; let overlay = layer.overlay; @@ -282,7 +284,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut let anchor = anchor_rect(ctx, layer, bounds, &mut memory); let min_width = overlay.least_width(anchor.width()); let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y)); - let unplaced = placement(ctx, layer, measured, bounds, anchor); + let unplaced = placement(ctx, layer, covers, measured, bounds, anchor); let parent = overlay::drawing_parent(ctx); let tier = overlay::layer_tier(ctx, overlay.rank); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); @@ -302,7 +304,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body)); }); let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None)); - let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) }; + let placed = if known.is_some() { unplaced } else { placement(ctx, layer, covers, Some(size), bounds, anchor) }; let rect = Rect::from_min_size(placed.at, size); if known.is_none() { windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2())); diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index d00d8c6fd..fbd2677a5 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -178,6 +178,16 @@ impl crate::runtime::env::EnvValue for LayerFloor { } } +/// Whether a layer opened by `opener` may cover the anchor [`opener_anchor`] gives it: the pointer, or the rect a context +/// request named. Both are a context menu's anchor, a point or a row. +pub(super) fn covers_anchor(opener: &Opener, opening: Opening, place: &Place) -> bool { + match opener_anchor(opener, opening, place) { + Anchor::Pointer => true, + Anchor::Rect(_) => opener.anchor.is_none() && matches!(opening, Opening::At(_)), + _ => false, + } +} + /// The anchor a layer opened by `opener` hangs from: the opener's own, else the layer's `Pointer` or `Corner` /// place, else the pointer for a context request a secondary release made, else the rect a key's context request /// named, else the opener's rect. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 526a2fdda..d8be6a235 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -1,7 +1,7 @@ //! Where a shown layer goes: its anchor, the region and screen it stays in, and the room its body has. use super::host::{Layer, LayerMemory, memory_slot}; -use super::opener::{Opening, opener_anchor}; +use super::opener::{Opening, covers_anchor, opener_anchor}; use super::place::{Anchor, OverlayFit, Place, ViewportShare}; use super::props::Overlay; use crate::runtime::egui::areas::{self}; @@ -51,6 +51,18 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option) -> bool { + match &overlay.opener { + Some(first) => { + let (opener, opening) = first.active(ctx, stored); + covers_anchor(opener, opening, &overlay.place) + } + None => matches!(overlay.place, Place::Anchored { anchor: Anchor::Pointer, .. }), + } +} + /// The opening the layer `id` decided when it appeared, `None` before the host has run for it. fn stored_opening(ctx: &Context, id: Id) -> Option { MemoryStage::peek::(ctx, memory_slot(id)).opening @@ -172,7 +184,9 @@ pub(crate) fn measuring_room( inset: f32, rtl: bool, ) -> Option { - let opened = opened_overlay(ctx, overlay, stored_opening(ctx, id)); + let stored = stored_opening(ctx, id); + let covers = layer_covers_anchor(ctx, overlay, stored); + let opened = opened_overlay(ctx, overlay, stored); let overlay = opened.as_ref().map_or(overlay, |(overlay, _)| overlay); if !matches!(overlay.place, Place::Anchored { .. }) { return None; @@ -183,7 +197,7 @@ pub(crate) fn measuring_room( let bounds = screen_for(ctx, env, overlay); let resolved = resolve_anchor(ctx, id, overlay, own, own_to_screen); let anchor = resolved_anchor(ctx, overlay, resolved, bounds, inset, &mut MemoryStage::peek::(ctx, memory_slot(id)).pointer_at); - Some(content_room(overlay, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl)) + Some(content_room(overlay, covers, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl)) } /// The most a layer's body may take: the fit's share of the safe rect `bounds`, at least as wide as the layer's @@ -198,13 +212,13 @@ fn cap(overlay: &Overlay, bounds: Rect, anchor: Rect) -> egui::Vec2 { } /// The room a layer offers its content before it is placed: the cap (a share of the safe rect `bounds`), and for an -/// anchored layer the cap within the larger side of its anchor along the side's axis, inside `kept` (`kept_in`). -/// Content measured in it fits wherever `placement` puts it: on its preferred side when it fits there, else on the -/// larger side. -pub(crate) fn content_room(overlay: &Overlay, bounds: Rect, kept: Rect, anchor: Rect, rtl: bool) -> egui::Vec2 { +/// anchored layer the cap within the larger side of its anchor along the side's axis, inside `kept` (`kept_in`), or +/// within `kept` for a layer that `covers` its anchor. Content measured in it fits wherever `placement` puts it: on its +/// preferred side when it fits there, else on the larger side, or over the anchor. +pub(crate) fn content_room(overlay: &Overlay, covers: bool, bounds: Rect, kept: Rect, anchor: Rect, rtl: bool) -> egui::Vec2 { let cap = cap(overlay, bounds, anchor); let Place::Anchored { side, .. } = &overlay.place else { return cap.min(bounds.size()) }; - let request = PlaceRequest::new(anchor, cap, kept).side(*side).rtl(rtl).min_width(overlay.min_width); + let request = PlaceRequest::new(anchor, cap, kept).side(*side).rtl(rtl).min_width(overlay.min_width).covers_anchor(covers); let on = |side: Side| craft_behavior::overlay::place(&request.kept(Some(side))).rect.size(); let (vertical, other) = match side { Side::Below => (true, Side::Above), @@ -228,17 +242,18 @@ pub(super) struct Placed { /// The pure placement of the anchored forms; the centre or the given position for floats, kept inside the safe rect /// within the overlay's bounds (`within_bounds`) by the keep rule moves follow. An anchored layer takes its side by its /// size: below its anchor, above when the room below is too short and the room above is larger, and keeps that side -/// while it stays open and the content fits there or that side is the larger. Before its size is known (a popup's -/// first, hidden pass) it takes no side and its body is offered `content_room`, so the size it measures decides the -/// side. -pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option, bounds: Rect, anchor: Rect) -> Placed { +/// while it stays open and the content fits there or that side is the larger. A layer that `covers` its anchor +/// ([`layer_covers_anchor`]) and fits neither side keeps its height within the bounds and slides over the anchor. +/// Before its size is known (a popup's first, hidden pass) it takes no side and its body is offered `content_room`, so +/// the size it measures decides the side. +pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Option, bounds: Rect, anchor: Rect) -> Placed { let rtl = layer.env.direction.is_rtl(); let cap = cap(layer.overlay, bounds, anchor); match &layer.overlay.place { Place::Anchored { side, align, flips_across, .. } => { let kept = layer_bounds(layer, bounds); let Some(size) = size else { - let room = content_room(layer.overlay, bounds, kept, anchor, rtl); + let room = content_room(layer.overlay, covers, bounds, kept, anchor, rtl); return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, room }; }; // The side taken in an earlier pass is the preferred one while the layer stays open: it stays while the @@ -249,9 +264,11 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option (Fixture, Id, egui::Pos2) { + let menu = Rc::new(Cell::new(None)); + let seen = Rc::clone(&menu); + let mut fixture = Fixture::new(move |ui| { + ui.add_space(top); + let target = Button::new("Target").show(ui); + let shown = Menu::context("Target menu", &target).show(ui, |ui, _| { + for at in 0..rows { + MenuItem::new(row(at)).show(ui); + } + }); + seen.set(Some(shown.output.response.id)); + }); + fixture.settle(); + let at = fixture.by_label("Target").expect("the target").center(); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![pointer::secondary(at, true)]); + fixture.frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + (fixture, menu.get().expect("the menu's id"), at) +} + +#[trial] +fn a_context_menu_too_tall_for_either_side_of_the_pointer_covers_it_and_shows_every_row_without_strips() { + let rows = 18; + let (fixture, menu, at) = context_menu(290.0, rows); + let room = fixture.ctx().content_rect(); + let rect = menu_rect(&fixture); + assert!(strips(&fixture, menu).is_none(), "the menu {rect:?} fits the window {room:?}: no strips"); + let (first, last) = (fixture.by_label(&row(0)).expect("the first row").rect, fixture.by_label(&row(rows - 1)).expect("the last row").rect); + let tall = last.bottom() - first.top(); + assert!(tall > at.y - room.top() && tall > room.bottom() - at.y, "the rows ({tall}) fit on neither side of the pointer at {at:?}"); + assert!(room.contains_rect(rect), "the menu {rect:?} stays inside the window {room:?}"); + assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}"); +} + /// A menu of `above` rows over a submenu row whose submenu has `rows` rows, in the fixture's 800 x 600 window. fn low_submenu(above: usize, rows: usize) -> Fixture { let mut fixture = Fixture::new(move |ui| { From 7a6827f5bfde0f97f19e8efede889bb500c50035 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:57:24 +0000 Subject: [PATCH 03/24] Overlay placement: a menu hung at a point also covers its anchor (photocraft#15552) Most context menus hang from Anchor::Point (table header, rulers, ribbon, places, versions, dock group menu). layer_covers_anchor decides every case in one place: the pointer, the rect a context request named, and a point for a layer whose key class is OwnerClass::Menu. Point-anchored layers that are not menus (the iconic flyout, a popover at a point) keep their rule. docs/contract-api.md regenerated. --- .../src/contract/overlay/opener.rs | 10 --- .../src/contract/overlay/placement.rs | 24 +++++-- crates/ui-widgets/tests/it/table.rs | 35 +++++++++- docs/contract-api.md | 64 ++++++++++++++----- 4 files changed, 100 insertions(+), 33 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index fbd2677a5..d00d8c6fd 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -178,16 +178,6 @@ impl crate::runtime::env::EnvValue for LayerFloor { } } -/// Whether a layer opened by `opener` may cover the anchor [`opener_anchor`] gives it: the pointer, or the rect a context -/// request named. Both are a context menu's anchor, a point or a row. -pub(super) fn covers_anchor(opener: &Opener, opening: Opening, place: &Place) -> bool { - match opener_anchor(opener, opening, place) { - Anchor::Pointer => true, - Anchor::Rect(_) => opener.anchor.is_none() && matches!(opening, Opening::At(_)), - _ => false, - } -} - /// The anchor a layer opened by `opener` hangs from: the opener's own, else the layer's `Pointer` or `Corner` /// place, else the pointer for a context request a secondary release made, else the rect a key's context request /// named, else the opener's rect. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index d8be6a235..59602d1bc 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -1,13 +1,14 @@ //! Where a shown layer goes: its anchor, the region and screen it stays in, and the room its body has. use super::host::{Layer, LayerMemory, memory_slot}; -use super::opener::{Opening, covers_anchor, opener_anchor}; +use super::opener::{Opening, opener_anchor}; use super::place::{Anchor, OverlayFit, Place, ViewportShare}; use super::props::Overlay; use crate::runtime::egui::areas::{self}; use crate::runtime::env::Env; use crate::runtime::memory::MemoryStage; use crate::runtime::overlay::{self}; +use craft_behavior::OwnerClass; use craft_behavior::overlay::{PlaceRequest, Side}; use egui::{Context, Id, Pos2, Rect}; @@ -51,15 +52,26 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option) -> bool { - match &overlay.opener { + let (anchor, requested) = match &overlay.opener { Some(first) => { let (opener, opening) = first.active(ctx, stored); - covers_anchor(opener, opening, &overlay.place) + (opener_anchor(opener, opening, &overlay.place), opener.anchor.is_none() && matches!(opening, Opening::At(_))) } - None => matches!(overlay.place, Place::Anchored { anchor: Anchor::Pointer, .. }), + None => match &overlay.place { + Place::Anchored { anchor, .. } => (anchor.clone(), false), + Place::Float(_) => return false, + }, + }; + match anchor { + Anchor::Pointer => true, + Anchor::Point(_) => overlay.keys == OwnerClass::Menu, + // `opener_anchor` gives a requested rect only for a context request's opening. + Anchor::Rect(_) => requested, + _ => false, } } diff --git a/crates/ui-widgets/tests/it/table.rs b/crates/ui-widgets/tests/it/table.rs index 8bb3a2d4d..7db9b8ffd 100644 --- a/crates/ui-widgets/tests/it/table.rs +++ b/crates/ui-widgets/tests/it/table.rs @@ -1,6 +1,7 @@ //! The table's header row and column widths: a double click on a column's edge fits the column to its widest cell in //! view, the header menu hides, shows and resets columns, Ctrl or Cmd with an arrow moves the focused column, and the -//! metadata table's name column follows its widest name up to a third of the table. +//! metadata table's name column follows its widest name up to a third of the table. A header menu too tall for either +//! side of its point covers the point instead of scrolling. use craft_behavior::{ColumnKey, ColumnWidth, keyed}; use craft_host::target::Os; @@ -217,6 +218,38 @@ fn the_header_menu_hides_shows_and_resets_columns() { assert!(menu_row(&fixture, Role::MENU_ITEM, "Move Column Right").is_none(), "with no column there are no column commands"); } +/// The hideable columns of a table whose header menu is taller than the room on either side of the point it opens at. +const EXTRA: [&str; 14] = + ["Kind", "Owner", "Group", "Created", "Modified", "Opened", "Tags", "Rating", "Label", "Path", "Format", "Pixels", "Profile", "Author"]; + +/// A header menu opened at a point mid-window, too tall for the room above or below the point but not for the window, +/// covers the point and shows every row. +#[trial] +fn a_header_menu_too_tall_for_either_side_of_its_point_covers_it_and_shows_every_row() { + let mut fixture = Fixture::new(|ui| { + ui.add_space(270.0); + let mut columns = vec![ColumnSpec::new(NAME, "Name", ColumnWidth::Controls(4.0)).movable()]; + columns.extend(EXTRA.iter().map(|name| ColumnSpec::new(ColumnKey::new(name), *name, ColumnWidth::Controls(2.0)).hideable())); + let keys = [0_usize]; + let source = keyed(&keys, |key: &usize| *key); + Table::new("Files", columns).show_items(ui, &source, &mut |key, icx| ListRow::new(format!("File {key}")).cells(icx.cells())); + }); + fixture.settle(); + let at = fixture.by_label("Name").expect("the header cell").center(); + secondary_click(&mut fixture, at); + let room = fixture.ctx().content_rect(); + let first = menu_row(&fixture, Role::MENU_ITEM_CHECK_BOX, EXTRA[0]).expect("the first column's row").rect; + let last = menu_row(&fixture, Role::MENU_ITEM, "Reset Columns").expect("the last row").rect; + let tall = last.bottom() - first.top(); + assert!(tall > at.y - room.top() && tall > room.bottom() - at.y, "the rows ({tall}) fit on neither side of the point {at:?}"); + let menus = fixture.by_role(Role::MENU); + assert!(!menus.is_empty(), "the header menu is open"); + for menu in menus { + assert!(room.contains_rect(menu.rect), "the menu {:?} stays inside the window {room:?}", menu.rect); + assert!(menu.rect.contains_rect(first) && menu.rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {:?}", menu.rect); + } +} + /// Ctrl or Cmd with Right on a focused movable header moves its column one place on; Right alone moves the focus. /// macOS makes Cmd+Right a move to the line's end, which the header reads the same. #[trial] diff --git a/docs/contract-api.md b/docs/contract-api.md index f5b3b99ef..fd4349515 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -538,11 +538,11 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `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 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 new(id: u64, column: Column

, rect: Rect) -> Self`. The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id + - `pub fn single(id: u64, panels: Vec

, active: usize, rect: Rect) -> Self`. The window `id` with one group. + - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id` in place of its own. Ids must be unique within a layout. - `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 stack(id: u64, groups: Vec>, rect: Rect) -> Option`. The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups. - `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 column, docked or floating. @@ -553,7 +553,9 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `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. - `craft_behavior::dock::Layout`: `pub struct Layout

{ pub root: Option>, pub floating: Vec> }`. The panels of a workspace: a docked tree plus floating windows. Every panel occurs once. - - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. + - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id + - `pub fn fresh_window_id(&mut self) -> u64`. An id for a new floating window: above every window id the layout held when it was built or loaded and every + - `pub fn window_floor(&self) -> u64`. The least id above every id the layout holds or has held. - `pub fn validate(&self) -> Result<(), DockError>`. Check depth, allocation bounds, geometry, selection, globally unique panel ownership and - `pub fn panels(&self) -> Vec<&P>`. Iterate identities without recursion. On excessive input returns no more than the limit. - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. @@ -562,7 +564,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `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. +- `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, pub closed_with: Vec

}`. A closed panel's former placement. Applications may retain this beside visibility flags. - `pub fn new(anchor: Option

, placement: DockPlacement

) -> Self`. A location relative to `anchor` by `placement`, with no recorded sizes or siblings. - `craft_behavior::dock::MAX_DEPTH`: `pub const MAX_DEPTH: usize`. Limits are checked before cloning or recursively modifying an application layout. - `craft_behavior::dock::MAX_PANELS`: `pub const MAX_PANELS: usize`. Most panels a layout may hold. Larger layouts fail with [`DockError::LimitExceeded`](super::DockError::LimitExceeded). @@ -600,10 +602,17 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn new_dock(side: DockEdge) -> Self`. Builds [`Target::NewDock`]. - `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. +- `craft_behavior::dock::Workspace`: `pub struct Workspace

`. 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 version(&self) -> u32`. The format version the workspace was read with. + - `pub fn layout(&self) -> &Layout

`. The current arrangement. + - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. + - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels with the docked location each one left. + - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. + - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. + - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + - `pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool)`. Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. + - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this - `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 - `pub fn apply_all(&mut self, actions: impl IntoIterator>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result, DockError>`. Apply every action in order, or none, as [`Self::apply`] does. Returns the panels the - `craft_behavior::dock::WorkspaceChrome`: `pub struct WorkspaceChrome { pub menu_bar: bool, pub tool_rail: bool, pub options_bar: bool, pub status_bar: bool }`. Chrome a workspace remembers beside the dock layout: which bars show. The default shows every bar. @@ -1375,7 +1384,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `craft_behavior::overlay::Align`: `pub enum Align { Start, Center, End }`. How the overlay lines up with the anchor along the edge it hangs from. - `craft_behavior::overlay::MinWidth`: `pub enum MinWidth { None, Anchor, Points(f32) }`. The narrowest an overlay may be. - `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`, -- `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option, pub flips_across: bool }`. What `place` reads. +- `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option, pub flips_across: bool, pub covers_anchor: bool }`. What `place` reads. - `pub const fn new(anchor: Rect, size: Vec2, bounds: Rect) -> Self`. A request for `size` around `anchor` inside `bounds`: below, aligned to the start, no gap, free width. - `pub const fn size(mut self, size: Vec2) -> Self`. Sets the content size. - `pub const fn side(mut self, side: Side) -> Self`. Sets the preferred side. @@ -1385,6 +1394,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `pub const fn min_width(mut self, min_width: MinWidth) -> Self`. Sets the narrowest width. - `pub const fn kept(mut self, side: Option) -> Self`. Keeps `side` instead of flipping. - `pub const fn flips_across(mut self, on: bool) -> Self`. Lines up with the anchor's other end, beside it, when that fits and the aligned end does not. + - `pub const fn covers_anchor(mut self, on: bool) -> Self`. Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds. - `craft_behavior::overlay::Placement`: `pub struct Placement { pub rect: Rect, pub side: Side }`. Where `place` put the overlay. - `craft_behavior::overlay::Side`: `pub enum Side { Below, Above, Start, End }`. The side of the anchor an overlay prefers. `Start` and `End` follow the reading direction. - `craft_behavior::overlay::place`: `pub fn place(request: &PlaceRequest) -> Placement`. Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to @@ -1955,6 +1965,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn labelled_with(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C, content: D,) -> C::Output`. `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The - `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 derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc`. The value this body derives from `key`: kept while `key` is unchanged, else built by `build` - `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]>, 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. @@ -1964,6 +1975,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `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::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. @@ -1971,7 +1983,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `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), Rested(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

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { // The content is a layout room of its own: the flow of the body around it does not reach in. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); @@ -114,6 +119,9 @@ impl MemoVie } out }); + if let Some(installed) = unbounded { + Env::restore(&ctx, installed); + } match shown { Shown::Ran(out) => Some(out), // A replay at another place moves what the run returned with its record. diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index fd3733682..4c3e1e8e1 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -409,6 +409,21 @@ impl Scoped { self.offered = None; } + /// Starts the layout room of a memoized view's content (`start_room`). A view in a shrinking `Row` is one of the + /// units the row narrows: its content's leaves fit the room the view is given (`Shrink::Fit`). + pub(crate) fn start_view_room(&mut self) { + let fits = self.row_unit(); + self.start_room(); + if fits { + self.shrink = Some(Shrink::Fit); + } + } + + /// Whether a child shown in flow here is a unit of the shrinking `Row` around it. + pub(crate) const fn row_unit(&self) -> bool { + matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))) + } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line @@ -678,9 +693,12 @@ impl Env { Env { scoped: Arc::new(scoped) } } - /// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot. + /// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot. The scope key is + /// computed again by the first view that asks after the edit. pub(crate) fn local_mut(&mut self) -> &mut Scoped { - Arc::make_mut(&mut self.scoped) + let scoped = Arc::make_mut(&mut self.scoped); + scoped.scope_key = std::sync::OnceLock::new(); + scoped } /// This env's container scope on top of `root`, the root env of the viewport the scope now runs in: the scale, diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 19b1b46e3..9edc13020 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -166,7 +166,7 @@ pub(crate) struct Measured { pub(crate) room: Rect, } -/// Where a memoized view ran: it replays only at a place of the same size, layer, layout and environment, and its +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, fit and environment, and its /// record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Place { @@ -182,6 +182,9 @@ pub(crate) struct Place { /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, + /// Whether the view is a unit of the shrinking `Row` around it, so the leaves of its content fit the view's room + /// (`Scoped::start_view_room`). + pub(crate) fits: bool, } /// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room. @@ -211,7 +214,8 @@ impl Place { && now.layout == self.layout && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas - && now.env == self.env; + && now.env == self.env + && now.fits == self.fits; let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed); if !same || !placeable { return None; diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 50e060a8f..c74ef97b5 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -37,7 +37,7 @@ use crate::runtime::words::common::CommonWords; use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, SurfaceLook, TextLook, TypeRole}; use crate::text::TextField; use craft_behavior::fit::{FitItem, FitKeep, fit_items}; -use craft_behavior::{Arrows, Axis, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Roving, Sense}; +use craft_behavior::{Arrows, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Proposal, Roving, Sense}; use craft_host::target::MenuPlacement; use craft_keymap::mnemonic; use craft_theme::Flags; @@ -436,18 +436,15 @@ impl Component for MenuBar<'_> { MenuBarStyle { metrics: Metrics::new() } } - /// Every title's width when the room allows it; the bar fills the row, so what is left over is room for the - /// overflow. + /// Every title's width; at its least (`Proposal::Min`) the width of the "…" title alone. A row that has less room + /// than every title needs narrows the bar, and the titles that no longer fit go into "…". fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { if !Self::in_window(&cx.env) { return Vec2::ZERO; } - let (widths, height, _) = self.widths(cx); - Vec2::new(widths.iter().sum(), height) - } - - fn fills(&self) -> Option { - Some(Axis::X) + let (widths, height, more) = self.widths(cx); + let width = if cx.proposal == Proposal::Min { more } else { widths.iter().sum() }; + Vec2::new(width, height) } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 0c52bb966..e175ecd2d 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -5,7 +5,7 @@ use crate::values::kit::Scrub; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Tracked}; -use craft_ui::display::Text; +use craft_ui::display::{Elide, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey}; use craft_ui::runtime::memory::{SaveKey, set_saved_value}; @@ -1128,3 +1128,48 @@ fn a_view_in_a_content_sized_column_lays_out_its_fill_width_row_as_outside_a_vie assert!(outside.0.width() < outside.1.width(), "the column outside a view is as narrow as its button: {outside:?}"); assert_eq!(inside, outside, "the view's column and its sibling lie as without the view"); } + +#[derive(MemoProps)] +struct Line { + line: String, +} + +/// One line of text cut with an ellipsis where its room is short. +fn line(props: &mut Line, ui: &mut Ui) -> Rect { + Text::new(props.line.clone()).elide(Elide::End).show(ui).rect +} + +/// A memoized view is one unit of the shrinking row around it: with room it is as wide as its content, and when a +/// sibling after it grows it narrows so the row fits, though the region it is offered stays the same. It replays while +/// the row's width for it is unchanged and runs once when that width changes. +#[trial] +fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { + const ROOM: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(310.0, 50.0) }; + let mut frames = Frames::new(); + let frame = |frames: &mut Frames, after: &str| { + let mut rects = (Rect::NOTHING, Rect::NOTHING); + frames.frame(vec![], |ui| { + in_region(ui, ROOM, |ui| { + Row::new().fill_width().show(ui, |ui, _| { + let view = MemoView::new("line", Line { line: "A line of text long enough to be cut".to_owned() }, line).show(ui); + let after = Button::new(after.to_owned()).show(ui).response.rect; + rects = (view.unwrap_or(Rect::NOTHING), after); + }); + }); + }); + rects + }; + for _ in 0..WARM { + frame(&mut frames, "B"); + } + let (wide, _) = frame(&mut frames, "B"); + assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view"); + let (narrow, after) = frame(&mut frames, "A much longer button label"); + assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view"); + assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}"); + assert!(narrow.right() <= after.left() && after.right() <= ROOM.right() + 0.5, "the row fits: {narrow:?}, {after:?} in {ROOM:?}"); + for _ in 0..WARM { + frame(&mut frames, "A much longer button label"); + } + assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again"); +} From df6c100b78803c6f47b39f967770178215e78127 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 09:23:14 +0000 Subject: [PATCH 13/24] Repin egui to storytold/egui next 72cb386ac: a word laid out in room equal to its width keeps its width egui's galley cache rounded a finite wrap width to whole points and then clamped the reported width to it, so "200" (22.47 pt) laid out at 22.47 came back 22.0 and an Info readout row stacked under its label. The fork rounds to GUI_ROUNDING instead. The repin also brings next's two commits ahead of the old pin (AccessKit parent map reader, replayed widgets as used ids). Trials: ui-contract text::band (a word in room equal to its width, Wrap and Elide, at 1x and 2x) and the Info panel trial at G=200, K=44%. --- Cargo.lock | 28 ++++----- Cargo.toml | 28 ++++----- crates/color-ui/tests/it/panels.rs | 6 +- crates/craft/src/egui_fork.rs | 2 +- crates/ui-contract/tests/it/text/band.rs | 75 ++++++++++++++++++++++++ crates/ui-contract/tests/it/text/mod.rs | 1 + 6 files changed, 108 insertions(+), 32 deletions(-) create mode 100644 crates/ui-contract/tests/it/text/band.rs diff --git a/Cargo.lock b/Cargo.lock index add7ab337..39b7cf0f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5449,7 +5449,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "emath", @@ -5505,7 +5505,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5540,7 +5540,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "accesskit", "ahash", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5578,7 +5578,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5598,7 +5598,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "egui", @@ -5611,7 +5611,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "eframe", "egui", @@ -5688,7 +5688,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", ] @@ -5761,7 +5761,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5787,7 +5787,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[package]] name = "equator" @@ -15118,19 +15118,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" diff --git a/Cargo.toml b/Cargo.toml index 984ee25ca..8afdc685c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index a02f696a9..fdd92d03e 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -429,13 +429,13 @@ fn run(fixture: &Fixture, text: &str) -> egui::Rect { #[trial] fn the_info_panel_shows_rgb_and_cmyk_as_two_aligned_columns() { let mut fixture = Fixture::new(|ui| { - let color = craft_color_ui::ui::InfoColor::from_parts([100, 128, 255], [11, 22, 33, 25]); + let color = craft_color_ui::ui::InfoColor::from_parts([10, 200, 30], [1, 22, 33, 44]); let readings = craft_color_ui::ui::InfoReadings::new().color(Some(color)).document(Some([640, 480])); let _ = craft_color_ui::ui::InfoPanel::new("Info", &readings).show(ui); }); fixture.settle(); - let [r, g, b] = ["100", "128", "255"].map(|value| run(&fixture, value)); - let [c, m, y, k] = ["11%", "22%", "33%", "25%"].map(|value| run(&fixture, value)); + let [r, g, b] = ["10", "200", "30"].map(|value| run(&fixture, value)); + let [c, m, y, k] = ["1%", "22%", "33%", "44%"].map(|value| run(&fixture, value)); assert!(c.left() > r.right().max(g.right()).max(b.right()), "CMYK starts right of RGB: {r:?} {c:?}"); assert!(r.left() == g.left() && g.left() == b.left(), "the RGB values share a column"); assert!(c.left() == m.left() && m.left() == y.left() && y.left() == k.left(), "the CMYK values share a column"); diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 32efeff02..acd621c1e 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "6525c87923ca47465aac244460fe4b1139349060"; +pub const REV: &str = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/ui-contract/tests/it/text/band.rs b/crates/ui-contract/tests/it/text/band.rs new file mode 100644 index 000000000..4e99a5730 --- /dev/null +++ b/crates/ui-contract/tests/it/text/band.rs @@ -0,0 +1,75 @@ +//! A run laid out in room equal to its own width. + +use craft_behavior::Sense; +use craft_ui::contract::{Common, Component, Cx, MeasureCx, Props as _, Role, Show as _}; +use craft_ui::primitives::{TextRun, Wrap}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Response, Vec2}; +use std::cell::Cell; +use std::rc::Rc; + +const WORDS: [&str; 9] = ["200", "100", "44%", "40%", "201", "45%", "Hello", "Width", "mm"]; + +/// Lays each word out unbounded and again in room equal to that width, and counts the words whose width is less than +/// half a point past a whole point: the widths a whole-point wrap width would round down. +#[derive(Component)] +struct OwnWidth { + #[common] + common: Common, + below_half: Rc>, +} + +impl Component for OwnWidth { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: OwnWidthStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + let mut below_half = 0; + for word in WORDS { + for wrap in [Wrap::Wrap, Wrap::Elide] { + let run = TextRun::new(word).wrap(wrap); + let whole = cx.layout_at(&run, f32::INFINITY); + let width = whole.size().x; + let fitted = cx.layout_at(&run, width); + assert_eq!(fitted.galley.rows.len(), 1, "{word:?} {wrap:?}"); + assert!(!fitted.elided, "{word:?} {wrap:?}"); + assert_eq!(fitted.size().x, width, "{word:?} {wrap:?}: room equal to its width keeps its width"); + } + let width = cx.layout_at(&TextRun::new(word), f32::INFINITY).size().x; + if width.fract() > 0.0 && width.fract() < 0.5 { + below_half += 1; + } + } + self.below_half.set(below_half); + Vec2::ZERO + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn room_equal_to_its_width_keeps_a_word_whole() { + for pixels_per_point in [1.0, 2.0] { + let below_half = Rc::new(Cell::new(0)); + let output = below_half.clone(); + let mut fixture = Fixture::new(move |ui| { + OwnWidth { common: Common::new(), below_half: output.clone() }.id_salt("own-width").show(ui); + }); + fixture.pixels_per_point(pixels_per_point); + fixture.frame(Vec::new()); + assert!(below_half.get() > 0, "at {pixels_per_point}x some word must be less than half a point past a whole point"); + } +} diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index abda7da2e..c121edcb9 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod band; pub(crate) mod editor; pub(crate) mod input_cap; pub(crate) mod memo; From 8db22341b4bf6fbf1445c5cfa72153d317c93eb3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 14/24] A memoized view in a Stack fits its content to its room, as in a shrinking row; the menu bar folds in any Stack --- crates/menu/README.md | 8 +++-- crates/menu/src/bar.rs | 3 +- crates/menu/tests/it/title_bar.rs | 32 ++++++++++++++++++-- crates/ui-contract/src/contract/lazy.rs | 2 +- crates/ui-contract/src/contract/memo_view.rs | 3 +- crates/ui-contract/src/runtime/env.rs | 14 +++++---- crates/ui-contract/src/runtime/lazy.rs | 4 +-- 7 files changed, 51 insertions(+), 15 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index a654dbcaf..edacb7028 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system. ## Windows, Linux and web: the in-window bar -`MenuBarUi` draws a laid-out bar in a top panel and returns the titles' rect (`MenuBarOutput`). +`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a +`Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold +into "…". Each item is a command row: its enabled state, check mark and chord follow the command in the runtime's command state and keymap, and a choice is a `Fired` with `FireSource::Menu` in the frame's output. `.help_search(true)` starts the Help menu with a search field over every command @@ -141,7 +143,9 @@ frame's output. `.help_search(true)` starts the Help menu with a search field ov ```rust let laid_out = craft_menu::layout(&menu_bar, Target::current(), &LayoutOptions::new("Sample")).bar; egui::Panel::top("menu-bar").show(ui, |ui| { - MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui); + Stack::new().show(ui, |ui, _| { + MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui); + }); }); // The commands chosen arrive in `FrameOutput.fired`. ``` diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 35e8fe9ae..8f40a716c 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -81,7 +81,8 @@ pub struct MenuBarOutput { /// The English-label hook a bar takes by default: none is set, so this type only names the slot. pub type EnglishFn = fn(Labeled<'_>) -> Option; -/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel. +/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top +/// panel's body) or the title bar's row: there it folds the titles that don't fit its room into "…". /// The commands chosen come back through the command queue, not from `show`. /// /// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 9eee46092..1e79bf5c1 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -1,12 +1,15 @@ //! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title -//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". +//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack` +//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. +use std::cell::Cell; use std::rc::Rc; use craft_host::target::{Os, WindowChrome}; use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items}; -use craft_ui::contract::{Role, Show as _, Tracked}; +use craft_ui::contract::{Role, Show as _, ShowContainer as _, Tracked}; use craft_ui::display::Picture; +use craft_ui::layout_components::Stack; use craft_ui::runtime::env::WindowKey; use craft_ui::shell::{AppShell, Caption, CaptionFamily, Captions, Frame, Title, TitleBar}; use craft_ui::testing::{Fixture, trial}; @@ -103,3 +106,28 @@ fn a_narrow_title_bar_folds_the_last_menus_into_more() { assert!(fixture.by_label("Help").is_some(), "{pixels_per_point}x: Help is a row of the \"…\" menu"); } } + +#[trial] +fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_its_edge() { + let bar = Rc::new(model()); + let stack = Rc::new(Cell::new(egui::Rect::NOTHING)); + let seen = Rc::clone(&stack); + let mut fixture = Fixture::new(move |ui| { + let bar = Rc::clone(&bar); + let shown = Stack::new().show(ui, |ui, _| { + MenuBarUi::new(&bar).target(Target::Windows).show(ui); + }); + seen.set(shown.output.rect); + }); + fixture.os(Os::Windows).room(vec2(240.0, 600.0)).settle(); + let shown = titles(&fixture); + assert_eq!(shown.last().map(String::as_str), Some("…"), "{shown:?}"); + assert!(!shown.iter().any(|title| title == "Help"), "Help is not a title: {shown:?}"); + let edge = stack.get().right(); + for run in fixture.texts().iter().filter(|run| MENUS.contains(&run.text.as_str()) || run.text == "…") { + assert!(run.rect.right() <= edge + 0.5, "{:?} at {:?} reaches past the stack's edge {edge}", run.text, run.rect); + } + let more = fixture.by_label("…").expect("the \"…\" title"); + fixture.click(&more).settle(); + assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu"); +} diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index c5d44670b..01d74889f 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -122,7 +122,7 @@ impl Lazy { pixels_per_point: ctx.pixels_per_point(), atlas: ctx.fonts(|fonts| fonts.atlas_generation()), env: Env::of(ui).key, - fits: Env::of(ui).row_unit(), + fits: Env::of(ui).view_fits(), }; if real && memo { crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index a391b8e53..d503b1895 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -53,7 +53,8 @@ use std::sync::Arc; /// cursor) does not reach in, so the room it is given reaches it only through its place. To the body /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its -/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room. +/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room, as they +/// fit the room of a `Stack` the view is shown in. /// /// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept /// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 4c3e1e8e1..891f8abb6 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -409,19 +409,21 @@ impl Scoped { self.offered = None; } - /// Starts the layout room of a memoized view's content (`start_room`). A view in a shrinking `Row` is one of the - /// units the row narrows: its content's leaves fit the room the view is given (`Shrink::Fit`). + /// Starts the layout room of a memoized view's content (`start_room`). Where a leaf shown here would fit its room + /// (`view_fits`), the leaves of the view's content fit the room the view is given (`Shrink::Fit`). pub(crate) fn start_view_room(&mut self) { - let fits = self.row_unit(); + let fits = self.view_fits(); self.start_room(); if fits { self.shrink = Some(Shrink::Fit); } } - /// Whether a child shown in flow here is a unit of the shrinking `Row` around it. - pub(crate) const fn row_unit(&self) -> bool { - matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))) + /// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body, + /// whose leaves show at most its room, and as one of the units a shrinking `Row` narrows. In a `Grid` cell, a + /// wrapping `Row` or a `Ui` with no body around it a leaf keeps its measured width, and so does the view's content. + pub(crate) const fn view_fits(&self) -> bool { + matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_) | Shrink::Fit)) } /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 9edc13020..5aa98cc1d 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -182,8 +182,8 @@ pub(crate) struct Place { /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, - /// Whether the view is a unit of the shrinking `Row` around it, so the leaves of its content fit the view's room - /// (`Scoped::start_view_room`). + /// Whether the leaves of the view's content fit the view's room, as in a `Stack` or a shrinking `Row` + /// (`Scoped::view_fits`). pub(crate) fits: bool, } From 688df999d5563f19023e9422d1631c3fd639b2ce Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 15/24] Layout: a labelled control's row takes its place in flow through place_in_cell, its control on the line --- crates/ui-contract/src/contract/label/step.rs | 180 +++++++++++++----- crates/ui-contract/src/layout/body.rs | 40 +--- crates/ui-contract/src/layout/mod.rs | 6 +- crates/ui-widgets/tests/it/layout/row_line.rs | 52 ++++- 4 files changed, 191 insertions(+), 87 deletions(-) diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index 2ec5f5a0a..e9126f28b 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -110,55 +110,124 @@ impl LeafPlaced { } } -/// The label step for one leaf child: measures the child's narrowest width, runs the step in `row` with the -/// `trailing` content inside the label and returns the rect left for the child. The caller shows the child there and -/// then calls `LeafPlaced::finish`. -pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { - let scope = sub(at.id, "field"); - let enabled = at.under.enabled; +/// The label step for one leaf child, decided: measures the child's narrowest width and decides where the label, with +/// content of `trailing` size inside it, and the child sit in `at.row`. Nothing shows and no room is taken; `show_leaf` +/// then shows the label where the row's place in flow puts it, and the caller shows the child at the control's rect +/// and calls `LeafPlaced::finish`. +pub(crate) fn decide_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided { // Read before the child measures: nothing it does there may count as a child placed in flow. let in_column = in_column(ui); let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; - let input = LabelIn { - scope, + let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER }; + decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing)) +} + +/// Shows the label of a leaf child's step `decided` for `at`, moved down by `down`, with the `trailing` content inside +/// it, and returns the rect left for the child. +pub(crate) fn show_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, decided: Decided, down: f32, trailing: Option>) -> LeafPlaced { + let size = trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size); + let input = leaf_input(env, at, at.row.translate(Vec2::new(0.0, down)), decided.facts, size); + let placed = show(ui, env, &input, decided.moved(down), trailing); + LeafPlaced { control: placed.control, label: placed.label, scope: input.scope } +} + +/// What a label step reads of its control before it decides. +#[derive(Clone, Copy)] +struct LeafFacts { + control_min: f32, + in_column: bool, + claims: bool, +} + +/// The step's input for the leaf child of `at` in `row`, with content of `trailing` size inside the label. +fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, trailing: Vec2) -> LabelIn<'a> { + LabelIn { + scope: sub(at.id, "field"), owner: at.owner, parent: at.parent, - row: at.row, - room: at.row.width(), + row, + room: row.width(), content_row: env.content.0, text: at.text, side: at.side, help: None, - enabled, + enabled: at.under.enabled, size: at.under.size, - control_min, + control_min: facts.control_min, leaf: true, - in_column, - claims: C::LABELLED_AFTER, + in_column: facts.in_column, + claims: facts.claims, status: false, - trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size), - }; - let placed = run(ui, env, &input, trailing); - LeafPlaced { control: placed.control, label: placed.label, scope } + trailing, + } +} + +/// The label step for one leaf child in `at.row`, decided and shown where it was decided: returns the rect left for +/// the child. The caller shows the child there and then calls `LeafPlaced::finish`. +pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { + let decided = decide_leaf(ui, env, at, child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); + show_leaf(ui, env, at, decided, 0.0, trailing) } /// Runs the label step in `ui`: shows the label and the `trailing` content inside it (`input.trailing` is its size), /// opens the label scope and returns where the label and the control sit. The caller closes the scope with /// `scope::finish` after the control ran. pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option>) -> Placed { + let decided = decide_step(ui, env, input); + show(ui, env, input, decided, trailing) +} + +/// The label step decided for a row, before anything shows: where the label and the control sit, and the label leaf +/// measured in the child `Ui` it shows in. +pub(crate) struct Decided { + placed: Placed, + /// `None` for a label that shows no leaf. + leaf: Option, + /// What the step read of its control. + facts: LeafFacts, +} + +struct DecidedLeaf { + leaf: LabelLeaf, + kids: Ui, + installed: crate::runtime::env::Installed, + reset: Option, +} + +impl Decided { + /// The rect left for the control. + pub(crate) fn control(&self) -> Rect { + self.placed.control + } + + /// The label's rect; `Rect::NOTHING` for a hidden label. + pub(crate) fn label(&self) -> Rect { + self.placed.label + } + + /// The step moved down by `down`, as the row's place in flow moves it. + fn moved(mut self, down: f32) -> Self { + let by = Vec2::new(0.0, down); + self.placed.label = self.placed.label.translate(by); + self.placed.control = self.placed.control.translate(by); + self.placed.trailing = self.placed.trailing.translate(by); + self + } +} + +/// Decides the label step for `input`: measures the label in the child `Ui` it shows in and places it and the control +/// in `input.row`. Nothing shows. +fn decide_step(ui: &mut Ui, env: &Env, input: &LabelIn<'_>) -> Decided { let ctx = ui.ctx().clone(); let rtl = env.direction.is_rtl(); - let tokens = &env.tokens; - let (gap, slot_side) = (label_gap(env), tokens.size.handle.sm); + let (gap, slot_side) = (label_gap(env), env.tokens.size.handle.sm); let reset = scope::last_reset(&ctx, input.scope); let flow = Flow::new(input.row, rtl); - let label_id = sub(input.scope, "label"); let content = input.trailing.x > 0.0; + let facts = LeafFacts { control_min: input.control_min, in_column: input.in_column, claims: input.claims }; if input.side.shows_no_leaf(content) { - scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING))); let control = hidden_control(&ctx, input, flow, gap); - scope::place_controls(&ctx, input.scope, control.top()); - return Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 }; + return Decided { placed: Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 }, leaf: None, facts }; } let slot = if reset.is_some() && input.side.reset_dot { slot_side } else { 0.0 }; let mut leaf = LabelLeaf::new(input.side.kind.shown(input.text).clone(), slot); @@ -192,24 +261,41 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< Some(parent) => access::with_parent(builder, parent), None => builder, }; - let mut kids = alloc::child(ui, builder); + let kids = alloc::child(ui, builder); let kid_env = crate::contract::cx::child_env(env, &Under::new(input.enabled, input.size)); let installed = Env::install_for(&kids, kid_env); let glyph = leaf.glyph.is_some(); let mut placed = decide(&ctx, env, input, &kids, &mut leaf, glyph, flow); - // The label without its reset dot, which keeps its own press; the content sits at its end, on the first line. - let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot); if input.trailing.x > 0.0 { + // The label without its reset dot, which keeps its own press; the content sits at its end, on the first line. + let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot); let cell = unslotted.take_end(input.trailing.x).0; let middle = cell.top() + leaf.first_line.get() / 2.0; placed.trailing = Rect::from_min_size(egui::pos2(cell.min.x, middle - input.trailing.y / 2.0), input.trailing); } - let label_id_for_scope = sub(input.scope, "label"); + Decided { placed, leaf: Some(DecidedLeaf { leaf, kids, installed, reset }), facts } +} + +/// Shows the label step `decided` for `input`: the label and the `trailing` content inside it, and opens the label +/// scope. Returns where the label and the control sit. +fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: Option>) -> Placed { + let ctx = ui.ctx().clone(); + let rtl = env.direction.is_rtl(); + let label_id = sub(input.scope, "label"); + let Decided { placed, leaf, .. } = decided; + let Some(DecidedLeaf { leaf, mut kids, installed, reset }) = leaf else { + scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING))); + scope::place_controls(&ctx, input.scope, placed.control.top()); + return placed; + }; + let slot = if reset.is_some() && input.side.reset_dot { env.tokens.size.handle.sm } else { 0.0 }; + // The label without its reset dot, which keeps its own press. + let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot); // A label shows with the control it names: where a bar's view shows the two only in part, neither shows. if crate::contract::run::cut_by_bar_view(env, placed.label.union(placed.control)) { kids.set_clip_rect(Rect::NOTHING); } - let shown = Props::id(leaf, label_id_for_scope).show_at(&mut kids, placed.label); + let shown = Props::id(leaf, label_id).show_at(&mut kids, placed.label); Env::restore(&ctx, installed); if let Some(fact) = reset.filter(|_| shown.double_click || shown.dot_click) { keys::route_whole_reset(&ctx, fact.control); @@ -219,8 +305,7 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< if let Some(trailing) = trailing { (trailing.show)(ui, placed.trailing); } - let label = - field_label(env, input, label_id_for_scope, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated); + let label = field_label(env, input, label_id, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated); scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label)); scope::place_controls(&ctx, input.scope, placed.control.top()); if input.claims { @@ -302,30 +387,36 @@ fn flow_leaf_row( region if in_cell => Rect::from_min_size(region.min, Vec2::new(flow.width(), region.height())), _ => flow, }; - // The child's own height: a stacked label pushes the control down, and the allocation below follows the placement. - // The row spans the room's own edges: a room that scrolls along x is unbounded at its start edge, the left one - // under RTL. - // Outside a grid's cell the row sits on the line of the flow around it, as a control without a label after it does. - let (above, taken) = if in_cell { (0.0, 0.0) } else { crate::layout::labelled_above(ui, avail.height(), ideal.y) }; - let row = Rect::from_min_max(egui::pos2(avail.min.x, avail.min.y + above), egui::pos2(avail.max.x, avail.min.y + above + ideal.y)); + // The label step decides where the label and the control sit at the flow's top, and the row then takes its place + // in flow as any other child does: its control's line is the row's line, on a row's or bracket's line, centred in a + // grid's cell or a horizontal layout. The row spans the room's own edges: a room that scrolls along x is unbounded + // at its start edge, the left one under RTL. + let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y)); let at = LeafLabel { id, owner, parent: None, row, text: &label, side: &side, under: &under }; - let placed = leaf(ui, &env, &at, &mut child, trailing); + let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); // In a column that sizes from its content the row is the label plus the control, never the room around them. // A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded. // So is a grid's cell: the room before it is the whole grid's, and a row spanning it measures its column as wide // as the grid, so the grid could never set two such cells beside each other (two columns of check boxes). let content = env.content.0 || ui.layout().is_horizontal() || in_cell; - let control_width = if content { placed.control.width().min(ideal.x) } else { placed.control.width() }; + let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() }; let rtl = env.direction.is_rtl(); - let cell = Rect::from_min_max(placed.control.min, egui::pos2(placed.control.max.x, placed.control.min.y + ideal.y)); - let control = Flow::new(cell, rtl).span(0.0, control_width); + let span = |cell: Rect| Flow::new(Rect::from_min_size(cell.min, Vec2::new(cell.width(), ideal.y)), rtl).span(0.0, control_width); + let (decided_control, decided_label) = (span(decided.control()), decided.label()); let extent = if !content { avail.width() } else if rtl { - avail.max.x - control.min.x.min(placed.label.min.x) + avail.max.x - decided_control.min.x.min(decided_label.min.x) } else { - control.max.x.max(placed.label.max.x) - avail.min.x + decided_control.max.x.max(decided_label.max.x) - avail.min.x }; + // The child's own height: a stacked label pushes the control down, and a label taller than the control reaches + // below it. + let height = (decided_control.bottom().max(decided_label.bottom()) - row.top()).max(ideal.y); + let first = decided_control.top() - row.top() + ideal.y / 2.0; + let took = crate::layout::place_in_cell(ui, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true }); + let placed = show_leaf(ui, &env, &at, decided, took.top() - row.top(), trailing); + let control = span(placed.control); // A control beside its label in a content-sized column reports how far it reaches past the label column, so // the column's container measures its rows at the widest label. if content && ui.is_sizing_pass() && side.layout == FieldLayout::Beside && placed.label.bottom() > placed.control.top() { @@ -355,10 +446,7 @@ fn flow_leaf_row( if let Some(installed) = installed { Env::restore(ui.ctx(), installed); } - let bottom = control.bottom().max(placed.label.bottom()); placed.finish(ui.ctx()); - // The grid's cursor takes the row as its next cell (outside a grid, the next allocation of `ui`'s layout). - let _ = crate::layout::take_in_flow(ui, Vec2::new(extent, (bottom - row.top()).max(ideal.y) + taken)); output } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index b1d4f3974..de1ac5bc8 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1155,8 +1155,9 @@ pub(crate) struct InFlow { /// rows run along Y, or a container whose first child is one. The child is one line when that centre lies at /// half its height (`one_line`). pub first: Option, - /// `first` is the line of the child's own unwrapped `Row` body: the child sits on a row's line by it even when it - /// is more than one line (a nested row with a child of two lines). + /// `first` is the line of the child's own unwrapped `Row` body, or of the control of a labelled control's row: the + /// child sits on a row's line by it even when it is more than one line (a nested row with a child of two lines, a + /// check box whose label has a detail line under it, a control under its label). pub line: bool, } @@ -1171,37 +1172,6 @@ fn one_line(first: Option, height: f32) -> Option { first.filter(|first| (2.0 * first - height).abs() <= ONE_LINE_SLACK) } -/// The offset of a child whose first line is `first` below its top, on the row line whose centre is `centre` below -/// the flow's top: its first line's centre lands on the line. -fn centre_on_line(centre: f32, first: f32) -> f32 { - (centre - first).max(0.0) -} - -/// The offset of a child in `spare` room left over beside it: half of it. -fn centred(spare: f32) -> f32 { - spare.max(0.0) / 2.0 -} - -/// Where a labelled control's row of `height` sits below the top of the flow, as `place_in_cell` places any other -/// one-line child: `(offset, taken)`. On the line of the unwrapped `Row` around it the row's centre is on the line, and -/// it takes the offset with its height, as the line does. Else, in a horizontal layout that does not wrap, it is -/// centred in `room`, the flow's height, and takes only its height, so a tall room does not make the row taller. -/// Anywhere else it sits at the top. An options bar shown in a slot shorter than it asks for centres its members this -/// way; without it a check box with its label after it stood at the bar's top edge while the fields beside it sat on -/// the bar's middle. -pub(crate) fn labelled_above(ui: &Ui, room: f32, height: f32) -> (f32, f32) { - let env = Env::of(ui); - let layout = ui.layout(); - match env.row_line.and_then(|line| line.centre) { - Some(centre) => { - let above = centre_on_line(centre, height / 2.0); - (above, above) - } - None if layout.is_horizontal() && !layout.main_wrap && !env.grid_top && room.is_finite() => (centred(room - height), 0.0), - None => (0.0, 0.0), - } -} - /// The rect a child of measured `size` takes in flow in `ui`: the next cell of the `Grid` or spread `Row` body that /// encloses it directly, else the next allocation of `ui`'s layout. A direct child of an unwrapped `Row` that is one /// line sits with its centre on the row's line; a child of more than one line (a column, a field with a help line) @@ -1226,7 +1196,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top()))) }); let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); - let above = centre.zip(child.first).map_or(0.0, |(centre, first)| centre_on_line(centre, first)); + let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); let (rect, in_cell) = take_in(ui, &env, slot); let placed = if child.fill && in_cell { @@ -1236,7 +1206,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { Some(_) => (above, (rect.height() - above - size.y).max(0.0)), None => { let spare = (rect.height() - size.y).max(0.0); - if env.grid_top { (0.0, spare) } else { (centred(spare), spare / 2.0) } + if env.grid_top { (0.0, spare) } else { (spare / 2.0, spare / 2.0) } } }; Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 6a499e060..b5fbb0c2e 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -25,7 +25,7 @@ pub use body::place_in_flow; pub(crate) use body::run_body; pub(crate) use body::{ BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, - flow_room, flow_start, grid_cell, in_grid_content_column, labelled_above, leaf_fill_room, members_line, open_first_lines, place_in_cell, - report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, - take_cell, take_in_flow, view_room, + flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, + report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, + view_room, }; diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 538ff2eff..9ba63754d 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,15 +1,20 @@ //! The row line: a child of an unwrapped row that is one line sits with its centre on the row's line; a child of more -//! than one line (a column, a field with its label above or a help line below) sits at the row's top. +//! than one line (a column, a field with its label above or a help line below) sits at the row's top. A control with +//! its label after it sits on the line by its control, as a bare control does, in a row and in a grid's cell. +use craft_behavior::ColumnWidth; use craft_theme::ControlSize; use craft_ui::buttons::Button; -use craft_ui::contract::{FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::Text; use craft_ui::form::{Field, Help}; -use craft_ui::layout_components::{Row, Stack}; +use craft_ui::layout_components::{Grid, Row, Stack}; use craft_ui::runtime::env::Label; use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial}; use egui::Rect; +use std::cell::Cell; +use std::rc::Rc; /// Half a pixel at the scales the box runs. const ROUNDING: f32 = 0.5; @@ -118,3 +123,44 @@ fn a_field_labelled_above_sits_at_the_rows_top() { assert!(caption.bottom() < control.top(), "the label sits above its control"); assert!(button.center().y < control.top(), "the button {button:?} sits level with the label, above the control {control:?}"); } + +/// A check box whose label runs to a second line under it, beside a button in a row: its box sits on the button's +/// line and the label's second line hangs below. In a grid's cell, beside a taller cell, a check box with its label +/// after it sits on the line of the button in the next cell. +#[trial] +fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_cell() { + const LONG: &str = "Smooth the edges of every selection the tool makes"; + for grid in [false, true] { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(260.0, 400.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + if grid { + Grid::new(&[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + Text::new("A").show(ui); + Text::new("B").show(ui); + }); + let button = Button::new("Go").show(ui).rect; + let check = Checkbox::new(Bind::given(true)).label("Snap").show(ui).response.rect; + out.set((button, check)); + }); + } else { + Row::new().show(ui, |ui, _| { + let button = Button::new("Go").show(ui).rect; + let check = Checkbox::new(Bind::given(true)).label(LONG).show(ui).response.rect; + out.set((button, check)); + }); + } + }); + }); + let (button, check) = seen.get(); + let at = if grid { "in a grid's cell" } else { "in a row" }; + if !grid { + assert!(text(&fixture, LONG).bottom() > check.bottom() + ROUNDING, "the label runs to a second line under the box {check:?}"); + } + assert!((button.center().y - check.center().y).abs() <= ROUNDING, "{at}: the box {check:?} sits on the button's line {button:?}"); + } +} From 75e8e49ef58c2b41282bf3e05a768ec4b1ab0537 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 16/24] Overlay placement: only a menu's layer covers its anchor --- .../src/contract/overlay/placement.rs | 12 +++-- crates/ui-widgets/tests/it/menu/overflow.rs | 47 +++++++++++++++++-- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 59602d1bc..47ca407e0 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -52,10 +52,13 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option) -> bool { + if overlay.keys != OwnerClass::Menu { + return false; + } let (anchor, requested) = match &overlay.opener { Some(first) => { let (opener, opening) = first.active(ctx, stored); @@ -67,8 +70,7 @@ pub(super) fn layer_covers_anchor(ctx: &Context, overlay: &Overlay, stored: Opti }, }; match anchor { - Anchor::Pointer => true, - Anchor::Point(_) => overlay.keys == OwnerClass::Menu, + Anchor::Pointer | Anchor::Point(_) => true, // `opener_anchor` gives a requested rect only for a context request's opening. Anchor::Rect(_) => requested, _ => false, diff --git a/crates/ui-widgets/tests/it/menu/overflow.rs b/crates/ui-widgets/tests/it/menu/overflow.rs index 66a4fe8a1..2cbd656e9 100644 --- a/crates/ui-widgets/tests/it/menu/overflow.rs +++ b/crates/ui-widgets/tests/it/menu/overflow.rs @@ -1,11 +1,12 @@ //! A menu taller than its room: it stays inside the room at the width of its rows, scrolls by the strips above and //! below its rows and by the wheel, and reopens at its first row; one that fits shows no strips. A tall submenu of a -//! low row opens upward. A context menu that fits on neither side of the pointer but fits the window covers the -//! pointer instead of scrolling. +//! low row opens upward. A context menu that fits on neither side of the pointer, or of the control a key asked it +//! for, but fits the window covers its anchor instead of scrolling; a tooltip at the pointer never covers the pointer. use craft_host::target::Os; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Entry, Role, STRIP_BACK, STRIP_FORWARD, Show as _, ShowContainer as _, Trigger}; +use craft_ui::contract::tooltip::DELAY; +use craft_ui::contract::{Bind, Entry, Props as _, Role, STRIP_BACK, STRIP_FORWARD, Show as _, ShowContainer as _, TooltipAt, TooltipSpec, Trigger}; use craft_ui::menu::bar::{MenuBar, MenuTitle}; use craft_ui::menu::{Menu, MenuItem}; use craft_ui::pickers::Select; @@ -147,6 +148,46 @@ fn a_context_menu_too_tall_for_either_side_of_the_pointer_covers_it_and_shows_ev assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}"); } +/// The same menu asked for with Shift+F10 on the focused target: it hangs from the target's rect, which it covers. +#[trial] +fn a_context_menu_a_key_asked_for_covers_its_target_when_it_fits_neither_side() { + let rows = 18; + let (mut fixture, menu, _) = context_menu(290.0, rows); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert!(fixture.by_role(Role::MENU).is_empty(), "Escape closes the menu the pointer opened"); + let target = fixture.by_label("Target").expect("the target").rect; + fixture.key(Key::Tab, Modifiers::NONE); + fixture.key(Key::F10, Modifiers::SHIFT).settle(); + let room = fixture.ctx().content_rect(); + let rect = menu_rect(&fixture); + assert!(strips(&fixture, menu).is_none(), "the menu {rect:?} fits the window {room:?}: no strips"); + let (first, last) = (fixture.by_label(&row(0)).expect("the first row").rect, fixture.by_label(&row(rows - 1)).expect("the last row").rect); + assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}"); + assert!(rect.intersects(target), "the menu {rect:?} covers its target {target:?}"); +} + +/// A tooltip at the pointer too tall for either side of it stays off the pointer: it opens on its preferred side, +/// below, where the room is larger, and does not slide up over the pointer as a menu does. +#[trial] +fn a_tooltip_at_the_pointer_too_tall_for_either_side_does_not_cover_the_pointer() { + let text = (0..40).map(|line| format!("Line {line}")).collect::>().join("\n"); + let mut fixture = Fixture::new(move |ui| { + ui.add_space(200.0); + Button::new("Target").tooltip(TooltipSpec::new(text.clone()).at(TooltipAt::Pointer)).show(ui); + }); + fixture.settle(); + let at = fixture.by_label("Target").expect("the target").center(); + fixture.frame(vec![pointer::moved(at)]); + fixture.advance(DELAY); + fixture.settle(); + let tips = fixture.by_role(Role::TOOLTIP); + let tip = tips.first().expect("the tooltip shows").rect; + let room = fixture.ctx().content_rect(); + let lines = fixture.texts().iter().filter(|run| run.text.starts_with("Line ")).fold(Rect::NOTHING, |all, run| all.union(run.rect)); + assert!(lines.height() > at.y - room.top() && lines.height() > room.bottom() - at.y, "the text ({lines:?}) fits on neither side of {at:?}"); + assert!(tip.top() >= at.y, "the tooltip {tip:?} opens below the pointer at {at:?} and does not cover it"); +} + /// A menu of `above` rows over a submenu row whose submenu has `rows` rows, in the fixture's 800 x 600 window. fn low_submenu(above: usize, rows: usize) -> Fixture { let mut fixture = Fixture::new(move |ui| { From 8983476f09e6bde4c6d040d3e3c201310eeed601 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 17/24] Memo trial: a view in a shrinking row runs at most once per measuring sweep of the row --- crates/ui-widgets/tests/it/body/memo_view.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index e175ecd2d..ad0671faa 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -1164,6 +1164,7 @@ fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { } let (wide, _) = frame(&mut frames, "B"); assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view"); + assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "an idle frame runs the view at most once per measuring sweep of the row"); let (narrow, after) = frame(&mut frames, "A much longer button label"); assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view"); assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}"); @@ -1172,4 +1173,18 @@ fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { frame(&mut frames, "A much longer button label"); } assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again"); + assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "at the same width the view runs at most once per measuring sweep of the row"); +} + +/// The sweeps of a shrinking row's measuring run that show its units: the counting sweep and, for a short row, the +/// sweep that asks its body units for their least. Until FW-310 moves `unbounded` out of the scope key, the counting +/// sweep's call keys apart from the real call's and a memoized unit runs in each sweep; FW-310 tightens this to none. +const SWEEPS: usize = 2; + +/// How many times the views named `name` ran in the last frame outside the real run of its last pass: in sizing and +/// measuring runs. +fn measuring_runs_of(frames: &Frames, name: &str) -> usize { + let ran = + |runs: Vec<(&'static str, egui::Id, MemoRun)>| runs.into_iter().filter(|(of, _, run)| of.contains(name) && *run == MemoRun::Ran).count(); + ran(last_frame_memo_runs(&frames.ctx)) - ran(last_pass_memo_runs(&frames.ctx)) } From 69ed953094d249f2dc769bf25a16ebe6350d0da5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 18/24] Preferences: host-labelled rows show their rule's help and follow its enabled state --- .../src/patterns/preferences/rows.rs | 8 ++++- .../ui-patterns/tests/it/preferences/page.rs | 35 +++++++++++++++++++ crates/ui-widgets/src/form/field.rs | 18 +++++++--- 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/ui-patterns/src/patterns/preferences/rows.rs b/crates/ui-patterns/src/patterns/preferences/rows.rs index 46d5c5d62..bc03be521 100644 --- a/crates/ui-patterns/src/patterns/preferences/rows.rs +++ b/crates/ui-patterns/src/patterns/preferences/rows.rs @@ -179,7 +179,13 @@ pub(super) fn show_row(ui: &mut Ui, host: &mut H, } } Kind::CustomRows => { - Stack::new().id_salt(key).show(ui, |ui, _| host.custom_row(ui, key)); + // The host draws the rows and their labels; the rule's enabled state and help apply to them as to a field. + Stack::new().id_salt(key).enabled(row.enabled).show(ui, |ui, _| { + host.custom_row(ui, key); + if let Some(help) = &row.help { + Help::Text(help.clone()).show(ui); + } + }); } Kind::Custom => { field().show(ui, |ui, _| { diff --git a/crates/ui-patterns/tests/it/preferences/page.rs b/crates/ui-patterns/tests/it/preferences/page.rs index edf044554..bc3759740 100644 --- a/crates/ui-patterns/tests/it/preferences/page.rs +++ b/crates/ui-patterns/tests/it/preferences/page.rs @@ -1,5 +1,6 @@ //! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in. +use craft_ui::buttons::Button; use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _}; use craft_ui::display::Text; use craft_ui::form::Field; @@ -141,3 +142,37 @@ fn a_host_labelled_custom_row_shows_its_label_once() { let fields = tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some("Hosted") && tree.role_of(*key) == Some(Role::GROUP)).count(); assert_eq!(fields, 1, "the host's field is the row's only labelled group"); } + +/// A disabled host-labelled row with help: the host draws a button. +struct HelpedRows; + +impl PreferencesModel for HelpedRows { + fn pages(&self) -> Vec> { + let row = RowSpec::new("general.host", "Hosted", RowKind::CustomRows).help("Drawn with its note").enabled(false); + vec![PageSpec::new("general", "General", vec![row])] + } + + fn set(&mut self, _: &str, _: PrefValue) {} + + fn custom_row(&mut self, ui: &mut Ui, _: &str) { + Button::new("Hosted button").show(ui); + } + + fn custom_page(&mut self, _: &mut Ui, _: &str) {} + + fn reset_page(&mut self, _: &str) {} +} + +/// The rule's help shows under the rows the host draws, and a disabled rule disables them. +#[trial] +fn a_host_labelled_row_shows_its_rules_help_and_follows_its_enabled_state() { + let mut state = PreferencesState::default(); + let mut fixture = Fixture::new(move |ui| { + PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut HelpedRows); + }); + fixture.settle(); + let button = fixture.by_label("Hosted button").expect("the host's button"); + let help = fixture.texts().iter().find(|run| run.text == "Drawn with its note").map(|run| run.rect).expect("the help shows"); + assert!(help.top() >= button.rect.bottom(), "the help {help:?} sits under the host's rows {:?}", button.rect); + assert!(fixture.tree().is_disabled_key(button.node), "the disabled rule disables the host's button"); +} diff --git a/crates/ui-widgets/src/form/field.rs b/crates/ui-widgets/src/form/field.rs index 5f634c2fd..dee769d3d 100644 --- a/crates/ui-widgets/src/form/field.rs +++ b/crates/ui-widgets/src/form/field.rs @@ -21,6 +21,16 @@ pub enum Help { Status(Tone, Label), } +impl Help { + /// Shows the help line as a field shows it under its control. + pub fn show(&self, ui: &mut Ui) { + match self { + Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui), + Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui), + }; + } +} + /// The style of a field: no look of its own; the label step and the help line carry it. #[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] #[non_exhaustive] @@ -116,10 +126,8 @@ impl Container for Field { Text::new(message.text.clone()).role(TypeRole::Caption).tone(tone).show(ui); return; } - match &self.help { - Some(Help::Text(text)) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui), - Some(Help::Status(tone, text)) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui), - None => return, - }; + if let Some(help) = &self.help { + help.show(ui); + } } } From 9bb77ccba4d724f366b2f8827d85c17e752ecd80 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 19/24] Preferences docs name host-labelled rows; trials for their search and for a palette's context menu popup --- .../src/patterns/preferences/model.rs | 12 ++-- crates/ui-patterns/tests/it/docking/native.rs | 71 ++++++++++++++++++- .../ui-patterns/tests/it/preferences/model.rs | 23 ++++++ 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/crates/ui-patterns/src/patterns/preferences/model.rs b/crates/ui-patterns/src/patterns/preferences/model.rs index f9b2826fd..feecabe47 100644 --- a/crates/ui-patterns/src/patterns/preferences/model.rs +++ b/crates/ui-patterns/src/patterns/preferences/model.rs @@ -102,8 +102,8 @@ pub struct RowSpec<'a> { pub key: &'a str, /// Translated; also the row's accessible name. pub label: &'a str, - /// Extra search text: the key, the English label, synonyms. A [`RowKind::Custom`] row, which the search can't look - /// into, lists the terms of its control here. + /// Extra search text: the key, the English label, synonyms. A [`RowKind::Custom`] or [`RowKind::CustomRows`] row, + /// which the search can't look into, lists the terms of what the host draws here. pub keywords: &'a str, /// Help under the control: "Applies at next launch." A line break starts a new paragraph. The search matches it. pub help: Option<&'a str>, @@ -206,8 +206,9 @@ pub enum RowKind<'a> { Text(&'a str), /// The host draws the control ([`PreferencesModel::custom_row`]); the window labels it beside the control. Custom, - /// The host draws whole rows, labels included ([`PreferencesModel::custom_row`]): the window adds no label. The - /// row's label stays its search text and its group's name. + /// The host draws whole rows, labels included ([`PreferencesModel::custom_row`]): the window adds no label, and + /// shows the row's help under them and its enabled state on them. The row's label stays its search text and its + /// group's name. CustomRows, } @@ -301,7 +302,8 @@ pub trait PreferencesModel { fn set_color(&mut self, key: &str, color: Srgba) { self.set(key, PrefValue::Color(color.into())); } - /// Draws a [`RowKind::Custom`] row's control. + /// Draws a [`RowKind::Custom`] row's control, which the window labels from the row's label (an empty label shows + /// an empty one), or a [`RowKind::CustomRows`] row's whole rows, labels included. fn custom_row(&mut self, ui: &mut Ui, key: &str); /// Draws a [`PageSpec::custom`] page. fn custom_page(&mut self, ui: &mut Ui, page: &str); diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 2cc0dd9c8..d31e9adf9 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -1,20 +1,23 @@ //! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and -//! docking the whole window by dragging its title row. +//! docking the whole window by dragging its title row. A context menu opened in a palette places its popup window as +//! it places the menu in the main window. use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; +use craft_ui::buttons::Button; use craft_ui::contract::Role; use craft_ui::contract::{Bind, BodyCx, DropMark, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs}; +use craft_ui::menu::{Menu, MenuItem}; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::drag; use craft_ui::testing::access::AccessTree; use craft_ui::testing::input::key_press; -use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::pointer::{moved, press, release, secondary}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; use craft_ui_test_kit::windows::{Out, Windows}; @@ -1218,3 +1221,67 @@ fn scaled(focused: bool, rect: Rect, pixels_per_point: f32) -> ViewportInfo { ..ViewportInfo::default() } } + +/// How far down panel 1's body the context menu's target sits, and the menu's rows: in the native palette at +/// `FLOAT_AT`, the pointer on the target has about 300 points above it and below it in the windows' span, and the +/// menu is taller than either and shorter than the span. +const CONTEXT_DROP: f32 = 220.0; +const CONTEXT_ROWS: usize = 18; + +/// A palette whose panel 1 holds a button with a context menu of `CONTEXT_ROWS` rows. +struct ContextTarget; + +impl DockPanels for ContextTarget { + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel != 1 { + return; + } + ui.add_space(CONTEXT_DROP); + let target = Button::new("Target").show(ui); + let _ = Menu::context("Target menu", &target).show(ui, |ui, _| { + for at in 0..CONTEXT_ROWS { + MenuItem::new(format!("Row {at}")).show(ui); + } + }); + } +} + +/// A context menu opened in a native palette shows in a popup OS window; too tall for the room on either side of the +/// pointer but not for the room the popup has, it covers the pointer and shows every row, as it does in the main window. +#[trial] +fn a_context_menu_from_a_native_palette_too_tall_for_either_side_covers_the_pointer_in_its_popup_window() { + let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE)); + let mut panels = ContextTarget; + let out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let target = node_rect(tree_of_viewport(&out, palette), "Target", Role::BUTTON).expect("the palette shows the target").center(); + for events in [vec![moved(target)], vec![secondary(target, true)], vec![secondary(target, false)]] { + collapsed_frame(&mut dock, &mut panels, &mut at, vec![], events); + } + let mut out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]); + for _ in 0..4 { + out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]); + } + let menu = popups(&dock, &out) + .into_iter() + .find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::MENU).is_empty()) + .expect("the menu shows in a popup window"); + let rect = window_rect(&dock, menu); + let pointer = at.min + target.to_vec2(); + let room = MAIN_AT.union(at); + assert!( + rect.height() > pointer.y - room.top() && rect.height() > room.bottom() - pointer.y, + "the menu {rect:?} fits on neither side of {pointer:?}" + ); + assert!(room.contains_rect(rect.shrink(0.5)), "the menu {rect:?} stays inside the windows' span {room:?}"); + assert!(rect.contains(pointer), "the menu {rect:?} covers the pointer at {pointer:?}"); + let tree = tree_of_viewport(&out, menu); + let window = Rect::from_min_size(Pos2::ZERO, rect.size()).expand(FIT_ROUNDING); + for row in [0, CONTEXT_ROWS - 1] { + let shown = node_rect(tree, &format!("Row {row}"), Role::MENU_ITEM).unwrap_or_else(|| panic!("row {row} shows")); + assert!(window.contains_rect(shown), "row {row} {shown:?} lies whole in the menu's window {window:?}"); + } +} diff --git a/crates/ui-patterns/tests/it/preferences/model.rs b/crates/ui-patterns/tests/it/preferences/model.rs index ca902ef50..3b370bdcd 100644 --- a/crates/ui-patterns/tests/it/preferences/model.rs +++ b/crates/ui-patterns/tests/it/preferences/model.rs @@ -1,8 +1,11 @@ //! The settings document without a window: rows, applied edits, rebase and row conditions. +use craft_i18n::Folder; +use craft_i18n::matcher::Matcher; use craft_theme::Rgba; use craft_ui::patterns::preferences::{ CustomSettings, PageInfo, PrefValue, PreferencesDraft, PreferencesModel, RowKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage, + list_pages, row_shown, }; use craft_ui::testing::trial; use serde::{Deserialize, Serialize}; @@ -276,3 +279,23 @@ fn a_removed_draft_value_applies_as_no_value() { assert_eq!(edits, vec![("memory.percent".to_owned(), None)]); assert_eq!(doc.saved().memory.percent, None); } + +/// A row whose app draws its own labels is found by its rule's label: the search lists its page and shows it. +#[trial] +fn the_search_finds_a_host_labelled_row_by_its_rules_label() { + let rules = vec![ + SettingRule::new("export.format").choices(&[("png", "PNG"), ("webp", "WebP")]), + SettingRule::new("export.tablet").label("Tablet pressure").custom_rows(), + ]; + let doc = SettingsDocument::new(ExportPrefs::default()).expect("serializes").rules(rules); + let pages = PreferencesModel::pages(&doc); + let matcher = Matcher::new(&Folder::new("en"), "tablet"); + let listed = list_pages(&pages, &matcher); + let found: Vec<(&str, bool)> = listed + .iter() + .flat_map(|listed| pages[listed.index].groups.iter().flat_map(|group| group.rows.iter()).map(move |row| (row, listed))) + .filter(|(row, listed)| row_shown(&matcher, listed, row)) + .map(|(row, _)| (row.key, matches!(row.kind, RowKind::CustomRows))) + .collect(); + assert_eq!(found, [("export.tablet", true)], "the search shows the host-labelled row alone"); +} From b62b64af52af53c22033ddecc3e8ef9fb79fa838 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 06:46:13 +0000 Subject: [PATCH 20/24] FloatingGroup::scale is a declared prop (display scale, pixels per point) --- crates/ui-panels/src/docking/floating.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index fc6369b3b..ba0c58ef9 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -277,8 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, - /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the - /// running window's. + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome, the rule under its title row included, is sized at that scale. + #[prop(quantity = "display scale, pixels per point")] scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, @@ -363,14 +364,6 @@ impl<'a> FloatingGroup<'a> { self } - /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the - /// running window's: its chrome is sized at that scale. - #[must_use] - pub fn scale(mut self, pixels_per_point: f32) -> Self { - self.scale = Some(pixels_per_point); - self - } - /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { From 2ef7bbff3843f4fbe7f0af8f3461966e65fced7d Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:33:46 +0000 Subject: [PATCH 21/24] A field labelled above sits on a row's line by its control, as a control labelled above does A container labelled above its body reports its body's first control line as the line it sits on in a row, so a button beside a field labelled above sits level with the field's control, not its label. --- crates/ui-contract/src/contract/body/hooks.rs | 9 +++++++-- crates/ui-contract/src/layout/body.rs | 11 ++++++----- crates/ui-widgets/tests/it/layout/row_line.rs | 13 +++++++------ 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c..3661a1a5f 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -416,10 +416,15 @@ impl ShapeHooks for BodyHooks<'_> { layout_memory::measured(ctx, sub(id, "first")).map(|found| found.took.y) } - /// A container with no header whose body is an unwrapped row reports that row's line as its first line. + /// A container with no header whose body is an unwrapped row reports that row's line as its first line, and one + /// labelled above its body the line of its body's first control: it sits on a row's line by that control, as a + /// control labelled above does. fn first_is_row_line(&self, comp: &C) -> bool { let props = comp.props(Internal::new()); - props.header.is_none() && super::size::unwrapped_row(props) + let above = props.label.as_ref().is_some_and(|side| { + matches!(side.layout, label::FieldLayout::Above | label::FieldLayout::Caption(_)) && side.kind != label::LabelKind::Hidden + }); + props.header.is_none() && (above || super::size::unwrapped_row(props)) } fn member(&self, comp: &C) -> bool { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index de1ac5bc8..5a7d9148a 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1155,9 +1155,10 @@ pub(crate) struct InFlow { /// rows run along Y, or a container whose first child is one. The child is one line when that centre lies at /// half its height (`one_line`). pub first: Option, - /// `first` is the line of the child's own unwrapped `Row` body, or of the control of a labelled control's row: the - /// child sits on a row's line by it even when it is more than one line (a nested row with a child of two lines, a - /// check box whose label has a detail line under it, a control under its label). + /// `first` is the line of the child's own unwrapped `Row` body, of the control of a labelled control's row, or of + /// the first control of a container labelled above its body: the child sits on a row's line by it even when it is + /// more than one line (a nested row with a child of two lines, a check box whose label has a detail line under it, + /// a control or a field under its label). pub line: bool, } @@ -1166,8 +1167,8 @@ const ONE_LINE_SLACK: f32 = 0.5; /// The centre of the line of a child `height` tall whose first line's centre lies `first` below its top, when the /// child is one line: a control, a row of one-line children, a container around one line (a field with its label -/// beside its control). A child of more than one line (a column, a field with its label above or a help line below) -/// has its first line above its middle. +/// beside its control). A child of more than one line (a column, a field with a help line below) has its first line +/// above its middle. fn one_line(first: Option, height: f32) -> Option { first.filter(|first| (2.0 * first - height).abs() <= ONE_LINE_SLACK) } diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 9ba63754d..92a3cd6b8 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,6 +1,7 @@ //! The row line: a child of an unwrapped row that is one line sits with its centre on the row's line; a child of more -//! than one line (a column, a field with its label above or a help line below) sits at the row's top. A control with -//! its label after it sits on the line by its control, as a bare control does, in a row and in a grid's cell. +//! than one line (a column, a field with a help line below) sits at the row's top. A control with its label after it +//! or above it, and a field labelled above, sit on the line by their control, as a bare control does, in a row and in +//! a grid's cell. use craft_behavior::ColumnWidth; use craft_theme::ControlSize; @@ -107,10 +108,10 @@ fn columns_sit_at_the_rows_top_and_lines_on_the_line() { assert!(four.top() <= control(&fixture, &["Go"]).top() + ROUNDING, "the four-line column starts below the button's top"); } -/// A field labelled above its control is two lines and sits at the row's top, so a button beside it sits level with -/// the label, not the control. +/// A field labelled above its control sits on the row's line by its control, as a control labelled above does: a +/// button beside it sits level with the control, and the label stands above the line. #[trial] -fn a_field_labelled_above_sits_at_the_rows_top() { +fn a_field_labelled_above_sits_on_the_row_line_by_its_control() { let fixture = settled(|ui| { Row::new().show(ui, |ui, _| { Field::new("Caption").layout(FieldLayout::Above).sizing(Sizing::Content).show(ui, |ui, _| { @@ -121,7 +122,7 @@ fn a_field_labelled_above_sits_at_the_rows_top() { }); let (caption, control, button) = (text(&fixture, "Caption"), text(&fixture, "X"), text(&fixture, "Y")); assert!(caption.bottom() < control.top(), "the label sits above its control"); - assert!(button.center().y < control.top(), "the button {button:?} sits level with the label, above the control {control:?}"); + assert!((button.center().y - control.center().y).abs() <= ROUNDING, "the button {button:?} sits on the control's line {control:?}"); } /// A check box whose label runs to a second line under it, beside a button in a row: its box sits on the button's From 6c72055339f113d73afdb9a7b85cfc0a86afbc5a Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:38:11 +0000 Subject: [PATCH 22/24] A memoized row unit's room follows the row, not its own content; a call's key is its own A memoized view the row does not narrow shows as in no room, in the row's flow region, and its content sizes from its content along x; only a row that narrows it cuts its room to the width it gives. The cap of a view the row did not narrow was its own counted width, so new content changed the view's room and the discard pass ran it again. The shrink record carries whether the row narrowed the unit. The replay decision of a pass covers the kept run; each call compares its own key. A row's counting sweep calls the view with another key (its content shows unbounded): that call no longer decides the pass against the real call after it, and a sizing call takes the extent the last sizing run measured for its own key. --- crates/ui-contract/src/contract/lazy.rs | 8 ++- crates/ui-contract/src/contract/memo_view.rs | 5 +- crates/ui-contract/src/layout/body.rs | 27 ++++++--- crates/ui-contract/src/runtime/env.rs | 8 ++- .../ui-contract/src/runtime/layout_memory.rs | 28 +++++---- crates/ui-contract/src/runtime/lazy.rs | 25 ++++---- .../ui-contract/tests/it/contract/memo_row.rs | 59 +++++++++++++++++++ crates/ui-contract/tests/it/contract/mod.rs | 1 + 8 files changed, 128 insertions(+), 33 deletions(-) create mode 100644 crates/ui-contract/tests/it/contract/memo_row.rs diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 01d74889f..b087b47f6 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -78,11 +78,13 @@ impl Lazy { }; let rtl = ui.layout().prefer_right_to_left(); let memo = matches!(key, Key::Memo(_)); - // A memoized view is one unit of the shrinking row around it: it shows at most the width the row's measuring - // run gave it, the room its place then holds, so a new width runs it. + // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width + // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not + // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a + // new content runs it once and the discard pass its new size asks for replays that run. let shrink = Env::of(ui).shrink.filter(|_| memo); let cap = match shrink { - Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id), + Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), _ => None, }; let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index d503b1895..aaea525f7 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -53,8 +53,9 @@ use std::sync::Arc; /// cursor) does not reach in, so the room it is given reaches it only through its place. To the body /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its -/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room, as they -/// fit the room of a `Stack` the view is shown in. +/// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no +/// room, in the row's flow region. Its content sizes from its content along x, and its leaves fit the view's room, as +/// they fit the room of a `Stack` the view is shown in. /// /// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept /// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 5a7d9148a..eef131a3a 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -541,11 +541,18 @@ pub(crate) struct ShrinkCap { pub width: f32, /// The unit dropped out of the row (`shrink_or_drop`): it shows nothing and takes no place. pub dropped: bool, + /// The row gave the unit less than it asks for in no room, or dropped it: what the unit shows depends on the row's + /// room. A unit the row did not narrow shows as in no room. + pub narrowed: bool, } /// What the shrink step of the row `row` gave its unit `leaf` in this pass's measuring run. pub(crate) fn shrink_cap(ctx: &egui::Context, row: Id, leaf: Id) -> Option { - layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, dropped)| ShrinkCap { width: found.took.x, dropped }) + layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, given)| ShrinkCap { + width: found.took.x, + dropped: given.dropped, + narrowed: given.narrowed, + }) } fn shrink_key(row: Id, leaf: Id) -> Id { @@ -649,9 +656,13 @@ fn shrink_or_drop( let shown_first: Vec = first.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(first, _)| *first).collect(); let mut widths = shrink_in_turns(&shown, &pick(whole), &shown_first, fixed, room, order).into_iter(); kept.iter() - .map(|kept| match kept { - true => ShrinkCap { width: widths.next().unwrap_or_default(), dropped: false }, - false => ShrinkCap { width: 0.0, dropped: true }, + .zip(units) + .map(|(kept, unit)| match kept { + true => { + let width = widths.next().unwrap_or_default(); + ShrinkCap { width, dropped: false, narrowed: unit.ideal - width >= 0.5 } + } + false => ShrinkCap { width: 0.0, dropped: true, narrowed: true }, }) .collect() } @@ -732,21 +743,23 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> let widths = if room.is_finite() { shrink_or_drop(&units, &whole, &first, (fixed + held, gap), room, order, drops) } else { - units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false }).collect() + units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect() }; // A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the // records its content's run leaves for the real run come from a sweep at the levels given. let mut again = !levelled.is_empty(); for (leaf, cap) in continuous.iter().zip(widths) { let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0)); - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, cap.dropped); + let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed }; + layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); // Half a point: less than a pixel shows at any scale the box runs. again |= (leaf.took - cap.width).abs() >= 0.5; } for (leaf, level) in levelled.iter().zip(levels) { // The level travels as the record's height (`level_of`). let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32)); - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, false); + let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 }; + layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); } again }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 891f8abb6..bf7ac1ed0 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -410,13 +410,19 @@ impl Scoped { } /// Starts the layout room of a memoized view's content (`start_room`). Where a leaf shown here would fit its room - /// (`view_fits`), the leaves of the view's content fit the room the view is given (`Shrink::Fit`). + /// (`view_fits`), the leaves of the view's content fit the room the view is given (`Shrink::Fit`). A view that is a + /// unit of a shrinking `Row` sizes from its content along x, as the row counted it: a child that fills there takes + /// its measured width, not the row's flow region a view the row does not narrow is shown in. pub(crate) fn start_view_room(&mut self) { let fits = self.view_fits(); + let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); self.start_room(); if fits { self.shrink = Some(Shrink::Fit); } + if row_unit { + self.content.0 = true; + } } /// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body, diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 3894fd46b..84ab4bb8c 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -97,8 +97,8 @@ pub(crate) type TakeBack = Box; #[derive(Clone, Debug, PartialEq)] enum Recorded { Measured(Measured), - /// The width a row's shrink step gave a unit, as a measure, and whether the unit dropped out of the row. - Shrink(Measured, bool), + /// The width a row's shrink step gave a unit, as a measure, and whether it narrowed the unit or dropped it. + Shrink(Measured, ShrinkGiven), Text(Option>), } @@ -499,10 +499,18 @@ pub(crate) fn emit_record(ctx: &Context, id: Id, measured: Measured) { emit(ctx, id, Recorded::Measured(measured)); } -/// Hands forward what a row's shrink step gave a unit under `id`: its width as `measured` and whether it `dropped` -/// out of the row. It serves as [`emit_record`]'s measure does. -pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, dropped: bool) { - emit(ctx, id, Recorded::Shrink(measured, dropped)); +/// Whether a row's shrink step narrowed a unit below what it asks for in no room, and whether it dropped the unit out +/// of the row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ShrinkGiven { + pub dropped: bool, + pub narrowed: bool, +} + +/// Hands forward what a row's shrink step gave a unit under `id`: its width as `measured` and what else it `given`. +/// It serves as [`emit_record`]'s measure does. +pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, given: ShrinkGiven) { + emit(ctx, id, Recorded::Shrink(measured, given)); } /// Hands forward a text a run found under `id` that content outside the body it runs in shows, as `emit_record` @@ -565,7 +573,7 @@ fn kept_differs(last: &Found, now: &Recorded, pass: u64, tolerance: f32) -> Opti }; let differs = match (was, now) { (Recorded::Measured(was), Recorded::Measured(now)) => measures(was, now, false), - (Recorded::Shrink(was, was_dropped), Recorded::Shrink(now, now_dropped)) => measures(was, now, was_dropped != now_dropped), + (Recorded::Shrink(was, was_given), Recorded::Shrink(now, now_given)) => measures(was, now, was_given != now_given), (was, now) => was != now, }; if *at != pass || !differs { @@ -922,12 +930,12 @@ pub(crate) fn measured(ctx: &Context, id: Id) -> Option { } /// What a row's shrink step of this pass gave the unit under `id` ([`emit_shrink`]): its width as a measure and -/// whether it dropped out of the row. -pub(crate) fn shrink(ctx: &Context, id: Id) -> Option<(Measured, bool)> { +/// whether it narrowed or dropped the unit. +pub(crate) fn shrink(ctx: &Context, id: Id) -> Option<(Measured, ShrinkGiven)> { let moment = Moment::of(ctx); let pass = ctx.cumulative_pass_nr(); with(ctx, &moment, |memory| match memory.measured.get(&id).filter(|found| found.pass == pass && !memory.probing()) { - Some(Found { recorded: Recorded::Shrink(measured, dropped), .. }) => Some((*measured, *dropped)), + Some(Found { recorded: Recorded::Shrink(measured, given), .. }) => Some((*measured, *given)), _ => None, }) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 5aa98cc1d..5e4031df6 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -449,10 +449,12 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// Whether the memoized view `id` adds its last real run to this pass in place of running, the extent that run took in /// a run of this kind (`sizing`: the room a sizing run offers it, `None` outside a sizing pass), the rect the kept real /// run takes now and the shift its record moves by. The first run of a pass decides from what changed since that run; a -/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. A sizing -/// run of a pass that replays takes the extent the last sizing run measured of the content the kept run showed (its -/// key) in the room it offers now; when that sizing run showed other content or had another room, or there was none, it -/// runs once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still +/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. Each call +/// also needs the key of the kept run: any other call with another key (a row's counting sweep shows the content +/// unbounded, and the scope key holds that) runs, and leaves the decision of the pass alone for the calls after it. A +/// sizing run of a pass that replays takes the extent the last sizing run measured of the content it shows (its key) in +/// the room it offers now; when that sizing run showed other content or had another room, or there was none, it runs +/// once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still /// replays. /// /// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then: @@ -464,8 +466,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes); /// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or, /// replaying a run of this frame, after that run started; -/// - its key is the one of its last run (its props key after that run), and its environment (theme, density, scale, -/// language, window active) the one it ran in; +/// - the call's key is the one of its last run (its props key after that run), and its environment (theme, density, +/// scale, language, window active) the one it ran in; /// - the run did nothing a replay cannot repeat (`runtime::replay`) and asked for no discard pass: what it added is /// what the pass was thrown away for; /// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is @@ -492,6 +494,10 @@ pub(crate) fn settled( // Usually `None`: only the values written this frame. let edited = changes.edited_in(frame); let entry = store.touch(owner, id, frame); + // The decision of the pass covers the kept run; the key is the call's own. A call that shows other content (a + // row's counting sweep, which shows it unbounded) leaves the decision alone for the calls after it: a sizing call + // takes the extent the last sizing run measured of its own content, and any other runs. + let keyed = entry.settled.as_ref().is_some_and(|settled| settled.key == key) || sizing.is_some(); let replays = match entry.replays { Some((decided_in, replays)) if decided_in == pass_nr => replays, _ => { @@ -500,7 +506,6 @@ pub(crate) fn settled( // A run of this frame read the values edited before it started. let edited = edited_since(edited.as_ref(), if settled.frame < frame { 0 } else { settled.edits }); (settled.frame < frame || settled.pass < pass_nr) - && settled.key == key && !settled.engaged && !facts.blocked && !facts.discards @@ -518,14 +523,14 @@ pub(crate) fn settled( Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed), None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }), }; - let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled))); - if replays && settled.is_none() { + let settled = entry.settled.clone().filter(|_| replays && keyed).and_then(|settled| Some((moved(&settled)?, settled))); + if replays && keyed && settled.is_none() { entry.replays = Some((pass_nr, false)); } settled.and_then(|(moved, settled)| { // An extent depends on the room's size, not on where the room is. let size = match sizing { - Some(room) => entry.sizes[0].filter(|measured| measured.key == settled.key && measured.room.size() == room.size())?.size, + Some(room) => entry.sizes[0].filter(|measured| measured.key == key && measured.room.size() == room.size())?.size, None => entry.sizes[1].filter(|measured| measured.key == settled.key).map_or(settled.rect.size(), |measured| measured.size), }; Some((size, moved, settled)) diff --git a/crates/ui-contract/tests/it/contract/memo_row.rs b/crates/ui-contract/tests/it/contract/memo_row.rs new file mode 100644 index 000000000..1c5019b3e --- /dev/null +++ b/crates/ui-contract/tests/it/contract/memo_row.rs @@ -0,0 +1,59 @@ +//! A memoized view that is one unit of a shrinking row: the row's counting sweep calls it with another key than its +//! real run, and that call leaves the replay decision of the pass to the calls after it and reuses its own measure. + +use craft_ui::contract::{MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::layout::BodyLayout; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, last_pass_memo_runs, trial}; +use craft_ui_test_kit::contract::{Panel, Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; + +/// A view that shows one probe `width` wide. +#[derive(MemoProps)] +struct Widened { + width: f32, +} + +fn widened(props: &mut Widened, ui: &mut Ui) { + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).size(Vec2::new(props.width, 20.0)).id_salt("content").show(ui); +} + +/// How the `Widened` views took part in `runs`. +fn of_view(runs: Vec<(&'static str, egui::Id, MemoRun)>) -> Vec { + runs.into_iter().filter(|(name, _, _)| name.contains("Widened")).map(|(_, _, run)| run).collect() +} + +/// A memoized view in a row that is not short, whose new content is wider: it runs once in the real run that meets the +/// new props and once as a measuring run in the row's counting sweep, whose call keys apart from the real run's +/// (the content shows unbounded there). The real run of the discard pass that sweep belongs to replays, and so does +/// every call of the next frame, a counting sweep's included. +#[trial] +fn a_memoized_row_unit_replays_after_the_rows_counting_call_with_another_key() { + let width = Cell::new(60.0); + let mut frames = Frames::new(); + let frame = |frames: &mut Frames| { + frames.frame(vec![], |ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(400.0, 40.0)), |ui| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("row").show(ui, |ui, _| { + let _ = MemoView::new("view", Widened { width: width.get() }, widened).show(ui); + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).id_salt("after").show(ui); + }); + }); + }); + }; + for _ in 0..30 { + frame(&mut frames); + } + assert_eq!(of_view(last_frame_memo_runs(&frames.ctx)), [MemoRun::Replayed], "an idle frame replays the view"); + width.set(90.0); + frame(&mut frames); + let calls = of_view(last_frame_memo_runs(&frames.ctx)); + assert_eq!(calls.iter().filter(|run| **run == MemoRun::Ran).count(), 2, "one real run and one measuring run: {calls:?}"); + assert_eq!(of_view(last_pass_memo_runs(&frames.ctx)), [MemoRun::Replayed], "the discard pass's real call replays: {calls:?}"); + frame(&mut frames); + let calls = of_view(last_frame_memo_runs(&frames.ctx)); + assert!(calls.iter().all(|run| *run == MemoRun::Replayed), "the next frame replays the view in every call: {calls:?}"); +} diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index 556140903..2e95af053 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -5,6 +5,7 @@ pub(crate) mod gesture; pub(crate) mod hit_order; pub(crate) mod level; pub(crate) mod memo_key; +pub(crate) mod memo_row; pub(crate) mod pages; pub(crate) mod pointer; pub(crate) mod style; From 282d45bb2875e01b83ec592d9fe70d08beb5f03f Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 11:19:46 +0000 Subject: [PATCH 23/24] Help gives the help line's Text, which its callers show --- crates/ui-patterns/src/patterns/preferences/rows.rs | 2 +- crates/ui-widgets/src/form/field.rs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/ui-patterns/src/patterns/preferences/rows.rs b/crates/ui-patterns/src/patterns/preferences/rows.rs index bc03be521..2ad99b1ca 100644 --- a/crates/ui-patterns/src/patterns/preferences/rows.rs +++ b/crates/ui-patterns/src/patterns/preferences/rows.rs @@ -183,7 +183,7 @@ pub(super) fn show_row(ui: &mut Ui, host: &mut H, Stack::new().id_salt(key).enabled(row.enabled).show(ui, |ui, _| { host.custom_row(ui, key); if let Some(help) = &row.help { - Help::Text(help.clone()).show(ui); + Help::Text(help.clone()).text().show(ui); } }); } diff --git a/crates/ui-widgets/src/form/field.rs b/crates/ui-widgets/src/form/field.rs index dee769d3d..19d4f456b 100644 --- a/crates/ui-widgets/src/form/field.rs +++ b/crates/ui-widgets/src/form/field.rs @@ -22,12 +22,12 @@ pub enum Help { } impl Help { - /// Shows the help line as a field shows it under its control. - pub fn show(&self, ui: &mut Ui) { + /// The help line as a field shows it under its control. + pub fn text(&self) -> Text { match self { - Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui), - Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui), - }; + Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted), + Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone), + } } } @@ -127,7 +127,7 @@ impl Container for Field { return; } if let Some(help) = &self.help { - help.show(ui); + help.text().show(ui); } } } From ed9823347c7e9435baed73ee1191b15d4c62c980 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 14:23:08 +0000 Subject: [PATCH 24/24] contract-api.md regenerated after the next merge --- docs/contract-api.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index fd4349515..691ee5a48 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -4223,7 +4223,7 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con - `craft_ui::runtime::toast::ToastEnd`: `pub enum ToastEnd { Action(usize), Dismissed, Expired, Dropped }`. How a toast left the queue. - `craft_ui::runtime::toast::ToastId`: `pub struct ToastId`. A posted toast's handle. - `pub fn value(self) -> u64`. The handle as a number, unique among the toasts of one queue: what a host reports to automation. -- `craft_ui::runtime::toast::cards`: `pub fn cards(ctx: &Context, window: &WindowKey) -> Vec`. The cards of the window `window` in the running viewport, oldest first. +- `craft_ui::runtime::toast::cards`: `pub fn cards(ctx: &Context, window: &WindowKey) -> Vec`. The cards of the window `window` in the running viewport, oldest first. A tracked input (`Input::Toasts`). - `craft_ui::runtime::toast::dismiss`: `pub fn dismiss(ctx: &Context, id: ToastId)`. Removes a toast before its timer ends, from whichever viewport holds it. The app asked for it, so no end is - `craft_ui::runtime::toast::end`: `pub fn end(ctx: &Context, id: ToastId) -> Option`. How the toast `id` ended, once: `Dropped` for a card the cap removed; `None` while it is queued, after the report - `craft_ui::runtime::toast::keep`: `pub fn keep(ctx: &Context, id: ToastId)`. Keeps the toast `id` until it is closed, whatever its timeout (an error the user must read). @@ -4587,6 +4587,7 @@ What the accessibility trials read: the AccessKit tree a frame produced, and the - `craft_ui::testing::access::Declared`: `pub enum Declared { Focus, Click, Increment, Decrement, SetValue, SetTextSelection, Expand, Collapse, Custom, ScrollUp, ScrollDown, ScrollLeft, ScrollRight }`. An action a node declares. - `craft_ui::testing::access::NodeKey`: `pub struct NodeKey`. A node's number in the tree. - `pub fn of(id: Id) -> NodeKey`. The key of the node of `id`. +- `craft_ui::testing::access::layer_root`: `pub fn layer_root(id: Id) -> Id`. The id of the root node of the overlay layer `id`. The root has an id of its own: the layer's container component - `craft_ui::testing::access::prune_controls`: re-export of `craft_ui::runtime::egui::access::prune_controls`. ## `craft_ui::testing::bypass`