diff --git a/Cargo.lock b/Cargo.lock index a0c55e90d..96a9f4e10 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5450,7 +5450,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "emath", @@ -5506,7 +5506,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5541,7 +5541,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "accesskit", "ahash", @@ -5560,7 +5560,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5579,7 +5579,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5599,7 +5599,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "egui", @@ -5612,7 +5612,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "eframe", "egui", @@ -5689,7 +5689,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", ] @@ -5762,7 +5762,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5788,7 +5788,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[package]] name = "equator" @@ -15119,19 +15119,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +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=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +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=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +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=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" diff --git a/Cargo.toml b/Cargo.toml index 44df434e2..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 = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +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/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 529f8bbf5..fc2391ee2 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -303,13 +303,18 @@ impl Codec for NumberCodec { fn format(&self, v: &Option) -> String { let Some(number) = v else { return String::new() }; - let fixed = format!("{number:.*}", self.decimals); + let written = format!("{number:.*}", self.decimals); + // A value that rounds to zero at these decimals carries no sign. + let fixed = match written.strip_prefix('-') { + Some(digits) if digits.bytes().all(|byte| matches!(byte, b'0' | b'.')) => digits, + _ => &written, + }; let trimmed = if self.fixed { - &fixed + fixed } else if fixed.contains('.') { fixed.trim_end_matches('0').trim_end_matches('.') } else { - &fixed + fixed }; trimmed.replace('.', &self.reader.decimal_separator().to_string()) } @@ -345,3 +350,17 @@ impl Codec for NumberCodec { Cow::Borrowed(NUMBER_SAMPLE) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_value_that_rounds_to_zero_is_written_without_a_sign() { + let one = NumberCodec::new(Reader::new(), 1); + assert_eq!(one.format(&Some(-0.0)), "0"); + assert_eq!(one.format(&Some(-0.04)), "0"); + assert_eq!(one.format(&Some(-0.06)), "-0.1"); + assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0"); + } +} 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/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/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() { diff --git a/crates/color-ui/src/ui/info.rs b/crates/color-ui/src/ui/info.rs index fb0486c6e..d9d37d124 100644 --- a/crates/color-ui/src/ui/info.rs +++ b/crates/color-ui/src/ui/info.rs @@ -4,8 +4,10 @@ use craft_behavior::ColumnWidth; use craft_cms::convert::CmykConverter; use craft_theme::Srgba; use craft_theme::variant::Tone; -use craft_ui::contract::{Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _}; -use craft_ui::display::Text; +use craft_ui::contract::{Gap, Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::{Divider, Text}; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::layout::{CellAlign, GridFit}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::notices::{Notice, NoticeLayout}; use craft_ui::runtime::env::{Env, Label}; @@ -19,9 +21,8 @@ pub(crate) mod stories; /// What a missing value shows. const DASH: &str = "–"; -/// The grid's columns: a name and its value, twice, so that the two readouts of a line stand side by side and each -/// column lines up down the grid. -const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +/// A block's two halves, equal in width. +const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; craft_ui::words! { /// The words of the Info panel, in the installed language unless set. @@ -179,9 +180,10 @@ impl<'a> InfoReadings<'a> { } } -/// A read-only grid: RGB beside CMYK, the Ruler tool's measure (the angle A beside the length L, or a protractor's arms -/// L1 and L2 stacked beside it), X/Y beside W/H, the document size, then one row group per sampler; a dash for a -/// missing value; `document: None` shows "No document" as a centred notice in place of the grid. +/// A read-only panel of blocks, a rule between them, each block two equal halves of labelled readouts: RGB beside CMYK +/// (in percent), the Ruler tool's measure (the angle A beside the length L, or a protractor's arms L1 and L2 stacked +/// beside it), X/Y beside W/H, the document size, then a position block and a colour block per sampler; a dash for a +/// missing value; `document: None` shows "No document" as a centred notice in place of the blocks. #[must_use = "show the panel with `show`"] #[derive(Pattern)] pub struct InfoPanel<'a> { @@ -192,43 +194,38 @@ pub struct InfoPanel<'a> { /// A name and its value, or `None` for a dash. type Cell = (Label, 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. It keeps how - // that body sizes from its content, so the view takes what its content used there, as the same content - // shown without the view would. + // that body sizes from its content and whether its leaves fit their room (`Scoped::start_view_room`), so + // the view takes what its content used there, as the same content shown without the view would. let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); let out = show(&mut props, ui); Env::restore(&ctx, installed); @@ -123,6 +130,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/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 1fffe99f1..95e1cc563 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(); @@ -287,6 +288,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; @@ -294,7 +296,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); @@ -314,7 +316,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/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 526a2fdda..47ca407e0 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -8,6 +8,7 @@ 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,6 +52,31 @@ 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); + (opener_anchor(opener, opening, &overlay.place), opener.anchor.is_none() && matches!(opening, Opening::At(_))) + } + None => match &overlay.place { + Place::Anchored { anchor, .. } => (anchor.clone(), false), + Place::Float(_) => return false, + }, + }; + match anchor { + Anchor::Pointer | Anchor::Point(_) => true, + // `opener_anchor` gives a requested rect only for a context request's opening. + Anchor::Rect(_) => requested, + _ => false, + } +} + /// 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 +198,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 +211,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 +226,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 +256,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 +278,11 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option 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 { @@ -668,9 +675,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() } @@ -751,21 +762,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 }; @@ -1180,8 +1193,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: 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, 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, } @@ -1190,8 +1205,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-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 081d101fe..35fc87158 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -409,14 +409,32 @@ impl Scoped { self.offered = None; } - /// Starts a memoized view's layout room (`start_room`), keeping whether the enclosing body is a content-sized or a - /// given column, as `start_room` keeps the content axes. The view's content then measures and fills as it would - /// shown without the view: a child that fills takes its measured size where the body sizes from content, never the - /// open room. + /// Starts the layout room of a memoized view's content (`start_room`), keeping whether the enclosing body is a + /// content-sized or a given column, as `start_room` keeps the content axes. The view's content then measures and + /// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from + /// content, never the open 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`). 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(_))); let (content_column, given_column) = (self.content_column, self.given_column); self.start_room(); (self.content_column, self.given_column) = (content_column, given_column); + 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, + /// 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 @@ -691,9 +709,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/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index e3bd41318..f4d56fd8a 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 f05c8ad86..d27a97934 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -166,8 +166,8 @@ 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, opacity and environment, and -/// its record moves with the room's position (`Place::shift_to`). +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, fit and +/// environment, and its record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Place { /// The region its parent offered it. @@ -185,6 +185,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 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, } /// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room. @@ -196,9 +199,9 @@ struct Moved { impl Place { /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its - /// size, the layer, layout, scale, font atlas, opacity and environment are the ones the run had. A record that shows - /// an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the room's move - /// when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and, + /// size, the layer, layout, scale, font atlas, opacity, fit and environment are the ones the run had. A record that + /// shows an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the + /// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and, /// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an /// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow /// the clip when either: @@ -216,7 +219,8 @@ impl Place { && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas && now.opacity == self.opacity - && now.env == self.env; + && now.env == self.env + && now.fits == self.fits; let placeable = if record.pinned() { offset == Vec2::ZERO && now.clip == self.clip } else { @@ -460,10 +464,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: @@ -477,8 +483,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 @@ -506,6 +512,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, _ => { @@ -514,7 +524,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 @@ -533,14 +542,14 @@ pub(crate) fn settled( Some(place) => settled.place.shift_to(settled.rect, place, &settled.record, 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; 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; diff --git a/crates/ui-patterns/src/patterns/preferences/document/model.rs b/crates/ui-patterns/src/patterns/preferences/document/model.rs index b766064d3..cc1a8bab4 100644 --- a/crates/ui-patterns/src/patterns/preferences/document/model.rs +++ b/crates/ui-patterns/src/patterns/preferences/document/model.rs @@ -91,7 +91,7 @@ impl Value::Float(clamp_float(n as f64)), (PrefValue::Float(x), Value::Float(_)) if x.is_finite() => Value::Float(clamp_float(x)), (PrefValue::Float(x), Value::Integer(_)) if x.is_finite() => Value::Integer(clamp_int(x.round() as i64)), - (PrefValue::Text(text), Value::String(_)) if matches!(kind, None | Some(RuleKind::Custom)) => Value::String(text), + (PrefValue::Text(text), Value::String(_)) if matches!(kind, None | Some(RuleKind::Custom | RuleKind::CustomRows)) => Value::String(text), (PrefValue::Choice(id), Value::String(_) | Value::Integer(_)) => match kind { Some(RuleKind::Choice(options)) if options.iter().any(|(option, _)| *option == id) => match id.parse::() { Ok(n) if self.rules.get(key).is_some_and(|rule| rule.integer) => Value::Integer(n), diff --git a/crates/ui-patterns/src/patterns/preferences/document/rules.rs b/crates/ui-patterns/src/patterns/preferences/document/rules.rs index f9244bbc4..c214a42b6 100644 --- a/crates/ui-patterns/src/patterns/preferences/document/rules.rs +++ b/crates/ui-patterns/src/patterns/preferences/document/rules.rs @@ -71,8 +71,10 @@ pub enum RuleKind { Choice(Vec<(String, String)>), /// A `#rrggbb` string as a swatch and hex field. Color, - /// The app draws it ([`CustomSettings::row`]). + /// The app draws it ([`CustomSettings::row`]); the window labels it. Custom, + /// The app draws whole rows, labels included ([`CustomSettings::row`]). + CustomRows, } impl SettingRule { @@ -158,13 +160,21 @@ impl SettingRule { self } - /// The app draws the control ([`CustomSettings::row`]). + /// The app draws the control ([`CustomSettings::row`]); the window labels it beside the control. #[must_use] pub fn custom(mut self) -> Self { self.kind = Some(RuleKind::Custom); self } + /// The app draws whole rows with their labels ([`CustomSettings::row`]): the window adds none. The rule's label + /// stays the row's search text and its group's name. + #[must_use] + pub fn custom_rows(mut self) -> Self { + self.kind = Some(RuleKind::CustomRows); + self + } + /// Shows the row only while the setting at `key` has `value`. Called again, the row shows only while every /// condition holds. #[must_use] diff --git a/crates/ui-patterns/src/patterns/preferences/document/texts.rs b/crates/ui-patterns/src/patterns/preferences/document/texts.rs index 8b796243f..878505bc8 100644 --- a/crates/ui-patterns/src/patterns/preferences/document/texts.rs +++ b/crates/ui-patterns/src/patterns/preferences/document/texts.rs @@ -57,6 +57,7 @@ enum Shape { Choice(Vec<(String, Label)>, Option), Color, Custom, + CustomRows, } /// The range of a number without a rule. @@ -65,8 +66,10 @@ pub(super) const OPEN_RANGE: f64 = 1e9; fn shape_of(rule: Option<&SettingRule>, value: Option<&toml::Value>) -> Option { use toml::Value; let kind = rule.and_then(|rule| rule.kind.as_ref()); - if matches!(kind, Some(RuleKind::Custom)) { - return Some(Shape::Custom); + match kind { + Some(RuleKind::Custom) => return Some(Shape::Custom), + Some(RuleKind::CustomRows) => return Some(Shape::CustomRows), + _ => {} } Some(match (kind, value?) { (Some(RuleKind::Choice(options)), Value::String(_) | Value::Integer(_)) => { @@ -169,7 +172,7 @@ impl choice_kind(options, *counted, id), (Shape::Color, Some(Value::String(text))) => RowKind::Color(Rgba::from_hex(text).unwrap_or(Rgba::rgb(128, 128, 128))), (Shape::Custom, _) => RowKind::Custom, + (Shape::CustomRows, _) => RowKind::CustomRows, _ => return None, }; let spec = RowSpec::new(&row.key, &row.label, kind).keywords(&row.keywords).visible(self.row_visible(&row.key)); diff --git a/crates/ui-patterns/src/patterns/preferences/model.rs b/crates/ui-patterns/src/patterns/preferences/model.rs index e63c0fcc3..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>, @@ -204,8 +204,12 @@ pub enum RowKind<'a> { }, /// A text field. Text(&'a str), - /// The host draws the control ([`PreferencesModel::custom_row`]). + /// 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, 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, } impl<'a> RowKind<'a> { @@ -298,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/src/patterns/preferences/page.rs b/crates/ui-patterns/src/patterns/preferences/page.rs index 2417f4fb3..bbc3f7b68 100644 --- a/crates/ui-patterns/src/patterns/preferences/page.rs +++ b/crates/ui-patterns/src/patterns/preferences/page.rs @@ -284,21 +284,24 @@ fn show_page( } else if page.groups.is_empty() && !searching { Notice::new(Tone::Info, words.empty_page.clone()).layout(NoticeLayout::Centred).show(ui); } - for (at, group) in page.groups.iter().enumerate() { - let mut rows = |ui: &mut Ui| { - let name = group.title.clone().unwrap_or_else(|| page.title.clone()); - FieldGroup::new(name).show(ui, |ui, _| { - for row in &group.rows { - show_row(ui, host, row, units, &mut out.rows); + if !page.groups.is_empty() { + FieldGroup::new(page.title.clone()).show(ui, |ui, _| { + for (at, group) in page.groups.iter().enumerate() { + let mut rows = |ui: &mut Ui| { + Stack::new().id_salt(at).show(ui, |ui, _| { + for row in &group.rows { + show_row(ui, host, row, units, &mut out.rows); + } + }); + }; + match &group.title { + Some(title) => { + Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui)); + } + None => rows(ui), } - }); - }; - match &group.title { - Some(title) => { - Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui)); } - None => rows(ui), - } + }); } if let Some(note) = &page.footnote { Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); diff --git a/crates/ui-patterns/src/patterns/preferences/rows.rs b/crates/ui-patterns/src/patterns/preferences/rows.rs index 03ff8929a..2ad99b1ca 100644 --- a/crates/ui-patterns/src/patterns/preferences/rows.rs +++ b/crates/ui-patterns/src/patterns/preferences/rows.rs @@ -35,6 +35,7 @@ pub(super) enum Kind { Float { value: f64, range: RangeInclusive, decimals: u8, step: Option, unit: Option }, Text(String), Custom, + CustomRows, } impl ShownRow { @@ -59,6 +60,7 @@ impl ShownRow { } RowKind::Text(text) => Kind::Text((*text).to_owned()), RowKind::Custom => Kind::Custom, + RowKind::CustomRows => Kind::CustomRows, }; Self { key: row.key.to_owned(), @@ -176,8 +178,14 @@ pub(super) fn show_row(ui: &mut Ui, host: &mut H, out.pick_color = ask; } } - Kind::Custom if label.as_str().is_empty() => { - Stack::new().id_salt(key).show(ui, |ui, _| host.custom_row(ui, key)); + Kind::CustomRows => { + // 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()).text().show(ui); + } + }); } Kind::Custom => { field().show(ui, |ui, _| { 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"); +} diff --git a/crates/ui-patterns/tests/it/preferences/page.rs b/crates/ui-patterns/tests/it/preferences/page.rs index 812d1581f..bc3759740 100644 --- a/crates/ui-patterns/tests/it/preferences/page.rs +++ b/crates/ui-patterns/tests/it/preferences/page.rs @@ -1,7 +1,12 @@ //! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in. -use craft_ui::contract::{Bind, Role}; -use craft_ui::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec}; +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; +use craft_ui::patterns::preferences::{ + GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec, +}; use craft_ui::runtime::env::Env; use craft_ui::runtime::words::CommonWords; use craft_ui::testing::pointer::{moved, press, release}; @@ -83,3 +88,91 @@ fn a_page_edit_reaches_the_model_in_the_same_pass_and_no_draft_method_runs() { assert_eq!(live.borrow().sets.len(), 1, "later passes apply nothing again"); assert!(live.borrow().snap, "the model holds the value"); } + +/// A page of two titled groups with labels of different lengths, and a host-labelled row that draws its own field. +struct Grouped; + +impl PreferencesModel for Grouped { + fn pages(&self) -> Vec> { + let text = |key, label| RowSpec::new(key, label, RowKind::Text("v")); + let mut page = PageSpec::new("general", "General", Vec::new()); + page.groups = vec![ + GroupSpec::new(Some("First"), vec![text("general.a", "Aa"), RowSpec::new("general.host", "Hosted", RowKind::CustomRows)]), + GroupSpec::new(Some("Second"), vec![text("general.b", "A much longer label")]), + ]; + vec![page] + } + + fn set(&mut self, _: &str, _: PrefValue) {} + + fn custom_row(&mut self, ui: &mut Ui, _: &str) { + let _ = Field::new("Hosted").show(ui, |ui, _| { + Text::new("hosted value").show(ui); + }); + } + + fn custom_page(&mut self, _: &mut Ui, _: &str) {} + + fn reset_page(&mut self, _: &str) {} +} + +fn grouped_page() -> Fixture { + let mut state = PreferencesState::default(); + let mut fixture = Fixture::new(move |ui| { + PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut Grouped); + }); + fixture.settle(); + fixture +} + +#[trial] +fn the_rows_of_every_group_of_a_page_share_one_label_column() { + let fixture = grouped_page(); + let end = |label: &str| { + let run = fixture.texts().iter().find(|run| run.text.trim_end_matches(':') == label).unwrap_or_else(|| panic!("no label {label}")); + run.rect.right() + }; + assert_eq!(end("Aa"), end("A much longer label"), "the labels of both groups end at one x"); +} + +#[trial] +fn a_host_labelled_custom_row_shows_its_label_once() { + let fixture = grouped_page(); + let tree = fixture.tree(); + 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-shell/tests/it/shell/app_shell.rs b/crates/ui-shell/tests/it/shell/app_shell.rs index 80b8bcb90..0ae4eb778 100644 --- a/crates/ui-shell/tests/it/shell/app_shell.rs +++ b/crates/ui-shell/tests/it/shell/app_shell.rs @@ -5,7 +5,8 @@ use craft_host::target::ShellInfo; use craft_ui::bars::{Bar, BarKind}; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Scroll, Show as _, ShowContainer as _}; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _}; use craft_ui::dialog::Dialog; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; @@ -137,6 +138,35 @@ fn a_top_slot_sized_by_its_content_stacks_it_and_takes_its_height() { assert!(body.min.y >= row.max.y - SLACK, "the body {body:?} starts under the row {row:?}"); } +/// A check box with its label after it sits on the options slot's middle, as a button beside it does: the slot is +/// shorter than the bar asks for, and the bar centres its members in it. +#[trial] +fn a_labelled_check_box_in_the_options_slot_sits_on_its_middle() { + let seen = Rc::new(Cell::new(None::<(Rect, Rect, Rect)>)); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let (mut check, mut button) = (Rect::NOTHING, Rect::NOTHING); + let mut on = true; + let shown = AppShell::new(WindowKey::main()) + .options_bar(true, |ui, _, _: &mut ()| { + let _ = Bar::new("Options", BarKind::Options).show(ui, |ui, _| { + check = Checkbox::new(Bind::bound(&mut on)).label("Anti-alias").show(ui).response.rect; + button = Button::new("Select and Mask").show(ui).rect; + }); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + if let Some(slot) = shown.regions.slots.iter().find(|(key, _)| *key == "options").map(|(_, rect)| *rect) { + out.set(Some((slot, check, button))); + } + }); + fixture.room(Vec2::new(600.0, 300.0)).settle(); + let (slot, check, button) = seen.get().expect("the options slot shows"); + assert!(check.height() > 0.0 && button.height() > 0.0, "both members show (check box {check:?}, button {button:?})"); + assert!((button.center().y - slot.center().y).abs() <= 1.0, "the button {button:?} sits on the slot's middle {slot:?}"); + assert!((check.center().y - slot.center().y).abs() <= 1.0, "the check box {check:?} sits on the slot's middle {slot:?}"); +} + /// A title bar in the title slot shows its leading content inside the slot, on the slot's middle. #[trial] fn a_title_bar_in_the_title_slot_shows_its_content_there() { diff --git a/crates/ui-widgets/src/bars/bar.rs b/crates/ui-widgets/src/bars/bar.rs index 570e4e7d8..711fb3490 100644 --- a/crates/ui-widgets/src/bars/bar.rs +++ b/crates/ui-widgets/src/bars/bar.rs @@ -11,7 +11,7 @@ use crate::layout_components::Row; use crate::runtime::access::Name; use crate::runtime::commands::{CommandSet as _, Commands as _}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind}; use craft_behavior::{IconId, Metrics, NavShape, Roving, Sense}; use craft_theme::ControlSize; use egui::{Response, Ui}; @@ -129,6 +129,9 @@ impl<'a> Bar<'a> { if kind == BarKind::Status { props = props.live(Politeness::Polite); } + if kind == BarKind::Options { + props = props.child_glyphs(GlyphRole::Tool); + } Bar { common: Common::new(), props, kind, commit_cancel: None, committed: false, cancelled: false, trailing: None }.label(label) } diff --git a/crates/ui-widgets/src/form/field.rs b/crates/ui-widgets/src/form/field.rs index 5f634c2fd..19d4f456b 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 { + /// 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), + Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone), + } + } +} + /// 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.text().show(ui); + } } } 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/bars/bar.rs b/crates/ui-widgets/tests/it/bars/bar.rs index 2bad1d981..bc72d33fd 100644 --- a/crates/ui-widgets/tests/it/bars/bar.rs +++ b/crates/ui-widgets/tests/it/bars/bar.rs @@ -14,6 +14,7 @@ use craft_ui::display::Text; use craft_ui::form::Field; use craft_ui::layout_components::{Row, Stack}; use craft_ui::pickers::Select; +use craft_ui::style::GlyphRole; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::layout::Block; use craft_ui::testing::{Fixture, shrink_least_runs, trial}; @@ -449,6 +450,26 @@ fn a_labelled_check_box_in_a_row_in_a_bar_lays_out_under_rtl() { assert!(label.max.x <= alpha.min.x + SLACK, "the check box {label:?} follows Alpha {alpha:?} from the right"); } +/// An icon-only button in an options bar draws its icon at the tool size, as the align strip's buttons do. +#[trial] +fn an_icon_button_in_an_options_bar_draws_its_icon_at_the_tool_size() { + let mut fixture = Fixture::new(|ui| { + Bar::new("Options", BarKind::Options).show(ui, |ui, _| { + IconButton::new(IconId::new("settings")).label("Plain").show(ui); + IconButton::new(IconId::new("settings")).label("Tool").glyphs(GlyphRole::Tool).show(ui); + }); + }); + fixture.room(Vec2::new(400.0, 80.0)).settle(); + let sides: Vec = fixture + .styles_of(std::any::type_name::>()) + .iter() + .flat_map(|seen| seen.looks.icons.iter().map(|icon| icon.side)) + .collect(); + // Buttons that resolve the same looks share one recorded style, so a single side means they agree. + assert!(!sides.is_empty(), "the buttons resolved a style"); + assert!(sides.iter().all(|side| (side - sides[0]).abs() <= 0.01), "the options bar's button and the tool button differ: {sides:?}"); +} + /// Each pass's stops, each with the roving group it registered in. type StopGroups = Rc)>>>>; diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 2ab48cf63..657f59440 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -7,7 +7,7 @@ use craft_ui::choice::Checkbox; use craft_ui::contract::{ Bind, CollectionEvent, MemoProps, MemoView, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Tracked, request_rename, }; -use craft_ui::display::Text; +use craft_ui::display::{Elide, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::{List, ListRow}; use craft_ui::popover::Popover; @@ -1595,3 +1595,63 @@ 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"); + 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:?}"); + 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"); + 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)) +} diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 538ff2eff..92a3cd6b8 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,15 +1,21 @@ //! 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 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; 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; @@ -102,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, _| { @@ -116,5 +122,46 @@ 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 +/// 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:?}"); + } } diff --git a/crates/ui-widgets/tests/it/menu/overflow.rs b/crates/ui-widgets/tests/it/menu/overflow.rs index b7ed03bb0..2cbd656e9 100644 --- a/crates/ui-widgets/tests/it/menu/overflow.rs +++ b/crates/ui-widgets/tests/it/menu/overflow.rs @@ -1,10 +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. +//! 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; @@ -108,6 +110,84 @@ fn a_menu_that_fits_shows_no_strips_and_hugs_its_rows() { assert!(((first.top() - rect.top()) - (rect.bottom() - last.bottom())).abs() < 0.5, "as tall as its rows: {rect:?}, rows {first:?} to {last:?}"); } +/// A context menu of `rows` rows on a target `top` down the fixture's 800 x 600 window, right-clicked at the target's +/// centre: the fixture, the menu's id and the pointer. +fn context_menu(top: f32, rows: usize) -> (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:?}"); +} + +/// 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| { 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 479a32dd0..d2b32e370 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -564,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). @@ -1384,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. @@ -1394,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 @@ -4223,7 +4224,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 +4588,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`