diff --git a/Cargo.lock b/Cargo.lock index add7ab337..96a9f4e10 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4252,6 +4252,7 @@ name = "craft-tracked" version = "0.1.0" dependencies = [ "craft-ui-macros", + "serde", ] [[package]] @@ -5449,7 +5450,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "emath", @@ -5505,7 +5506,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5540,7 +5541,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "accesskit", "ahash", @@ -5559,7 +5560,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5578,7 +5579,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5598,7 +5599,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "egui", @@ -5611,7 +5612,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "eframe", "egui", @@ -5688,7 +5689,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", ] @@ -5761,7 +5762,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5787,7 +5788,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[package]] name = "equator" @@ -15118,19 +15119,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" diff --git a/Cargo.toml b/Cargo.toml index 984ee25ca..8afdc685c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/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/browse/src/ui/bin/free_view.rs b/crates/browse/src/ui/bin/free_view.rs index 3b42beebd..9eddab3f5 100644 --- a/crates/browse/src/ui/bin/free_view.rs +++ b/crates/browse/src/ui/bin/free_view.rs @@ -32,7 +32,7 @@ where let (entries, _) = entries_of(model, state, collator); let searching = !state.search.trim().is_empty(); let shown = Cards::new(model, entries); - let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); if let Some(key) = rename { request_rename(ui.ctx(), id, &key); } diff --git a/crates/browse/src/ui/bin/icon.rs b/crates/browse/src/ui/bin/icon.rs index 941e44333..9fde6bb1d 100644 --- a/crates/browse/src/ui/bin/icon.rs +++ b/crates/browse/src/ui/bin/icon.rs @@ -152,7 +152,7 @@ where let (entries, user_order) = entries_of(model, state, collator); let searching = !state.search.trim().is_empty(); let cards = Cards::new(model, entries); - let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); if let Some(key) = rename { request_rename(ui.ctx(), id, &key); } diff --git a/crates/browse/src/ui/bin/list.rs b/crates/browse/src/ui/bin/list.rs index 2893f2225..78c587f30 100644 --- a/crates/browse/src/ui/bin/list.rs +++ b/crates/browse/src/ui/bin/list.rs @@ -103,7 +103,7 @@ where let thumb = state.settings.thumbnails; let specs = columns_of(columns, &state.settings.widths, words.name.clone()); let value_columns: Vec = specs.iter().map(|spec| spec.key.clone()).filter(|key| *key != NAME).collect(); - let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); let tile_words = Env::of(ui).words::(); if let Some(key) = rename { request_rename(ui.ctx(), id, &key); diff --git a/crates/color-ui/src/gradient/value.rs b/crates/color-ui/src/gradient/value.rs index a0d70a8fc..76819b4c2 100644 --- a/crates/color-ui/src/gradient/value.rs +++ b/crates/color-ui/src/gradient/value.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; /// How a gradient's opacity is stored, which decides the rows of its stop bar. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[non_exhaustive] pub enum StopRows { /// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is @@ -36,6 +37,7 @@ pub enum StopRow { /// A colour stop. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct ColorStop { @@ -56,6 +58,7 @@ pub struct ColorStop { /// An opacity stop of a [`StopRows::Split`] gradient. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct OpacityStop { @@ -120,6 +123,7 @@ impl OpacityStop { /// A gradient's stops, each list sorted by location. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct GradientStops { diff --git a/crates/color-ui/src/palette.rs b/crates/color-ui/src/palette.rs index b8d97267e..fb7b69230 100644 --- a/crates/color-ui/src/palette.rs +++ b/crates/color-ui/src/palette.rs @@ -97,6 +97,7 @@ impl SwatchFormat { /// A swatch colour in its own model. #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(tag = "model", content = "values", rename_all = "camelCase")] pub enum SwatchColor { /// Encoded RGB, 0–1 each, in the RGB working space. @@ -148,6 +149,7 @@ impl SwatchColor { /// How an `.ase` file marks a colour. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] pub enum SwatchKind { #[default] @@ -161,6 +163,7 @@ pub enum SwatchKind { /// One named swatch. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct SwatchEntry { /// The swatch's label. pub name: String, @@ -181,6 +184,7 @@ impl SwatchEntry { /// A named group of swatches, as the Swatches panel shows them. A file without groups reads as /// one group named after the file. #[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct SwatchGroup { /// The group's label. pub name: String, diff --git a/crates/color-ui/src/ui/disc.rs b/crates/color-ui/src/ui/disc.rs index dda1ca904..8d953c248 100644 --- a/crates/color-ui/src/ui/disc.rs +++ b/crates/color-ui/src/ui/disc.rs @@ -226,7 +226,8 @@ impl Component for ColorDisc<'_> { /// A band across the width it is given, as tall as the square that fits it: the picture is centred in it. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - Vec2::new(cx.picture_width(cx.style.least, f32::INFINITY), cx.picture_width(cx.style.least, cx.style.most)) + let most = cx.style.most.max(cx.style.least); + cx.picture_size(cx.style.least, f32::INFINITY, |width| width.min(most)) } fn sense(&self) -> Sense { 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. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + // 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 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); run.output = Some(Arc::new(out.clone())); @@ -114,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/mount.rs b/crates/ui-contract/src/contract/mount.rs index e56a51a47..34137bf9a 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -342,6 +342,8 @@ impl Host for ViewportHost { return; } let ctx = parent.ctx().clone(); + // The window's content runs in its own viewport's pass, which no record of this one holds. + crate::runtime::replay::block(&ctx); let focus = self.overlay.focus; let mut window_rules = self.overlay.clone(); window_rules.dismiss.outside = Outside::Keep; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 8ce555ead..e2c8379e3 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -96,8 +96,7 @@ pub(super) fn popup_dismissal( /// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { - let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) - else { + let Some(press) = pointer::primary_press(ctx) else { return false; }; let inside_family = overlay::family(ctx, layer.id).iter().filter_map(|id| overlay::entry(ctx, *id)).any(|entry| entry.rect.contains(press)); @@ -125,6 +124,8 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) { return None; } + // The focus may be in no record of the layer's host: the Escape is read from the events of the frame. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent); let step = keys::scope_escape(ctx, policy.cancel, pointer::press_captured(ctx), false)?; matches!(step, craft_behavior::focus::EscapeStep::CloseScope).then_some(CloseReason::Escape) } diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index a37aa15b5..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(); @@ -180,7 +181,12 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U }; let parent = overlay::drawing_parent(ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); - let spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting }; + let mut spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + // A popup's or a modal's layer, and any layer while it fades out, has a root node, made before its `Area` shows so + // egui hangs the layer's content below it. A sizing pass of the `Area` reports nothing. + if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { + spec.root = areas::content_rect(ctx, &spec).map(|rect| access::report_layer(ctx, layer.id, rect, layer.exiting)); + } // The opener of the layer's scope is the stop focused when the layer first appears: egui's modal gate takes focus // from the widgets below a modal layer by the first pass that shows the layer. A dropdown that keeps its anchor's key // focus belongs to the component that opened it: a press moves the key focus onto that component only at the end of @@ -207,8 +213,8 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U // from the opener's inherited env with the layer-local fields fresh, and outside the opener's scopes. let installed = Env::install_for(ui, layer.env.capture().env()); let real = !ui.is_sizing_pass(); - if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) { - access::report_layer(ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting); + if spec.root.is_some() && layer.exiting { + access::hide_exiting_content(ctx, ui.unique_id()); } // Every layer is a focus scope, one without a policy (`FocusPolicy::NONE`) included: its stops are the layer's, // not those of the scope it was opened in, so a trap around it leaves them out (a menu's companion bar). @@ -225,6 +231,9 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U // checks them. Without the boundary a tooltip's text was checked against the body's kept transcript, which // asked for a discard pass every other frame while the tooltip showed. access::scope::outside(ctx, || layout_memory::boundary(ctx, true, || body(ui))); + if real && overlay.rank.is_modal() { + access::report_modal(ctx, layer.id); + } if real { focus::pop_scope(ctx); } @@ -245,6 +254,10 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U entry.absorbs = overlay.dismiss.outside == Outside::Absorb; overlay::record(ctx, entry); let dismissed = if layer.exiting { None } else { dismissal(ctx, layer, shown.rect, anchor, scope, &mut memory) }; + // The layer closes after its body ran: the run shows it open, so a record of the run is not replayed. + if dismissed.is_some() { + crate::runtime::replay::note_unsettled(ctx); + } if let Some(nudge) = &nudge { // `dismissal` above records the press beside the layer (`dismissal.rs`, `note_pressed_outside`), so the nudge // starts after it and moves the layer from the next pass on. @@ -275,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; @@ -282,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); @@ -302,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())); @@ -357,14 +371,18 @@ fn show_in_popup( // The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts. let opener = layer.env.capture().env(); let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root)); - let spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting }; + let mut spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + // The layer's root node, made before its `Area` shows, as in `host`. + if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { + spec.root = areas::content_rect(&ctx, &spec).map(|rect| access::report_layer(&ctx, layer.id, rect, layer.exiting)); + } overlay::begin_layer(&ctx, layer.id, tier, layer.exiting, placed.side); let shown = areas::show_layer(&ctx, &spec, |ui| { areas::fade(ui, layer.fade * overlay.opacity); let installed = Env::install_for(ui, env.clone()); let real = !ui.is_sizing_pass(); - if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) { - access::report_layer(&ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting); + if spec.root.is_some() && layer.exiting { + access::hide_exiting_content(&ctx, ui.unique_id()); } // The focused stop the scope returns to is in the opener's window; the opener's window takes the OS focus // back when the popup closes (`windows::close_popup`). @@ -377,6 +395,9 @@ fn show_in_popup( ui.set_min_size(overlay.size_limits.min.min(placed.room)); } access::scope::outside(&ctx, || layout_memory::boundary(&ctx, true, || body(ui))); + if real && overlay.rank.is_modal() { + access::report_modal(&ctx, layer.id); + } if real { focus::pop_scope(&ctx); } @@ -487,6 +508,8 @@ impl Nudge { /// The layer-stack side of an OS-window mount: records the window as an entry of its viewport's stack (rank, key /// class, scope; no egui layer) and decides its dismissal after the body ran. `rect` is the window's inner rect. pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> LayerOut { + // The entry stands for a window of another viewport, whose pass no record of this one holds. + crate::runtime::replay::block(ctx); let overlay = layer.overlay; let mut memory = recall(layer, ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); 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, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); // The column's first sweep learns which of its held children measured narrower than it settles on. if let Some(ColumnSweep::Count(column)) = env.column { - crate::layout::report_held(&ctx, column, flowed.width()); + crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Fill, flowed.width()); } let across = Vec2::new(size.x.max(flowed.width()).max(column), flowed.height()); if rtl { Rect::from_min_size(Pos2::new(flowed.max.x - across.x, flowed.min.y), across) } else { Rect::from_min_size(flowed.min, across) } } else { let fill = p.p.fills_width() && !p.p.fills_width_only(); let size = if inert { Vec2::ZERO } else { size }; - steps::place(ui, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }) + let placed = steps::place(ui, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); + // A picture its measure held (`MeasureCx::picture_size`) reports its placed width, padding included. + if let Some(ColumnSweep::Count(column)) = env.column + && crate::layout::held_kind(&ctx, column, id) == Some(crate::layout::HeldKind::Picture) + { + crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Picture, placed.width()); + } + placed }; (rect, held) } @@ -1570,9 +1577,14 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { let room = match at { ShowAt::Rect(rect) => Some(rect.width()), // A measuring run in a content column asks for what the content needs: nothing there fills the room. Once the - // column settled its width, a child that fills its width measures at that width. + // column settled its width, a child that fills its width, or a picture its first sweep held, measures at + // that width. ShowAt::Flow => match env.column { - Some(ColumnSweep::Column(width)) if env.content_column && t.fills_width() => Some(width), + Some(ColumnSweep::Column(column, width)) + if env.content_column && (t.fills_width() || crate::layout::held_kind(ctx, column, id) == Some(crate::layout::HeldKind::Picture)) => + { + Some(width) + } _ => Some(crate::layout::flow_room(ui).x) .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(ctx))), }, diff --git a/crates/ui-contract/src/contract/steps/value.rs b/crates/ui-contract/src/contract/steps/value.rs index 0618346c3..e3e265fb8 100644 --- a/crates/ui-contract/src/contract/steps/value.rs +++ b/crates/ui-contract/src/contract/steps/value.rs @@ -10,12 +10,11 @@ use craft_behavior::{CancelReason, EditEvent, Gesture, Mixed, Value}; use egui::{Context, Id}; use std::sync::Arc; -/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the pass its value -/// step last ran in, the `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased +/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the +/// `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased /// hover, press and on. pub(crate) struct Shown { pub copy: Option>, - pub drawn: u64, pub state: ShownState, } @@ -38,13 +37,13 @@ impl ShownState { impl Clone for Shown { fn clone(&self) -> Self { - Shown { copy: self.copy.clone(), drawn: self.drawn, state: self.state.clone() } + Shown { copy: self.copy.clone(), state: self.state.clone() } } } impl Default for Shown { fn default() -> Self { - Shown { copy: None, drawn: 0, state: ShownState::default() } + Shown { copy: None, state: ShownState::default() } } } @@ -99,10 +98,9 @@ fn resolve_value(comp: &mut dyn ValueSource, stage: &mut MemoryStag let slot = gesture_key(id); let (serial, all_reason) = crate::runtime::edit::latest(stage.ctx()); let mut cancelled = None; - // A component not drawn for a pass loses its press at the end hook; its running gesture ends here, the first pass it is - // drawn again. - let pass_nr = crate::runtime::pointer::pass_of(stage.ctx()); - let removed = std::mem::replace(&mut stage.shown::>(id).drawn, pass_nr).saturating_add(1) < pass_nr; + // A component not shown for a pass, by a run or a replay of one, loses its press at the end hook; its running gesture + // ends here, the first pass it is shown again. + let removed = !crate::runtime::memory::shown_last_pass(stage.ctx(), id); if stage.shown::>(slot).is_running() { // `(given, value)` of a single-valued binding the app owns. let host = comp.binding().and_then(|bind| match bind.get() { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 2daf30757..f65e44ecc 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -138,21 +138,40 @@ pub(crate) struct Cursors(IdMap); #[derive(Default)] pub(crate) struct FillCounts(IdMap); -/// The narrowest width a held fill-width child of each content-sized `Stack` column measured at in the first sweep of -/// the column's measuring run (`report_held`), by column id. -#[derive(Default)] -pub(crate) struct HeldWidths(IdMap); +/// What makes a child of a content-sized `Stack` column a held child: it measures at its own width while the column +/// settles its width from the others, and the column's second sweep gives it the settled width. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HeldKind { + /// A fill-width child: it shows across the width the column settles on. + Fill, + /// A picture whose height follows from its width that took its least for want of room + /// (`MeasureCx::picture_size`): it shows at the width it sizes at in the column's width, which may be narrower than + /// the column. + Picture, +} -/// Reports a held fill-width child of the content-sized column `column` in its first sweep: the `width` it measured -/// at. A column with no first sweep open takes no report. -pub(crate) fn report_held(ctx: &egui::Context, column: Id, width: f32) { +/// The held children of each content-sized `Stack` column in its measuring run, by column id: each child's kind and +/// the narrowest width it measured at in the column's first sweep, by child id. +#[derive(Default)] +pub(crate) struct HeldWidths(IdMap>); + +/// Reports a held child `child` of the content-sized column `column` in its first sweep: its kind and the `width` it +/// measured at. A column with no first sweep open takes no report. +pub(crate) fn report_held(ctx: &egui::Context, column: Id, child: Id, kind: HeldKind, width: f32) { pass_state::with::(ctx, |held| { - if let Some(narrowest) = held.0.get_mut(&column) { - *narrowest = narrowest.min(width); + if let Some(children) = held.0.get_mut(&column) { + let entry = children.entry(child).or_insert((kind, width)); + entry.1 = entry.1.min(width); } }); } +/// The kind of the held child `child` of the column `column`, as the column's first sweep reported it, while the +/// column's measuring run runs. +pub(crate) fn held_kind(ctx: &egui::Context, column: Id, child: Id) -> Option { + pass_state::with::(ctx, |held| held.0.get(&column).and_then(|children| children.get(&child)).map(|(kind, _)| *kind)) +} + /// What the first child a measuring sweep placed in flow in each open target reported (`Scoped::first_line`): the y /// of its first line's centre, or `None` for a child with no line of its own. A container's measuring sweep opens and /// closes its header's and body's targets; a body's sweep starts its own target afresh. @@ -577,11 +596,18 @@ pub(crate) struct ShrinkCap { pub width: f32, /// The unit dropped out of the row (`shrink_or_drop`): it shows nothing and takes no place. pub dropped: bool, + /// The row gave the unit less than it asks for in no room, or dropped it: what the unit shows depends on the row's + /// room. A unit the row did not narrow shows as in no room. + pub narrowed: bool, } /// What the shrink step of the row `row` gave its unit `leaf` in this pass's measuring run. pub(crate) fn shrink_cap(ctx: &egui::Context, row: Id, leaf: Id) -> Option { - layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, dropped)| ShrinkCap { width: found.took.x, dropped }) + layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, given)| ShrinkCap { + width: found.took.x, + dropped: given.dropped, + narrowed: given.narrowed, + }) } fn shrink_key(row: Id, leaf: Id) -> Id { @@ -685,9 +711,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() } @@ -768,21 +798,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 }; @@ -944,13 +976,14 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: /// is bounded: each sweep is `run_sharing`'s, with the column's sweep (`ColumnSweep`) in its children's env. It adds no /// `Ui` of its own, so the children have the ids `run_sharing` gives them when the column's width is not bounded. /// -/// A held fill-width child measures at its own width while the column settles its width from the others, so it may -/// measure narrower than it shows. A measuring run sweeps the children once, each held child reporting the width it -/// measured at (`report_held`). When one of them measured narrower than the column settled on, it sweeps them again -/// with that width, at which the held children measure across the column and the others reuse their records; else the -/// first sweep stands, and each held child keeps the record it made at its own width, which is the column's. It -/// records which (`sub(id, "column")`): the real run gives the held children the width the column shows at only after -/// a second sweep, so each shows as its records were made. +/// A held child (`HeldKind`: a fill-width child, or a picture that took its least for want of room) measures at its +/// own width while the column settles its width from the others, so it may measure narrower than it shows. A +/// measuring run sweeps the children once, each held child reporting the width it measured at (`report_held`). When +/// one of them measured narrower than the column settled on, it sweeps them again with that width, at which the held +/// children measure in the column's width and the others reuse their records; else the first sweep stands, and each +/// held child keeps the record it made at its own width, which is the column's. It records which +/// (`sub(id, "column")`): the real run gives the held children the width the column shows at only after a second +/// sweep, so each shows as its records were made. // PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse // rule: a container that reused its content-sized record there would be laid out across in the real run under records // not made across. @@ -967,29 +1000,34 @@ fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: }; if !measure::active(&ctx) { let across = this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.0); - let column = across.then(|| ColumnSweep::Column(flow_room(ui).x)); + let column = across.then(|| ColumnSweep::Column(id, flow_room(ui).x)); return sweep(ui, column, &mut body); } let (inner, rect, again) = crate::contract::keeping_ids(&ctx, || { - pass_state::with::(&ctx, |held| held.0.insert(id, f32::INFINITY)); + pass_state::with::(&ctx, |held| held.0.insert(id, IdMap::default())); let env = column_env(Some(ColumnSweep::Count(id))); let installed = Env::install_for(ui, env.clone()); let (inner, rect) = measure_sharing(ui, &env, id, Axis::Y, layout, &mut body); Env::restore(&ctx, installed); - let narrowest = pass_state::with::(&ctx, |held| held.0.remove(&id)); + let narrowest = pass_state::with::(&ctx, |held| { + held.0.get(&id).map_or(f32::INFINITY, |children| children.values().fold(f32::INFINITY, |least, (_, width)| least.min(*width))) + }); // Half a point: less than a pixel shows at any scale the box runs. - let again = narrowest.is_some_and(|narrowest| narrowest < rect.width() - 0.5); + let again = narrowest < rect.width() - 0.5; ((inner, rect, again), again) }); let column = rect.width(); // 0 when the first sweep stands, so nothing an earlier run of the pass left is read. found(&ctx, true, key, Vec2::ZERO, Vec2::new(if again { column } else { 0.0 }, 0.0)); - if again { - sweep(ui, Some(ColumnSweep::Column(column)), &mut body) + // The second sweep reads the held children's kinds (`held_kind`); the column's record closes after it. + let inner = if again { + sweep(ui, Some(ColumnSweep::Column(id, column)), &mut body) } else { ui.advance_cursor_after_rect(rect); inner - } + }; + pass_state::with::(&ctx, |held| held.0.remove(&id)); + inner } /// What places the children in flow of a body that places them itself. @@ -1191,8 +1229,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, } @@ -1201,8 +1241,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/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index bc6ed6396..c9afb1e1d 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,8 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BodyLine, BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, - flow_region, flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, - report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, - take_cell, take_in_flow, view_room, + BodyLine, BracketTook, HeldKind, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, + flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, + place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, + take_bracket, take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index b9645b533..ae2716b40 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -400,7 +400,15 @@ impl<'a> Draw<'a> { self.initial(rect, letter, StyleColor(color)); return; } - _ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon, self.data != DataMode::Full), + _ => super::icon::paint( + self.painter, + self.env.tokens, + self.env.direction, + rect, + icon, + self.data != DataMode::Full, + self.env.ink == Ink::OnDark, + ), } match icon.badge { Some(super::IconMark::Dot(badge)) => { @@ -487,6 +495,11 @@ impl<'a> Draw<'a> { self.painter.extend(super::rule::Rule::shapes(look, from, to, self.painter.pixels_per_point())); } + /// Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a grip's dotted line. + pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32) { + self.painter.extend(super::rule::Rule::dotted(look, from, to, gap, self.painter.pixels_per_point())); + } + /// Paints a surface of `kind` (tracks, plot wells). pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners) { let style = surface_style(self.env.tokens, kind); diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 57e414720..6a8bedfc8 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -268,8 +268,10 @@ pub fn icon_names() -> &'static [&'static str] { } /// Paints `spec`'s glyph centred in the square of `rect`'s shorter side; `Draw::icon` adds the badge. `single_ink` paints -/// every layer of an app icon in the one colour: the icon of a component in its disabled state. -pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool) { +/// every layer of an app icon in the one colour: the icon of a component in its disabled state. `on_dark` is whether +/// the icon stands on a strong fill or scrim (the surface's ink is `Ink::OnDark`): its accent parts then paint in the +/// icon's colour, since `accent.solid` would vanish on the brand fill. +pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool, on_dark: bool) { let color = spec.color_in(tokens); let rtl = direction == Direction::Rtl; let side = rect.width().min(rect.height()); @@ -283,7 +285,7 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, IconSource::Glyph(glyph) => glyph.paint(painter, tokens, square, color, rtl && glyph.directional() && spec.mirror == Mirror::Auto), IconSource::Svg(id) => { if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.mirror) { - icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink)); + icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink, on_dark || spec.ink == Ink::OnDark)); } } IconSource::Mark(badge) => super::pointer_art::paint_badge(painter, tokens, direction, square, *badge, color), @@ -396,8 +398,13 @@ impl LayerInks { } /// The inks of an icon painted in `color`: the accent parts in `colors.accent.solid` and the fixed parts as drawn, - /// except that with `single_ink` (a disabled component) every layer paints in `color`. - pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool) -> Self { + /// except that with `single_ink` (a disabled component) every layer paints in `color`, and with `on_dark` (a strong + /// fill or scrim, where the accent colour would vanish) the accent parts paint in `color` and the fixed parts stay + /// as drawn. + pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool, on_dark: bool) -> Self { + if on_dark && !single_ink { + return LayerInks { ink: color, accent: color, fixed: None }; + } if single_ink { return LayerInks::single(color); } diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index 053c41e4c..d50fdbd9c 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -469,9 +469,6 @@ const MINOR_SHARE: f32 = 0.45; /// How many times a thinned grid doubles its step before it gives up. const MAX_DOUBLINGS: u32 = 32; -/// The radius of a dot, in screen points. -const DOT_RADIUS: f32 = 0.6; - /// What a grid does when its lines come closer than the minimum step. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] @@ -693,7 +690,7 @@ pub fn grid_lines_with(look: &GridLook, grid: &GridLines, ink: &GridInk, pixels_ match ink.stroke { GridStroke::Solid => shapes.extend(Rule::shapes(&RuleLook { color, width: look.width }, a, b, pixels_per_point)), GridStroke::Dashed => shapes.extend(dashed(&[a, b], Dashes::new(look.dash, look.gap), look.width.points(pixels_per_point), color)), - GridStroke::Dots => shapes.extend(Shape::dotted_line(&[a, b], color, look.gap, DOT_RADIUS)), + GridStroke::Dots => shapes.extend(Rule::dotted(&RuleLook { color, width: look.width }, a, b, look.gap, pixels_per_point)), } } } diff --git a/crates/ui-contract/src/primitives/rule.rs b/crates/ui-contract/src/primitives/rule.rs index 522edbb92..3cf908347 100644 --- a/crates/ui-contract/src/primitives/rule.rs +++ b/crates/ui-contract/src/primitives/rule.rs @@ -1,7 +1,7 @@ //! `Rule`: dividers, edges, grid lines and drop marks, with one pixel-snap rule. use crate::style::RuleLook; -use egui::{Pos2, Rect, Shape, Stroke}; +use egui::{Mesh, Pos2, Rect, Shape, Stroke, Vec2}; pub use crate::style::RuleKind; @@ -47,16 +47,20 @@ impl RectSide { } } +/// `v` (points) snapped for a line `physical` pixels wide: an odd width on a physical pixel centre, an even one on a +/// pixel edge. +fn snap(v: f32, physical: f32, pixels_per_point: f32) -> f32 { + let px = v * pixels_per_point; + let snapped = if physical % 2.0 == 1.0 { px.floor() + 0.5 } else { px.round() }; + snapped / pixels_per_point +} + impl Rule { /// The line from `from` to `to`, snapped across its direction: a line whose physical width is odd sits on a /// pixel centre, an even one on a pixel edge, and no line is thinner than one physical pixel. pub fn shapes(look: &RuleLook, from: Pos2, to: Pos2, pixels_per_point: f32) -> Vec { let physical = look.width.pixels(pixels_per_point); - let snap = |v: f32| { - let px = v * pixels_per_point; - let snapped = if physical % 2.0 == 1.0 { px.floor() + 0.5 } else { px.round() }; - snapped / pixels_per_point - }; + let snap = |v: f32| snap(v, physical, pixels_per_point); let (from, to) = if (from.y - to.y).abs() <= (from.x - to.x).abs() { (Pos2::new(from.x, snap(from.y)), Pos2::new(to.x, snap(to.y))) } else { @@ -65,6 +69,35 @@ impl Rule { vec![Shape::line_segment([from, to], Stroke::new(physical / pixels_per_point, look.color))] } + /// The dotted form of the line from `from` to `to`: square dots as wide as the line, `gap` points apart, the run + /// of whole dots centred between the ends (a grip, a dotted guide or grid line). The gap is whole physical pixels, + /// at least one, and each dot's centre is snapped on both axes by the rule `shapes` snaps across with, so every dot + /// covers whole physical pixels and dots on a level or upright line are evenly spaced. The dots are one mesh. + pub fn dotted(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, pixels_per_point: f32) -> Vec { + let ppp = pixels_per_point.max(f32::EPSILON); + let side = look.width.pixels(ppp); + let gap = (gap * ppp).round().max(1.0); + let length = (to - from).length() * ppp; + // The run leaves at least a physical pixel of the line free, so snapping, which moves a dot at most half a + // pixel, keeps every dot between the ends. + let count = ((length - 1.0 + gap) / (side + gap)).floor(); + if !count.is_finite() || count < 1.0 { + return Vec::new(); + } + let direction = (to - from).normalized(); + let first = (length - (count * side + (count - 1.0) * gap)) / 2.0 + side / 2.0; + let dot = Vec2::splat(side / ppp); + // One mesh of plain quads: a filled rect two pixels wide or less is tessellated as a line segment, whose ends + // the tessellator rounds inward, and a one-pixel dot drawn that way vanishes. + let mut mesh = Mesh::default(); + for i in 0..count as usize { + let centre = from + direction * ((first + i as f32 * (side + gap)) / ppp); + let centre = Pos2::new(snap(centre.x, side, ppp), snap(centre.y, side, ppp)); + mesh.add_colored_rect(Rect::from_center_size(centre, dot), look.color); + } + vec![Shape::mesh(mesh)] + } + /// The line along the `side` edge of `rect`, on the physical pixels just inside it: a row's bottom rule or a /// cell's gridline, which a line centred on the edge would put on the first pixel outside, under the next row's /// clip or the next cell's fill. diff --git a/crates/ui-contract/src/primitives/textures/thumbnails.rs b/crates/ui-contract/src/primitives/textures/thumbnails.rs index 697befc80..431810161 100644 --- a/crates/ui-contract/src/primitives/textures/thumbnails.rs +++ b/crates/ui-contract/src/primitives/textures/thumbnails.rs @@ -486,7 +486,7 @@ fn paint_placeholder(cx: &ContentPainterCx<'_>, rect: Rect, paper: Option, rect: Rect) { let side = cx.tokens.size.icon.sm.min(rect.width().min(rect.height())); let icon = Rect::from_center_size(rect.center(), vec2(side, side)); - crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false); + crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false, false); } /// A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets, diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 1f80642c2..5864bd09e 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -22,10 +22,12 @@ pub use crate::runtime::egui::access::bounds; #[doc(hidden)] pub use emit::SubDecl; #[doc(hidden)] +pub use emit::layer_root; +#[doc(hidden)] pub use emit::report_sub; #[doc(hidden)] pub use emit::sub_node_id; -pub(crate) use emit::{FaceFacts, Own, PopupShown, report, report_layer}; +pub(crate) use emit::{FaceFacts, Own, PopupShown, hide_exiting_content, report, report_layer, report_modal}; pub use live::announce; pub(crate) use live::{begin_pass as begin_live_pass, end_pass as end_live_pass}; pub use scope::{FieldLabel, FieldLabelRole}; diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index 1631aefad..4cb7b5585 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -52,7 +52,7 @@ pub(crate) struct Own<'a> { /// A popup an anchor shows this pass. #[derive(Clone, Copy, Debug)] pub(crate) struct PopupShown { - /// The popup's layer id: the id of its root node. + /// The popup's layer id (its root node is [`layer_root`]'s). pub id: Id, pub kind: PopupKind, pub open: bool, @@ -257,7 +257,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) { let expanded = expanded_of(own.flags, access.expanded.or_else(|| popup.filter(|_| !own.popups_by_part).map(|popup| popup.open))); let mut relations = access.relations.clone(); relations.labelled_by.extend(name.labelled_by.iter().copied()); - relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| popup.id)); + relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| layer_root(popup.id))); let numeric = access.numeric.as_ref(); let mut spec = NodeSpec::new(own.role); spec.rect = Some(own.rect); @@ -419,19 +419,34 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { } } -/// The root node of an overlay layer: the layer's content attaches below it, and a modal layer's root is modal. An -/// exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported while it still -/// paints; the ids stay the same if the layer reopens. -pub(crate) fn report_layer(ctx: &Context, id: Id, content: Id, rect: Rect, modal: bool, exiting: bool) { - adapter::register_parent(ctx, content, 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 +/// takes the layer's id for its widget and node, inside the layer's content, which attaches below the root. +pub fn layer_root(id: Id) -> Id { + sub(id, "layer") +} + +/// Writes the root node of the overlay layer `id`, whose content takes `rect`, and returns its id. The layer's content +/// hangs below it. An exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported +/// while it still paints; the ids stay the same if the layer reopens. Called before the layer's `Area` shows, which +/// egui hangs below the root. The root is a plain container: a modal layer's flag sits on its container component's +/// node ([`report_modal`]), which carries the role, since screen readers drop a container without one. +pub(crate) fn report_layer(ctx: &Context, id: Id, rect: Rect, exiting: bool) -> Id { + let root = layer_root(id); let mut spec = NodeSpec::layer_root(); spec.rect = Some(rect); - spec.modal = modal; spec.hidden = exiting; - write_node(ctx, id, &spec); - if exiting { - // The content `Ui` can attach to the viewport rather than to the root (a popup body that names its own - // parent), so it is hidden itself. - adapter::hide(ctx, content); - } + write_node(ctx, root, &spec); + root +} + +/// Marks the node of the modal overlay layer `id` modal: the node its container component wrote with the layer's id +/// and its role. Called after the layer's body ran, so the node exists when the component reported it. +pub(crate) fn report_modal(ctx: &Context, id: Id) { + adapter::set_modal(ctx, id); +} + +/// Hides the node of the content `Ui` of an exiting overlay layer: a popup body that names its own parent can hang +/// its content outside the layer's root. +pub(crate) fn hide_exiting_content(ctx: &Context, content: Id) { + adapter::hide(ctx, content); } diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 0f109e029..7e68df41a 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -180,7 +180,7 @@ pub trait WindowDropTarget

{ /// Where a drop target lies: a rect on an egui layer, in that layer's space. A component's own target lies over its /// visible rect on its layer; a component that takes drops over an area it does not draw (a preset browser's canvas) /// names the area with [`DropZone::new`] and registers with [`zone_target`]. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct DropZone { layer: Layer, rect: Rect, diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index be6d1ac13..dd78c1a09 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -167,8 +167,17 @@ pub(crate) fn pass_through(ctx: &Context, id: Id) { }); } -/// Reports `id` as the focused node of this pass. +/// Marks the node of `id` modal, when the pass has written it. +pub(crate) fn set_modal(ctx: &Context, id: Id) { + if ctx.has_accesskit_node(id) { + ctx.accesskit_node_builder(id, accesskit::Node::set_modal); + } +} + +/// Reports `id` as the focused node of this pass. A replay of the run that reported it reports it again: a view that +/// holds focus replays while nothing reaches it. pub(crate) fn set_focus(ctx: &Context, id: Id) { + crate::runtime::replay::journal(ctx, || id, |ctx, &id| set_focus(ctx, id)); with_emitted(ctx, |emitted| emitted.focus_set = true); ctx.set_accesskit_focus(id); } @@ -209,6 +218,37 @@ pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) { emit(ctx, id); } +/// The trials' pass-end check that egui's AccessKit parents of the pass hold no cycle; panics naming the ids of the +/// first one found. egui places a node under the first ancestor that has a node by walking the parents, which a cycle +/// sends into endless recursion when no node of the cycle exists yet: a replay adds a run's nodes in the order they +/// were created, and a run only tolerates a cycle while some node of it already exists. +#[cfg(feature = "testing")] +pub(crate) fn check_parents_acyclic(ctx: &Context) { + let cycle = ctx.with_accesskit_parents(|parents| { + let mut acyclic = IdSet::default(); + for &start in parents.keys() { + let mut path: Vec = Vec::new(); + let mut on_path = IdSet::default(); + let mut at = Some(start); + while let Some(id) = at.filter(|id| !acyclic.contains(id)) { + if !on_path.insert(id) { + let from = path.iter().position(|on| *on == id).unwrap_or_default(); + return Some(path.split_off(from)); + } + path.push(id); + at = parents.get(&id).copied(); + } + acyclic.extend(path); + } + None + }); + let cycle = cycle.flatten(); + assert!( + cycle.is_none(), + "the AccessKit parents of the pass hold a cycle: {cycle:?}, each the parent of the one before and the first the parent of the last" + ); +} + /// Notes that the runtime emitted the node of `id`. fn emit(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| emitted.emit(id)); diff --git a/crates/ui-contract/src/runtime/egui/access/node.rs b/crates/ui-contract/src/runtime/egui/access/node.rs index 6fcfcab2f..85a51ef96 100644 --- a/crates/ui-contract/src/runtime/egui/access/node.rs +++ b/crates/ui-contract/src/runtime/egui/access/node.rs @@ -86,7 +86,6 @@ pub(crate) struct NodeSpec { pub disabled: bool, pub read_only: bool, pub required: bool, - pub modal: bool, pub actions: Vec, pub custom_actions: Vec<(i32, String)>, /// The content keeps its left-to-right order under a right-to-left interface. @@ -133,7 +132,6 @@ impl NodeSpec { disabled: false, read_only: false, required: false, - modal: false, actions: Vec::new(), custom_actions: Vec::new(), ltr_axis: false, @@ -295,7 +293,6 @@ fn write_states(node: &mut accesskit::Node, spec: &NodeSpec) { (spec.disabled, accesskit::Node::set_disabled), (spec.read_only, accesskit::Node::set_read_only), (spec.required, accesskit::Node::set_required), - (spec.modal, accesskit::Node::set_modal), ] { if on { set(node); diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index bf7c2d9be..a27b7a8b1 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -1,5 +1,6 @@ //! `Area` with its left-top pivot, `Order`, sublayers, transform layers and `set_layer_order`. +use crate::runtime::shift::Shift; #[cfg(feature = "testing")] use egui::Ui; use egui::emath::TSTransform; @@ -211,6 +212,9 @@ pub(crate) struct LayerSpec { pub at: Pos2, /// Whether the layer takes input; a tooltip and the ghost layer never do. pub interactable: bool, + /// The accessibility node the layer's content hangs under, created before the layer shows: egui attaches the + /// layer's `Area`, and through it the content, below it. + pub root: Option, } /// What `show_layer` reports. @@ -224,20 +228,81 @@ pub(crate) struct LayerShown { /// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. The motion /// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off. pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut egui::Ui)) -> LayerShown { - let shown = egui::Area::new(spec.id) + let mut sizing = false; + let mut area = egui::Area::new(spec.id) .fade_in(false) .order(spec.tier.order()) .pivot(egui::Align2::LEFT_TOP) .fixed_pos(spec.at) .constrain(false) - .interactable(spec.interactable) - .show(ctx, body); + .interactable(spec.interactable); + if let Some(root) = spec.root { + area = area.accessibility_parent(root); + } + let shown = area.show(ctx, |ui| { + sizing = ui.is_sizing_pass(); + body(ui); + }); + register_area(ctx, shown.response.layer_id, sizing); // The `Area`'s own widget senses a click over the whole layer, beneath the layer's widgets: it stands for none of // the layer's components. crate::runtime::pointer::record_layer_widget(ctx, shown.response.id); LayerShown { rect: shown.response.rect, layer: shown.response.layer_id } } +/// The rect the content of the layer `spec` shows takes in this pass, before the layer shows: its left-top and the size +/// egui keeps for its `Area`. `None` when the layer shows in an egui sizing pass, which paints and reports nothing. +pub(crate) fn content_rect(ctx: &Context, spec: &LayerSpec) -> Option { + egui::AreaState::load(ctx, spec.id).and_then(|state| state.size).map(|size| Rect::from_min_size(spec.at, size)) +} + +/// What an overlay layer's `Area` keeps in egui's memory for a pass it shows in: its egui layer, its left-top in +/// screen space, its size and whether it takes input. +#[derive(Clone, Copy, Debug, PartialEq)] +struct AreaRecord { + layer: LayerId, + at: Pos2, + size: Vec2, + interactable: bool, +} + +/// A replay moves the left-top; the size stays. +impl Shift for AreaRecord { + fn shifted(&self, by: &egui::RecordShift) -> Self { + AreaRecord { at: self.at.shifted(by), ..*self } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + AreaRecord { at: self.at.snapped(&to.at, within), ..*self } + } +} + +/// Registers the `Area` of `layer` that was shown now (an egui sizing pass of it when `sizing`) as an overlay of the +/// records open around it, which journal the registration: a replay shows the area again in egui's memory, as shown +/// this pass with the place, size and input it had, so egui finds the layer and orders it. A sizing pass paints +/// nothing and asks for the next pass, so the run that made it runs again. +fn register_area(ctx: &Context, layer: LayerId, sizing: bool) { + let Some(state) = egui::AreaState::load(ctx, layer.id) else { return }; + if sizing { + crate::runtime::replay::note_unsettled(ctx); + } + show_again(ctx, &AreaRecord { layer, at: state.left_top_pos(), size: state.size.unwrap_or_default(), interactable: state.interactable }); +} + +fn show_again(ctx: &Context, area: &AreaRecord) { + crate::runtime::replay::journal(ctx, || *area, show_again); + crate::runtime::replay::note_overlay(ctx, area.layer, Rect::from_min_size(area.at, area.size)); + let became = egui::AreaState::load(ctx, area.layer.id).and_then(|state| state.last_became_visible_at); + let state = egui::AreaState { + pivot_pos: Some(area.at), + pivot: egui::Align2::LEFT_TOP, + size: Some(area.size), + interactable: area.interactable, + last_became_visible_at: became, + }; + ctx.memory_mut(|memory| memory.areas_mut().set_state(area.layer, state)); +} + /// What [`show_cover_layer`] shows: the layer's id and tier, the `screen` it covers, its `scrim`, the `through` canvas /// left open, and whether it `absorbs` pointer hits. pub(crate) struct CoverLayer { @@ -263,6 +328,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { Some(clear) => bands(screen, clear).into_iter().filter(|band| band.is_positive()).collect(), None => vec![screen], }; + let mut sizing = false; egui::Area::new(id) .fade_in(false) .order(tier.order()) @@ -272,6 +338,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { .interactable(absorbs) .sense(Sense::hover()) .show(ctx, |ui| { + sizing = ui.is_sizing_pass(); for rect in covered { ui.painter().rect_filled(rect, 0.0, scrim); let absorber = ui.allocate_rect(rect, Sense::click_and_drag()); @@ -279,6 +346,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { crate::runtime::egui::access::hide(ui.ctx(), absorber.id); } }); + register_area(ctx, layer_of(tier, id), sizing); } /// The four rects of `screen` around `hole`: above, below, left of and right of it. @@ -297,8 +365,15 @@ pub(crate) fn layer_rect(ctx: &Context, id: Id) -> Option { } /// The viewport's safe rect: the room overlays must stay inside, the part of the content rect the user can see on -/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. +/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. A tracked input +/// (`Input::Shell`), which the frame's root env observes. pub(crate) fn safe_rect(ctx: &Context) -> Rect { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Shell); + safe_rect_raw(ctx) +} + +/// `safe_rect` without noting the read: for the root env, which moves `Input::Shell` by it. +pub(crate) fn safe_rect_raw(ctx: &Context) -> Rect { let content = ctx.content_rect(); ctx.input(|input| { let viewport = input.viewport(); diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index 4285d9b79..ff7b38fd3 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -10,6 +10,11 @@ pub(crate) fn set_text_cursor(ui: &mut Ui, visible: bool) { } } +/// The width of the caret an editable text draws past its last letter: the one value measuring and styling both read. +pub(crate) fn caret_width(ctx: &Context) -> f32 { + ctx.global_style().visuals.text_cursor.stroke.width +} + /// Paints the selected text of `ui`'s text edits in `ink` on `fill`. pub(crate) fn set_text_selection(ui: &mut Ui, fill: egui::Color32, ink: egui::Color32) { let selection = &mut ui.visuals_mut().selection; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index a37c5dc6b..20124780b 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -284,9 +284,9 @@ pub(crate) enum ColumnSweep { /// The first sweep of the measuring run of the column `Id`: each held fill-width child reports the width it /// measured at (`layout::report_held`). Count(Id), - /// The width the column settled on, in its second sweep and in the real run after one: a held fill-width child - /// measures and shows across it. - Column(f32), + /// The width the content-sized `Stack` column `Id` settled on, in its second sweep and in the real run after one: + /// a held fill-width child measures and shows across it, and a held picture measures in it. + Column(Id, f32), } /// The line of an unwrapped `Row` body, as its direct children placed in flow see it: a child of one line sits with @@ -417,18 +417,48 @@ impl Scoped { self.offered = None; } + /// 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 /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line - /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The - /// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own - /// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then. + /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of + /// the flow fields of the enclosing body only how it sizes from its content is in it: a memoized view's content + /// starts a layout room of its own (`start_view_room`) that keeps those facts. Computed once per scope, on the + /// first view that asks; the bytes it fed are counted then. pub(crate) fn scope_key(&self) -> u128 { *self.scope_key.get_or_init(|| { use crate::contract::{MemoKey, MemoProps as _}; let mut key = MemoKey::of_view(&self.ctx); key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel)); key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded, self.content)); + key.feed_hash(&(self.content_column, self.given_column)); key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view)))); self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key); self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key); @@ -525,8 +555,9 @@ impl Env { let shell = Arc::new(windows::shell_of(ctx, pass::current_viewport(ctx))); let active = shell.window.active; let keyboard = Arc::new(crate::runtime::keys::layout_of(ctx)); - // The window facts and the layout are tracked inputs: a view that read them runs when they change. - crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, (*shell).clone()); + // The window facts, the safe rect and the layout are tracked inputs: a view that read them runs when they change. + let safe = crate::runtime::egui::areas::safe_rect_raw(ctx); + crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, ((*shell).clone(), safe)); crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Keyboard, (*keyboard).clone()); let words = host_words(ctx, host.as_ref()); let key = EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash()) @@ -686,9 +717,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/env/view.rs b/crates/ui-contract/src/runtime/env/view.rs index 42d7cb568..b418809b6 100644 --- a/crates/ui-contract/src/runtime/env/view.rs +++ b/crates/ui-contract/src/runtime/env/view.rs @@ -58,6 +58,14 @@ impl<'a> EnvView<'a> { self.scoped.measure } + /// The content-sized `Stack` column whose first sweep runs now, if the scope is a direct child of it in flow. + pub(crate) fn column_first_sweep(&self) -> Option { + match self.scoped.column { + Some(super::ColumnSweep::Count(column)) => Some(column), + _ => None, + } + } + /// The inside label the scope carries ([`inside_label`](EnvView::inside_label) reads it back). pub(crate) fn inside_held(&self) -> Option<&'a Held> { self.scoped.inside_label.as_ref() diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index ac9e6f5ab..1adf515be 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -386,7 +386,8 @@ pub(crate) fn replay(ctx: &Context, transcript: &Transcript) { with(ctx, |state| { let placed = transcript.placed(state.open.last().map(|(id, _)| *id)); for (id, mut scope) in placed.scopes { - // No replayed scope has a noted opener: an overlay, which notes one, blocks its record. + // A replayed scope keeps the opener the last pass held: an overlay's scope, the one kind that notes an opener, + // took it in the pass that first showed the layer, which ran. scope.opener = opener(state, id, None, focused); if scope.entering.is_none() { state.seen.insert(id, frame); diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 3efa412a9..57b6b3b11 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -645,7 +645,9 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { // H0: one press per pass. let frame = pass::frame_nr(ctx, viewport); let held_back = PerViewport::::with(ctx, viewport, |record| raw_input::hold_back_presses(&mut events, frame, &mut record.held)); - // H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. + // H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. The events sent + // to the focus are counted first, before the IME and key stages take theirs. + keys::count_sent(ctx, viewport, &events); ime::input_hook(ctx, &mut events, viewport); let (stripped, later) = keys::input_hook(ctx, input, &mut events); if !later.is_empty() { @@ -755,6 +757,8 @@ pub(crate) fn end_pass(ui: &mut Ui) { for prune in prunes { prune(&ctx, &live); } + #[cfg(feature = "testing")] + crate::runtime::egui::access::check_parents_acyclic(&ctx); RUNNING.with(|running| { let mut running = running.borrow_mut(); if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) { diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index 0e19f1a6d..48705289b 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -373,8 +373,14 @@ pub(crate) fn composing(ctx: &Context, owner: Id) -> bool { current(ctx, |engine| engine.owner == Some(owner) && engine.composing) } -/// Records the caret rect for the OS candidate window. +/// Records the caret rect for the OS candidate window. A replay of the run that recorded it records it again, so the +/// pass writes the IME output and the OS keeps the IME open for a focused field that replays. pub(crate) fn note_caret(ctx: &Context, owner: Id, field: Rect, caret: Rect, password: bool) { + crate::runtime::replay::journal( + ctx, + || (owner, field, caret, password), + |ctx, &(owner, field, caret, password)| note_caret(ctx, owner, field, caret, password), + ); current(ctx, |engine| engine.caret = Some((owner, field, caret, password))); } diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 4c3d8d51c..a4d543eeb 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -1,6 +1,7 @@ -//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's -//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held), each with a generation -//! that moves when its value changes. The accessor that reads one notes it into the records open around the running +//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, its presses, the +//! window's facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the toast queues, the keys held, +//! the events sent to the focus, the requests to collections), each with a generation that moves when its value +//! changes. The accessor that reads one notes it into the records open around the running //! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation //! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed //! runs when it is shown again. @@ -20,9 +21,14 @@ pub(crate) enum Input { Modifiers, /// The pointer's frame (`pointer::frame`, `pointer::with_pass_pointer`). Pointer, + /// The pointer's presses and releases, an outside press the layer stack absorbed included (`pointer::primary_press`, + /// `overlay::absorbed_press`): a layer's dismissal reads them, so a press anywhere runs the views that show layers, + /// and a pointer move does not. + Press, /// The keys held, Caps Lock and whether a key arrived (`keys::input::down`, `keyed`, `lock_keys::caps_lock`). Keys, - /// The platform and window facts (`EnvView::shell`). + /// The platform and window facts (`EnvView::shell`) and the viewport's safe rect (`areas::safe_rect`): its + /// content rect and the visible part of its monitor. Shell, /// The keyboard layout (`EnvView::keyboard_layout`). Keyboard, @@ -32,23 +38,36 @@ pub(crate) enum Input { Drag, /// Where key focus is (`focus::focused_rec`, `focus_in_scope`, `commands::focus_within`). Focus, + /// The key, text, IME, clipboard and AccessKit action events of the frame: a run that ends holding focus reads them + /// (`replay::close`), so any such event runs the views the focus is in, and an idle frame replays them. + Sent, /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). Overlays, + /// The cards queued in the running viewport's toast queues (`toast::cards`): a post, a close or an expiry runs the + /// views that show them. + Toasts, + /// The requests to collections from outside them (`items::request_rename`), read by the item step that takes + /// them, so a pending request runs the view that takes it. + Requests, /// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value. Scroll, } impl Input { - pub(crate) const ALL: [Input; 10] = [ + pub(crate) const ALL: [Input; 14] = [ Input::Modifiers, Input::Pointer, + Input::Press, Input::Keys, Input::Shell, Input::Keyboard, Input::Keymap, Input::Drag, Input::Focus, + Input::Sent, Input::Overlays, + Input::Toasts, + Input::Requests, Input::Scroll, ]; @@ -115,17 +134,20 @@ pub(crate) fn observe(ctx: &Context, input }); } -/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are -/// observed here; the pointer and the modifiers by the pointer's begin hook, the window facts and the layout where -/// the frame's root env is built, the keymap by the command board. +/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers, toast +/// queues) are observed here, and so are the events sent to the focus, which the key stage counts; the pointer, its +/// presses and the modifiers by the pointer's begin hook, the window facts and the layout where the frame's root env is built, the +/// keymap by the command board, the requests by each request. pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { match input { Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)), + Input::Sent => observe(ctx, input, crate::runtime::keys::sent(ctx)), Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)), Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), + Input::Toasts => observe(ctx, input, crate::runtime::toast::queued(ctx)), Input::Keymap => return crate::runtime::commands::keymap_built(ctx), - Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} + Input::Modifiers | Input::Pointer | Input::Press | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} } with(ctx, |generations| generations.gens[input as usize]) } diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index f8d80f3f1..b4a350730 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -27,7 +27,7 @@ pub use claims::take_claimed; pub(crate) use claims::take_first_claimed; /// The types `Intents` reads and returns, for an app that reads the window's intents (`with_window_intents`). pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef}; -pub(crate) use input::{claims_press, input_hook, keys_state, queue_nav, take_menu_keys, take_nav}; +pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, queue_nav, sent, take_menu_keys, take_nav}; #[doc(hidden)] pub use input::{down, keyed}; pub use intents::Intents; @@ -242,6 +242,8 @@ pub(crate) struct Stage { down: Vec, /// The input hook read a key press, typed text or a clipboard event in this pass, withheld ones included. keyed: bool, + /// How many inputs of the viewport held an event sent to the focus (`count_sent`). + sent: u64, /// The keys whose press the strip took and whose release it is still to drop. consumed: Vec, shortcuts: Shortcuts, diff --git a/crates/ui-contract/src/runtime/keys/claims.rs b/crates/ui-contract/src/runtime/keys/claims.rs index 587c00366..874f05c6d 100644 --- a/crates/ui-contract/src/runtime/keys/claims.rs +++ b/crates/ui-contract/src/runtime/keys/claims.rs @@ -2,6 +2,8 @@ use super::current; use craft_keymap::Chord; + +crate::stays!(Chord); use egui::{Context, Id}; /// Reads the claimed chord: whether it arrived this pass for `id`, consuming it. Also true for a chord @@ -32,8 +34,10 @@ pub(crate) fn take_first_claimed(ctx: &Context, id: Id, chords: &[Chord]) -> Opt }) } -/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. +/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. Like the +/// claims below, a replay of the run that recorded it records it again: a focused view replays while nothing reaches it. pub(crate) fn hold_escape(ctx: &Context, owner: Id) { + crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| hold_escape(ctx, owner)); current(ctx, |stage| stage.open_edits.push(owner)); } @@ -41,6 +45,7 @@ pub(crate) fn hold_escape(ctx: &Context, owner: Id) { /// component. #[doc(hidden)] pub fn claim(ctx: &Context, owner: Id, chord: Chord) { + crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| claim(ctx, owner, chord)); current(ctx, |stage| stage.claims.push((owner, chord))); } @@ -49,6 +54,9 @@ pub fn claim(ctx: &Context, owner: Id, chord: Chord) { /// keys, Enter and Escape (the window move and size modes, 16.3); the claim lapses when it is not renewed. #[doc(hidden)] pub fn capture(ctx: &Context, owner: Id, chord: Chord) { + crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| capture(ctx, owner, chord)); + // The captured chord reaches `owner` wherever the focus is: a run that captures reads what is sent. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent); current(ctx, |stage| { if !stage.captures.contains(&(owner, chord)) { stage.captures.push((owner, chord)); diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 78074d5fb..d508086ee 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -593,6 +593,33 @@ pub(crate) fn keys_state(ctx: &Context) -> (Vec, bool, bool) { (down, keyed, crate::runtime::lock_keys::caps_on(ctx)) } +/// Counts an input of `viewport` whose `events` hold one sent to the focus: a key, text, IME, clipboard or AccessKit +/// action event (`Input::Sent`). Read before any stage takes events, so the IME's and the ones a shortcut takes count. +pub(crate) fn count_sent(ctx: &Context, viewport: ViewportId, events: &[Arrived]) { + let sent = events.iter().any(|arrived| { + matches!( + arrived.event, + egui::Event::Key { .. } + | egui::Event::Text(_) + | egui::Event::Ime(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::MiddleClickPaste { .. } + | egui::Event::AccessKitActionRequest(_) + ) + }); + if sent { + with(ctx, viewport, |stage| stage.sent += 1); + } +} + +/// How many inputs of the running viewport held an event sent to the focus: its value moves with each one. +pub(crate) fn sent(ctx: &Context) -> u64 { + current(ctx, |stage| stage.sent) +} + /// Whether the running viewport's input hook read a key press, typed text or a clipboard event in this pass, the ones /// the key stage took from egui's input included: an app that redraws state after input asks this, not egui's events. pub fn keyed(ctx: &Context) -> bool { diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 3894fd46b..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, }) } @@ -1236,7 +1244,7 @@ pub(crate) mod guard { ("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"), ("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"), ("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"), - ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), + ("layout::body::HeldWidths", "held children: opened by the column's own first sweep and closed after its last"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), ( diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 19b1b46e3..d27a97934 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -15,7 +15,7 @@ //! framework tracks has changed for it since (`settled`). Its entry outlives a few frames of absence. use crate::runtime::egui::areas::Layer; -use crate::runtime::egui::{focus as focus_state, input as input_state, pass}; +use crate::runtime::egui::{input as input_state, pass}; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; use crate::runtime::inputs::{self, Input}; @@ -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 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. @@ -179,9 +179,15 @@ pub(crate) struct Place { /// The font atlas the run's text points into (`Fonts::atlas_generation`): egui clears the atlas when it fills up /// and rebuilds it for new text options, and a kept galley's glyphs then name other glyphs. pub(crate) atlas: u64, + /// The opacity everything painted in the room is faded to (`Ui::opacity`, a layer fading in or out): the run's + /// colours hold it. + pub(crate) opacity: f32, /// 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. @@ -193,9 +199,10 @@ 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 and environment are the ones the run had. The 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 (`movable`: no paint callback) on an + /// 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: /// - the clip moved with the room (`with_clip`): every rect and clip moves exactly, whatever the clip cut; @@ -204,15 +211,21 @@ impl Place { /// so the run's clip becomes the clip now and inner clips move (`RecordShift::clip`). /// /// Otherwise it runs: a run cut by its clip lacks what was culled. - fn shift_to(&self, rect: Rect, now: Place, movable: bool, transformed: bool) -> Option { + fn shift_to(&self, rect: Rect, now: Place, record: &Record, transformed: bool) -> Option { let offset = now.room.min - self.room.min; let same = now.room.size() == self.room.size() && now.layer == self.layer && now.layout == self.layout && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas - && now.env == self.env; - let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed); + && now.opacity == self.opacity + && now.env == self.env + && now.fits == self.fits; + let placeable = if record.pinned() { + offset == Vec2::ZERO && now.clip == self.clip + } else { + offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && record.movable() && !transformed) + }; if !same || !placeable { return None; } @@ -433,6 +446,12 @@ pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, meas }); } +/// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it +/// ran), at whatever room it had; `None` before any run showed it. +pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option { + with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[1].map(|measured| measured.size))) +} + /// Registers what the skipped child `id` registered with the focus service in the last real run that showed it, in /// the real run that skips it. pub(crate) fn replay(ctx: &Context, id: Id) { @@ -445,30 +464,34 @@ 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: /// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still /// loading, no wake time reached; -/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and -/// none of that held in its last run; -/// - none of its stops holds focus or is the target of a focus request, now or in its last run; +/// - the pointer is not over it or an overlay layer it shows, no press started on either and none of its widgets is +/// dragged, and none of that held in its last run; +/// - the focus is where its run left it (`replay::Held`: the same stop and egui widget of it, or none), and while the +/// focus is in it no key, text, IME, clipboard or AccessKit event came (`Input::Sent`, which such a run reads); +/// - none of its stops is the target of a focus request, now or in its last run; /// - 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 /// gone; /// - no framework input its run read outside its props has moved (`runtime::inputs`), the scroll view a nested `Lazy` -/// child of it decided by is the same (moved with it, `moved`), and no command waits for a command scope instance of -/// it. +/// child of it decided by is the same (moved with it, `moved`), no command waits for a command scope instance of +/// it, and no close waits for a layer it shows. pub(crate) fn settled( ctx: &Context, owner: Option, @@ -478,16 +501,21 @@ pub(crate) fn settled( view: Option, key: Key, ) -> Option<(Vec2, Rect, RecordShift)> { - let targets = focus::targets(ctx); + let revealed = focus::targets(ctx)[1]; let routed = crate::runtime::keys::routed_to(ctx); let now = frame::clock(ctx); - let held = (input_state::dragged(ctx), focus_state::focused(ctx)); + let dragged = input_state::dragged(ctx); + let focused = replay::Held::focused(ctx); let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some()); let settled = write(ctx, id, |store, pass_nr, frame| { let changes = &store.changes; // 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, _ => { @@ -496,14 +524,14 @@ 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 && facts.quiet(now, edited.as_ref()) - && !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)) || routed.contains(&stop)) + && !settled.record.focus.stop_ids().any(|stop| revealed == Some(stop) || routed.contains(&stop)) && !routed.iter().any(|id| settled.record.widgets.contains(id)) - && ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget)) + && !dragged.is_some_and(|widget| settled.record.widgets.contains(&widget)) + && focused.within(&settled.record.focus, &settled.record.widgets) == settled.record.held }); entry.replays = Some((pass_nr, replays)); replays @@ -511,17 +539,17 @@ pub(crate) fn settled( }; // A measuring run cannot tell the place: it replays where the run was. let moved = |settled: &Settled| match place { - Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed), + 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)) @@ -534,7 +562,7 @@ pub(crate) fn settled( // The scroll view a nested child decided by: the run's, moved with the record, while the clip moved with it; a run // that lay wholly in its clip ran every nested child, which holds at any view. let view = place.and_then(|_| with_clip.then(|| (settled.view.map(|ran| ran.moved(shift.offset)), view))); - if engaged(ctx, settled.place.layer, rect.intersect(shift.clip)) + if engaged(ctx, settled.place.layer, rect.intersect(shift.clip), &settled.record.facts.overlays) || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) || moved(ctx, &settled, view) { @@ -551,18 +579,26 @@ pub(crate) fn settled( /// Whether something a memoized view's run read outside its props moved since: a framework input it read has another /// generation, the scroll view a nested `Lazy` child decided by is another than the one it needs (`view`: the view it /// needs and the view now, in a real run whose record replays only in that view; a measuring run lays the content out -/// from offset zero, so its view is not the one the real run decided by), or a command waits for one of its instances. +/// from offset zero, so its view is not the one the real run decided by), a command waits for one of its instances, +/// or a close waits for a layer it shows. fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option)>) -> bool { let facts = &settled.record.facts; inputs::moved(ctx, facts.inputs, &settled.seen) || (facts.inputs.contains(Input::Scroll) && view.is_some_and(|(needs, now)| needs != now)) || crate::runtime::commands::queued_for(ctx, &facts.instances) + || crate::runtime::overlay::close_queued(ctx, &facts.layers) } -/// Whether the pointer is over `rect` (shown) on `layer`, or a press that is held started there. -fn engaged(ctx: &Context, layer: Layer, rect: Rect) -> bool { - let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); - ctx.rect_contains_pointer(layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin)) +/// Whether the pointer is over `rect` (shown) on `layer` or over one of the overlay layers `overlays` shown, or a +/// press that is held started there. Both halves ask whether the layer is the top layer at the point, so a pointer or +/// a press on an overlay above the view leaves it alone. +fn engaged(ctx: &Context, layer: Layer, rect: Rect, overlays: &[replay::ShownLayer]) -> bool { + let over = |layer: Layer, rect: Rect| { + let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); + ctx.rect_contains_pointer(layer, rect) + || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) + }; + over(layer, rect) || overlays.iter().any(|shown| over(shown.layer, shown.rect)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` @@ -628,11 +664,11 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec if ctx.will_discard() { return; } - let targets = focus::targets(ctx); - let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); + let revealed = focus::targets(ctx)[1]; + let engaged_now = record.focus.stop_ids().any(|stop| revealed == Some(stop)); let lives = crate::runtime::memory::ended_generation(ctx); let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, key, pass: 0, edits, output, lives, seen, view }; - settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip)); + settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip), &settled.record.facts.overlays); with(ctx, |store, pass_nr, frame| { settled.frame = frame; settled.pass = pass_nr; diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 27ed98177..a7667d012 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -203,6 +203,8 @@ struct OwnerRecord { viewport: ViewportId, pass: u64, at: f64, + /// The pass of the owner's registration before `pass`, in the same viewport. + before: Option, } /// One entry the runtime keeps for a component, and the owner that is tested for its eviction. @@ -270,11 +272,28 @@ pub(crate) fn register_owner(ctx: &Context, owner: Id) { crate::runtime::replay::note_owner(ctx, owner); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { - reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); + let before = match reg.owners.get(&owner) { + Some(last) if last.viewport == facts.viewport && last.pass == facts.pass_nr => last.before, + Some(last) if last.viewport == facts.viewport => Some(last.pass), + _ => None, + }; + reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now, before }); reg.ended.remove(&owner); }); } +/// Whether `owner` was registered in the pass before the running one of its viewport, by a run or a replay: its +/// component was shown there. +pub(crate) fn shown_last_pass(ctx: &Context, owner: Id) -> bool { + let facts = frame::facts(ctx); + pass_state::with::(ctx, |reg| { + reg.owners.get(&owner).filter(|last| last.viewport == facts.viewport).is_some_and(|last| { + let shown = if last.pass == facts.pass_nr { last.before } else { Some(last.pass) }; + shown.is_some_and(|shown| shown + 1 >= facts.pass_nr) + }) + }) +} + /// The generation of ended shown lives now: a kept run stores it, and `ended_since` compares with it. pub(crate) fn ended_generation(ctx: &Context) -> u64 { pass_state::with::(ctx, |reg| reg.ended_generation) diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index 9f73466f1..5fb7df0be 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -395,6 +395,10 @@ impl Driver<'_> { let sizing = self.stage.is_peek(); let now = frame::clock(ctx); let existing = if sizing { store::peek_clone::>(ctx, id) } else { store::take::>(ctx, id) }; + // A tween that moves in this pass (a new target, also one it jumps to, or a step, also its last one) leaves the + // slot in another state than the run found it in, which the next run reads (`layer_fading` among others): a + // record of the run is not replayed. Only a tween still running asks for another frame. + let moved = existing.as_ref().is_some_and(|tween| tween.target() != target || !tween.is_settled()); let mut tween = match existing { Some(tween) => tween, None => { @@ -409,6 +413,8 @@ impl Driver<'_> { if !sizing { if !tween.is_settled() { note_unsettled(ctx); + } else if moved { + crate::runtime::replay::note_unsettled(ctx); } store::put(ctx, id, tween); } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 015651a50..ea79ef4d5 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -9,6 +9,7 @@ use crate::runtime::egui::pass; use crate::runtime::frame::{PassStep, PerViewport, Stamped}; use crate::runtime::pass_state; use crate::runtime::pointer; +use crate::runtime::shift::Shift; use craft_behavior::OwnerClass; use craft_behavior::overlay::Side; use egui::emath::TSTransform; @@ -120,7 +121,7 @@ pub enum OpenFilter { } /// One shown egui layer. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[doc(hidden)] pub struct OpenEntry { /// The layer's id. @@ -164,6 +165,29 @@ pub struct OpenEntry { dialog: Option, } +/// A replay moves the entry's screen rects with its record; the rest stays. +impl Shift for OpenEntry { + fn shifted(&self, by: &egui::RecordShift) -> Self { + OpenEntry { + anchor: self.anchor.shifted(by), + peers: self.peers.shifted(by), + rect: self.rect.shifted(by), + region: self.region.shifted(by), + ..self.clone() + } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + OpenEntry { + anchor: self.anchor.snapped(&to.anchor, within), + peers: self.peers.snapped(&to.peers, within), + rect: self.rect.snapped(&to.rect, within), + region: self.region.snapped(&to.region, within), + ..self.clone() + } + } +} + impl OpenEntry { /// An entry for the layer `id` of `rank`. pub(crate) fn new(id: Id, rank: Rank, keys: OwnerClass, rect: Rect, layer: Layer) -> Self { @@ -484,7 +508,8 @@ pub(crate) fn appears(ctx: &Context, id: Id, exiting: bool) -> bool { /// Marks the layer `id`'s body as running, so layers opened from inside it become its children, with the `side` of /// its anchor it was placed on. A layer shown again while it fades out opens anew: it appears in this frame and pass. pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side: Option) { - crate::runtime::replay::block(ctx); + // Which layers a press opened reads the presses and releases. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); let reopened = reopened(ctx, id, exiting); with_pass(ctx, |pass| { pass.drawing.push((id, tier)); @@ -649,13 +674,27 @@ pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::in input.events.len() != before } -/// The outside press the input hook removed for the running pass. +/// The outside press the input hook removed for the running pass. A tracked input (`Input::Press`). pub(crate) fn absorbed_press(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); + absorbed_press_raw(ctx) +} + +/// `absorbed_press` without noting the read: for the pointer's begin hook, which moves `Input::Press` by it. +pub(crate) fn absorbed_press_raw(ctx: &Context) -> Option { with_persist(ctx, pass::current_viewport(ctx), |persist| persist.outside_press) } -/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. +/// Whether a close is queued for one of the layers `ids`: only a run of the layer's owner takes it, so a memoized view +/// that showed one of them runs while it waits. +pub(crate) fn close_queued(ctx: &Context, ids: &[Id]) -> bool { + !ids.is_empty() && pass_state::with::(ctx, |closes| closes.0.iter().any(|(closed, ..)| ids.contains(closed))) +} + +/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. A replay of the run +/// that showed the layer records them again. pub(crate) fn note_peers(ctx: &Context, id: Id, peers: Vec) { + crate::runtime::replay::journal(ctx, || (id, peers.clone()), |ctx, (id, peers)| note_peers(ctx, *id, peers.clone())); with_pass(ctx, |pass| { if let Some(entry) = pass.current.iter_mut().find(|entry| entry.id == id) { entry.peers = peers; @@ -697,12 +736,16 @@ pub fn end_stack_dialog(ctx: &Context, dialog: Id) { /// Records the layer shown in this pass, parent first: a layer is recorded once its body ran, after the layers opened /// from inside it, so it goes in front of them, and every layer then stacks above the layer it was opened from. A -/// layer shown again in a discarded pass replaces its entry. +/// layer shown again in a discarded pass replaces its entry. A replay of the run that showed the layer records the +/// entry again, its stack place and dialog filled, and the records open around it note the layer as one they show. pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) { - crate::runtime::replay::block(ctx); with_pass(ctx, |pass| { entry.place = entry.place.or(pass.place); entry.dialog = entry.dialog.or(pass.dialog); + }); + crate::runtime::replay::note_layer(ctx, entry.id); + crate::runtime::replay::journal(ctx, || entry.clone(), |ctx, entry| record(ctx, entry.clone())); + with_pass(ctx, |pass| { if let Some(at) = pass.current.iter().position(|recorded| recorded.id == entry.id) { pass.current[at] = entry; return; diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index d32f5b886..7e99402fb 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -237,6 +237,10 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if events { inputs::bump(ctx, Input::Pointer); } + // A press or release, or an outside press the layer stack's input hook took before egui saw it. + if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() { + inputs::bump(ctx, Input::Press); + } } PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { @@ -325,6 +329,13 @@ pub fn mods(ctx: &Context) -> Mods { with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods)) } +/// Where the primary press of the running pass started. A tracked input (`Input::Press`): a layer's dismissal decides by +/// it, so a memoized view that shows a layer runs on a press anywhere, and a pointer move leaves it alone. +pub(crate) fn primary_press(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, Input::Press); + frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) +} + /// `frame` without noting the read: for the steps of the component under the pointer and the pass machinery. pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame { with_pass_raw(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame { @@ -444,6 +455,7 @@ pub(crate) fn record_text_widget(ctx: &Context, widget: Id, owner: Id) { /// it the press where no widget on the layer is, and the press and hover there go to the layer's shapes as if egui /// had named no target. pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) { + crate::runtime::replay::journal(ctx, || widget, |ctx, &widget| record_layer_widget(ctx, widget)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_grounds.insert(widget); }); diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index bde005d12..c89872ac5 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -9,8 +9,11 @@ //! //! The record also holds the facts the settled test reads (`runtime::lazy`): the values the run read, whether //! something in it still moves (an animation that is not at its end, a repaint request) and the earliest time it asked -//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another -//! layer, a label scope open around it). Such a record is never replayed: the view runs. +//! to be shown again, the overlay layers it shows and where the focus was in it, and whether it did something a replay +//! cannot repeat (paint on a layer that is neither its own nor an overlay it shows, such as a raw egui popup or a +//! transformed body; a window of another viewport; a label scope open around it). Such a record is never replayed: +//! the view runs. An overlay it shows is journaled as every other registration is (its `Area`, its layer stack +//! entry), so its record replays only where it ran (`Record::pinned`). use crate::runtime::egui::areas::Layer; use crate::runtime::focus::{self, Transcript}; @@ -19,7 +22,7 @@ use crate::runtime::inputs::{Input, Inputs}; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; use crate::runtime::shift::Shift; -use egui::{Context, IdSet, RecordShift}; +use egui::{Context, IdSet, RecordShift, Rect}; use std::any::Any; use std::collections::HashSet; use std::fmt; @@ -90,6 +93,15 @@ impl PartialEq for Entry { } } +impl Entry { + /// The entry at the place `shift` names. A shift that leaves every record as it is (`RecordShift::is_none`, a + /// pinned record's) leaves the entry too, as it leaves egui's records: a clip a layer the record shows sets lies + /// outside the clip around the record, which `RecordShift::clip` would cut it to. + fn at(&self, shift: &RecordShift) -> Entry { + if shift.is_none() { self.clone() } else { self.0.shifted(shift) } + } +} + impl fmt::Debug for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.describe(f) @@ -164,6 +176,43 @@ pub(crate) struct Facts { /// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one /// is taken only by a run, so a replay waits until the queue holds none. pub(crate) instances: Vec, + /// The overlay layers the run showed (`note_overlay`): their paint and widgets are the record's, and the pointer over + /// one of them engages the record. + pub(crate) overlays: Vec, + /// The layer stack entries the run recorded (`note_layer`): a close queued for one is taken only by a run. + pub(crate) layers: Vec, +} + +/// An overlay layer a run showed: its egui layer and its rect in screen space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct ShownLayer { + pub(crate) layer: Layer, + pub(crate) rect: Rect, +} + +/// Where the focus was in a run: the component of the focused stop when the run registered it, and the egui widget +/// that held egui focus when the run made it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Held { + pub(crate) stop: Option, + pub(crate) widget: Option, +} + +impl Held { + /// Where the focus is now: the component of the focused stop and the egui widget that holds egui focus. + pub(crate) fn focused(ctx: &Context) -> Held { + Held { stop: focus::focused_stop(ctx).map(|key| key.0), widget: crate::runtime::egui::focus::focused(ctx) } + } + + /// The part of the focus `self` that is among the stops of `focus` and the egui widgets `widgets`. + pub(crate) fn within(self, focus: &Transcript, widgets: &IdSet) -> Held { + Held { stop: self.stop.filter(|stop| focus.stop_ids().any(|id| id == *stop)), widget: self.widget.filter(|widget| widgets.contains(widget)) } + } + + /// Whether the focus is in the run at all. + pub(crate) fn any(self) -> bool { + self.stop.is_some() || self.widget.is_some() + } } /// What one real run of a region added to its pass. @@ -173,14 +222,22 @@ pub(crate) struct Record { egui: egui::PassRecords, /// The egui widgets of the run. pub(crate) widgets: IdSet, + /// Where the focus was in the run when it ended. + pub(crate) held: Held, pub(crate) facts: Facts, } impl Record { /// Whether a replay can add the record at another place: egui's records hold no paint callback - /// (`PassRecords::paints_callback`). + /// (`PassRecords::paints_callback`) and the record is not pinned. pub(crate) fn movable(&self) -> bool { - !self.egui.paints_callback() + !self.egui.paints_callback() && !self.pinned() + } + + /// Whether the record replays only where it ran, at the offset and clip of its run: it shows an overlay, which a + /// host places in screen space by its anchor, so a move of the record is no move of the layer. + pub(crate) fn pinned(&self) -> bool { + !self.facts.overlays.is_empty() } } @@ -218,7 +275,8 @@ pub(crate) fn in_audit_run(ctx: &Context) -> bool { OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| recorder.open.iter().any(|open| open.audit)) } -/// Ends the innermost record, the one around a run on `layer`: paint or widgets on another layer block it. +/// Ends the innermost record, the one around a run on `layer`: paint or widgets on a layer that is neither `layer` nor +/// an overlay the run showed block it. pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { OPEN.fetch_sub(1, Ordering::AcqRel); let (open, journal) = pass_state::with::(ctx, |recorder| { @@ -242,6 +300,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..)))); outer.facts.inputs.extend(open.facts.inputs); outer.facts.instances.extend(open.facts.instances.iter().copied()); + outer.facts.overlays.extend(open.facts.overlays.iter().copied()); + outer.facts.layers.extend(open.facts.layers.iter().copied()); } else { recorder.journal.clear(); } @@ -254,13 +314,23 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { facts.layout_keeps.dedup(); facts.derived_keeps.sort_unstable_by_key(|id| id.value()); facts.derived_keeps.dedup(); - // A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees: - // its run is never replayed. - facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback(); + // Paint on a layer that is neither the run's own nor an overlay it showed (a raw egui popup, a transformed body) + // comes from code that registers nothing to replay it with. A paint callback's output depends on what its closure + // holds, which neither a view's key nor a comparison sees. Either run is never replayed. + facts.blocked |= egui.layers().any(|on| on != layer && !facts.overlays.iter().any(|shown| shown.layer == on)) || egui.paints_callback(); // Every discard request reaches egui's output (`sizing::request_discard` and egui's own); layout memory's waits // for the end of the pass and notes itself (`note_discard`). facts.discards |= discard_requests(ctx) > open.discards; - Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts } + let focus = focus::transcript(ctx, open.focus); + let widgets = egui.widgets().iter().map(|widget| widget.id).collect(); + // A run that ends holding focus reads where the focus is and what is sent to it: a focus move, and the next key, + // text, IME, clipboard or AccessKit event wherever the framework routes it, run it. + let held = Held::focused(ctx).within(&focus, &widgets); + if held.any() { + facts.inputs.insert(Input::Focus); + facts.inputs.insert(Input::Sent); + } + Record { focus, journal, widgets, held, egui, facts } } #[cfg(feature = "testing")] @@ -280,6 +350,10 @@ impl Record { // The display names a widget by its rect only; the difference may be in its sense, state or interact rect. Some(egui::PassRecordsDiff::Widget { index, left, right }) => found.push(format!("widget rect {index}: left {left:?} / right {right:?}")), // The display names a node by its bounds only; the difference may be in any other property. + // The display names a shape by its rects only; the difference may be in its colour, stroke, texture or text. + Some(egui::PassRecordsDiff::Shape { layer, index, left, right }) => { + found.push(format!("paint: shape {index} on {layer:?}: left {left:?} / right {right:?}")) + } Some(egui::PassRecordsDiff::Node { index, left, right }) => { found.push(format!("AccessKit node {index}: left {left:?} / right {right:?}")) } @@ -289,7 +363,7 @@ impl Record { if let Some(diff) = self.focus.first_difference(&run.focus) { found.push(format!("focus: {diff}")); } - let shifted: Vec = self.journal.iter().map(|entry| entry.0.shifted(shift)).collect(); + let shifted: Vec = self.journal.iter().map(|entry| entry.at(shift)).collect(); let (left, right) = (&shifted, &run.journal); if let Some(index) = left .iter() @@ -355,7 +429,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { let noting = recording(ctx); if noting { pass_state::with::(ctx, |recorder| { - recorder.journal.extend(record.journal.iter().map(|entry| if shift.is_none() { entry.clone() } else { entry.0.shifted(shift) })); + recorder.journal.extend(record.journal.iter().map(|entry| entry.at(shift))); recorder.replaying = true; }); } @@ -471,6 +545,17 @@ pub(crate) fn note_wake(ctx: &Context, at: f64) { with_open(ctx, |facts| facts.wake = min_wake(facts.wake, Some(at))); } +/// Notes that the running code showed the overlay layer `layer` at the screen rect `rect`. Called by the journaled +/// registration of the layer's `Area`, so a record that replays it notes it again in the records open around it. +pub(crate) fn note_overlay(ctx: &Context, layer: Layer, rect: Rect) { + with_open(ctx, |facts| facts.overlays.push(ShownLayer { layer, rect })); +} + +/// Notes that the running code recorded the layer stack entry `id`, by a run or a replay. +pub(crate) fn note_layer(ctx: &Context, id: egui::Id) { + with_open(ctx, |facts| facts.layers.push(id)); +} + /// Notes that the running code did something a replay cannot repeat. pub(crate) fn block(ctx: &Context) { with_open(ctx, |facts| facts.blocked = true); diff --git a/crates/ui-contract/src/runtime/toast.rs b/crates/ui-contract/src/runtime/toast.rs index be51a8b36..4649ad0b9 100644 --- a/crates/ui-contract/src/runtime/toast.rs +++ b/crates/ui-contract/src/runtime/toast.rs @@ -285,14 +285,22 @@ pub fn keep(ctx: &Context, id: ToastId) { } } -/// The cards of the window `window` in the running viewport, oldest first. +/// The cards of the window `window` in the running viewport, oldest first. A tracked input (`Input::Toasts`). pub fn cards(ctx: &Context, window: &WindowKey) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Toasts); PerViewport::::with(ctx, pass::current_viewport(ctx), |queue| { let cards = queue.windows.iter().find(|(key, _)| key == window); cards.map_or_else(Vec::new, |(_, live)| live.iter().map(|live| live.card.clone()).collect()) }) } +/// The ids of the cards each window of the running viewport queues: what `Input::Toasts` observes. +pub(crate) fn queued(ctx: &Context) -> Vec<(WindowKey, Vec)> { + PerViewport::::with(ctx, pass::current_viewport(ctx), |queue| { + queue.windows.iter().map(|(key, live)| (key.clone(), live.iter().map(|live| live.card.id).collect())).collect() + }) +} + /// Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's. pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)> { let mut cards = Vec::new(); diff --git a/crates/ui-contract/src/runtime/windows/native.rs b/crates/ui-contract/src/runtime/windows/native.rs index 9974910df..c426eb9cd 100644 --- a/crates/ui-contract/src/runtime/windows/native.rs +++ b/crates/ui-contract/src/runtime/windows/native.rs @@ -9,7 +9,7 @@ use super::spec::{Standing, WindowLevel}; use super::{HandOff, Record, SEARCH_EVERY, shared}; use crate::runtime::egui::{pass, viewports}; use crate::runtime::frame::{PerViewport, Stored}; -use craft_host::target::{Caps, DoubleClick, WindowState}; +use craft_host::target::{Caps, DoubleClick, Os, WindowState}; use craft_window::native::NativeWindow; use craft_window::policy::Frame; use egui::{Context, Pos2, Rect, Vec2, ViewportId}; @@ -49,7 +49,7 @@ pub enum WindowAction { StartResize(ResizeEdge), /// Moves the window's outer top-left corner to a desktop position in points. SetOuterPosition(Pos2), - /// Sizes the window's inner area in points. + /// Sizes the window's inner area in points; its outer top-left corner stays where it is known to be. SetInnerSize(Vec2), /// Restores a minimized window. Restore, @@ -138,7 +138,18 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { } WindowAction::SetInnerSize(size) => { viewports::command(ctx, viewport, egui::ViewportCommand::InnerSize(size)); - PerViewport::::with(ctx, viewport, |record| record.known = record.known.map(|known| Rect::from_min_size(known.min, size))); + let known = PerViewport::::with(ctx, viewport, |record| { + record.known = record.known.map(|known| Rect::from_min_size(known.min, size)); + record.known + }); + // AppKit keeps a window's bottom-left corner when its size changes (`setContentSize`), so a new height + // moves its top edge: the window goes back to the top-left corner its caller knows it at, which a position + // sent before the size has already set. + if base.os == Os::Mac + && let Some(known) = known + { + viewports::command(ctx, viewport, egui::ViewportCommand::OuterPosition(known.min)); + } } WindowAction::Restore => viewports::command(ctx, viewport, egui::ViewportCommand::Minimized(false)), WindowAction::SetMinInnerSize(size) => viewports::command(ctx, viewport, egui::ViewportCommand::MinInnerSize(size)), diff --git a/crates/ui-contract/src/testing/access.rs b/crates/ui-contract/src/testing/access.rs index 2d05eb316..e6e343f64 100644 --- a/crates/ui-contract/src/testing/access.rs +++ b/crates/ui-contract/src/testing/access.rs @@ -3,6 +3,7 @@ use crate::runtime::access::{FieldLabel, scope}; use egui::{Context, Id}; +pub use crate::runtime::access::layer_root; pub use crate::runtime::egui::access::{AccessTree, Declared, NodeKey, prune_controls}; /// The AccessKit tree a finished pass of a viewport produced, taken out of its output; empty when it made none. diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index a78daa48e..19c73c055 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -111,6 +111,36 @@ fn texel(image: &ColorImage, x: usize, y: usize) -> Color32 { image.pixels[y * 24 + x] } +/// On a strong fill or scrim (the surface's ink is `OnDark`: a brand rail) the accent parts paint in the icon's own +/// colour, since `accent.solid` would vanish on the brand fill; the fixed parts stay as drawn, and on a panel the +/// accent parts keep the accent ink. +#[trial] +fn an_accent_part_on_a_dark_surface_paints_in_the_icons_ink() { + register_app_icons(&LAYERED_SET); + let tokens = style::tokens(Mode::Light, Contrast::Standard); + let rect = Rect::from_min_max(pos2(10.0, 10.0), pos2(34.0, 34.0)); + let mut frames = Frames::new(); + let mut tints = |surface: Ink, spec_ink: Option| { + let on = ink_color(&tokens, Ink::OnDark); + let mut spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(LAYERED_NAME))).color(StyleColor(on)); + if let Some(ink) = spec_ink { + spec = spec.ink(ink); + } + let record = RefCell::new(PaintRecord::default()); + let shapes = frames.frame_shapes(|ui| { + let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: surface }; + Draw::new(ui.painter(), &record, env).icon(rect, &spec); + }); + textured(&shapes).into_iter().map(|(_, tint)| tint).collect::>() + }; + let on = ink_color(&tokens, Ink::OnDark); + // design: allow[raw-colour/const](a fixed layer keeps the colours it is drawn in: the trial expects the white tint that leaves them unchanged) + let fixed = Color32::WHITE; + assert_eq!(tints(Ink::OnDark, None), [on, on, fixed], "on a brand rail the accent parts read in the icon's ink"); + assert_eq!(tints(Ink::OnPanel, Some(Ink::OnDark)), [on, on, fixed], "an icon that asks for the on-dark ink does the same"); + assert_eq!(tints(Ink::OnPanel, None), [on, rgba_color(tokens.color.accent.solid), fixed], "on a panel the accent ink is kept"); +} + #[trial] fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_the_disabled_ink_when_disabled() { register_app_icons(&LAYERED_SET); 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/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index c5844b134..a8055982a 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -1,13 +1,14 @@ //! `BodyLayout` under direction: the physical layouts, measured `Row` placement and the `Grid` cursor; a content-sized //! column's held children, a spread row's room and the end region's line. -use craft_behavior::{ColumnWidth, Proposal, Sense}; +use craft_behavior::{ColumnWidth, Insets, Metrics, Proposal, Sense}; use craft_ui::contract::{ - BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, Sizing, + BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, MemoProps, MemoView, Props as _, Role, Show as _, + ShowContainer as _, Sizing, }; use craft_ui::layout::{BodyLayout, RowAlign}; use craft_ui::runtime::env::{Direction, with_env}; -use craft_ui::style::StyleCx; +use craft_ui::style::{ComponentStyle, StyleCx}; use craft_ui::testing::layout::{Block, body}; use craft_ui::testing::{Fixture, Frames, is_measuring, trial}; use craft_ui_test_kit::contract::{Panel, PlainStyle, Probe, Seen}; @@ -237,6 +238,145 @@ fn a_held_fill_width_child_measures_again_only_when_a_sibling_widens_the_column( assert!(unbounded >= 1 && bounded == 0, "the narrower sibling: the held child measured again: {unbounded} and {bounded}"); } +/// A picture from `least` up to `MOST_PICTURE` wide: square (`picture_size`), or a band of its own height +/// (`picture_width`), with `PICTURE_PAD` of padding at each side. +#[derive(Component)] +struct Picture<'a> { + #[common] + common: Common, + least: f32, + square: bool, + seen: &'a RefCell, + measures: &'a Measures, +} + +/// The widest a `Picture` takes. +const MOST_PICTURE: f32 = 1000.0; + +/// A `Picture`'s padding at each side. +const PICTURE_PAD: f32 = 20.0; + +/// A style padded `PICTURE_PAD` at each side. +#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +struct PaddedStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for Picture<'_> { + const ROLE: Role = Role::GROUP; + type Style = PaddedStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: PictureStyleKey) -> PaddedStyle { + PaddedStyle { metrics: Metrics::new().padding(Insets::new(PICTURE_PAD, PICTURE_PAD, 0.0, 0.0)) } + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if cx.proposal == Proposal::Ideal && is_measuring(cx.ui.ctx()) { + let count = if cx.room.is_some() { &self.measures.bounded } else { &self.measures.unbounded }; + count.set(count.get() + 1); + } + match self.square { + true => cx.picture_size(self.least, MOST_PICTURE, |width| width), + false => Vec2::new(cx.picture_width(self.least, MOST_PICTURE), LINE), + } + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + self.seen.borrow_mut().rect = cx.rect; + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// The picture a column trial shows: its least width and whether it is square. +#[derive(Clone, Copy)] +struct Shown { + least: f32, + square: bool, +} + +impl Shown { + const fn square(least: f32) -> Self { + Shown { least, square: true } + } +} + +/// What a content-sized column shows with a picture (none when `None`), a `Wrap` and a probe under them `sibling` +/// wide: the column's rect, the picture's and the probe's, the picture's ideal measures in measuring runs without a +/// room and in one, and the wrap's. +struct PictureColumn { + rects: [Rect; 3], + picture: (usize, usize), + wrap: (usize, usize), +} + +fn picture_in_column(picture: Option, sibling: f32) -> PictureColumn { + let (seen, under, wrap) = + (Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default()))); + let (pictures, wraps, column) = (Rc::new(Measures::default()), Rc::new(Measures::default()), Rc::new(Cell::new(Rect::NOTHING))); + let (shown_picture, shown_under, shown_wrap) = (Rc::clone(&seen), Rc::clone(&under), Rc::clone(&wrap)); + let (counted_pictures, counted_wraps, shown_column) = (Rc::clone(&pictures), Rc::clone(&wraps), Rc::clone(&column)); + let mut fixture = Fixture::new(move |ui| { + let shown = Panel::new().id_salt("column").show(ui, |ui, _| { + if let Some(Shown { least, square }) = picture { + let picture = Picture { common: Common::new(), least, square, seen: &shown_picture, measures: &counted_pictures }; + picture.id_salt("picture").show(ui); + } + Wrap::new(&shown_wrap, &counted_wraps).id_salt("wrap").show(ui); + Probe::new(&shown_under).size(Vec2::new(sibling, LINE)).id_salt("under").show(ui); + }); + shown_column.set(shown.output.rect); + }); + fixture.room(Vec2::splat(800.0)).settle(); + let rects = [column.get(), seen.borrow().rect, under.borrow().rect]; + PictureColumn { rects, picture: (pictures.unbounded.get(), pictures.bounded.get()), wrap: (wraps.unbounded.get(), wraps.bounded.get()) } +} + +// A square picture in a content-sized column takes no width of its own there; the column settles on its siblings' +// width and the picture shows across it, as tall as wide, with what follows it laid out below the shown square. +#[trial] +fn a_square_picture_in_a_content_column_pushes_what_follows_below_its_shown_size() { + let PictureColumn { rects: [column, picture, under], .. } = picture_in_column(Some(Shown::square(60.0)), 300.0); + let dump = format!("column {column:?}, picture {picture:?}, under {under:?}"); + assert!(picture.width() > 60.0 + 2.0 * PICTURE_PAD + SLACK, "the picture shows wider than its least, across the column: {dump}"); + assert!((picture.width() - 2.0 * PICTURE_PAD - picture.height()).abs() < SLACK, "a square picture's content is as tall as it shows wide: {dump}"); + assert!(under.top() >= picture.bottom() - SLACK, "what follows lies below the shown picture: {dump}"); + assert!(column.bottom() >= under.bottom() - SLACK, "the column holds everything it shows: {dump}"); +} + +// Count trial: a column whose square picture took its least sweeps again once at its settled width; a column without +// a picture, whose square picture is its widest child (padding included), or whose picture is a band of its own +// height, sweeps once. +#[trial] +fn a_content_column_sweeps_again_only_for_a_square_picture_narrower_than_it() { + let none = picture_in_column(None, 300.0); + let narrow = picture_in_column(Some(Shown::square(60.0)), 300.0); + assert!(none.wrap.0 >= 1 && none.wrap.1 == 0, "no picture: the column sweeps its children: {:?}", none.wrap); + let (unbounded, bounded) = narrow.picture; + assert!( + bounded >= 1 && bounded == unbounded, + "a narrower square picture measures once more per measuring run, at the column: {unbounded} and {bounded}" + ); + let once = [ + ("a square picture wider than the column", Shown::square(400.0)), + ("a square picture as wide as the column with its padding", Shown::square(300.0 - 2.0 * PICTURE_PAD)), + ("a band picture", Shown { least: 60.0, square: false }), + ]; + for (what, shown) in once { + let column = picture_in_column(Some(shown), 300.0); + assert_eq!(column.wrap, none.wrap, "{what} adds no sweep"); + assert!(column.picture.0 >= 1 && column.picture.1 == 0, "{what} keeps its first measure: {:?}", column.picture); + } +} + #[trial] fn a_space_between_child_leaves_room_for_the_siblings_after_it() { let (first, last) = (Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default()))); @@ -322,6 +462,39 @@ fn the_end_region_shares_the_members_line() { assert!((end.center().y - member.center().y).abs() < SLACK, "the end region's probe {end:?} is off the members' line {member:?}"); } +/// A memoized view of one short block. +#[derive(MemoProps)] +struct Short {} + +fn short(_: &mut Short, ui: &mut Ui) -> Rect { + Block::new(Vec2::new(40.0, 10.0)).show(ui).rect +} + +/// A memoized view in a row sits on the row's line, as the one-line child beside it does, also while it replays. Its +/// content starts a layout room of its own, which left it at the row's top (a menu bar beside an app icon, +/// storytold/photocraft#16113). +#[trial] +fn a_memoized_view_sits_on_the_rows_line() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).id_salt("row").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; + let view = MemoView::new("short", Short {}, short).show(ui); + if !is_measuring(ui.ctx()) { + shown.set((tall, view.unwrap_or(Rect::NOTHING))); + } + }); + }); + fixture.room(Vec2::splat(400.0)).settle(); + for frame in 0..3 { + let (tall, view) = seen.get(); + assert!(view.height() > 0.0, "frame {frame}: the view showed: {view:?}"); + assert!((view.center().y - tall.center().y).abs() < SLACK, "frame {frame}: the view {view:?} is off the line of {tall:?}"); + fixture.settle(); + } +} + /// A Row in right-to-left holding a vertically scrolling container (content-sized, then filling its height) beside a /// probe: the container, the probe inside it and the probe beside it are finite, and the container lies in the row. #[trial] diff --git a/crates/ui-contract/tests/it/paint/painters.rs b/crates/ui-contract/tests/it/paint/painters.rs index a5ba01714..84b652ccb 100644 --- a/crates/ui-contract/tests/it/paint/painters.rs +++ b/crates/ui-contract/tests/it/paint/painters.rs @@ -130,6 +130,45 @@ fn an_edge_rule_lies_on_the_pixels_just_inside_its_side_at_any_scale() { } } +#[trial] +fn a_dotted_rule_is_whole_pixel_dots_at_one_pitch_between_its_ends() { + use craft_ui::primitives::Rule; + use craft_ui::style::{RuleLook, RuleWidth}; + use egui::{Color32, Rect, Shape}; + + let whole = |v: f32| (v - v.round()).abs() < EPS; + for ppp in [1.0, 1.5, 2.0] { + for width in [RuleWidth::Hairline, RuleWidth::Points(1.0), RuleWidth::Points(2.0)] { + let look = RuleLook { color: Color32::WHITE, width }; + // Ends off the pixel grid, level and upright. + for (from, to) in [(pos2(10.3, 20.6), pos2(41.1, 20.6)), (pos2(7.7, 3.2), pos2(7.7, 29.9))] { + let shapes = Rule::dotted(&look, from, to, 3.0, ppp); + let [Shape::Mesh(mesh)] = shapes.as_slice() else { panic!("the dots are one mesh") }; + let dots: Vec = + mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::>())).collect(); + assert!(dots.len() > 2, "{width:?} at {ppp}x: several dots"); + let level = from.y == to.y; + let across = width.points(ppp); + let span = if level { + Rect::from_two_pos(from, to).expand2(egui::vec2(0.0, across)) + } else { + Rect::from_two_pos(from, to).expand2(egui::vec2(across, 0.0)) + }; + for dot in &dots { + let px = *dot * ppp; + assert!([px.min.x, px.min.y, px.max.x, px.max.y].into_iter().all(whole), "{width:?} at {ppp}x: {px:?} is not whole pixels"); + assert!((dot.width() - dot.height()).abs() < EPS, "{width:?} at {ppp}x: a dot is square"); + assert!(span.expand(EPS).contains_rect(*dot), "{width:?} at {ppp}x: {dot:?} leaves the line {from:?}..{to:?}"); + } + let starts: Vec = dots.iter().map(|dot| if level { dot.min.x } else { dot.min.y }).collect(); + let pitch = starts[1] - starts[0]; + assert!(pitch > dots[0].width(), "{width:?} at {ppp}x: dots are apart"); + assert!(starts.windows(2).all(|w| (w[1] - w[0] - pitch).abs() < EPS), "{width:?} at {ppp}x: one pitch: {starts:?}"); + } + } + } +} + #[trial] fn ant_edges_are_whole_device_pixels_at_a_fractional_scale() { use craft_theme::{Contrast, Mode}; diff --git a/crates/ui-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-panels/src/dialog/prompt.rs b/crates/ui-panels/src/dialog/prompt.rs index d9e890628..42a3d23a0 100644 --- a/crates/ui-panels/src/dialog/prompt.rs +++ b/crates/ui-panels/src/dialog/prompt.rs @@ -103,10 +103,15 @@ impl Outcome for PromptOutput { } /// The index Escape and the close action answer with: the answer of `chosen` when there is one, else Cancel, else -/// the first Other answer, else the default answer. +/// the first Alternate answer, else the first Other answer, else the default answer. fn escape_answer(answers: &[FooterButton], chosen: Option) -> Option { let find = |wanted: DialogRole| answers.iter().position(|answer| answer.role() == wanted); - chosen.and_then(find).or_else(|| find(DialogRole::Cancel)).or_else(|| find(DialogRole::Other)).or_else(|| default_answer(answers)) + chosen + .and_then(find) + .or_else(|| find(DialogRole::Cancel)) + .or_else(|| find(DialogRole::Alternate)) + .or_else(|| find(DialogRole::Other)) + .or_else(|| default_answer(answers)) } /// The first Accept answer, else the first Destructive one, whether it is enabled or not. diff --git a/crates/ui-panels/src/dialog/prompt/stories.rs b/crates/ui-panels/src/dialog/prompt/stories.rs index 84a5e1f81..2219bcc57 100644 --- a/crates/ui-panels/src/dialog/prompt/stories.rs +++ b/crates/ui-panels/src/dialog/prompt/stories.rs @@ -26,7 +26,7 @@ const AGES: [(&str, Duration); 4] = [ fn answers() -> [FooterButton; 3] { [ FooterButton::new("Save", DialogRole::Accept).letter('S'), - FooterButton::new("Don't Save", DialogRole::Other).letter('D'), + FooterButton::new("Don't Save", DialogRole::Alternate).letter('D'), FooterButton::new("Cancel", DialogRole::Cancel).letter('C'), ] } diff --git a/crates/ui-panels/src/dialog/prompts.rs b/crates/ui-panels/src/dialog/prompts.rs index a62726da4..2349889c1 100644 --- a/crates/ui-panels/src/dialog/prompts.rs +++ b/crates/ui-panels/src/dialog/prompts.rs @@ -79,7 +79,7 @@ impl PromptChoice { fn role(self) -> DialogRole { match self { PromptChoice::Proceed => DialogRole::Accept, - PromptChoice::Alternate => DialogRole::Other, + PromptChoice::Alternate => DialogRole::Alternate, PromptChoice::Cancel => DialogRole::Cancel, } } @@ -347,7 +347,7 @@ impl StandardPrompt { let own = self.buttons.iter().find(|(button, _)| *button == choice).map(|(_, label)| Reply::new(label.clone(), choice.role())); let reply = own.unwrap_or_else(|| match choice { PromptChoice::Proceed => Reply::new(proceed.clone(), role), - PromptChoice::Alternate => Reply::new(words.discard.clone(), DialogRole::Other), + PromptChoice::Alternate => Reply::new(words.discard.clone(), DialogRole::Alternate), PromptChoice::Cancel => Reply::new(common.cancel.clone(), DialogRole::Cancel), }); (choice, reply.enabled(enabled, None)) diff --git a/crates/ui-panels/src/dialog/recovery.rs b/crates/ui-panels/src/dialog/recovery.rs index 06cc70da0..1dfe997c6 100644 --- a/crates/ui-panels/src/dialog/recovery.rs +++ b/crates/ui-panels/src/dialog/recovery.rs @@ -105,7 +105,7 @@ impl RecoveryDialog { let message = words.recovery_message.fill(&[("name", self.document.name.as_str()), ("age", age.as_str())]); let reason = self.document.blocked.clone().map(|reason| Label::from_cow(reason.into())); let replies = vec![ - Reply::plain(words.recovery_discard.clone(), DialogRole::Other), + Reply::plain(words.recovery_discard.clone(), DialogRole::Alternate), Reply::plain(words.recovery_recover.clone(), DialogRole::Accept).enabled(reason.is_none(), reason), ]; let mut prompt = Prompt::new(words.recovery_title.clone(), message).answers(buttons(&env, replies)); diff --git a/crates/ui-panels/src/dialog/unsaved.rs b/crates/ui-panels/src/dialog/unsaved.rs index c716fc53a..e69c9a488 100644 --- a/crates/ui-panels/src/dialog/unsaved.rs +++ b/crates/ui-panels/src/dialog/unsaved.rs @@ -127,9 +127,9 @@ impl UnsavedChangesDialog { CloseAnswer::Save => Reply::new(if mac { &words.unsaved_save } else { &words.unsaved_yes }.clone(), DialogRole::Accept), CloseAnswer::DontSave if self.scope == CloseScope::Revert => Reply::new(words.unsaved_revert.clone(), DialogRole::Accept), CloseAnswer::DontSave if mac => { - Reply::new(words.unsaved_dont_save.clone(), DialogRole::Other).chord(Chord::new(Mods::CMD, Key::D)) + Reply::new(words.unsaved_dont_save.clone(), DialogRole::Alternate).chord(Chord::new(Mods::CMD, Key::D)) } - CloseAnswer::DontSave => Reply::new(words.unsaved_no.clone(), DialogRole::Other), + CloseAnswer::DontSave => Reply::new(words.unsaved_no.clone(), DialogRole::Alternate), CloseAnswer::Cancel => Reply::new(cancel.clone(), DialogRole::Cancel), }; (answer, reply) diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index b08d63c16..887a46116 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -326,7 +326,7 @@ impl DockDropTarget<'_, P> { } let unit = drag.unit(self.layout)?; let window = matches!(unit, DragUnit::Window(_)); - if pointer::frame(self.ctx).mods.cmd { + if pointer::mods(self.ctx).cmd { return if window { None } else { self.float(&unit, at, drag.source(), drag.strip()) }; } if window && !self.title_bar_docks { diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index fc6369b3b..ba0c58ef9 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -277,8 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, - /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the - /// running window's. + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome, the rule under its title row included, is sized at that scale. + #[prop(quantity = "display scale, pixels per point")] scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, @@ -363,14 +364,6 @@ impl<'a> FloatingGroup<'a> { self } - /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the - /// running window's: its chrome is sized at that scale. - #[must_use] - pub fn scale(mut self, pixels_per_point: f32) -> Self { - self.scale = Some(pixels_per_point); - self - } - /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 6ab02daf3..3a850af21 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -13,15 +13,15 @@ use crate::contract::{ WordSetCx as _, }; use crate::menu::GroupItem; -use crate::primitives::{IconSpec, PaintShape, TextRun}; +use crate::primitives::{IconSpec, TextRun}; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind, UiTokens}; +use crate::style::{ComponentStyle, Corners, GlyphRole, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::overlay::Side; use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value}; use craft_theme::ControlSize; -use egui::{CornerRadius, Id, Pos2, Rect, Response, Ui, Vec2}; +use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; use std::fmt::Debug; use std::hash::Hash; @@ -54,11 +54,11 @@ pub struct IconicSizes { /// The column width, in rail widths, from which the cells show their panels' names: 96 points at the Compact size. const LABELS_IN_RAIL_WIDTHS: f32 = 2.4; -/// The length of a group's grip bar, in icon cell heights: half a cell, 15 points at the Compact size (18 at -/// Comfortable). That is several times the bar's thickness, so it reads as a handle and not as a dot, and in a -/// rail-wide column (40 points at Compact) it leaves more than a quarter of the width free on each side, so it does -/// not read as a rule between the groups. -const GRIP_BAR_IN_CELLS: f32 = 0.5; +/// The length of a group's grip line, in icon cell heights: half a cell, 15 points at the Compact size (18 at +/// Comfortable). That holds several dots, so it reads as a handle and not as a dot, and in a rail-wide column (40 +/// points at Compact) it leaves more than a quarter of the width free on each side, so it does not read as a rule +/// between the groups. +const GRIP_LINE_IN_CELLS: f32 = 0.5; impl IconicSizes { /// The sizes of the style context `cx`. @@ -149,22 +149,21 @@ pub struct IconicColumnStyle { name_open: StyleColor, /// The room between an icon and its name. name_gap: f32, - /// The ink of a group's grip bar. + /// The ink of a group's grip line. grip: StyleColor, - /// The ink of a group's grip bar while the pointer is over it or drags it. + /// The ink of a group's grip line while the pointer is over it or drags it. grip_active: StyleColor, - /// The grip bar's length across the group and its thickness. + /// The grip line's length across the group. grip_length: f32, - grip_thickness: f32, - /// The grip bar's corners: the theme's pill rounding. - grip_radius: CornerRadius, + /// The side of the grip line's dots, and the gap between two of them. + grip_dot: f32, } /// A column collapsed to icons: the column bar over icon groups, one cell per panel. A panel without an icon shows the /// first letter of its name in a box. A column widened past `IconicSizes::labels` shows each panel's name beside its /// icon, cut with an ellipsis to the cell; a click or drag on the name acts as one on the icon. A click or Enter on an icon /// opens the flyout of its panel beside the column, switches it to that panel or closes it; one flyout is open at a -/// time. A drag of an icon starts a move of its panel, a drag of the grip bar on top of a group a move of the group, a +/// time. A drag of an icon starts a move of its panel, a drag of the grip line on top of a group a move of the group, a /// drag of the bar beside its button a move of the column; each starts through the drag session, and a press outside /// the flyout closes it. Escape and a press /// outside close the flyout; with `auto_collapse` the focus leaving it does too. @@ -423,11 +422,12 @@ impl Component for IconicColumn<'_, P> { name: cx.color(colors.text.normal), name_open: cx.color(colors.accent.text), name_gap: cx.tokens.space.gap.item, - grip: cx.color(colors.text.muted), + // A handle that is found when looked for, as the references' faint grips: hairline dots one dot apart in + // the faint ink, the normal ink under the pointer. + grip: cx.color(colors.text.faint), grip_active: cx.color(colors.text.normal), - grip_length: cx.tokens.size.rail.button * GRIP_BAR_IN_CELLS, - grip_thickness: cx.tokens.stroke.thick, - grip_radius: UiTokens::corner(cx.tokens.shape.radius.pill), + grip_length: cx.tokens.size.rail.button * GRIP_LINE_IN_CELLS, + grip_dot: cx.tokens.stroke.thin, } } @@ -580,8 +580,9 @@ impl Component for IconicColumn<'_, P> { for (group, strip) in self.laid.as_ref().map_or(&[][..], |plan| &plan.grips[..]) { let part = cx.part(GRIP.at(*group as u64)); let ink = if part.hovered || part.pressed() { style.grip_active } else { style.grip }; - let bar = Rect::from_center_size(strip.center(), Vec2::new(style.grip_length.min(strip.width()), style.grip_thickness)); - ui.draw().fill(&PaintShape::Rect(bar, style.grip_radius), ink); + let half = Vec2::new(style.grip_length.min(strip.width()) / 2.0, 0.0); + let look = RuleLook { color: ink.egui(), width: RuleWidth::Points(style.grip_dot) }; + ui.draw().dotted_rule_with(&look, strip.center() - half, strip.center() + half, style.grip_dot); } // The edge's line lies on the column's inner edge; its handle stays inside the column. A floating window's // edges are the window's. diff --git a/crates/ui-panels/src/sections/footer.rs b/crates/ui-panels/src/sections/footer.rs index d983d9722..1fc926d23 100644 --- a/crates/ui-panels/src/sections/footer.rs +++ b/crates/ui-panels/src/sections/footer.rs @@ -376,25 +376,34 @@ impl FooterDrop { pub enum DialogRole { /// The default outcome: the primary look, last in the row (first on Windows). Accept, - /// An outcome that destroys something: the danger look. + /// An outcome that destroys something (Delete, Replace): the danger look. It proceeds, so Windows puts it with the + /// accepting button, before Cancel. Destructive, /// Leaves without an outcome. Cancel, + /// Another answer that closes the question: No, Don't Save, Discard. It stands with the other outcomes on macOS + /// and Linux and next to the accepting button on Windows. + Alternate, /// Any other outcome. Other, } impl DialogRole { - /// The position in the row: later roles stand nearer the end. Windows puts the accepting button first and the - /// others after it; macOS and Linux put it last. + /// The position in the row: later roles stand nearer the end. Windows puts the committing buttons first (the + /// accepting one, then a destructive proceed) and the answers that close the question after them, before Cancel; + /// macOS and Linux put the accepting button last. fn rank(self, windows: bool) -> u8 { - let rank = match self { - DialogRole::Other => 0, - DialogRole::Destructive => 1, - DialogRole::Cancel => 2, - DialogRole::Accept => 3, - }; - if windows { 3 - rank } else { rank } + match (windows, self) { + (false, DialogRole::Other | DialogRole::Alternate) => 0, + (false, DialogRole::Destructive) => 1, + (false, DialogRole::Cancel) => 2, + (false, DialogRole::Accept) => 3, + (true, DialogRole::Accept) => 0, + (true, DialogRole::Destructive) => 1, + (true, DialogRole::Alternate) => 2, + (true, DialogRole::Cancel) => 3, + (true, DialogRole::Other) => 4, + } } } @@ -515,14 +524,15 @@ enum Content { } /// The indexes of `roles` in display order: by role rank, and in the given order within a rank. A column puts -/// `Accept` on top and `Cancel` under it on every platform, then the others. +/// `Accept` on top, `Alternate` and `Cancel` under it on every platform, then the others. pub(crate) fn display_order(roles: &[DialogRole], windows: bool, column: bool) -> Vec { let mut order: Vec = (0..roles.len()).collect(); if column { order.sort_by_key(|&at| match roles[at] { DialogRole::Accept => 0, - DialogRole::Cancel => 1, - DialogRole::Destructive | DialogRole::Other => 2, + DialogRole::Alternate => 1, + DialogRole::Cancel => 2, + DialogRole::Destructive | DialogRole::Other => 3, }); } else { order.sort_by_key(|&at| roles[at].rank(windows)); @@ -546,7 +556,7 @@ impl FooterBar { } /// The members stand in a column at the top of the bar, each as wide as the widest: the buttons of a dialog whose - /// footer stands beside the body. Buttons go `Accept`, `Cancel`, then the others in the given order. + /// footer stands beside the body. Buttons go `Accept`, `Alternate`, `Cancel`, then the others in the given order. #[must_use] pub fn column(mut self) -> Self { self.props = self.props.layout(BodyLayout::stack()); @@ -633,7 +643,7 @@ impl FooterBar { let variant = match button.role { DialogRole::Accept => Variant::PRIMARY, DialogRole::Destructive => Variant::DANGER, - DialogRole::Cancel | DialogRole::Other => Variant::SECONDARY, + DialogRole::Cancel | DialogRole::Alternate | DialogRole::Other => Variant::SECONDARY, }; let mut widget = Button::new(button.label.clone()).variant(variant).enabled(button.enabled).least_width(least); if column { @@ -681,7 +691,7 @@ impl FooterBar { } }); let inner = shown.inner.unwrap_or_default(); - let mods = if inner.picked.is_some() { crate::runtime::pointer::frame(ui.ctx()).mods } else { craft_keymap::Mods::NONE }; + let mods = if inner.picked.is_some() { crate::runtime::pointer::mods(ui.ctx()) } else { craft_keymap::Mods::NONE }; let output = FooterOutput { response: shown.output, picked: inner.picked, diff --git a/crates/ui-panels/tests/it/dialogs.rs b/crates/ui-panels/tests/it/dialogs.rs index 5eac75e7e..ef4a79649 100644 --- a/crates/ui-panels/tests/it/dialogs.rs +++ b/crates/ui-panels/tests/it/dialogs.rs @@ -365,6 +365,75 @@ fn cmd_d_answers_dont_save_on_macos() { } } +/// The unsaved-changes buttons run Yes, No, Cancel on Windows and Don't Save, Cancel, Save on macOS; on every OS Escape +/// answers Cancel, and the Yes and No letters answer Save and Don't Save. +#[trial] +fn the_unsaved_question_orders_its_buttons_by_platform_and_answers_by_role() { + let order = |os: Os, names: [&str; 3]| { + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.os(os); + host.borrow_mut().open(UnsavedChangesDialog::new(CloseScope::Close, "poster.psd")); + fixture.idle(6); + let lefts = names.map(|name| fixture.by_label(name).unwrap_or_else(|| panic!("{os:?}: {name} shows")).rect.left()); + assert!(lefts.windows(2).all(|pair| pair[0] < pair[1]), "{os:?}: {names:?} run left to right, at {lefts:?}"); + }; + order(Os::Windows, ["Yes", "No", "Cancel"]); + order(Os::Mac, ["Don't Save", "Cancel", "Save"]); + + for (key, expected) in [(egui::Key::Escape, CloseAnswer::Cancel), (egui::Key::Y, CloseAnswer::Save), (egui::Key::N, CloseAnswer::DontSave)] { + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.os(Os::Windows); + host.borrow_mut().open(UnsavedChangesDialog::new(CloseScope::Close, "poster.psd")); + fixture.idle(6); + fixture.key(key, Modifiers::NONE).idle(4); + let answered = host.borrow_mut().take::().and_then(DialogResult::ok).map(|answer| answer.answer); + assert_eq!(answered, Some(expected), "{key:?} answers {expected:?}"); + } +} + +/// Apply, an auxiliary action, stands after Cancel on Windows; the Alternate role does not move it. +#[trial] +fn windows_puts_an_auxiliary_apply_after_cancel() { + let mut fixture = Fixture::new(|ui| { + let mut open = true; + Dialog::new("Options") + .opened(Bind::bound(&mut open)) + .buttons([ + FooterButton::new("OK", DialogRole::Accept), + FooterButton::new("Apply", DialogRole::Other).stays_open(true), + FooterButton::new("Cancel", DialogRole::Cancel), + ]) + .show(ui, |_, _| {}); + }); + fixture.os(Os::Windows); + fixture.idle(30); + let left = |name: &str| fixture.by_label(name).expect("the button shows").rect.left(); + assert!(left("OK") < left("Cancel") && left("Cancel") < left("Apply"), "OK, Cancel, Apply from the start edge"); +} + +/// A destructive proceed is a committing button: Windows puts it first, before Cancel; macOS keeps Cancel nearer the +/// end edge than Delete. +#[trial] +fn a_delete_prompt_reads_delete_then_cancel_on_windows() { + for os in [Os::Windows, Os::Mac] { + let mut fixture = Fixture::new(|ui| { + let mut open = true; + Dialog::new("Delete Layer") + .opened(Bind::bound(&mut open)) + .buttons([FooterButton::new("Cancel", DialogRole::Cancel), FooterButton::new("Delete", DialogRole::Destructive)]) + .show(ui, |_, _| {}); + }); + fixture.os(os); + fixture.idle(30); + let left = |name: &str| fixture.by_label(name).expect("the button shows").rect.left(); + assert!(left("Delete") < left("Cancel"), "{os:?}: Delete, then Cancel, from the start edge"); + } +} + /// Each open of a dialog has its own serial, kept while it stays open, though its id is the same at every open: a /// reopened dialog is told apart from the one cancelled before it. #[trial] diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 92f838b93..69d9af12a 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -2,7 +2,7 @@ //! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview. use super::fields::{DialogFields, FieldValue}; -use crate::patterns::presets::{PresetKind, PresetRow}; +use crate::patterns::presets::{PresetKind, PresetRow, PresetSource}; use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest}; use super::form::{FormDialog, FormDialogWords}; @@ -243,9 +243,10 @@ pub struct ParamDialog<'a> { /// dialog open; a press comes back as `ParamDialogOutput::footer_action`. #[prop] extra_buttons: Vec<(String, Label)>, - /// The patterns the dialog's [`ParamKind::Pattern`] rows offer. + /// The patterns the dialog's [`ParamKind::Pattern`] rows offer. A hosted dialog's build gives a source over + /// owned inputs. #[prop] - patterns: Cow<'a, [PresetRow]>, + patterns: Option>, /// A muted line at the footer's start edge, left of the buttons (a file size estimate, say). #[prop(into)] footer_note: Option

) -> 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 @@ -2301,7 +2302,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component. - `pub fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above - `pub fn column_room(&self) -> Option`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the - - `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up + - `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes + - `pub fn picture_size(&self, least: f32, most: f32, height: impl FnOnce(f32) -> f32) -> Vec2`. The size of a picture whose height follows from its width (a square graph, a wheel, an image at its aspect): - `pub fn label(&self) -> Label`. The label as given. - `pub fn cell_width(&self, column: &craft_behavior::ColumnKey, width: f32)`. Reports, from the `Ideal` measure of a collection's item, the width its content in `column` takes unclipped, - `pub fn layout(&self, run: &TextRun<'_>) -> TextLayout`. Lays `run` out in the content's room, as `Draw::text` will paint it. @@ -2908,6 +2910,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub fn scroll_bar(&self, look: &crate::style::ScrollBarLook, track: Rect, axis: craft_behavior::Axis, rtl: bool, span: &craft_behavior::ScrollSpan, state: &crate::style::StateSet,)`. Paints the scroll bar in `track` along `axis` for `span`, in the bar's `state` (`ScrollBar::shapes`; - `pub fn rule_width(&self, kind: RuleKind) -> f32`. The width in points of the line `rule` paints for `kind`. - `pub fn rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2)`. Paints the line `look` from `from` to `to`, snapped to physical pixels as `rule` is: a rule in a component's own + - `pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32)`. Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a grip's dotted line. - `pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners)`. Paints a surface of `kind` (tracks, plot wells). - `pub fn surface_styled(&self, rect: Rect, style: &SurfaceStyle)`. Paints a surface of an already resolved `style` (a kind's look with one field changed, as a knob's round radius). - `pub fn surface_look(&self, rect: Rect, look: &crate::style::SurfaceLook, state: &crate::style::StateSet)`. Paints `look` over `rect` in `state`, as the paint step paints a component's surface: a part's own surface (an @@ -3046,6 +3049,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub fn of(value: &impl Hash) -> Revision`. The revision of anything hashable: `Revision::of(&(fingerprint, doc_width))`. Stable within one run of the - `craft_ui::primitives::Rule`: `pub struct Rule`. The rule painter. - `pub fn shapes(look: &RuleLook, from: Pos2, to: Pos2, pixels_per_point: f32) -> Vec`. The line from `from` to `to`, snapped across its direction: a line whose physical width is odd sits on a + - `pub fn dotted(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, pixels_per_point: f32) -> Vec`. The dotted form of the line from `from` to `to`: square dots as wide as the line, `gap` points apart, the run - `pub fn edge(look: &RuleLook, rect: Rect, side: RectSide, pixels_per_point: f32) -> Vec`. The line along the `side` edge of `rect`, on the physical pixels just inside it: a row's bottom rule or a - `craft_ui::primitives::RuleKind`: `pub enum RuleKind { Divider, Edge, Grid, DropMark }`. Which rule a look is for. - `craft_ui::primitives::RulerFace`: `pub enum RulerFace { Edge, Centred }`. How a ruler lays out its marks and numbers. A ruler takes a face from its `face` prop, else from the scope's @@ -4223,7 +4227,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 +4591,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` diff --git a/migration/api-map/craft-menu.toml b/migration/api-map/craft-menu.toml index 3cb23d23a..056edf546 100644 --- a/migration/api-map/craft-menu.toml +++ b/migration/api-map/craft-menu.toml @@ -107,7 +107,12 @@ old = "id(Id)" new = "" note = "Use `Props::id_salt` on the bar's parent scope." +[[call]] +old = "MenuBarUi::english(hook)" +new = "" +note = "The English name is a field of the model (`Item::english`, `Node::english`, `Menu::english`), set where the app translates a label." + [[call]] old = "MenuBar::palette_entries(&keymap, target, &options, english, os)" -new = "MenuBar::help_entries(target, &options, english)" -note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go." +new = "MenuBar::help_entries(target, &options)" +note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go, and so does the English hook: set `Item::english` on the model."