From 7f56589f5a146676f971cd78ae7357a98cb4d6c0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 22:55:39 +0100 Subject: [PATCH 01/29] Add Anchor: reach a segment within 5 points The reference application adds an anchor when a click is up to 5 px from a segment at 100 % and adds none at 6 px. The overlay's segments hit within a line's 4 points, so a click 4.5 or 5 points away added nothing under Add Anchor. craft-behavior's polyline hit shape gets its own reach (`HitShape::polyline_within`; `polyline` keeps `LINE_REACH`), and the overlay gives Add Anchor's segments a 5-point reach. Delete Anchor, Direct Selection and the other tools keep a line's reach. Co-Authored-By: Claude Opus 5.5 --- crates/behavior/src/hit.rs | 38 +++++++++++++++---- crates/draw/src/ui/pen/bezier/mod.rs | 20 +++++++--- crates/draw/tests/it/bezier.rs | 57 ++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 12 deletions(-) diff --git a/crates/behavior/src/hit.rs b/crates/behavior/src/hit.rs index 1a77ccf26..0ca496cdd 100644 --- a/crates/behavior/src/hit.rs +++ b/crates/behavior/src/hit.rs @@ -30,13 +30,15 @@ pub enum HitShape { /// The other end. b: Pos2, }, - /// A chain of segments, hit within [`LINE_REACH`]. + /// A chain of segments, hit within `reach` ([`LINE_REACH`] unless [`HitShape::polyline_within`] says otherwise). #[non_exhaustive] Polyline { /// The corners in order. points: Vec, /// Whether the last corner joins the first. closed: bool, + /// How far from the chain a point still hits it, in points. + reach: f32, }, /// A filled polygon. Polygon(Vec), @@ -62,9 +64,16 @@ impl HitShape { HitShape::Segment { a, b } } - /// A chain of segments, closed when `closed`. + /// A chain of segments, closed when `closed`, hit within [`LINE_REACH`]. pub fn polyline(points: Vec, closed: bool) -> Self { - HitShape::Polyline { points, closed } + HitShape::Polyline { points, closed, reach: LINE_REACH } + } + + /// A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from + /// a line's. A negative or non-finite `reach` is [`LINE_REACH`]. + pub fn polyline_within(points: Vec, closed: bool, reach: f32) -> Self { + let reach = if reach.is_finite() && reach >= 0.0 { reach } else { LINE_REACH }; + HitShape::Polyline { points, closed, reach } } /// The part of `within` outside `polygon`. @@ -95,7 +104,8 @@ impl HitShape { } HitShape::Circle { center, radius } => center.distance(point) <= radius.max(across / 2.0), HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= reach, - HitShape::Polyline { points, closed } => { + HitShape::Polyline { points, closed, reach: own } => { + let reach = own.max(across / 2.0); let closing = closed.then(|| points.first().zip(points.last())).flatten(); points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= reach) || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= reach) @@ -116,10 +126,10 @@ impl HitShape { HitShape::Rect(rect) => rect.contains(point), HitShape::Circle { center, radius } => center.distance(point) <= *radius, HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= LINE_REACH, - HitShape::Polyline { points, closed } => { + HitShape::Polyline { points, closed, reach } => { let closing = closed.then(|| points.first().zip(points.last())).flatten(); - points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= LINE_REACH) - || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= LINE_REACH) + points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= *reach) + || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= *reach) } HitShape::Polygon(points) => inside_polygon(point, points), HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon), @@ -330,4 +340,18 @@ mod tests { let tie = [shape(big(), Sense::CLICK, 1, 0, HitLevel::Body, 0), shape(big(), Sense::CLICK, 2, 0, HitLevel::Body, 0)]; assert_eq!(owner(&tie), Some(2)); } + + #[test] + fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() { + let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)]; + let line = HitShape::polyline(points.clone(), false); + assert!(line.hit(pos2(50.0, LINE_REACH)) && !line.hit(pos2(50.0, LINE_REACH + 0.5))); + let wide = HitShape::polyline_within(points.clone(), false, 5.0); + assert!(wide.hit(pos2(50.0, 5.0)) && wide.hit(pos2(50.0, -5.0)) && !wide.hit(pos2(50.0, 5.5))); + let hits = |shape: HitShape, y: f32| Shape::new(shape, Sense::CLICK, 0_u8, None, HitPriority::BODY, 0).min_across(8.0).hits(pos2(50.0, y)); + assert!(hits(wide.clone(), 5.0) && !hits(wide, 5.5), "a target size under twice the reach keeps the reach"); + for bad in [f32::NAN, f32::INFINITY, -1.0] { + assert_eq!(HitShape::polyline_within(points.clone(), false, bad), line); + } + } } diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 20e1d040a..0f58a91b5 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -47,6 +47,11 @@ use super::{PathOptionsSettings, PathTool}; /// Insert on a picked anchor adds one halfway along the segment leaving it. const INSERT: Chord = Chord::plain(Key::Insert); +/// How far from a segment, in screen points, an Add Anchor press or hover still takes it: the reference application +/// adds an anchor 5 px from a segment at 100 % and none at 6 px. The other tools keep a line's reach +/// ([`LINE_REACH`](craft_behavior::hit::LINE_REACH)). +const ADD_ANCHOR_REACH: f32 = 5.0; + /// Above this many anchors in the paths shown, the overlay draws outlines only and declares no part (no anchor in /// the AccessKit tree either) (VectorCraft's `OVERLAY_MAX_ANCHORS`). pub const MAX_ANCHORS: usize = 100_000; @@ -66,10 +71,10 @@ pub enum BezierTool { Convert, /// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). Anchors, - /// Add Anchor Point: a press on a segment inserts an anchor at the hit's `t` ([`PathEdit::InsertAnchor`]); a drag - /// moves the new anchor, which is selected; ⌥ makes it Delete Anchor Point. Hover: the segment mark with the - /// anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor the arrow; the crosshair under the - /// canvas's precise cursor ([`CanvasSpace::precise`]). + /// Add Anchor Point: a press on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` + /// ([`PathEdit::InsertAnchor`]); a drag moves the new anchor, which is selected; ⌥ makes it Delete Anchor Point. + /// Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor the + /// arrow; the crosshair under the canvas's precise cursor ([`CanvasSpace::precise`]). AddAnchor, /// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it /// Add Anchor Point, except that a ⌥ click on an anchor selects its whole subpath. Hover: the anchor mark. @@ -504,13 +509,18 @@ impl<'a> BezierOverlay<'a> { let start = if ends && i == 0 { reach } else { 0.0 }; let end = if ends && i + 1 == sub.segment_count() { reach } else { 0.0 }; let Some(points) = trim_polyline(points, start, end) else { continue }; + let shape = if self.tool == BezierTool::AddAnchor { + HitShape::polyline_within(points, false, ADD_ANCHOR_REACH) + } else { + HitShape::polyline(points, false) + }; items.push(Item { kind: Kind::Segment, path: at, key: path.key, knot: KnotRef::new(s, i), at: corners[0], - shape: HitShape::polyline(points, false), + shape, interior: true, straight: sub.is_straight(i), shown: true, diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 1cd1cb17a..ed91f4df5 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -744,6 +744,63 @@ fn add_anchor_shows_the_pen_with_plus_over_a_segment_and_the_arrow_over_an_ancho } } +// Add Anchor reaches a segment within 5 screen points, as the reference application does (PhotoCraft #12732): a click +// 2 to 5 points above or below a straight segment adds an anchor and shows the pen with "+", one 5.5 or 6 points away +// adds nothing; Delete Anchor and Direct Selection keep a line's reach. +#[trial] +fn add_anchor_reaches_a_segment_within_5_points() { + use craft_behavior::{Cursor, CursorBadge, PaintedCursor}; + let segment = p(110.0, 60.0); + let at_tool = |tool: BezierTool| { + let mut h = two_paths(); + h.update(|st| st.tool = tool); + h + }; + let click = |h: &mut Harness, at: Pos2| { + h.press_at(at); + h.release_at(at); + }; + let pen_plus = |h: &Harness| { + matches!( + craft_ui::runtime::cursor::current(h.fixture.ctx()), + Some(Cursor::Painted(PaintedCursor::Tool { badge: Some(CursorBadge::Add), .. })) + ) + }; + for off in [2.0_f32, 3.0, 4.5, 5.0, -2.0, -5.0] { + let mut h = at_tool(BezierTool::AddAnchor); + let at = h.screen(segment) + vec2(0.0, off); + h.move_to(at); + h.fixture.frame(Vec::new()); + assert!(pen_plus(&h), "{off}: the pen with + shows where a click adds"); + click(&mut h, at); + let st = h.state.borrow(); + assert!(matches!(st.changes.last(), Some(PathEdit::InsertAnchor { path: 1, segment, .. }) if *segment == kr(0)), "{off}: {:?}", st.changes); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "{off}"); + } + for off in [5.5_f32, 6.0, -6.0] { + let mut h = at_tool(BezierTool::AddAnchor); + let at = h.screen(segment) + vec2(0.0, off); + h.move_to(at); + h.fixture.frame(Vec::new()); + assert!(!pen_plus(&h), "{off}: no + past the reach"); + click(&mut h, at); + let st = h.state.borrow(); + assert!(st.changes.is_empty() && st.seen.is_empty(), "{off}: {:?} {:?}", st.changes, st.seen); + assert_eq!(st.paths, [path_a(), path_b()], "{off}"); + } + // The other tools keep a line's reach: 4.5 points from the segment misses it, 3 points hits it. + for tool in [BezierTool::DeleteAnchor, BezierTool::Direct] { + let mut h = at_tool(tool); + let near = h.screen(segment) + vec2(0.0, 3.0); + h.drag(near, vec2(0.0, FAR)); + assert!(matches!(h.last_change(), Some(PathEdit::BendSegment { path: 1, .. })), "{tool:?}: {:?}", h.last_change()); + let mut h = at_tool(tool); + let past = h.screen(segment) + vec2(0.0, 4.5); + h.drag(past, vec2(0.0, FAR)); + assert!(!matches!(h.last_change(), Some(PathEdit::BendSegment { .. })), "{tool:?}: {:?}", h.last_change()); + } +} + // The anchor tools' canvas tool: a press off the paths begins nothing (it never starts a path), and off the paths the // cursor says what a click does: the arrow for Add Anchor (the pen with "-" under ⌥, where a click deletes), the pen // with "-" for Delete Anchor, the Convert Point icon, the arrow for Direct Selection and under ⌘, the crosshair when From 326438a6f9266be2a7d89d20d0bacd6de326c3d0 Mon Sep 17 00:00:00 2001 From: ussoewwin <136552381+ussoewwin@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:11:01 +0900 Subject: [PATCH 02/29] access: a popup's node this update does not carry leaves no dangling controls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit accesskit_consumer's Node::controls() unwraps every id in the relation, so an update whose controls names a node it does not carry aborts the app once the host's UIA adapter applies it. In PhotoCraft on Windows, clicking Image, Edit or Layer in the menu bar did exactly that (photocraft#15597), and on one machine Filter too — an ordering difference per menu. emit.rs adds every open popup's id, and a menu reports its popup open on a frame where the popup's own node is not emitted. The runtime plugin now prunes the finished update in output_hook, keeping a controls id only when the same update carries its node. Other relations are untouched: they are built from nodes the pass wrote. The tests fail without the change: the relation keeps an id with no node. --- crates/ui-contract/src/runtime/egui/access.rs | 65 ++++++++++++++++++- crates/ui-contract/src/runtime/egui/plugin.rs | 6 +- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 8eee24e44..8250b26c7 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -10,9 +10,7 @@ mod text; mod tree; use crate::runtime::pass_state; -#[cfg(feature = "testing")] -use egui::FullOutput; -use egui::{Context, Id, IdMap, IdSet, ViewportId}; +use egui::{Context, FullOutput, Id, IdMap, IdSet, ViewportId}; use std::collections::HashMap; use super::pass; @@ -200,3 +198,64 @@ fn hide_behind_modal(ctx: &Context, viewport: ViewportId, written: &IdSet) { pub(crate) fn tree_of(output: &mut FullOutput) -> Option { output.platform_output.accesskit_update.take().map(AccessTree::new) } + +/// Drops relations that name a node this update does not carry. +/// +/// A menu reports its popup open on a frame where the popup's own node is not emitted (the ordering +/// differs per menu), and `runtime::access::emit` puts that id in `controls`. A host's UIA adapter +/// unwraps every `controls` lookup (`accesskit_consumer`'s `Node::controls`), so one id with no node +/// in the same update aborts the app: photocraft#15597, where clicking Image, Edit or Layer — and on +/// one machine Filter — closed PhotoCraft on the click that opened the menu. +pub(crate) fn drop_dangling_relations(output: &mut FullOutput) { + let Some(update) = output.platform_output.accesskit_update.as_mut() else { return }; + prune_controls(update); +} + +/// The step itself, for the tests: every `controls` id of `update` that names no node of `update` is +/// dropped. Other relations keep their ids: they are built from nodes this pass wrote. +fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { let ids: std::collections::HashSet = update.nodes.iter().map(|(id, _)| *id).collect(); + for (_, node) in update.nodes.iter_mut() { + if node.controls().iter().all(|id| ids.contains(id)) { + continue; + } + let kept: Vec = node.controls().iter().copied().filter(|id| ids.contains(id)).collect(); + node.set_controls(kept); + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use egui::accesskit::{Node, NodeId, Role, TreeId, TreeUpdate}; + + fn update(controls: Vec, carried: Vec) -> TreeUpdate { + let mut node = Node::new(Role::Button); + node.set_controls(controls); + TreeUpdate { + nodes: carried.into_iter().map(|id| (id, Node::new(Role::Button))).chain(std::iter::once((NodeId(1), node))).collect(), + tree: None, + tree_id: TreeId::ROOT, + focus: NodeId(1), + } + } + + /// A popup that reports itself open on a frame where its node is not emitted leaves its id in + /// `controls`; the host's UIA adapter unwraps that lookup and aborts (photocraft#15597). The id + /// that has a node stays. + #[test] + fn controls_keep_the_ids_the_update_carries_and_drop_the_rest() { + let mut tree = update(vec![NodeId(2), NodeId(9)], vec![NodeId(2)]); + prune_controls(&mut tree); + let kept: Vec = tree.nodes.iter().find(|(id, _)| *id == NodeId(1)).map(|(_, node)| node.controls().to_vec()).unwrap_or_default(); + assert_eq!(kept, vec![NodeId(2)], "the id without a node is gone, the one with a node stays"); + } + + #[test] + fn controls_with_every_node_carried_are_left_alone() { + let mut tree = update(vec![NodeId(2)], vec![NodeId(2)]); + prune_controls(&mut tree); + let kept: Vec = tree.nodes.iter().find(|(id, _)| *id == NodeId(1)).map(|(_, node)| node.controls().to_vec()).unwrap_or_default(); + assert_eq!(kept, vec![NodeId(2)]); + } +} diff --git a/crates/ui-contract/src/runtime/egui/plugin.rs b/crates/ui-contract/src/runtime/egui/plugin.rs index efa49785b..6ae26f33b 100644 --- a/crates/ui-contract/src/runtime/egui/plugin.rs +++ b/crates/ui-contract/src/runtime/egui/plugin.rs @@ -1,7 +1,7 @@ //! The plugin impl, its registration and hook order, and the plugin lock. use crate::runtime::frame; -use egui::{Context, Plugin, RawInput, Ui}; +use egui::{Context, FullOutput, Plugin, RawInput, Ui}; /// The runtime's plugin. egui holds a plugin's mutex while it calls a hook, so the struct holds no state: /// every record lives in context data behind its own lock. @@ -17,6 +17,10 @@ impl Plugin for RuntimePlugin { frame::input_hook(ctx, input); } + fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) { + let _ = ctx; + crate::runtime::egui::access::drop_dangling_relations(output); + } fn on_begin_pass(&mut self, ui: &mut Ui) { frame::begin_pass(ui); } From c6537b6d07b0d8c2d3f9eb498c447a81145e1664 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 04:09:37 +0000 Subject: [PATCH 03/29] access: rustfmt --- crates/ui-contract/src/runtime/egui/access.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 8250b26c7..69359c87d 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -213,7 +213,8 @@ pub(crate) fn drop_dangling_relations(output: &mut FullOutput) { /// The step itself, for the tests: every `controls` id of `update` that names no node of `update` is /// dropped. Other relations keep their ids: they are built from nodes this pass wrote. -fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { let ids: std::collections::HashSet = update.nodes.iter().map(|(id, _)| *id).collect(); +fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { + let ids: std::collections::HashSet = update.nodes.iter().map(|(id, _)| *id).collect(); for (_, node) in update.nodes.iter_mut() { if node.controls().iter().all(|id| ids.contains(id)) { continue; @@ -223,7 +224,6 @@ fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { let ids: std::c } } - #[cfg(test)] mod tests { use super::*; From 4ec453ed5a604c443fe17109b5c61c8460fd22bb Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:38:55 +0000 Subject: [PATCH 04/29] access: the controls tests live in the integration binary --- crates/ui-contract/src/runtime/egui/access.rs | 42 ++----------------- crates/ui-contract/src/testing/access.rs | 6 +++ .../ui-contract/tests/it/access/controls.rs | 37 ++++++++++++++++ crates/ui-contract/tests/it/access/mod.rs | 1 + 4 files changed, 47 insertions(+), 39 deletions(-) create mode 100644 crates/ui-contract/tests/it/access/controls.rs diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 69359c87d..f02dfc930 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -211,9 +211,9 @@ pub(crate) fn drop_dangling_relations(output: &mut FullOutput) { prune_controls(update); } -/// The step itself, for the tests: every `controls` id of `update` that names no node of `update` is -/// dropped. Other relations keep their ids: they are built from nodes this pass wrote. -fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { +/// The step itself: every `controls` id of `update` that names no node of `update` is dropped. Other +/// relations keep their ids: they are built from nodes this pass wrote. +pub(crate) fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { let ids: std::collections::HashSet = update.nodes.iter().map(|(id, _)| *id).collect(); for (_, node) in update.nodes.iter_mut() { if node.controls().iter().all(|id| ids.contains(id)) { @@ -223,39 +223,3 @@ fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { node.set_controls(kept); } } - -#[cfg(test)] -mod tests { - use super::*; - use egui::accesskit::{Node, NodeId, Role, TreeId, TreeUpdate}; - - fn update(controls: Vec, carried: Vec) -> TreeUpdate { - let mut node = Node::new(Role::Button); - node.set_controls(controls); - TreeUpdate { - nodes: carried.into_iter().map(|id| (id, Node::new(Role::Button))).chain(std::iter::once((NodeId(1), node))).collect(), - tree: None, - tree_id: TreeId::ROOT, - focus: NodeId(1), - } - } - - /// A popup that reports itself open on a frame where its node is not emitted leaves its id in - /// `controls`; the host's UIA adapter unwraps that lookup and aborts (photocraft#15597). The id - /// that has a node stays. - #[test] - fn controls_keep_the_ids_the_update_carries_and_drop_the_rest() { - let mut tree = update(vec![NodeId(2), NodeId(9)], vec![NodeId(2)]); - prune_controls(&mut tree); - let kept: Vec = tree.nodes.iter().find(|(id, _)| *id == NodeId(1)).map(|(_, node)| node.controls().to_vec()).unwrap_or_default(); - assert_eq!(kept, vec![NodeId(2)], "the id without a node is gone, the one with a node stays"); - } - - #[test] - fn controls_with_every_node_carried_are_left_alone() { - let mut tree = update(vec![NodeId(2)], vec![NodeId(2)]); - prune_controls(&mut tree); - let kept: Vec = tree.nodes.iter().find(|(id, _)| *id == NodeId(1)).map(|(_, node)| node.controls().to_vec()).unwrap_or_default(); - assert_eq!(kept, vec![NodeId(2)]); - } -} diff --git a/crates/ui-contract/src/testing/access.rs b/crates/ui-contract/src/testing/access.rs index e3f440cc8..b1a80a5d5 100644 --- a/crates/ui-contract/src/testing/access.rs +++ b/crates/ui-contract/src/testing/access.rs @@ -10,6 +10,12 @@ pub fn tree_of(output: &mut crate::runtime::egui::fixture::FullOutput) -> Access crate::runtime::egui::access::tree_of(output).unwrap_or_else(AccessTree::none) } +/// Drops every `controls` id of `update` that names no node of `update`, as the runtime does to each +/// frame's AccessKit output. +pub fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { + crate::runtime::egui::access::prune_controls(update); +} + /// Opens the label scope of `container` with `label`, as a field container's body step does; the container's /// report step closes it. pub fn begin_label_scope(ctx: &Context, container: Id, label: FieldLabel) { diff --git a/crates/ui-contract/tests/it/access/controls.rs b/crates/ui-contract/tests/it/access/controls.rs new file mode 100644 index 000000000..81e3435f0 --- /dev/null +++ b/crates/ui-contract/tests/it/access/controls.rs @@ -0,0 +1,37 @@ +//! Relations that name a node the update does not carry. + +use craft_ui::testing::access::prune_controls; +use craft_ui::testing::trial; +use egui::accesskit::{Node, NodeId, Role, TreeId, TreeUpdate}; + +fn update(controls: Vec, carried: Vec) -> TreeUpdate { + let mut node = Node::new(Role::Button); + node.set_controls(controls); + TreeUpdate { + nodes: carried.into_iter().map(|id| (id, Node::new(Role::Button))).chain(std::iter::once((NodeId(1), node))).collect(), + tree: None, + tree_id: TreeId::ROOT, + focus: NodeId(1), + } +} + +fn controls_of_first(tree: &TreeUpdate) -> Vec { + tree.nodes.iter().find(|(id, _)| *id == NodeId(1)).map(|(_, node)| node.controls().to_vec()).unwrap_or_default() +} + +/// A popup that reports itself open on a frame where its node is not emitted leaves its id in +/// `controls`; the host's UIA adapter unwraps that lookup and aborts (photocraft#15597). The id +/// that has a node stays. +#[trial] +fn controls_keep_the_ids_the_update_carries_and_drop_the_rest() { + let mut tree = update(vec![NodeId(2), NodeId(9)], vec![NodeId(2)]); + prune_controls(&mut tree); + assert_eq!(controls_of_first(&tree), vec![NodeId(2)], "the id without a node is gone, the one with a node stays"); +} + +#[trial] +fn controls_with_every_node_carried_are_left_alone() { + let mut tree = update(vec![NodeId(2)], vec![NodeId(2)]); + prune_controls(&mut tree); + assert_eq!(controls_of_first(&tree), vec![NodeId(2)]); +} diff --git a/crates/ui-contract/tests/it/access/mod.rs b/crates/ui-contract/tests/it/access/mod.rs index 67a826aac..3e9415678 100644 --- a/crates/ui-contract/tests/it/access/mod.rs +++ b/crates/ui-contract/tests/it/access/mod.rs @@ -1,6 +1,7 @@ //! The accessibility emitter: the label scope and merge rule, announcements, modal inertness, viewports. mod bounds; +mod controls; mod face_record; mod face_state; mod nodes; From 8a7e1e6bea7ec2fbb37c42879063bf69c6e8e358 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:39:51 +0000 Subject: [PATCH 05/29] Add count-trial counters for settling, text layout and measure asks, and an idle-frame trial --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 19 ++- crates/ui-contract/src/runtime/measure.rs | 116 ++++++++++++++++++ crates/ui-contract/src/testing/mod.rs | 5 +- crates/ui-widgets/tests/it/body/settle.rs | 72 +++++++---- 7 files changed, 190 insertions(+), 25 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6293bebde..856259c7a 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 0170bb71d..e75201bd6 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size))); diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 113581b1b..1d64bf0df 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 8cefd9fb5..7850311c1 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -240,7 +240,7 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { /// pass gets the same answer, so a measuring run and the real run lay out the same children. pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision { let targets = crate::runtime::focus::targets(ctx); - with(ctx, |store, pass_nr, frame| { + let decision = with(ctx, |store, pass_nr, frame| { let entry = store.touch(Some(view.owner), id, frame); let kind = usize::from(!sizing); // A child the other kind of run showed last takes that run's extent. @@ -255,7 +255,11 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - } }; if skip { Decision::Skip(size) } else { Decision::Run } - }) + }); + if matches!(decision, Decision::Skip(_)) { + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); + } + decision } /// Records what a run that showed the child `id` found: its extent in a run of this kind and, from a real run, what @@ -298,6 +302,17 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { + use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; + // The 8 bytes of a keyed call's content version are the key fed in. + if content.is_some() { + count_memo_key_bytes(ctx, 8); + } + let size = decide_settled(ctx, owner, id, sizing, place, content); + count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); + size +} + +fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index c281c04a5..5bed8a5e6 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -305,3 +305,119 @@ pub(crate) fn count_least(ctx: &Context, id: Id) { pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| log.runs.clone()) } + +/// What a settling child's decision was. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Settle { + /// The child ran. + Ran, + /// The child's last run was replayed in place of running. + Replayed, + /// The child is out of view and took its last extent without running. + OutOfView, +} + +/// The settled-test decisions of one pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct SettleLog { + pass: u64, + decisions: Vec<(Id, Settle)>, +} + +/// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and +/// `lazy::decide` (out of view); a rename of that decision point moves both calls. +pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { + #[cfg(feature = "testing")] + { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); + } + #[cfg(not(feature = "testing"))] + let _ = (ctx, id, what); +} + +/// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. +#[cfg(feature = "testing")] +pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) +} + +/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct PassTotals { + pass: u64, + key_bytes: usize, + text_layouts: u32, + asks: Vec<(&'static str, u32)>, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = PassTotals { pass, ..PassTotals::default() }; + } + f(log) + }) +} + +#[cfg(feature = "testing")] +fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) +} + +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.key_bytes += bytes); + #[cfg(not(feature = "testing"))] + let _ = (ctx, bytes); +} + +/// The bytes fed into memo keys in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { + last_totals(ctx, |log| log.key_bytes, 0) +} + +/// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +pub(crate) fn count_text_layout(ctx: &Context) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.text_layouts += 1); + #[cfg(not(feature = "testing"))] + let _ = ctx; +} + +/// The text layouts handed to egui in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_text_layouts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.text_layouts, 0) +} + +/// Counts a measure call of a leaf component of the type `name` in this pass. +pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { + #[cfg(feature = "testing")] + totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { + Some((_, count)) => *count += 1, + None => log.asks.push((name, 1)), + }); + #[cfg(not(feature = "testing"))] + let _ = (ctx, name); +} + +/// The leaf types that were asked to measure in the last pass, and how many times each. +#[cfg(feature = "testing")] +pub fn last_pass_measure_asks(ctx: &Context) -> Vec<(&'static str, u32)> { + last_totals(ctx, |log| log.asks.clone(), Vec::new()) +} diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 90ed467df..9dcb90e6a 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -41,8 +41,9 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ - active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, - last_pass_runs, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + Settle, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, + last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_runs, last_pass_settles, + last_pass_text_layouts, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index f7dae2c36..317b8d902 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -13,7 +13,7 @@ use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Comm use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; -use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial}; +use craft_ui::testing::{Fixture, Frames, Settle, last_pass_measuring_runs, last_pass_runs, last_pass_settles, last_pass_text_layouts, trial}; use egui::{Id, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -36,6 +36,8 @@ struct Scene { versions: [Cell>; 2], repaints: Cell, app_repaints: Cell, + /// Whether the scene shows only what is outside the settling children. + bare: Cell, runs: [Cell; 2], buttons: [Cell<(Id, Rect)>; 2], seen: Seen, @@ -51,6 +53,7 @@ impl Scene { versions: Default::default(), repaints: Cell::new(false), app_repaints: Cell::new(false), + bare: Cell::new(false), runs: Default::default(), buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))], seen: Seen::default(), @@ -73,28 +76,30 @@ impl Scene { if self.editor_first { self.editor(ui); } - in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { - self.child("reader", 0).show(ui, |ui| { - self.runs[0].set(self.runs[0].get() + 1); - let response = Button::new("Alpha").show(ui).response; - self.buttons[0].set((response.id, response.rect)); - Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); - }); - self.child("other", 1).show(ui, |ui| { - self.runs[1].set(self.runs[1].get() + 1); - if self.repaints.get() { - frame::request_repaint(ui.ctx()); - } - // In a body, whose measure a run that is not settled takes from what its last run kept. - Stack::new().show(ui, |ui, _| { - let response = Button::new("Beta").show(ui).response; - self.buttons[1].set((response.id, response.rect)); + if !self.bare.get() { + in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { + self.child("reader", 0).show(ui, |ui| { + self.runs[0].set(self.runs[0].get() + 1); + let response = Button::new("Alpha").show(ui).response; + self.buttons[0].set((response.id, response.rect)); + Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); + }); + self.child("other", 1).show(ui, |ui| { + self.runs[1].set(self.runs[1].get() + 1); + if self.repaints.get() { + frame::request_repaint(ui.ctx()); + } + // In a body, whose measure a run that is not settled takes from what its last run kept. + Stack::new().show(ui, |ui, _| { + let response = Button::new("Beta").show(ui).response; + self.buttons[1].set((response.id, response.rect)); + }); + if self.spinner { + Spinner::new().show(ui); + } }); - if self.spinner { - Spinner::new().show(ui); - } }); - }); + } if !self.editor_first { self.editor(ui); } @@ -146,6 +151,31 @@ fn a_settled_child_does_not_run_and_still_paints() { } } +/// After two warm-up frames, an idle frame with no input runs nothing that settles: every keyed child replays, the +/// components that run are those outside every settling child, the frame takes one pass and lays out no text. +#[trial] +fn an_idle_frame_runs_nothing_that_settles() { + let scene = Scene::new(false, false); + scene.versions.iter().for_each(|version| version.set(Some(1))); + let mut frames = Frames::new(); + scene.settle(&mut frames); + let reference = Scene::new(false, false); + reference.bare.set(true); + let mut bare = Frames::new(); + reference.settle(&mut bare); + let outside = { + reference.frame(&mut bare, vec![]); + last_pass_runs(&bare.ctx).iter().map(|(_, runs)| runs).sum::() + }; + let passes = frames.frame(vec![], |ui| scene.show(ui)); + let ran = last_pass_settles(&frames.ctx).into_iter().filter(|(_, what)| *what == Settle::Ran).count(); + let runs = last_pass_runs(&frames.ctx); + assert_eq!(ran, 0, "an idle frame ran keyed children: {:?}", last_pass_settles(&frames.ctx)); + assert_eq!(runs.iter().map(|(_, runs)| runs).sum::(), outside, "components ran inside settling children: {runs:?}"); + assert_eq!(passes, 1, "an idle frame takes one pass"); + assert_eq!(last_pass_text_layouts(&frames.ctx), 0, "an idle frame laid out text"); +} + /// The pointer over a settled child runs it, and only it, in the frame it arrives, from the measures its last run /// kept; leaving, the child runs until its hover has faded out, then settles again. #[trial] From fc8d1205abf18cf40719313af633c40bd7bfee00 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:40:20 +0000 Subject: [PATCH 06/29] Use const for immutable UI tables (#2336) --- crates/browse/src/ui/relink/badge.rs | 8 ++++---- crates/color-ui/src/ui/info.rs | 2 +- crates/color-ui/src/ui/picker/stories.rs | 2 +- crates/draw/src/ui/transform/transform_fields.rs | 4 ++-- crates/font-manager/src/panel/app.rs | 2 +- crates/font-manager/src/panel/browse.rs | 2 +- crates/font-manager/src/panel/details.rs | 2 +- crates/imaging/src/ui/scopes/panel.rs | 2 +- crates/menu/src/shortcuts/view.rs | 2 +- crates/table/src/ui/error_tag/stories.rs | 2 +- crates/text/src/ui/character.rs | 2 +- crates/ui-canvas/src/canvas/full_window_parts/stories.rs | 4 ++-- crates/ui-contract/src/contract/entry.rs | 2 +- crates/ui-contract/src/testing/icon_trials.rs | 4 ++-- crates/ui-gallery/src/chrome/card.rs | 2 +- .../ui-patterns/src/patterns/form_dialogs/new_document.rs | 2 +- crates/ui-widgets/src/controls/disclosure.rs | 6 +++--- crates/ui-widgets/src/display/spinner/stories.rs | 2 +- crates/ui-widgets/src/graph/stories.rs | 2 +- crates/ui-widgets/src/layout_components/stories.rs | 6 +++--- 20 files changed, 30 insertions(+), 30 deletions(-) diff --git a/crates/browse/src/ui/relink/badge.rs b/crates/browse/src/ui/relink/badge.rs index 8451a06ea..b1981a39d 100644 --- a/crates/browse/src/ui/relink/badge.rs +++ b/crates/browse/src/ui/relink/badge.rs @@ -34,10 +34,10 @@ enum StatusGlyph { Modified, } -static MISSING: StatusGlyph = StatusGlyph::Missing; -static UNREADABLE: StatusGlyph = StatusGlyph::Unreadable; -static REFUSED: StatusGlyph = StatusGlyph::Refused; -static MODIFIED: StatusGlyph = StatusGlyph::Modified; +const MISSING: StatusGlyph = StatusGlyph::Missing; +const UNREADABLE: StatusGlyph = StatusGlyph::Unreadable; +const REFUSED: StatusGlyph = StatusGlyph::Refused; +const MODIFIED: StatusGlyph = StatusGlyph::Modified; impl Glyph for StatusGlyph { fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, _: Color32, _: bool) { diff --git a/crates/color-ui/src/ui/info.rs b/crates/color-ui/src/ui/info.rs index 46238e585..1c7d6ef4e 100644 --- a/crates/color-ui/src/ui/info.rs +++ b/crates/color-ui/src/ui/info.rs @@ -21,7 +21,7 @@ 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. -static COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; craft_ui::words! { /// The words of the Info panel, in the installed language unless set. diff --git a/crates/color-ui/src/ui/picker/stories.rs b/crates/color-ui/src/ui/picker/stories.rs index ca0df2461..a3302806a 100644 --- a/crates/color-ui/src/ui/picker/stories.rs +++ b/crates/color-ui/src/ui/picker/stories.rs @@ -52,7 +52,7 @@ impl ColorModel for NaiveCmyk { } } -static CMYK_MODEL: NaiveCmyk = NaiveCmyk; +const CMYK_MODEL: NaiveCmyk = NaiveCmyk; /// The picker's output with the readout of its latest event, kept in the story's data across passes. fn with_readout(data: &mut StoryData, shown: ColorPickerOutput) -> StoryOutput { diff --git a/crates/draw/src/ui/transform/transform_fields.rs b/crates/draw/src/ui/transform/transform_fields.rs index 86c62b5ad..6514371c4 100644 --- a/crates/draw/src/ui/transform/transform_fields.rs +++ b/crates/draw/src/ui/transform/transform_fields.rs @@ -359,9 +359,9 @@ struct Cells<'a> { } /// The panel form's columns: a field, the link, a field; the fields share the width. -static FIELD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const FIELD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// The panel form's columns with the reference point before them. -static REFERENCE_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const REFERENCE_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// Which form the cells show in. #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/crates/font-manager/src/panel/app.rs b/crates/font-manager/src/panel/app.rs index dc92fc3af..e3feab10d 100644 --- a/crates/font-manager/src/panel/app.rs +++ b/crates/font-manager/src/panel/app.rs @@ -42,7 +42,7 @@ pub fn install_interface_fonts(ctx: &Context, language: &str, craft_faces: &[Emb } /// The filters column takes the width of its widest section; the list and toolbar take the rest. -static PANES: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const PANES: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// Preview downloads: at most this much per file, and this many faces in a session. const PREVIEW_LIMITS: Limits = Limits { max_file_bytes: 64 << 20, max_faces_per_file: 512, max_added_faces: 20_000 }; diff --git a/crates/font-manager/src/panel/browse.rs b/crates/font-manager/src/panel/browse.rs index d954b2c05..574b36113 100644 --- a/crates/font-manager/src/panel/browse.rs +++ b/crates/font-manager/src/panel/browse.rs @@ -159,7 +159,7 @@ impl Texts<'_> { const TABS_SHARE: f32 = 2.0; /// The search field's share of the top bar beside the tabs. const SEARCH_SHARE: f32 = 1.0; -static TOP_BAR: [ColumnWidth; 2] = [ColumnWidth::fill(TABS_SHARE), ColumnWidth::fill(SEARCH_SHARE)]; +const TOP_BAR: [ColumnWidth; 2] = [ColumnWidth::fill(TABS_SHARE), ColumnWidth::fill(SEARCH_SHARE)]; impl FontsPanel { pub(crate) fn top_bar(&mut self, ui: &mut Ui, browse: &FontsBrowseWords, format: &Format, search: Id) { diff --git a/crates/font-manager/src/panel/details.rs b/crates/font-manager/src/panel/details.rs index c47105448..f38fe36c1 100644 --- a/crates/font-manager/src/panel/details.rs +++ b/crates/font-manager/src/panel/details.rs @@ -37,7 +37,7 @@ const HERO_POINTS: f32 = 96.0; const LANGUAGES_SHOWN: usize = 60; /// The facts' labels over their values. -static FACT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; +const FACT_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; /// The installed catalog and the preview catalog, which the faces of the two owners load from. type Catalogs = (Arc, Arc); diff --git a/crates/imaging/src/ui/scopes/panel.rs b/crates/imaging/src/ui/scopes/panel.rs index 9ef85fd14..76686ea94 100644 --- a/crates/imaging/src/ui/scopes/panel.rs +++ b/crates/imaging/src/ui/scopes/panel.rs @@ -33,7 +33,7 @@ use craft_ui::style::TypeRole; use egui::{Rect, Response, Ui, pos2}; /// The columns of the statistics grid: label and value, twice. -static STATISTICS_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content; 4]; +const STATISTICS_COLUMNS: [ColumnWidth; 4] = [ColumnWidth::Content; 4]; /// Runs `content` in a block that resolves the dark mode when `dark`, else in the flow. fn themed(ui: &mut Ui, dark: bool, mut content: impl FnMut(&mut Ui) -> R) -> Option { diff --git a/crates/menu/src/shortcuts/view.rs b/crates/menu/src/shortcuts/view.rs index cbb4858d7..524d7566c 100644 --- a/crates/menu/src/shortcuts/view.rs +++ b/crates/menu/src/shortcuts/view.rs @@ -35,7 +35,7 @@ use crate::shortcuts::{keyboard, review, sets}; const TABLE_SHARE: f32 = 0.62; /// The detail pane's share of the width beside the table. const DETAIL_SHARE: f32 = 0.38; -static PANES: [ColumnWidth; 2] = [ColumnWidth::fill(TABLE_SHARE), ColumnWidth::fill(DETAIL_SHARE)]; +const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(TABLE_SHARE), ColumnWidth::fill(DETAIL_SHARE)]; /// One frame of the dialog body. pub(crate) fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, env: &mut Env<'_>, state: &mut DialogState) { diff --git a/crates/table/src/ui/error_tag/stories.rs b/crates/table/src/ui/error_tag/stories.rs index 39c295e28..1084b9e6b 100644 --- a/crates/table/src/ui/error_tag/stories.rs +++ b/crates/table/src/ui/error_tag/stories.rs @@ -6,7 +6,7 @@ use craft_ui::runtime::env::Label; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; -static FIXES: [Label; 3] = [Label::Static("Convert to Number"), Label::Static("Help on this Error"), Label::Static("Ignore Error")]; +const FIXES: [Label; 3] = [Label::Static("Convert to Number"), Label::Static("Help on this Error"), Label::Static("Ignore Error")]; #[story(ErrorTag<'static>, covers = [Default], drive = Drive::Activate)] fn error_tag(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/text/src/ui/character.rs b/crates/text/src/ui/character.rs index 4d45ed78f..34e186e24 100644 --- a/crates/text/src/ui/character.rs +++ b/crates/text/src/ui/character.rs @@ -135,7 +135,7 @@ const TRACKING_RANGE: RangeInclusive = -1000.0..=10000.0; /// The range of the scale fields, percent. const SCALE_RANGE: RangeInclusive = 0.0..=1000.0; /// Two columns of the same share, for the rows of two fields. -static TWO_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; +const TWO_COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)]; /// The variable-font axes of the current face: what the axis sliders under the style row show. #[cfg(feature = "font-picker")] diff --git a/crates/ui-canvas/src/canvas/full_window_parts/stories.rs b/crates/ui-canvas/src/canvas/full_window_parts/stories.rs index 101de494e..dc8fe5de4 100644 --- a/crates/ui-canvas/src/canvas/full_window_parts/stories.rs +++ b/crates/ui-canvas/src/canvas/full_window_parts/stories.rs @@ -104,8 +104,8 @@ fn status_failed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(FullWindowCanvas<'static>, covers = [], drive = Drive::Never)] fn canvas(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - static IMAGE_SOURCE: Flat = Flat { colour: Color32::from_rgb(0x4a, 0x7f, 0xc1), half: true }; - static MASK: Flat = Flat { colour: Color32::from_rgba_premultiplied(0x40, 0x00, 0x00, 0x40), half: false }; + const IMAGE_SOURCE: Flat = Flat { colour: Color32::from_rgb(0x4a, 0x7f, 0xc1), half: true }; + const MASK: Flat = Flat { colour: Color32::from_rgba_premultiplied(0x40, 0x00, 0x00, 0x40), half: false }; let checkerboard = *data.value("checkerboard", true); let overlay = *data.value("overlay", true); let tint = *data.value("tint", true); diff --git a/crates/ui-contract/src/contract/entry.rs b/crates/ui-contract/src/contract/entry.rs index 51bae9f28..dfffeaf84 100644 --- a/crates/ui-contract/src/contract/entry.rs +++ b/crates/ui-contract/src/contract/entry.rs @@ -6,7 +6,7 @@ use crate::runtime::env::Label; use craft_theme::Srgba; /// The label of a separator, which has none. -static NO_LABEL: Label = Label::Empty; +const NO_LABEL: Label = Label::Empty; /// A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator /// between groups of items. diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index db89c9f64..27c72f843 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -17,8 +17,8 @@ const DISC: &[u8] = b""; -static FIRST_SET: AppIcons = AppIcons { name: "t10-first", stroke_width: None, icons: &[(FIRST_NAME, DISC), (CATALOG_NAME, DISC)] }; -static SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, icons: &[(FIRST_NAME, SQUARE), (SECOND_NAME, SQUARE)] }; +const FIRST_SET: AppIcons = AppIcons { name: "t10-first", stroke_width: None, icons: &[(FIRST_NAME, DISC), (CATALOG_NAME, DISC)] }; +const SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, icons: &[(FIRST_NAME, SQUARE), (SECOND_NAME, SQUARE)] }; fn icon(name: &'static str) -> Option { let tokens = style::tokens(Mode::Light, Contrast::Standard); diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index 9f5d56520..75754c601 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -123,7 +123,7 @@ pub struct CardEvents { } /// The column lists of story grids, by count. -static COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4]; +const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4]; /// The columns of a form-rows card: the captions, the stories, then the values they show. The stories' column is as /// wide as its widest story, so each value sits a gap past its control, as the old gallery showed it. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs index 95b449b17..c9b8f6745 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs @@ -377,7 +377,7 @@ impl Outcome for NewDocumentOutput { } /// The columns of the body: the cards take the room the details column leaves. -static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::Content]; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::Content]; /// The body of the dialog: the columns, then what they asked for. fn body(ui: &mut Ui, form: &mut FormCx<'_, '_>, values: &mut DocumentOptions, shared: &Shared<'_>) -> bool { diff --git a/crates/ui-widgets/src/controls/disclosure.rs b/crates/ui-widgets/src/controls/disclosure.rs index 8f306a17f..7453bdd4c 100644 --- a/crates/ui-widgets/src/controls/disclosure.rs +++ b/crates/ui-widgets/src/controls/disclosure.rs @@ -53,11 +53,11 @@ pub struct DisclosureGlyph { } /// The arrow of a field or picker. -static DROPDOWN: DisclosureGlyph = DisclosureGlyph::dropdown_form(); +const DROPDOWN: DisclosureGlyph = DisclosureGlyph::dropdown_form(); /// The arrow of a button that opens a menu. -static MENU_BUTTON: DisclosureGlyph = DisclosureGlyph { open: 1.0, form: ArrowForm::Dropdown, stroke: StrokeWidth::Medium }; +const MENU_BUTTON: DisclosureGlyph = DisclosureGlyph { open: 1.0, form: ArrowForm::Dropdown, stroke: StrokeWidth::Medium }; /// The submenu arrow. -static SUBMENU: DisclosureGlyph = DisclosureGlyph { open: 0.0, form: ArrowForm::Submenu, stroke: StrokeWidth::Thin }; +const SUBMENU: DisclosureGlyph = DisclosureGlyph { open: 0.0, form: ArrowForm::Submenu, stroke: StrokeWidth::Thin }; impl DisclosureGlyph { /// The disclosure triangle `open` of the way turned. diff --git a/crates/ui-widgets/src/display/spinner/stories.rs b/crates/ui-widgets/src/display/spinner/stories.rs index 5d8569835..ad6a865f0 100644 --- a/crates/ui-widgets/src/display/spinner/stories.rs +++ b/crates/ui-widgets/src/display/spinner/stories.rs @@ -9,7 +9,7 @@ use craft_behavior::ColumnWidth; use egui::Ui; /// The name and the spinner of each size, in two columns that fit their content. -static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; #[story(Spinner, covers = [Default], drive = Drive::Never)] fn spinner(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-widgets/src/graph/stories.rs b/crates/ui-widgets/src/graph/stories.rs index c644dcabb..71240217d 100644 --- a/crates/ui-widgets/src/graph/stories.rs +++ b/crates/ui-widgets/src/graph/stories.rs @@ -26,7 +26,7 @@ enum CompEdit { /// Two inputs on the left and an output on the right. struct Mix; -static MIX: Mix = Mix; +const MIX: Mix = Mix; impl NodeKind for Mix { fn title(&self) -> &str { diff --git a/crates/ui-widgets/src/layout_components/stories.rs b/crates/ui-widgets/src/layout_components/stories.rs index 50bb18891..f2f3472d5 100644 --- a/crates/ui-widgets/src/layout_components/stories.rs +++ b/crates/ui-widgets/src/layout_components/stories.rs @@ -32,14 +32,14 @@ fn stack_footer(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { outlined(ui, |ui| Stack::new().gap(Gap::Stack).pad(Pad::Regular).footer(|ui, _| words(ui, 2..3)).show(ui, |ui, _| words(ui, 0..2)).into()) } -static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Fixed(60.0)]; +const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Fixed(60.0)]; #[story(Grid, covers = [Default])] fn grid(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { outlined(ui, |ui| Grid::new(&COLUMNS).pad(Pad::Regular).show(ui, |ui, _| words(ui, 0..4)).into()) } -static FIXED: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; +const FIXED: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; /// A grid whose arrangement is fixed: in a room narrower than its columns it keeps them beside each other and /// overflows, and its second row leaves the first cell empty, so the cells after it stay in their columns. @@ -58,7 +58,7 @@ fn grid_fixed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { }) } -static TOP: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; +const TOP: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; /// A grid whose cells stand at the top of their row: a short column of words beside a taller one starts level with it. #[story(Grid, covers = [])] From 21b790af4a60f81331054ef82effd64f2523c0ac Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:41:32 +0000 Subject: [PATCH 07/29] Gate the counters on the testing feature --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 23 ++++++------ crates/ui-contract/src/runtime/measure.rs | 35 +++++++------------ 5 files changed, 29 insertions(+), 32 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 856259c7a..6ccec0dbf 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + #[cfg(feature = "testing")] crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index e75201bd6..237e116be 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 1d64bf0df..d07364659 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 7850311c1..b6fd3756c 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -256,6 +256,7 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - }; if skip { Decision::Skip(size) } else { Decision::Run } }); + #[cfg(feature = "testing")] if matches!(decision, Decision::Skip(_)) { crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); } @@ -302,17 +303,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { - use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; - // The 8 bytes of a keyed call's content version are the key fed in. + // Keyed calls feed their 8-byte content version into the key. + #[cfg(feature = "testing")] if content.is_some() { - count_memo_key_bytes(ctx, 8); + crate::runtime::measure::count_memo_key_bytes(ctx, 8); } - let size = decide_settled(ctx, owner, id, sizing, place, content); - count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); - size -} - -fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); @@ -355,15 +350,23 @@ fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: settled.map(|settled| (entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(settled.rect.size()), settled)) }); // The pointer over it, or a press that started on it, is read outside the store. - let (size, settled) = settled?; + let Some((size, settled)) = settled else { + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); + return None; + }; if engaged(ctx, &settled) { with(ctx, |store, pass_nr, _| { if let Some(entry) = store.entries.get_mut(&id) { entry.replays = Some((pass_nr, false)); } }); + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); return None; } + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Replayed); Some(size) } diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 5bed8a5e6..85afc682f 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -328,19 +328,15 @@ struct SettleLog { /// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and /// `lazy::decide` (out of view); a rename of that decision point moves both calls. +#[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { - #[cfg(feature = "testing")] - { - let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { - if log.pass != pass { - *log = SettleLog { pass, decisions: Vec::new() }; - } - log.decisions.push((id, what)); - }); - } - #[cfg(not(feature = "testing"))] - let _ = (ctx, id, what); + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); } /// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. @@ -377,12 +373,11 @@ fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } -/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes +/// per call with a content version). +#[cfg(feature = "testing")] pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { - #[cfg(feature = "testing")] totals(ctx, |log| log.key_bytes += bytes); - #[cfg(not(feature = "testing"))] - let _ = (ctx, bytes); } /// The bytes fed into memo keys in the last pass. @@ -392,11 +387,9 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { } /// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_text_layout(ctx: &Context) { - #[cfg(feature = "testing")] totals(ctx, |log| log.text_layouts += 1); - #[cfg(not(feature = "testing"))] - let _ = ctx; } /// The text layouts handed to egui in the last pass. @@ -406,14 +399,12 @@ pub fn last_pass_text_layouts(ctx: &Context) -> u32 { } /// Counts a measure call of a leaf component of the type `name` in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { - #[cfg(feature = "testing")] totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { Some((_, count)) => *count += 1, None => log.asks.push((name, 1)), }); - #[cfg(not(feature = "testing"))] - let _ = (ctx, name); } /// The leaf types that were asked to measure in the last pass, and how many times each. From fc4fce56a040d46fd163f35457b5e25ccecc08ae Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:43:32 +0000 Subject: [PATCH 08/29] design-lint: contract/no-global-state (#2336) --- crates/design-lint/README.md | 1 + .../design-lint/src/contract/global_state.rs | 134 ++++++++++++++++++ crates/design-lint/src/contract/mod.rs | 7 +- crates/design-lint/src/workspace.rs | 65 +++++++++ crates/design-lint/tests/contract_rules.rs | 18 ++- .../contract-rules/accept/global-state.rs | 17 +++ .../reject/contract-global-state.rs | 20 +++ .../reject/contract-unsafe-allow.rs | 4 +- 8 files changed, 260 insertions(+), 6 deletions(-) create mode 100644 crates/design-lint/src/contract/global_state.rs create mode 100644 crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs create mode 100644 crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 8dc858f0f..eff1954ab 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,6 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` (only the derive implements it). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed list `NO_GLOBAL_STATE` in `workspace.rs`, each entry with the fact or later task that covers it. Clocks are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs new file mode 100644 index 000000000..b85e663f2 --- /dev/null +++ b/crates/design-lint/src/contract/global_state.rs @@ -0,0 +1,134 @@ +//! `contract/no-global-state`: no process-level state in UI crates. A memoized view's inputs are its props and the +//! environment keys the framework tracks; a `static`, a `thread_local!`, a filesystem read or a hand-written `MemoProps` +//! impl is an input the framework cannot see. +//! +//! Clocks are covered by `contract/motion:clock`, and `unsafe_code` by the workspace `forbid` plus `contract/unsafe-allow`. +//! Build scripts and binaries (`build.rs`, `src/bin/`) are not views and are skipped. + +use syn::visit::{self, Visit}; +use syn::{Attribute, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemUse, Path as SynPath, UseTree}; + +use crate::report::Finding; + +use super::Cx; + +pub const ID: &str = "contract/no-global-state"; + +const PATH_FS: [&str; 2] = ["std", "fs"]; + +struct Hits { + found: Vec<(proc_macro2::Span, String)>, +} + +fn is_cfg_test(attrs: &[Attribute]) -> bool { + attrs.iter().any(|a| { + a.path().is_ident("cfg") + && matches!(&a.meta, syn::Meta::List(list) if list.tokens.clone().into_iter().any(|t| matches!(t, proc_macro2::TokenTree::Ident(i) if i == "test"))) + }) +} + +fn names_fs(segments: &[String]) -> bool { + segments.windows(2).any(|w| w[0] == PATH_FS[0] && w[1] == PATH_FS[1]) +} + +fn use_paths(tree: &UseTree, prefix: &mut Vec, out: &mut Vec<(proc_macro2::Span, Vec)>) { + match tree { + UseTree::Path(p) => { + prefix.push(p.ident.to_string()); + use_paths(&p.tree, prefix, out); + prefix.pop(); + } + UseTree::Name(n) => { + let mut full = prefix.clone(); + full.push(n.ident.to_string()); + out.push((n.ident.span(), full)); + } + UseTree::Rename(n) => { + let mut full = prefix.clone(); + full.push(n.ident.to_string()); + out.push((n.ident.span(), full)); + } + UseTree::Glob(g) => out.push((g.star_token.span, prefix.clone())), + UseTree::Group(g) => g.items.iter().for_each(|t| use_paths(t, prefix, out)), + } +} + +impl Visit<'_> for Hits { + fn visit_item_mod(&mut self, node: &ItemMod) { + if !is_cfg_test(&node.attrs) { + visit::visit_item_mod(self, node); + } + } + + fn visit_item_static(&mut self, node: &ItemStatic) { + let what = if matches!(node.mutability, syn::StaticMutability::Mut(_)) { "static mut" } else { "static" }; + self.found.push(( + node.static_token.span, + format!("`{what} {}` is process-level state; use `const`, or pass it as a prop or environment key", node.ident), + )); + visit::visit_item_static(self, node); + } + + fn visit_item_macro(&mut self, node: &ItemMacro) { + self.macro_path(&node.mac.path); + visit::visit_item_macro(self, node); + } + + fn visit_stmt_macro(&mut self, node: &syn::StmtMacro) { + self.macro_path(&node.mac.path); + visit::visit_stmt_macro(self, node); + } + + fn visit_item_use(&mut self, node: &ItemUse) { + let mut paths = Vec::new(); + use_paths(&node.tree, &mut Vec::new(), &mut paths); + for (span, path) in paths { + if names_fs(&path) { + self.found.push((span, "`std::fs` reads the file system, which the framework does not track; read it outside the view".to_owned())); + } + } + visit::visit_item_use(self, node); + } + + fn visit_path(&mut self, node: &SynPath) { + let names: Vec = node.segments.iter().map(|s| s.ident.to_string()).collect(); + if names_fs(&names) { + self.found.push(( + node.segments[0].ident.span(), + "`std::fs` reads the file system, which the framework does not track; read it outside the view".to_owned(), + )); + } + visit::visit_path(self, node); + } + + fn visit_item_impl(&mut self, node: &ItemImpl) { + if let Some((_, path, _)) = &node.trait_ + && path.segments.last().is_some_and(|s| s.ident == "MemoProps") + { + self.found.push((node.impl_token.span, "`MemoProps` is implemented by the derive only".to_owned())); + } + visit::visit_item_impl(self, node); + } +} + +impl Hits { + fn macro_path(&mut self, path: &SynPath) { + if let Some(last) = path.segments.last() + && matches!(last.ident.to_string().as_str(), "thread_local" | "lazy_static") + { + self.found.push((last.ident.span(), format!("`{}!` declares process-level state; pass it as a prop or environment key", last.ident))); + } + } +} + +pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { + let normal = cx.path.to_string_lossy().replace('\\', "/"); + if normal.ends_with("/build.rs") || normal == "build.rs" || normal.contains("/src/bin/") { + return; + } + let mut hits = Hits { found: Vec::new() }; + hits.visit_file(cx.file); + for (span, message) in hits.found { + cx.flag_span(out, ID, ID, span, message); + } +} diff --git a/crates/design-lint/src/contract/mod.rs b/crates/design-lint/src/contract/mod.rs index 4ae66e4db..4aa6a400b 100644 --- a/crates/design-lint/src/contract/mod.rs +++ b/crates/design-lint/src/contract/mod.rs @@ -10,6 +10,7 @@ mod egui_import; mod egui_widget; mod entry; mod facts; +mod global_state; mod keys; mod layers; mod memory; @@ -39,7 +40,7 @@ use crate::report::Finding; use sites::Site; /// Every rule id of this module, for the marker and exemption validation in [`crate::RULES`]. -pub(crate) const IDS: [&str; 39] = [ +pub(crate) const IDS: [&str; 40] = [ egui_import::ID, runtime_egui::ID, text_edit::ID, @@ -79,12 +80,13 @@ pub(crate) const IDS: [&str; 39] = [ shape::OVERLAY_FLAG, shape::REGISTRATION, unsafe_allow::ID, + global_state::ID, ]; type Check = fn(&Cx<'_>, &mut Vec); /// REGISTRY: add a rule by adding its `check` here and its ids to [`IDS`]. -const REGISTRY: [Check; 21] = [ +const REGISTRY: [Check; 22] = [ egui_import::check, runtime_egui::check, text_edit::check, @@ -106,6 +108,7 @@ const REGISTRY: [Check; 21] = [ entry::check, shape::check, unsafe_allow::check, + global_state::check, ]; /// One file as the rules see it. diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index eded9fe6a..fb81d44a3 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -120,6 +120,68 @@ fn places(key: &str) -> Vec { } } +/// The reviewed allowlist of `contract/no-global-state`: path prefixes (relative to the repository root, as in +/// findings), each with the settled fact or environment key that covers it, or the later task of craft-libs#2336 that +/// removes the state. Stories and test helpers are allowed by [`no_global_state_everywhere`]. +const NO_GLOBAL_STATE: &[&str] = &[ + // Framework runtime: the state the memoized views read through environment keys. + "crates/ui-contract/src/runtime", + // Compile-time code, not a view: the proc macro reads the compiling crate's Cargo.toml. + "crates/ui-macros/src/component.rs", + // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. + "crates/ui-contract/src/fonts/defaults.rs", + // Environment fact (font environment): the font providers, the system UI face and its repaint waiters, and the + // locale lists derived from them. + "crates/ui-contract/src/fonts/system", + // Environment fact (font environment): the scan of the font folders and the font files read from them. + "crates/ui-contract/src/fonts/on_demand", + "crates/ui-contract/src/fonts/on_demand.rs", + // Environment fact: the icon-set registry, filled at app start before the first pass. + "crates/ui-contract/src/primitives/svg_set.rs", + // Settled fact: the thumbnail texture cache, keyed by its content. + "crates/ui-contract/src/primitives/textures/thumbnails.rs", + // Settled fact: the log-once set of unknown token names; it has no effect on output. + "crates/ui-contract/src/style/tokens.rs", + // Settled fact: the viewer's component catalog, computed once from compile-time input and immutable after init. + "crates/ui-gallery/src/viewer/catalog.rs", + // Settled fact: reads a file the user dropped, in the drop handler and not during the pass. + "crates/ui-gallery/src/chrome/shell.rs", + // Settled fact: the fallback text format, computed once from constants and immutable after init. + "crates/ui-canvas/src/canvas/tool.rs", + // Settled fact: the identity curve, computed once from constants and immutable after init. + "crates/imaging/src/ui/curve/preview.rs", + // Settled fact: the default layer-style draft and its preview paint, computed once from constants. + "crates/imaging/src/ui/layer_style/hosted.rs", + // Settled fact: a test fake of the font store; it writes a temporary folder. + "crates/font-manager/src/store/fake.rs", + // later task of #2336: the dock node id counter is hidden state. + "crates/behavior/src/dock/node.rs", + // later task of #2336: the brush trail id counter is hidden state. + "crates/ui-canvas/src/canvas_controls/brush/trail.rs", + // later task of #2336: the outline hover generation counter is hidden state. + "crates/ui-canvas/src/canvas_controls/outline/hover.rs", + // later task of #2336: the texture serial counter is hidden state. + "crates/imaging/src/ui/transform_preview/textures.rs", + // later task of #2336: the mock image read cache is hidden state. + "crates/imaging/src/ui/mock_image.rs", + // later task of #2336: the ranking cache is hidden state. + "crates/font-manager/src/picker/rank.rs", + // later task of #2336: the face loader reads file sizes during the pass. + "crates/font-manager/src/panel/faces.rs", + // later task of #2336: the gallery's set of seen names is hidden state. + "crates/ui-gallery/src/viewer/layout.rs", + // later task of #2336: the LUT picker reads the process clock and scans folders during the pass. + "crates/color-ui/src/ui/lut_picker.rs", +]; + +/// Stories hold constant demo data and pure caches of it (the owner's rule allows caches of pure test data), and +/// `ui-contract`'s `testing` modules are test helpers. +fn no_global_state_everywhere(file: &Path) -> bool { + file.starts_with("crates/ui-contract/src/testing") + || file.components().any(|c| c.as_os_str() == "stories") + || file.file_stem().is_some_and(|stem| stem == "stories") +} + struct CrateInfo { name: String, dir: PathBuf, @@ -287,6 +349,9 @@ fn has_prefix(path: &[String], prefix: &[&str]) -> bool { impl RuleScope for WorkspaceScope { fn allows(&self, key: &str, file: &Path) -> bool { let Some(krate) = self.crate_of(file) else { return false }; + if key == "contract/no-global-state" { + return no_global_state_everywhere(file) || NO_GLOBAL_STATE.iter().any(|prefix| file.starts_with(prefix)); + } if key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); } diff --git a/crates/design-lint/tests/contract_rules.rs b/crates/design-lint/tests/contract_rules.rs index 90ac096ac..19a4c6437 100644 --- a/crates/design-lint/tests/contract_rules.rs +++ b/crates/design-lint/tests/contract_rules.rs @@ -31,7 +31,7 @@ fn rules_at(src: &str, path: &str, scope: &StaticScope) -> Vec<&'static str> { } /// Reject fixtures: file and the rules it must trigger (all of them, nothing else). -const REJECT: [(&str, &[&str]); 19] = [ +const REJECT: [(&str, &[&str]); 20] = [ ("behavior-pipeline-only.rs", &["behavior/pipeline-only"]), ("props-reserved-setter.rs", &["props/reserved-setter"]), ("props-hand-setter.rs", &["props/hand-setter"]), @@ -51,6 +51,7 @@ const REJECT: [(&str, &[&str]); 19] = [ ("contract-overlay-flag.rs", &["contract/overlay-flag"]), ("contract-unsafe-allow.rs", &["contract/unsafe-allow"]), ("contract-registration.rs", &["contract/registration"]), + ("contract-global-state.rs", &["contract/no-global-state"]), ]; #[test] @@ -72,7 +73,7 @@ fn unsafe_allow_is_accepted_only_in_the_ffi_crates() { #[test] fn accept_fixtures_pass() { - for file in ["behavior-pipeline-only.rs", "props.rs", "style.rs", "entry.rs"] { + for file in ["behavior-pipeline-only.rs", "props.rs", "style.rs", "entry.rs", "global-state.rs"] { let findings = analyze_contract(&fixture("accept", file), Path::new(FAMILY), &scope(), false); assert!(findings.is_empty(), "{file}: {findings:?}"); } @@ -94,3 +95,16 @@ fn type_facts_cross_files_of_a_crate() { ] ); } + +#[test] +fn global_state_counts_every_form_and_honours_the_allowlist() { + let src = fixture("reject", "contract-global-state.rs"); + let found = analyze_contract(&src, Path::new(FAMILY), &scope(), false); + // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`. + assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 8, "{found:?}"); + let allowed = StaticScope::new().allow("contract/no-global-state", "crates/x/src/chips"); + assert!(rules_at(&src, FAMILY, &allowed).is_empty()); + for skipped in ["crates/x/build.rs", "crates/x/src/bin/tool.rs"] { + assert!(rules_at(&src, skipped, &scope()).is_empty(), "{skipped}"); + } +} diff --git a/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs new file mode 100644 index 000000000..11d96951c --- /dev/null +++ b/crates/design-lint/tests/fixtures/contract-rules/accept/global-state.rs @@ -0,0 +1,17 @@ +use std::path::Path; + +const COLUMNS: [u32; 2] = [1, 2]; + +#[derive(MemoProps)] +struct Props { + path: String, +} + +fn exists(path: &Path) -> bool { + COLUMNS.len() > 1 && path.is_absolute() +} + +#[cfg(test)] +mod tests { + static SEEN: std::sync::Mutex = std::sync::Mutex::new(0); +} diff --git a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs new file mode 100644 index 000000000..0e7401d29 --- /dev/null +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs @@ -0,0 +1,20 @@ +use std::cell::RefCell; +use std::fs; +use std::sync::{Mutex, OnceLock}; + +static COUNTER: Mutex = Mutex::new(0); +static mut RAW: u32 = 0; +static CACHE: OnceLock = OnceLock::new(); + +thread_local! { + static LOCAL: RefCell = const { RefCell::new(0) }; +} + +struct Props; + +impl MemoProps for Props {} + +fn read(path: &str) -> Vec { + static INNER: Mutex = Mutex::new(0); + std::fs::read(path).unwrap_or_default() +} diff --git a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs index 2b90f29a8..b811d6dc8 100644 --- a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-unsafe-allow.rs @@ -1,7 +1,7 @@ #![allow(unsafe_code)] #[allow(unsafe_code)] -static REGISTRATION: u8 = 0; +const REGISTRATION: u8 = 0; #[expect(unsafe_code, reason = "link section")] -static OTHER: u8 = 0; +const OTHER: u8 = 0; From b083a40316e9607d58f179b488ffd832f2de2a5b Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:47:09 +0000 Subject: [PATCH 09/29] craft-tracked: Tracked, PlainData and its derive, field! and Bind::tracked Tracked owns its value, a process-unique source id and a write count. Deref reads; DerefMut, edit and a Field's writes move the count, and a clone is a new source. T must be PlainData, a marker with no implementation for interior mutability, raw pointers, dyn objects or closures, so no write can bypass the count. #[derive(PlainData)] in ui-macros checks every field through a field-check helper the plain-data derives share; #[plain_data(assume = "reason")] skips one field of a foreign plain type. field!(a.b) builds a read and a write projection from a field path only. Bind::tracked(&mut t, field!(a.b)) reads through the read projection and moves the revision only when an edit changes the field. --- Cargo.lock | 9 + Cargo.toml | 1 + crates/craft/Cargo.toml | 5 + crates/craft/src/lib.rs | 2 + crates/tracked/Cargo.toml | 17 + crates/tracked/src/lib.rs | 443 ++++++++++++++++++ crates/ui-contract/Cargo.toml | 2 + crates/ui-contract/src/contract/mod.rs | 3 +- crates/ui-contract/src/contract/values.rs | 30 +- crates/ui-contract/tests/it/contract/mod.rs | 1 + .../tests/it/contract/tracked_bind.rs | 32 ++ crates/ui-macros/src/lib.rs | 13 +- crates/ui-macros/src/plain.rs | 154 ++++++ 13 files changed, 709 insertions(+), 3 deletions(-) create mode 100644 crates/tracked/Cargo.toml create mode 100644 crates/tracked/src/lib.rs create mode 100644 crates/ui-contract/tests/it/contract/tracked_bind.rs create mode 100644 crates/ui-macros/src/plain.rs diff --git a/Cargo.lock b/Cargo.lock index 263fc929a..f2351888f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,6 +1914,7 @@ dependencies = [ "craft-tiff", "craft-time", "craft-timeline", + "craft-tracked", "craft-ui", "craft-update", "craft-usd", @@ -4128,6 +4129,13 @@ dependencies = [ "web-time", ] +[[package]] +name = "craft-tracked" +version = "0.1.0" +dependencies = [ + "craft-ui-macros", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -4193,6 +4201,7 @@ dependencies = [ "craft-settings", "craft-svg", "craft-theme", + "craft-tracked", "craft-ui-contract", "craft-ui-macros", "craft-ui-test-kit", diff --git a/Cargo.toml b/Cargo.toml index 4e7ad18c7..4c4920066 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -219,6 +219,7 @@ craft-table = { path = "crates/table" } craft-theme = { path = "crates/theme" } craft-theme-editor = { path = "crates/theme-editor" } craft-theme-store = { path = "crates/theme-store" } +craft-tracked = { path = "crates/tracked" } craft-ui = { path = "crates/ui" } craft-ui-canvas = { path = "crates/ui-canvas" } craft-ui-contract = { path = "crates/ui-contract" } diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 708bbf2b6..b090960f8 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -143,6 +143,7 @@ craft-stream-codecs = { workspace = true, optional = true } craft-svg = { workspace = true, optional = true } craft-tga = { workspace = true, optional = true } craft-tiff = { workspace = true, optional = true } +craft-tracked = { workspace = true, optional = true } craft-time = { workspace = true, optional = true } craft-vcard = { workspace = true, optional = true } craft-vectordrawable = { workspace = true, optional = true } @@ -217,6 +218,8 @@ craft-xfa = { workspace = true, optional = true } [features] ui = [ "dep:craft-ui", + # The framework's memoized views key app models by their `Tracked` revision. + "tracked", "dep:egui", "craft-automation?/ui", "craft-browse?/ui", @@ -839,6 +842,8 @@ theme-store = ["dep:craft-theme-store"] tiff = ["dep:craft-tiff"] +tracked = ["dep:craft-tracked"] + time = ["dep:craft-time"] timeline = ["dep:craft-timeline", "keymap"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 2509c4069..4a1a568b7 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -356,6 +356,8 @@ pub use craft_tiff as tiff; pub use craft_time as time; #[cfg(feature = "timeline")] pub use craft_timeline as timeline; +#[cfg(feature = "tracked")] +pub use craft_tracked as tracked; #[cfg(feature = "ui")] pub use craft_ui as ui; #[cfg(feature = "update")] diff --git a/crates/tracked/Cargo.toml b/crates/tracked/Cargo.toml new file mode 100644 index 000000000..24265919f --- /dev/null +++ b/crates/tracked/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-tracked" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "Tracked: app data whose every write moves a revision, so a reader compares two integers instead of the data" + +[lints] +workspace = true + +# No dependencies, so engine crates can hold and move a revision without the UI. + +[dev-dependencies] +# `#[derive(PlainData)]` in the doc tests. +craft-ui-macros = { workspace = true } diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs new file mode 100644 index 000000000..e24e94165 --- /dev/null +++ b/crates/tracked/src/lib.rs @@ -0,0 +1,443 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! `Tracked`: app data whose every write moves a revision. +//! +//! A reader that only needs to know whether the data changed compares the [`Revision`] (two integers) instead of the +//! data. The revision is complete because the compiler sees every write: +//! +//! - Every way to change the data goes through `&mut Tracked`: [`DerefMut`], [`Tracked::edit`] and a +//! [`Field`]'s writes, and each moves the revision. +//! - `T` is [`PlainData`], so a shared reference can't change it: interior mutability, raw pointers, `dyn` objects +//! and closures have no implementation, and a `Tracked` holding one does not compile. +//! +//! ``` +//! use craft_tracked::Tracked; +//! let mut names = Tracked::new(vec!["a".to_owned()]); +//! let before = names.revision(); +//! assert_eq!(names.len(), 1); +//! assert_eq!(names.revision(), before, "reading leaves the revision"); +//! names.push("b".to_owned()); +//! assert_ne!(names.revision(), before, "a write moves it"); +//! ``` +//! +//! # App types +//! +//! App types derive the marker with `#[derive(PlainData)]` (craft-ui-macros, re-exported by craft-ui and the +//! `craft` facade), which requires it of every field and names the field whose type has none: +//! +//! ``` +//! use craft_tracked::Tracked; +//! use craft_ui_macros::PlainData; +//! +//! #[derive(PlainData)] +//! enum Node { +//! Leaf(String), +//! Group { name: String, children: Vec }, +//! } +//! +//! let tree = Tracked::new(Node::Group { name: "root".into(), children: vec![Node::Leaf("a".into())] }); +//! # let _ = tree; +//! ``` +//! +//! Two kinds of type have no derived implementation and take one of two escapes, each a stated promise that a shared +//! reference can't change what readers see: +//! +//! - **A foreign plain type** used as a field (an egui `Rect`, a `serde_json::Value`): the field carries +//! `#[plain_data(assume = "why the type is plain")]`, which skips the check for that field only. The reason is +//! required; an empty one does not compile. +//! - **A type that encapsulates interior mutability readers can't observe** (a tile whose bytes move between memory +//! and disk while its pixels stay the same): the crate that owns the type implements the marker by hand, +//! `impl PlainData for Tile {}`, with a comment saying why. UI crates have no such types and use the derive. +//! +//! ``` +//! use craft_tracked::Tracked; +//! use craft_ui_macros::PlainData; +//! +//! # mod egui { pub struct Rect; } +//! #[derive(PlainData)] +//! struct Panel { +//! title: String, +//! #[plain_data(assume = "egui geometry: plain numbers, no interior mutability")] +//! rect: egui::Rect, +//! } +//! # let _ = Tracked::new(Panel { title: String::new(), rect: egui::Rect }); +//! ``` +//! +//! # Threads +//! +//! The revision is a plain `u64`: every write needs `&mut Tracked`, so the thread that owns the value is the one +//! that moves it. An engine that runs jobs on worker threads and applies their results on the UI thread keeps its +//! model in a `Tracked` there: a worker computes on a snapshot and sends its result back, and applying the result +//! through `&mut` moves the revision on the owning side. +//! +//! # Rejected types +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::cell::Cell::new(1)); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::cell::RefCell::new(1)); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::sync::Mutex::new(1)); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::sync::RwLock::new(1)); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::sync::atomic::AtomicU32::new(1)); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::sync::OnceLock::::new()); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::ptr::null::()); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(Box::new(|| 1) as Box i32>); +//! ``` +//! +//! ```compile_fail,E0277 +//! let _ = craft_tracked::Tracked::new(std::sync::Arc::new(std::sync::Mutex::new(1))); +//! ``` +//! +//! A derived type with a rejected field: +//! +//! ```compile_fail,E0277 +//! #[derive(craft_ui_macros::PlainData)] +//! struct Counter { +//! hits: std::cell::Cell, +//! } +//! ``` +//! +//! A generic derived type used with a rejected parameter: +//! +//! ```compile_fail,E0277 +//! #[derive(craft_ui_macros::PlainData)] +//! struct Wrap(T); +//! let _ = craft_tracked::Tracked::new(Wrap(std::cell::Cell::new(1))); +//! ``` +//! +//! An `assume` without a reason: +//! +//! ```compile_fail +//! #[derive(craft_ui_macros::PlainData)] +//! struct Panel { +//! #[plain_data(assume = "")] +//! rect: std::cell::Cell, +//! } +//! ``` + +// The derive reaches this crate as `::craft_tracked`, here too. +extern crate self as craft_tracked; + +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Data that a shared reference can't change: no interior mutability, no raw pointers, no `dyn` objects, no +/// closures. Implemented for plain std types and their containers; app types derive it. +/// +/// A hand implementation is a promise the compiler can't check. It belongs only in this crate and in the crate that +/// owns a type whose interior mutability readers can't observe; see the crate docs. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not plain data", + label = "`{Self}` can change behind a shared reference, or has no `PlainData` implementation", + note = "`Cell`, `RefCell`, `Mutex`, `RwLock`, `OnceLock`, atomics, raw pointers, `dyn` objects and closures are rejected, because a write through them would not move the revision", + note = "app types use `#[derive(PlainData)]`; a field of a foreign plain type takes `#[plain_data(assume = \"why the type is plain\")]`" +)] +pub trait PlainData {} + +macro_rules! plain { + ($($t:ty),* $(,)?) => { $(impl PlainData for $t {})* }; +} + +plain!(bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, str, String, ()); +plain!(std::num::NonZeroU8, std::num::NonZeroU16, std::num::NonZeroU32, std::num::NonZeroU64, std::num::NonZeroUsize); +plain!(std::num::NonZeroI8, std::num::NonZeroI16, std::num::NonZeroI32, std::num::NonZeroI64, std::num::NonZeroIsize); +plain!(std::cmp::Ordering, std::time::Duration, std::time::Instant, std::time::SystemTime); +plain!(std::path::PathBuf, std::path::Path, std::ffi::OsString, std::ffi::OsStr); +plain!(std::collections::hash_map::RandomState); + +impl PlainData for &T {} +impl PlainData for Box {} +impl PlainData for std::sync::Arc {} +impl PlainData for std::rc::Rc {} +impl PlainData for std::borrow::Cow<'_, B> where B::Owned: PlainData {} +impl PlainData for Option {} +impl PlainData for Result {} +impl PlainData for Vec {} +impl PlainData for [T] {} +impl PlainData for [T; N] {} +impl PlainData for std::ops::Range {} +impl PlainData for std::ops::RangeInclusive {} +impl PlainData for std::collections::VecDeque {} +impl PlainData for std::collections::BinaryHeap {} +impl PlainData for std::collections::HashMap {} +impl PlainData for std::collections::HashSet {} +impl PlainData for std::collections::BTreeMap {} +impl PlainData for std::collections::BTreeSet {} +impl PlainData for std::hash::BuildHasherDefault {} +impl PlainData for std::marker::PhantomData {} +impl PlainData for Tracked {} + +macro_rules! tuples { + ($(($($n:ident),+)),* $(,)?) => { $(impl<$($n: PlainData),+> PlainData for ($($n,)+) {})* }; +} + +tuples!( + (A), + (A, B), + (A, B, C), + (A, B, C, D), + (A, B, C, D, E), + (A, B, C, D, E, F), + (A, B, C, D, E, F, G), + (A, B, C, D, E, F, G, H), + (A, B, C, D, E, F, G, H, I), + (A, B, C, D, E, F, G, H, I, J), + (A, B, C, D, E, F, G, H, I, J, K), + (A, B, C, D, E, F, G, H, I, J, K, L), +); + +/// The next source id. Ids start at 1 and are never reused in a process. +static NEXT_SOURCE: AtomicU64 = AtomicU64::new(1); + +fn next_source() -> u64 { + NEXT_SOURCE.fetch_add(1, Ordering::Relaxed) +} + +/// Which tracked value, and which state of it: equal revisions mean equal data. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Revision { + /// The value's source: unique in the process, and new for every clone. + pub source: u64, + /// How many writes the value has had. + pub count: u64, +} + +/// `T` with a revision that every write moves. +/// +/// `Deref` reads; `DerefMut`, [`edit`](Self::edit) and a [`Field`]'s writes move the revision whether or not the +/// write changes the data (a write with no change costs a reader one needless run, never a stale one). A clone is a +/// new source: two clones written apart never share a revision. +#[derive(Debug)] +pub struct Tracked { + value: T, + revision: Revision, +} + +impl Default for Tracked { + fn default() -> Tracked { + Tracked::new(T::default()) + } +} + +impl Tracked { + /// `value`, as a new source at count 0. + pub fn new(value: T) -> Tracked { + Tracked { value, revision: Revision { source: next_source(), count: 0 } } + } + + /// The current revision. + pub fn revision(&self) -> Revision { + self.revision + } + + /// The value's source id: unique in the process, new for every clone. + pub fn source(&self) -> u64 { + self.revision.source + } + + /// Changes the value through `f` and moves the revision. + pub fn edit(&mut self, f: impl FnOnce(&mut T) -> R) -> R { + f(&mut **self) + } + + /// One place inside the value, chosen with [`field!`]: reading it leaves the revision, writing it moves it. + pub fn field(&mut self, projection: Projection) -> Field<'_, T, U> { + Field { tracked: self, projection } + } + + /// The value, leaving the tracking. + pub fn into_inner(self) -> T { + self.value + } +} + +impl Clone for Tracked { + fn clone(&self) -> Tracked { + Tracked::new(self.value.clone()) + } +} + +impl Deref for Tracked { + type Target = T; + + fn deref(&self) -> &T { + &self.value + } +} + +impl DerefMut for Tracked { + fn deref_mut(&mut self) -> &mut T { + self.revision.count = self.revision.count.wrapping_add(1); + &mut self.value + } +} + +/// The way to one field of an `M`, as a read and a write projection. Only [`field!`] builds one, from a field path, +/// so neither projection can do anything but select the field: the read projection leaves the revision, and only a +/// write runs the write projection. +pub struct Projection { + read: fn(&M) -> &U, + write: fn(&mut M) -> &mut U, +} + +impl Clone for Projection { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Projection {} + +impl Projection { + /// Called by [`field!`] only: a hand-written projection could write the value while selecting a field, and that + /// write would not move the revision. + #[doc(hidden)] + pub const fn __from_field_path(read: fn(&M) -> &U, write: fn(&mut M) -> &mut U) -> Self { + Projection { read, write } + } +} + +/// A [`Projection`] to the field at `path` (`field!(name)`, `field!(style.size)`, `field!(0.title)`): field names +/// and tuple indices only. +/// +/// ``` +/// use craft_tracked::{Tracked, field}; +/// # #[derive(craft_ui_macros::PlainData)] struct Style { size: f32 } +/// # #[derive(craft_ui_macros::PlainData)] struct Doc { style: Style } +/// let mut doc = Tracked::new(Doc { style: Style { size: 12.0 } }); +/// let before = doc.revision(); +/// let mut size = doc.field(field!(style.size)); +/// assert_eq!(*size.get(), 12.0); +/// size.set(14.0); +/// assert_ne!(doc.revision(), before); +/// ``` +/// +/// A method call or an index is not a field path: +/// +/// ```compile_fail +/// use craft_tracked::{Tracked, field}; +/// let mut names = Tracked::new(vec![String::new()]); +/// let _ = names.field(field!(first())); +/// ``` +#[macro_export] +macro_rules! field { + ($first:tt $(. $rest:tt)*) => { + $crate::Projection::__from_field_path(|m| &m.$first $(.$rest)*, |m| &mut m.$first $(.$rest)*) + }; +} + +/// One field inside a [`Tracked`]: reading it leaves the revision, writing it moves it. +pub struct Field<'a, M: PlainData, U> { + tracked: &'a mut Tracked, + projection: Projection, +} + +impl Field<'_, M, U> { + /// The field's value. + pub fn get(&self) -> &U { + (self.projection.read)(&self.tracked.value) + } + + /// Replaces the field's value and moves the revision. + pub fn set(&mut self, value: U) { + self.edit(|field| *field = value); + } + + /// Changes the field through `f` and moves the revision. + pub fn edit(&mut self, f: impl FnOnce(&mut U) -> R) -> R { + f((self.projection.write)(&mut **self.tracked)) + } + + /// The same field, borrowed for a shorter time. + pub fn reborrow(&mut self) -> Field<'_, M, U> { + Field { tracked: &mut *self.tracked, projection: self.projection } + } +} + +/// A field of some tracked value, for code that knows only the field's type (a value binding). +pub trait Place { + /// The field's value. + fn get(&self) -> &U; + /// Replaces the field's value and moves the revision. + fn set(&mut self, value: U); +} + +impl Place for Field<'_, M, U> { + fn get(&self) -> &U { + Field::get(self) + } + + fn set(&mut self, value: U) { + Field::set(self, value); + } +} + +impl + ?Sized> Place for &mut P { + fn get(&self) -> &U { + (**self).get() + } + + fn set(&mut self, value: U) { + (**self).set(value); + } +} + +#[cfg(test)] +mod tests { + use super::Tracked; + + struct Doc { + name: String, + size: (u32, u32), + } + + impl super::PlainData for Doc {} + + #[test] + fn the_revision_moves_on_writes_only_and_a_clone_is_a_new_source() { + let mut doc = Tracked::new(Doc { name: "a".into(), size: (1, 2) }); + let start = doc.revision(); + assert_eq!(doc.name, "a"); + let size = doc.field(field!(size.1)); + assert_eq!(*size.get(), 2); + assert_eq!(doc.revision(), start, "reads leave the revision"); + + doc.name.push('b'); + let after_deref = doc.revision(); + assert_eq!(after_deref.count, start.count + 1, "a `&mut` access moves it"); + doc.edit(|doc| doc.size.0 = 3); + assert_eq!(doc.revision().count, start.count + 2, "an edit moves it"); + doc.field(field!(size.1)).set(4); + doc.field(field!(name)).edit(|name| name.clear()); + assert_eq!(doc.revision().count, start.count + 4, "a field's set and edit move it"); + assert_eq!((doc.size, doc.name.as_str()), ((3, 4), "")); + assert_eq!(doc.source(), start.source); + + let mut a = Tracked::new(1_u32); + let mut b = a.clone(); + assert_ne!(a.source(), b.source(), "a clone is a new source"); + *a += 1; + *b += 2; + assert_ne!(a.revision(), b.revision(), "two clones written apart never share a revision"); + } +} diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 112697346..07aa7ae2d 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -34,6 +34,8 @@ accesskit = "0.25" craft-keymap = { workspace = true, features = ["egui"] } craft-theme = { workspace = true } craft-ui-macros = { workspace = true } +# `Tracked`: app models whose revision keys memoized views and write-through bindings. +craft-tracked = { workspace = true } craft-settings = { workspace = true } toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } egui = { workspace = true } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 6c4877339..b9f384e92 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -66,7 +66,8 @@ pub use container::{ BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth, }; -pub use craft_ui_macros::{CommandSet, Component, Pattern, Props, register_contract}; +pub use craft_tracked::{Field, Place, PlainData, Projection, Revision, Tracked, field}; +pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract}; #[doc(hidden)] pub use cx::THUMB; pub use cx::{ diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index a19e87a01..d79ebd33c 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -5,6 +5,7 @@ use crate::runtime::env::Message; use crate::runtime::memory::{MemoryStage, Savable, SaveKey, StageAccess}; use crate::runtime::reads::{self, BindKey}; use craft_behavior::{Applied, CanvasView, EditEvent, EditEvents, EditPolicy, Mixed, Value}; +use craft_tracked::{Place, PlainData, Projection, Tracked}; use egui::Id; use egui::Response; use std::any::TypeId; @@ -106,6 +107,8 @@ enum Source<'a, T> { Mut(&'a mut T), /// Write-through for a multi-selection field. MutMixed(&'a mut Mixed), + /// Write-through to a field of a `Tracked`, whose revision moves only when an edit changes the field. + Tracked(Box + 'a>), /// No caller value: session memory under the component id, or the saved tier. Kept, } @@ -136,6 +139,13 @@ impl<'a, T: Value> Bind<'a, T> { Self::from_source(Source::MutMixed(v)) } + /// Edits write through to one field of `tracked`, chosen with `craft_tracked::field!` + /// (`Bind::tracked(&mut doc, field!(style.size))`). Making and reading the binding leaves the revision; only an + /// edit that changes the field moves it, so a binding made every pass does not invalidate the value's readers. + pub fn tracked(tracked: &'a mut Tracked, field: Projection) -> Self { + Self::from_source(Source::Tracked(Box::new(tracked.field(field)))) + } + /// No caller value: the component keeps it in session memory under its id. Until something is stored, it reads /// as the [`reset`](Self::reset) value when one is given, else as nothing. pub fn kept() -> Self { @@ -188,6 +198,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => Source::Given(value.clone()), Source::Mut(value) => Source::Mut(&mut **value), Source::MutMixed(value) => Source::MutMixed(&mut **value), + Source::Tracked(place) => Source::Tracked(Box::new(&mut **place)), Source::Kept => Source::Kept, }; let check = self.check.as_deref().map(|check| Box::new(move |value: &T| check(value)) as Box>); @@ -211,6 +222,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(Mixed::Same(value)) => value == shown, Source::Mut(value) => **value == *shown, Source::MutMixed(Mixed::Same(value)) => value == shown, + Source::Tracked(place) => place.get() == shown, _ => false, } } @@ -221,6 +233,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => SourceMut::Given(value), Source::Mut(value) => SourceMut::Mut(&mut **value), Source::MutMixed(value) => SourceMut::MutMixed(&mut **value), + Source::Tracked(place) => SourceMut::Tracked(&mut **place), Source::Kept => SourceMut::Kept, }; BindMut { source, policy: self.policy, check: self.check.as_deref(), save: self.save.as_ref(), reset: self.reset.as_ref() } @@ -237,6 +250,7 @@ enum SourceMut<'a, T> { Given(&'a Mixed), Mut(&'a mut T), MutMixed(&'a mut Mixed), + Tracked(&'a mut dyn Place), Kept, } @@ -258,6 +272,7 @@ impl BindMut<'_, T> { SourceMut::Given(value) => Some((*value).clone()), SourceMut::Mut(value) => Some(Mixed::Same((**value).clone())), SourceMut::MutMixed(value) => Some((**value).clone()), + SourceMut::Tracked(place) => Some(Mixed::Same(place.get().clone())), SourceMut::Kept => None, } } @@ -269,6 +284,7 @@ impl BindMut<'_, T> { SourceMut::Given(_) => None, SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::>(value) as usize, TypeId::of::>())), + SourceMut::Tracked(place) => Some(BindKey::Place(std::ptr::from_ref::(place.get()) as usize, TypeId::of::())), SourceMut::Kept => Some(match self.save { Some(save) => BindKey::Saved(Id::NULL.with(&save.key)), None => BindKey::Kept(id), @@ -290,6 +306,7 @@ impl BindMut<'_, T> { match &self.source { SourceMut::Given(Mixed::Same(value)) | SourceMut::MutMixed(Mixed::Same(value)) => value == shown, SourceMut::Mut(value) => **value == *shown, + SourceMut::Tracked(place) => place.get() == shown, _ => false, } } @@ -388,7 +405,9 @@ impl BindMut<'_, T> { pub(crate) fn writes(&self, event: &EditEvent) -> bool { match self.source { SourceMut::Given(_) | SourceMut::Kept => false, - SourceMut::Mut(_) | SourceMut::MutMixed(_) => self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. }), + SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked(_) => { + self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. }) + } } } @@ -401,6 +420,15 @@ impl BindMut<'_, T> { match &mut self.source { SourceMut::Mut(value) => event.apply(&mut **value), SourceMut::MutMixed(value) => event.apply_mixed(&mut **value), + // Applied to a copy, so an event that leaves the field as it was does not move the revision. + SourceMut::Tracked(place) => { + let mut value = place.get().clone(); + let applied = event.apply(&mut value); + if applied != Applied::Unchanged { + place.set(value); + } + applied + } SourceMut::Given(_) | SourceMut::Kept => Applied::Unchanged, } } diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index b37aa95dc..b85c87339 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -6,4 +6,5 @@ mod hit_order; mod pages; mod pointer; mod style; +mod tracked_bind; mod visited_type; diff --git a/crates/ui-contract/tests/it/contract/tracked_bind.rs b/crates/ui-contract/tests/it/contract/tracked_bind.rs new file mode 100644 index 000000000..1bab1ca19 --- /dev/null +++ b/crates/ui-contract/tests/it/contract/tracked_bind.rs @@ -0,0 +1,32 @@ +//! A write-through binding to a field of a `Tracked` value. + +use craft_behavior::{EditEvent, Mixed}; +use craft_ui::contract::{Bind, PlainData, Tracked, field}; +use craft_ui::testing::trial; + +#[derive(PlainData)] +struct Doc { + title: String, + size: f32, +} + +/// Making and reading the binding every pass leaves the revision, and so does an edit to the value the field already +/// holds; an edit that changes the field moves it once and lands in the field. +#[trial] +fn a_tracked_binding_moves_the_revision_only_when_it_writes() { + let mut doc = Tracked::new(Doc { title: "a".into(), size: 12.0 }); + let start = doc.revision(); + for _ in 0..3 { + let mut bind = Bind::tracked(&mut doc, field!(size)); + assert_eq!(bind.reborrow().get(), Some(Mixed::Same(12.0))); + } + assert_eq!(doc.revision(), start, "bindings made and read every pass leave the revision"); + + let set = |after: f32| EditEvent::set(Mixed::Same(12.0), after, "Size".into(), None); + Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(12.0)); + assert_eq!(doc.revision(), start, "an edit to the value the field holds leaves the revision"); + + Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(14.0)); + assert_eq!(doc.revision().count, start.count + 1, "a changing edit moves it once"); + assert_eq!((doc.size, doc.title.as_str()), (14.0, "a")); +} diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 06c321c09..05958548b 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -1,4 +1,4 @@ -//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue)]`, +//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue, PlainData)]`, //! `words!`, `#[story]`, `#[craft_ui::testing::trial]` and `register_contract!`. #![warn(missing_docs)] @@ -6,6 +6,7 @@ mod command_set; mod component; mod env; mod pattern; +mod plain; mod props; mod style; mod token_group; @@ -82,6 +83,16 @@ pub fn derive_props(input: TokenStream) -> TokenStream { expanded(props::derive(input.into())) } +/// Writes craft-tracked's `PlainData` marker and requires it of every field, so a field whose type can change behind +/// a shared reference (interior mutability, raw pointers, `dyn` objects, closures) does not compile; the error names +/// the field. Works on structs, tuple structs and enums. A field of a foreign plain type without an implementation +/// carries `#[plain_data(assume = "why the type is plain")]`, which skips the check for that field; the reason is +/// required. +#[proc_macro_derive(PlainData, attributes(plain_data))] +pub fn derive_plain_data(input: TokenStream) -> TokenStream { + expanded(plain::derive(input.into())) +} + /// Writes `ComponentStyle` from `#[style(surface)]`, `#[style(focus)]` and `#[style(metrics)]` fields (one each), /// any number of `#[style(text)]` (`TextLook`) and `#[style(icon)]` (`IconLook`) fields, and /// `#[style(variants = [..])]` on the type. diff --git a/crates/ui-macros/src/plain.rs b/crates/ui-macros/src/plain.rs new file mode 100644 index 000000000..9260890bf --- /dev/null +++ b/crates/ui-macros/src/plain.rs @@ -0,0 +1,154 @@ +//! The field check the plain-data derives share, and `#[derive(PlainData)]`. +//! +//! A derive that must hold only plain data (`PlainData`, `MemoProps`) requires its trait of every field. The trait has +//! no implementation for the types that can change behind a shared reference, so a field holding one is a compile +//! error at that field. The rejected types, the one list both traits keep out: +//! +//! - `Cell`, `RefCell`, `OnceCell`, `LazyCell`, `UnsafeCell` +//! - `Mutex`, `RwLock`, `OnceLock`, `LazyLock`, `Condvar` and every atomic +//! - raw pointers (`*const T`, `*mut T`) +//! - `dyn Trait` objects (`Box` and every other) and closures +//! - containers and smart pointers of any of these (`Arc>`, `Vec>`) +//! +//! A field of a foreign plain type that has no implementation (an egui `Rect`, a `serde_json::Value`) carries +//! `#[plain_data(assume = "why the type is plain")]`, which skips the check for that field only. The reason is +//! required. + +use crate::util::ui_crate; +use proc_macro_crate::{FoundCrate, crate_name}; +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::visit::Visit; +use syn::{Data, DeriveInput}; + +/// The impl generics, with a bound for every checked field whose type names a type parameter, and the item that +/// checks every other checked field. +pub(crate) struct FieldChecks { + pub(crate) generics: syn::Generics, + pub(crate) checks: TokenStream, +} + +/// Requires `trait_path` of every field of `input` (structs, tuple structs, enums; a union is an error). A field whose +/// type names a type parameter gets a bound on the impl; a field of a concrete type is checked by a generated +/// `check::()` spanned at the field's type, so the error points at the field, and a recursive type (a node +/// holding `Vec`) does not make its impl require itself. With `assume` set to an attribute name, a field +/// carrying `#[(assume = "reason")]` is not checked. +pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, assume: Option<&str>) -> syn::Result { + let fields: Vec<&syn::Field> = match &input.data { + Data::Struct(data) => data.fields.iter().collect(), + Data::Enum(data) => data.variants.iter().flat_map(|variant| variant.fields.iter()).collect(), + Data::Union(data) => return Err(syn::Error::new(data.union_token.span(), "a union cannot hold only plain data")), + }; + let mut generics = input.generics.clone(); + let params: Vec = input.generics.type_params().map(|param| param.ident.clone()).collect(); + let where_clause = generics.make_where_clause(); + let mut concrete = Vec::new(); + for field in fields { + if let Some(name) = assume + && assumed(field, name)? + { + continue; + } + let ty = &field.ty; + if mentions(ty, ¶ms) { + where_clause.predicates.push(syn::parse2(quote_spanned!(ty.span()=> #ty: #trait_path))?); + } else { + concrete.push(ty); + } + } + let (impl_generics, _, where_clause) = generics.split_for_impl(); + let each = concrete.iter().map(|ty| quote_spanned!(ty.span()=> check::<#ty>();)); + let checks = quote! { + const _: () = { + #[allow(dead_code, clippy::extra_unused_type_parameters)] + fn check() {} + #[allow(dead_code)] + fn fields #impl_generics () #where_clause { + #(#each)* + } + }; + }; + Ok(FieldChecks { generics, checks }) +} + +/// Whether `field` carries `#[(assume = "reason")]`. Any other content of the attribute, or an empty reason, is +/// an error. +fn assumed(field: &syn::Field, name: &str) -> syn::Result { + let mut found = false; + for attr in field.attrs.iter().filter(|attr| attr.path().is_ident(name)) { + attr.parse_nested_meta(|meta| { + if !meta.path.is_ident("assume") { + return Err(meta.error(format!("expected `#[{name}(assume = \"why the type is plain\")]`"))); + } + let reason: syn::LitStr = meta.value()?.parse()?; + if reason.value().trim().is_empty() { + return Err(syn::Error::new(reason.span(), "`assume` needs a reason: why this field's type is plain data")); + } + found = true; + Ok(()) + })?; + } + Ok(found) +} + +/// Whether `ty` names one of the type parameters `params`. +fn mentions(ty: &syn::Type, params: &[syn::Ident]) -> bool { + struct Finder<'p> { + params: &'p [syn::Ident], + found: bool, + } + impl<'ast> Visit<'ast> for Finder<'_> { + fn visit_path(&mut self, path: &'ast syn::Path) { + if path.leading_colon.is_none() && path.segments.first().is_some_and(|segment| self.params.contains(&segment.ident)) { + self.found = true; + } + syn::visit::visit_path(self, path); + } + } + let mut finder = Finder { params, found: false }; + finder.visit_type(ty); + finder.found +} + +/// The path of craft-tracked as the crate being compiled reaches it: the facade's `tracked` module, a direct +/// dependency (`::craft_tracked` in craft-tracked itself, which declares that name), or the framework's re-export in +/// `contract`. +fn tracked_crate() -> TokenStream { + match crate_name("craft") { + Ok(FoundCrate::Name(name)) => { + let name = format_ident!("{name}"); + return quote!(::#name::tracked); + } + Ok(FoundCrate::Itself) => return quote!(::craft::tracked), + Err(_) => {} + } + match crate_name("craft-tracked") { + Ok(FoundCrate::Name(name)) => { + let name = format_ident!("{name}"); + quote!(::#name) + } + Ok(FoundCrate::Itself) => quote!(::craft_tracked), + Err(_) => { + let k = ui_crate(); + quote!(#k::contract) + } + } +} + +/// `#[derive(PlainData)]`: the marker, required of every field not marked `#[plain_data(assume = "..")]`. +pub(crate) fn derive(input: TokenStream) -> syn::Result { + let input: DeriveInput = syn::parse2(input)?; + let k = tracked_crate(); + let trait_path = quote!(#k::PlainData); + let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some("plain_data"))?; + let ident = &input.ident; + let (impl_generics, _, where_clause) = generics.split_for_impl(); + let (_, type_generics, _) = input.generics.split_for_impl(); + Ok(quote! { + #[automatically_derived] + impl #impl_generics #trait_path for #ident #type_generics #where_clause {} + + #checks + }) +} From 7199467079637458f0b8ae7280b41486f3024f95 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:51:05 +0000 Subject: [PATCH 10/29] design-lint: no-global-state rejects PlainData impls and __from_field_path (#2336) --- crates/design-lint/README.md | 2 +- .../design-lint/src/contract/global_state.rs | 51 +++++++++++++++++-- crates/design-lint/tests/contract_rules.rs | 9 ++-- .../reject/contract-global-state.rs | 6 +++ 4 files changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index eff1954ab..5c69c2bff 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` (only the derive implements it). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed list `NO_GLOBAL_STATE` in `workspace.rs`, each entry with the fact or later task that covers it. Clocks are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__from_field_path` (only the `field!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed list `NO_GLOBAL_STATE` in `workspace.rs`, each entry with the fact or later task that covers it. Clocks are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs index b85e663f2..fccc503b8 100644 --- a/crates/design-lint/src/contract/global_state.rs +++ b/crates/design-lint/src/contract/global_state.rs @@ -16,8 +16,27 @@ pub const ID: &str = "contract/no-global-state"; const PATH_FS: [&str; 2] = ["std", "fs"]; +/// Permission keys of the two derive-only rules; no location is allowed. +const PLAIN_DATA: &str = "contract/no-global-state:plain-data"; +const PROJECTION: &str = "contract/no-global-state:projection"; + +/// The hidden constructor behind `field!`; the lint reads source before macro expansion, so every textual hit is a direct call. +const FROM_FIELD_PATH: &str = "__from_field_path"; + struct Hits { found: Vec<(proc_macro2::Span, String)>, + derive_only: Vec<(proc_macro2::Span, String)>, + projection: Vec<(proc_macro2::Span, String)>, +} + +fn field_path_in(tokens: proc_macro2::TokenStream, out: &mut Vec) { + for token in tokens { + match token { + proc_macro2::TokenTree::Ident(i) if i == FROM_FIELD_PATH => out.push(i.span()), + proc_macro2::TokenTree::Group(g) => field_path_in(g.stream(), out), + _ => {} + } + } } fn is_cfg_test(attrs: &[Attribute]) -> bool { @@ -90,6 +109,21 @@ impl Visit<'_> for Hits { visit::visit_item_use(self, node); } + fn visit_ident(&mut self, node: &proc_macro2::Ident) { + if node == FROM_FIELD_PATH { + self.projection.push((node.span(), format!("`{FROM_FIELD_PATH}` is called by `field!` only"))); + } + } + + fn visit_macro(&mut self, node: &syn::Macro) { + let mut spans = Vec::new(); + field_path_in(node.tokens.clone(), &mut spans); + for span in spans { + self.projection.push((span, format!("`{FROM_FIELD_PATH}` is called by `field!` only"))); + } + visit::visit_macro(self, node); + } + fn visit_path(&mut self, node: &SynPath) { let names: Vec = node.segments.iter().map(|s| s.ident.to_string()).collect(); if names_fs(&names) { @@ -103,9 +137,14 @@ impl Visit<'_> for Hits { fn visit_item_impl(&mut self, node: &ItemImpl) { if let Some((_, path, _)) = &node.trait_ - && path.segments.last().is_some_and(|s| s.ident == "MemoProps") + && let Some(name) = path.segments.last().map(|s| s.ident.to_string()).filter(|n| n == "MemoProps" || n == "PlainData") { - self.found.push((node.impl_token.span, "`MemoProps` is implemented by the derive only".to_owned())); + let message = format!("`{name}` is implemented by the derive only"); + if name == "MemoProps" { + self.found.push((node.impl_token.span, message)); + } else { + self.derive_only.push((node.impl_token.span, message)); + } } visit::visit_item_impl(self, node); } @@ -126,9 +165,15 @@ pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { if normal.ends_with("/build.rs") || normal == "build.rs" || normal.contains("/src/bin/") { return; } - let mut hits = Hits { found: Vec::new() }; + let mut hits = Hits { found: Vec::new(), derive_only: Vec::new(), projection: Vec::new() }; hits.visit_file(cx.file); for (span, message) in hits.found { cx.flag_span(out, ID, ID, span, message); } + for (span, message) in hits.derive_only { + cx.flag_span(out, ID, PLAIN_DATA, span, message); + } + for (span, message) in hits.projection { + cx.flag_span(out, ID, PROJECTION, span, message); + } } diff --git a/crates/design-lint/tests/contract_rules.rs b/crates/design-lint/tests/contract_rules.rs index 19a4c6437..3070bffae 100644 --- a/crates/design-lint/tests/contract_rules.rs +++ b/crates/design-lint/tests/contract_rules.rs @@ -100,10 +100,13 @@ fn type_facts_cross_files_of_a_crate() { fn global_state_counts_every_form_and_honours_the_allowlist() { let src = fixture("reject", "contract-global-state.rs"); let found = analyze_contract(&src, Path::new(FAMILY), &scope(), false); - // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`. - assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 8, "{found:?}"); + // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`, + // and the two derive-only forms: impl PlainData and a direct `__from_field_path`. + assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 10, "{found:?}"); let allowed = StaticScope::new().allow("contract/no-global-state", "crates/x/src/chips"); - assert!(rules_at(&src, FAMILY, &allowed).is_empty()); + // The derive-only forms have no allowed location, whatever the scope says. + let left = analyze_contract(&src, Path::new(FAMILY), &allowed, false); + assert_eq!(left.len(), 2, "{left:?}"); for skipped in ["crates/x/build.rs", "crates/x/src/bin/tool.rs"] { assert!(rules_at(&src, skipped, &scope()).is_empty(), "{skipped}"); } diff --git a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs index 0e7401d29..fafa76037 100644 --- a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs @@ -14,6 +14,12 @@ struct Props; impl MemoProps for Props {} +impl PlainData for Props {} + +fn project() -> Path { + Path::__from_field_path(&[]) +} + fn read(path: &str) -> Vec { static INNER: Mutex = Mutex::new(0); std::fs::read(path).unwrap_or_default() From 6d1d6bb6d14d60109451125dda64c8f3d61e693d Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:53:55 +0000 Subject: [PATCH 11/29] design-lint: per-item no-global-state allowlist; motion:clock flags clock fn values (#2336) --- crates/design-lint/README.md | 2 +- .../design-lint/src/contract/global_state.rs | 55 ++++++--- crates/design-lint/src/contract/mod.rs | 1 + crates/design-lint/src/contract/motion.rs | 10 +- crates/design-lint/src/workspace.rs | 110 ++++++++++++------ crates/design-lint/tests/contract_rules.rs | 12 +- crates/design-lint/tests/egui_rules.rs | 3 +- .../reject/contract-motion-clock-fn.rs | 3 + 8 files changed, 141 insertions(+), 55 deletions(-) create mode 100644 crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 5c69c2bff..c3a66b336 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__from_field_path` (only the `field!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed list `NO_GLOBAL_STATE` in `workspace.rs`, each entry with the fact or later task that covers it. Clocks are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__from_field_path` (only the `field!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs index fccc503b8..f1791c0da 100644 --- a/crates/design-lint/src/contract/global_state.rs +++ b/crates/design-lint/src/contract/global_state.rs @@ -14,6 +14,10 @@ use super::Cx; pub const ID: &str = "contract/no-global-state"; +/// What an allowlist entry names for file-system use. +pub(crate) const FS: &str = "std::fs"; +const FS_MESSAGE: &str = "`std::fs` reads the file system, which the framework does not track; read it outside the view"; + const PATH_FS: [&str; 2] = ["std", "fs"]; /// Permission keys of the two derive-only rules; no location is allowed. @@ -24,11 +28,27 @@ const PROJECTION: &str = "contract/no-global-state:projection"; const FROM_FIELD_PATH: &str = "__from_field_path"; struct Hits { - found: Vec<(proc_macro2::Span, String)>, + found: Vec<(proc_macro2::Span, String, String)>, derive_only: Vec<(proc_macro2::Span, String)>, projection: Vec<(proc_macro2::Span, String)>, } +/// The identifiers after `static` in a `thread_local!` or `lazy_static!` body. +fn static_names(tokens: proc_macro2::TokenStream, out: &mut Vec) { + let mut after_static = false; + for token in tokens { + match token { + proc_macro2::TokenTree::Ident(i) if after_static => { + out.push(i.to_string()); + after_static = false; + } + proc_macro2::TokenTree::Ident(i) => after_static = i == "static", + proc_macro2::TokenTree::Group(g) => static_names(g.stream(), out), + _ => after_static = false, + } + } +} + fn field_path_in(tokens: proc_macro2::TokenStream, out: &mut Vec) { for token in tokens { match token { @@ -84,17 +104,18 @@ impl Visit<'_> for Hits { self.found.push(( node.static_token.span, format!("`{what} {}` is process-level state; use `const`, or pass it as a prop or environment key", node.ident), + node.ident.to_string(), )); visit::visit_item_static(self, node); } fn visit_item_macro(&mut self, node: &ItemMacro) { - self.macro_path(&node.mac.path); + self.macro_path(&node.mac); visit::visit_item_macro(self, node); } fn visit_stmt_macro(&mut self, node: &syn::StmtMacro) { - self.macro_path(&node.mac.path); + self.macro_path(&node.mac); visit::visit_stmt_macro(self, node); } @@ -103,7 +124,7 @@ impl Visit<'_> for Hits { use_paths(&node.tree, &mut Vec::new(), &mut paths); for (span, path) in paths { if names_fs(&path) { - self.found.push((span, "`std::fs` reads the file system, which the framework does not track; read it outside the view".to_owned())); + self.found.push((span, FS_MESSAGE.to_owned(), FS.to_owned())); } } visit::visit_item_use(self, node); @@ -127,10 +148,7 @@ impl Visit<'_> for Hits { fn visit_path(&mut self, node: &SynPath) { let names: Vec = node.segments.iter().map(|s| s.ident.to_string()).collect(); if names_fs(&names) { - self.found.push(( - node.segments[0].ident.span(), - "`std::fs` reads the file system, which the framework does not track; read it outside the view".to_owned(), - )); + self.found.push((node.segments[0].ident.span(), FS_MESSAGE.to_owned(), FS.to_owned())); } visit::visit_path(self, node); } @@ -141,7 +159,7 @@ impl Visit<'_> for Hits { { let message = format!("`{name}` is implemented by the derive only"); if name == "MemoProps" { - self.found.push((node.impl_token.span, message)); + self.found.push((node.impl_token.span, message, name)); } else { self.derive_only.push((node.impl_token.span, message)); } @@ -151,11 +169,20 @@ impl Visit<'_> for Hits { } impl Hits { - fn macro_path(&mut self, path: &SynPath) { - if let Some(last) = path.segments.last() + fn macro_path(&mut self, mac: &syn::Macro) { + if let Some(last) = mac.path.segments.last() && matches!(last.ident.to_string().as_str(), "thread_local" | "lazy_static") { - self.found.push((last.ident.span(), format!("`{}!` declares process-level state; pass it as a prop or environment key", last.ident))); + let mut names = Vec::new(); + static_names(mac.tokens.clone(), &mut names); + let listed = names.join("`, `"); + for name in if names.is_empty() { vec![last.ident.to_string()] } else { names } { + self.found.push(( + last.ident.span(), + format!("`{}!` declares process-level state (`{listed}`); pass it as a prop or environment key", last.ident), + name, + )); + } } } } @@ -167,8 +194,8 @@ pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { } let mut hits = Hits { found: Vec::new(), derive_only: Vec::new(), projection: Vec::new() }; hits.visit_file(cx.file); - for (span, message) in hits.found { - cx.flag_span(out, ID, ID, span, message); + for (span, message, what) in hits.found { + cx.flag_span(out, ID, &format!("{ID}:{what}"), span, message); } for (span, message) in hits.derive_only { cx.flag_span(out, ID, PLAIN_DATA, span, message); diff --git a/crates/design-lint/src/contract/mod.rs b/crates/design-lint/src/contract/mod.rs index 4aa6a400b..28449dc33 100644 --- a/crates/design-lint/src/contract/mod.rs +++ b/crates/design-lint/src/contract/mod.rs @@ -11,6 +11,7 @@ mod egui_widget; mod entry; mod facts; mod global_state; +pub(crate) use global_state::FS; mod keys; mod layers; mod memory; diff --git a/crates/design-lint/src/contract/motion.rs b/crates/design-lint/src/contract/motion.rs index edc888c82..bbd1af79f 100644 --- a/crates/design-lint/src/contract/motion.rs +++ b/crates/design-lint/src/contract/motion.rs @@ -16,12 +16,18 @@ pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { name.starts_with("animate_") || matches!(name, "request_repaint_after" | "animation_time" | "prefers_reduced_motion" | "reduced_motion") }); for site in &cx.sites { - if let Kind::Path { path, call: true, .. } = &site.kind + if let Kind::Path { path, in_use: false, .. } = &site.kind && path.len() >= 2 && matches!(path[path.len() - 2].as_str(), "Instant" | "SystemTime") && path[path.len() - 1] == "now" { - cx.flag(out, ID, CLOCK, site, format!("`{}` reads a clock; read the runtime's motion clock", path.join("::"))); + cx.flag( + out, + ID, + CLOCK, + site, + format!("`{}` reads a clock, called or passed as a fn value; read the runtime's motion clock", path.join("::")), + ); } } } diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index fb81d44a3..17510ae8e 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; -use crate::contract::RuleScope; +use crate::contract::{FS, RuleScope}; use crate::graph::{Metadata, Package}; use crate::layers::{LayerMaps, relative}; use crate::resolve::Index; @@ -120,66 +120,95 @@ fn places(key: &str) -> Vec { } } -/// The reviewed allowlist of `contract/no-global-state`: path prefixes (relative to the repository root, as in -/// findings), each with the settled fact or environment key that covers it, or the later task of craft-libs#2336 that -/// removes the state. Stories and test helpers are allowed by [`no_global_state_everywhere`]. -const NO_GLOBAL_STATE: &[&str] = &[ +/// Locations of `contract/no-global-state` where everything is allowed, as path prefixes relative to the repository +/// root, as in findings. +const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ // Framework runtime: the state the memoized views read through environment keys. "crates/ui-contract/src/runtime", + // Test helpers. + "crates/ui-contract/src/testing", // Compile-time code, not a view: the proc macro reads the compiling crate's Cargo.toml. "crates/ui-macros/src/component.rs", +]; + +/// The reviewed per-item allowlist of `contract/no-global-state`: a file and what it may hold, either the identifier of +/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that +/// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. +const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. - "crates/ui-contract/src/fonts/defaults.rs", - // Environment fact (font environment): the font providers, the system UI face and its repaint waiters, and the - // locale lists derived from them. - "crates/ui-contract/src/fonts/system", + ("crates/ui-contract/src/fonts/defaults.rs", "HACK"), + ("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"), + ("crates/ui-contract/src/fonts/defaults.rs", "UBUNTU_LIGHT"), + ("crates/ui-contract/src/fonts/defaults.rs", "NOTO_EMOJI"), + ("crates/ui-contract/src/fonts/defaults.rs", "EMOJI_ICON_FONT"), + ("crates/ui-contract/src/fonts/defaults.rs", "INTER_REGULAR"), + ("crates/ui-contract/src/fonts/defaults.rs", "INTER_SEMIBOLD"), + // Environment fact (font environment): the system font index and the locale list derived from it, the font + // providers, the system UI face and its repaint waiters. + ("crates/ui-contract/src/fonts/system/fontique.rs", "INDEX"), + ("crates/ui-contract/src/fonts/system/fontique.rs", "HAN_LOCALES"), + ("crates/ui-contract/src/fonts/system/mod.rs", "PROVIDERS"), + ("crates/ui-contract/src/fonts/system/ui_face.rs", "FACE"), + ("crates/ui-contract/src/fonts/system/ui_face.rs", "WAITING"), // Environment fact (font environment): the scan of the font folders and the font files read from them. - "crates/ui-contract/src/fonts/on_demand", - "crates/ui-contract/src/fonts/on_demand.rs", + ("crates/ui-contract/src/fonts/on_demand/files.rs", "FILES"), + ("crates/ui-contract/src/fonts/on_demand/files.rs", "SCAN"), + ("crates/ui-contract/src/fonts/on_demand/files.rs", FS), + ("crates/ui-contract/src/fonts/on_demand.rs", FS), // Environment fact: the icon-set registry, filled at app start before the first pass. - "crates/ui-contract/src/primitives/svg_set.rs", + ("crates/ui-contract/src/primitives/svg_set.rs", "APPS"), // Settled fact: the thumbnail texture cache, keyed by its content. - "crates/ui-contract/src/primitives/textures/thumbnails.rs", + ("crates/ui-contract/src/primitives/textures/thumbnails.rs", "MADE"), // Settled fact: the log-once set of unknown token names; it has no effect on output. - "crates/ui-contract/src/style/tokens.rs", + ("crates/ui-contract/src/style/tokens.rs", "REPORTED"), // Settled fact: the viewer's component catalog, computed once from compile-time input and immutable after init. - "crates/ui-gallery/src/viewer/catalog.rs", + ("crates/ui-gallery/src/viewer/catalog.rs", "CATALOG"), // Settled fact: reads a file the user dropped, in the drop handler and not during the pass. - "crates/ui-gallery/src/chrome/shell.rs", + ("crates/ui-gallery/src/chrome/shell.rs", FS), // Settled fact: the fallback text format, computed once from constants and immutable after init. - "crates/ui-canvas/src/canvas/tool.rs", + ("crates/ui-canvas/src/canvas/tool.rs", "FALLBACK"), // Settled fact: the identity curve, computed once from constants and immutable after init. - "crates/imaging/src/ui/curve/preview.rs", + ("crates/imaging/src/ui/curve/preview.rs", "IDENTITY"), // Settled fact: the default layer-style draft and its preview paint, computed once from constants. - "crates/imaging/src/ui/layer_style/hosted.rs", + ("crates/imaging/src/ui/layer_style/hosted.rs", "DRAFT"), + ("crates/imaging/src/ui/layer_style/hosted.rs", "PAINT"), // Settled fact: a test fake of the font store; it writes a temporary folder. - "crates/font-manager/src/store/fake.rs", + ("crates/font-manager/src/store/fake.rs", FS), // later task of #2336: the dock node id counter is hidden state. - "crates/behavior/src/dock/node.rs", + ("crates/behavior/src/dock/node.rs", "NEXT"), // later task of #2336: the brush trail id counter is hidden state. - "crates/ui-canvas/src/canvas_controls/brush/trail.rs", + ("crates/ui-canvas/src/canvas_controls/brush/trail.rs", "NEXT_ID"), // later task of #2336: the outline hover generation counter is hidden state. - "crates/ui-canvas/src/canvas_controls/outline/hover.rs", + ("crates/ui-canvas/src/canvas_controls/outline/hover.rs", "GENERATIONS"), // later task of #2336: the texture serial counter is hidden state. - "crates/imaging/src/ui/transform_preview/textures.rs", + ("crates/imaging/src/ui/transform_preview/textures.rs", "SERIAL"), // later task of #2336: the mock image read cache is hidden state. - "crates/imaging/src/ui/mock_image.rs", + ("crates/imaging/src/ui/mock_image.rs", "READS"), // later task of #2336: the ranking cache is hidden state. - "crates/font-manager/src/picker/rank.rs", + ("crates/font-manager/src/picker/rank.rs", "CACHE"), // later task of #2336: the face loader reads file sizes during the pass. - "crates/font-manager/src/panel/faces.rs", + ("crates/font-manager/src/panel/faces.rs", FS), // later task of #2336: the gallery's set of seen names is hidden state. - "crates/ui-gallery/src/viewer/layout.rs", + ("crates/ui-gallery/src/viewer/layout.rs", "NAMES"), // later task of #2336: the LUT picker reads the process clock and scans folders during the pass. + ("crates/color-ui/src/ui/lut_picker.rs", "START"), + ("crates/color-ui/src/ui/lut_picker.rs", FS), +]; + +/// Files that may read a clock (`contract/motion:clock`) beyond the runtime's motion module. A file key, because +/// color-ui has no layer map. +const MOTION_CLOCK_FILES: &[&str] = &[ + // later task of #2336: the LUT picker reads the process clock during the pass. "crates/color-ui/src/ui/lut_picker.rs", ]; -/// Stories hold constant demo data and pure caches of it (the owner's rule allows caches of pure test data), and -/// `ui-contract`'s `testing` modules are test helpers. -fn no_global_state_everywhere(file: &Path) -> bool { - file.starts_with("crates/ui-contract/src/testing") +/// Whether `what` (an item identifier or [`FS`]) may be declared or used in `file` for `contract/no-global-state`. +/// Stories hold constant demo data and pure caches of it (the owner's rule allows caches of pure test data). +fn no_global_state_allows(what: &str, file: &Path) -> bool { + NO_GLOBAL_STATE_PREFIXES.iter().any(|prefix| file.starts_with(prefix)) || file.components().any(|c| c.as_os_str() == "stories") || file.file_stem().is_some_and(|stem| stem == "stories") + || NO_GLOBAL_STATE.iter().any(|(path, item)| *item == what && file == Path::new(path)) } struct CrateInfo { @@ -349,8 +378,11 @@ fn has_prefix(path: &[String], prefix: &[&str]) -> bool { impl RuleScope for WorkspaceScope { fn allows(&self, key: &str, file: &Path) -> bool { let Some(krate) = self.crate_of(file) else { return false }; - if key == "contract/no-global-state" { - return no_global_state_everywhere(file) || NO_GLOBAL_STATE.iter().any(|prefix| file.starts_with(prefix)); + if let Some(what) = key.strip_prefix("contract/no-global-state:") { + return no_global_state_allows(what, file); + } + if key == "contract/motion:clock" && MOTION_CLOCK_FILES.iter().any(|f| file == Path::new(f)) { + return true; } if key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); @@ -401,6 +433,16 @@ pub fn check_workspace(root: &Path, config: &Config, meta: &Metadata) -> Result< mod tests { use super::*; + #[test] + fn no_global_state_allowlist_is_per_item() { + let file = Path::new("crates/imaging/src/ui/curve/preview.rs"); + assert!(no_global_state_allows("IDENTITY", file)); + assert!(!no_global_state_allows("SECOND", file), "a new static in an allowlisted file is flagged"); + assert!(!no_global_state_allows(FS, file)); + assert!(no_global_state_allows("ANYTHING", Path::new("crates/ui-contract/src/runtime/focus.rs"))); + assert!(no_global_state_allows("ANYTHING", Path::new("crates/x/src/ui/stories.rs"))); + } + fn package(name: &str, features: &str, dependencies: &[&str]) -> String { format!(r#"{{"name":"{name}","features":{{{features}}},"dependencies":[{}],"targets":[]}}"#, dependencies.join(",")) } diff --git a/crates/design-lint/tests/contract_rules.rs b/crates/design-lint/tests/contract_rules.rs index 3070bffae..bd10dae4d 100644 --- a/crates/design-lint/tests/contract_rules.rs +++ b/crates/design-lint/tests/contract_rules.rs @@ -103,10 +103,16 @@ fn global_state_counts_every_form_and_honours_the_allowlist() { // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`, // and the two derive-only forms: impl PlainData and a direct `__from_field_path`. assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 10, "{found:?}"); - let allowed = StaticScope::new().allow("contract/no-global-state", "crates/x/src/chips"); - // The derive-only forms have no allowed location, whatever the scope says. + // An entry names one item; the rest of the file is still flagged. The three derive-only forms have no entry. + let mut allowed = StaticScope::new(); + for what in ["COUNTER", "RAW", "CACHE", "LOCAL", "INNER", "std::fs"] { + allowed = allowed.allow(&format!("contract/no-global-state:{what}"), "crates/x/src/chips"); + } let left = analyze_contract(&src, Path::new(FAMILY), &allowed, false); - assert_eq!(left.len(), 2, "{left:?}"); + assert_eq!(left.len(), 3, "{left:?}"); + let some = StaticScope::new().allow("contract/no-global-state:COUNTER", "crates/x/src/chips"); + let left = analyze_contract(&src, Path::new(FAMILY), &some, false); + assert_eq!(left.len(), 9, "a second static in an allowlisted file is flagged: {left:?}"); for skipped in ["crates/x/build.rs", "crates/x/src/bin/tool.rs"] { assert!(rules_at(&src, skipped, &scope()).is_empty(), "{skipped}"); } diff --git a/crates/design-lint/tests/egui_rules.rs b/crates/design-lint/tests/egui_rules.rs index 56b29f7e5..e6f39e183 100644 --- a/crates/design-lint/tests/egui_rules.rs +++ b/crates/design-lint/tests/egui_rules.rs @@ -35,7 +35,7 @@ fn rules_at(src: &str, path: &str, scope: &StaticScope) -> Vec<&'static str> { } /// Reject fixtures: file, the rule it must trigger, the path it is checked at. -const REJECT: [(&str, &str, &str); 21] = [ +const REJECT: [(&str, &str, &str); 22] = [ ("contract-egui-import.rs", "contract/egui-import", "src/ui/a.rs"), ("contract-allocate.rs", "contract/allocate", "src/ui/a.rs"), ("contract-egui-widget.rs", "contract/egui-widget", "src/ui/a.rs"), @@ -47,6 +47,7 @@ const REJECT: [(&str, &str, &str); 21] = [ ("contract-pointer.rs", "contract/pointer", "src/ui/a.rs"), ("contract-motion.rs", "contract/motion", "src/ui/a.rs"), ("contract-motion-clock.rs", "contract/motion", "src/ui/a.rs"), + ("contract-motion-clock-fn.rs", "contract/motion", "src/ui/a.rs"), ("contract-containers.rs", "contract/containers", "src/ui/a.rs"), ("contract-containers-scroll.rs", "contract/containers", "src/ui/a.rs"), ("contract-platform.rs", "contract/platform", "src/ui/a.rs"), diff --git a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs new file mode 100644 index 000000000..1b303589e --- /dev/null +++ b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-motion-clock-fn.rs @@ -0,0 +1,3 @@ +fn f(cell: &std::sync::OnceLock) -> std::time::Instant { + *cell.get_or_init(std::time::Instant::now) +} From c0df0345246ab485e7c8d23229f61a928269d5ed Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:57:03 +0000 Subject: [PATCH 12/29] ui-macros: plain-data check bounds type parameters and checks every field The impl bounds each type parameter by the derive's trait, and every field is checked under those bounds, so a generic recursive type derives without overflowing and a Cell field fails at the derive, naming the field. A field type written with Self is checked as the type itself. The escape is an Escape { attr, keyword } parsed by escaped(), and the check item is a separate output a derive may leave out. A direct craft-tracked dependency is preferred over the facade when finding the crate path. --- crates/tracked/src/lib.rs | 48 ++++++++++++- crates/ui-macros/src/plain.rs | 129 ++++++++++++++++++---------------- 2 files changed, 116 insertions(+), 61 deletions(-) diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs index e24e94165..b8aeba34f 100644 --- a/crates/tracked/src/lib.rs +++ b/crates/tracked/src/lib.rs @@ -39,6 +39,39 @@ //! # let _ = tree; //! ``` //! +//! Generic and self-referring types derive it too; each type parameter must then be plain data, and a type that +//! holds a parameter only in `PhantomData` (a typed id) needs nothing more: +//! +//! ``` +//! use craft_tracked::Tracked; +//! use craft_ui_macros::PlainData; +//! use std::marker::PhantomData; +//! +//! #[derive(PlainData)] +//! struct Tree { +//! value: T, +//! children: Vec>, +//! } +//! +//! #[derive(PlainData)] +//! struct List { +//! name: String, +//! next: Option>, +//! } +//! +//! #[derive(PlainData)] +//! struct Id { +//! raw: u64, +//! kind: PhantomData, +//! } +//! +//! let mut tree = Tracked::new(Tree { value: 1_u32, children: vec![Tree { value: 2, children: Vec::new() }] }); +//! tree.children[0].value = 3; +//! let list = Tracked::new(List { name: "a".into(), next: Some(Box::new(List { name: "b".into(), next: None })) }); +//! let id = Tracked::new(Id:: { raw: 7, kind: PhantomData }); +//! # let _ = (list, id); +//! ``` +//! //! Two kinds of type have no derived implementation and take one of two escapes, each a stated promise that a shared //! reference can't change what readers see: //! @@ -47,7 +80,9 @@ //! required; an empty one does not compile. //! - **A type that encapsulates interior mutability readers can't observe** (a tile whose bytes move between memory //! and disk while its pixels stay the same): the crate that owns the type implements the marker by hand, -//! `impl PlainData for Tile {}`, with a comment saying why. UI crates have no such types and use the derive. +//! `impl PlainData for Tile {}`, with a comment saying why. Hand implementations are allowed by design in the +//! non-UI crate that owns such a type; UI crates have no such types, use the derive, and design-lint rejects a hand +//! implementation there. //! //! ``` //! use craft_tracked::Tracked; @@ -117,6 +152,15 @@ //! } //! ``` //! +//! A generic derived type whose field is rejected for every parameter fails at the derive: +//! +//! ```compile_fail,E0277 +//! #[derive(craft_ui_macros::PlainData)] +//! struct Counter { +//! hits: std::cell::Cell, +//! } +//! ``` +//! //! A generic derived type used with a rejected parameter: //! //! ```compile_fail,E0277 @@ -125,7 +169,7 @@ //! let _ = craft_tracked::Tracked::new(Wrap(std::cell::Cell::new(1))); //! ``` //! -//! An `assume` without a reason: +//! An `assume` without a reason (the derive reports it with `compile_error!`, which has no error code): //! //! ```compile_fail //! #[derive(craft_ui_macros::PlainData)] diff --git a/crates/ui-macros/src/plain.rs b/crates/ui-macros/src/plain.rs index 9260890bf..e13425528 100644 --- a/crates/ui-macros/src/plain.rs +++ b/crates/ui-macros/src/plain.rs @@ -19,22 +19,33 @@ use proc_macro_crate::{FoundCrate, crate_name}; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; -use syn::visit::Visit; +use syn::visit_mut::VisitMut; use syn::{Data, DeriveInput}; -/// The impl generics, with a bound for every checked field whose type names a type parameter, and the item that -/// checks every other checked field. +/// What the plain-data check gives a derive. pub(crate) struct FieldChecks { + /// The impl generics: the type's own, with every type parameter bound by the derive's trait. pub(crate) generics: syn::Generics, + /// The item that checks each field not escaped, under those bounds. A derive whose impl body already uses every + /// field through its trait may leave it out. pub(crate) checks: TokenStream, } -/// Requires `trait_path` of every field of `input` (structs, tuple structs, enums; a union is an error). A field whose -/// type names a type parameter gets a bound on the impl; a field of a concrete type is checked by a generated -/// `check::()` spanned at the field's type, so the error points at the field, and a recursive type (a node -/// holding `Vec`) does not make its impl require itself. With `assume` set to an attribute name, a field -/// carrying `#[(assume = "reason")]` is not checked. -pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, assume: Option<&str>) -> syn::Result { +/// The escape a derive allows for one field: `#[( = "reason")]`. +pub(crate) struct Escape { + /// The attribute's name (`plain_data`). + pub(crate) attr: &'static str, + /// The one key it takes (`assume`). + pub(crate) keyword: &'static str, +} + +/// Requires `trait_path` of every field of `input` (structs, tuple structs, enums; a union is an error). The impl +/// bounds each type parameter by `trait_path`; every field is checked under those bounds by a generated +/// `check::()` spanned at the field's type, so a rejected field (`Cell` included) is an error at the derive +/// that names the field, and a recursive type (a node holding `Vec` or `Vec>`) does not make its impl +/// require itself. A field type written with `Self` is checked as the type itself. A field carrying `escape` is not +/// checked. +pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, escape: Option<&Escape>) -> syn::Result { let fields: Vec<&syn::Field> = match &input.data { Data::Struct(data) => data.fields.iter().collect(), Data::Enum(data) => data.variants.iter().flat_map(|variant| variant.fields.iter()).collect(), @@ -43,47 +54,66 @@ pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, assume let mut generics = input.generics.clone(); let params: Vec = input.generics.type_params().map(|param| param.ident.clone()).collect(); let where_clause = generics.make_where_clause(); - let mut concrete = Vec::new(); + for param in ¶ms { + where_clause.predicates.push(syn::parse2(quote!(#param: #trait_path))?); + } + let ident = &input.ident; + let (_, type_generics, _) = input.generics.split_for_impl(); + let this: syn::Type = syn::parse2(quote!(#ident #type_generics))?; + let mut checked = Vec::new(); for field in fields { - if let Some(name) = assume - && assumed(field, name)? + if let Some(escape) = escape + && escaped(field, escape)? { continue; } - let ty = &field.ty; - if mentions(ty, ¶ms) { - where_clause.predicates.push(syn::parse2(quote_spanned!(ty.span()=> #ty: #trait_path))?); - } else { - concrete.push(ty); - } + let mut ty = field.ty.clone(); + ReplaceSelf(&this).visit_type_mut(&mut ty); + checked.push(quote_spanned!(field.ty.span()=> check::<#ty>();)); } let (impl_generics, _, where_clause) = generics.split_for_impl(); - let each = concrete.iter().map(|ty| quote_spanned!(ty.span()=> check::<#ty>();)); let checks = quote! { const _: () = { #[allow(dead_code, clippy::extra_unused_type_parameters)] fn check() {} #[allow(dead_code)] fn fields #impl_generics () #where_clause { - #(#each)* + #(#checked)* } }; }; Ok(FieldChecks { generics, checks }) } -/// Whether `field` carries `#[(assume = "reason")]`. Any other content of the attribute, or an empty reason, is -/// an error. -fn assumed(field: &syn::Field, name: &str) -> syn::Result { +/// Replaces the type `Self` with the deriving type, which the generated free function can't name as `Self`. +struct ReplaceSelf<'t>(&'t syn::Type); + +impl VisitMut for ReplaceSelf<'_> { + fn visit_type_mut(&mut self, ty: &mut syn::Type) { + if let syn::Type::Path(path) = ty + && path.qself.is_none() + && path.path.is_ident("Self") + { + *ty = self.0.clone(); + return; + } + syn::visit_mut::visit_type_mut(self, ty); + } +} + +/// Whether `field` carries `#[( = "reason")]`. Any other content of the attribute, or an empty +/// reason, is an error. +pub(crate) fn escaped(field: &syn::Field, escape: &Escape) -> syn::Result { + let Escape { attr: name, keyword } = *escape; let mut found = false; for attr in field.attrs.iter().filter(|attr| attr.path().is_ident(name)) { attr.parse_nested_meta(|meta| { - if !meta.path.is_ident("assume") { - return Err(meta.error(format!("expected `#[{name}(assume = \"why the type is plain\")]`"))); + if !meta.path.is_ident(keyword) { + return Err(meta.error(format!("expected `#[{name}({keyword} = \"reason\")]`"))); } let reason: syn::LitStr = meta.value()?.parse()?; if reason.value().trim().is_empty() { - return Err(syn::Error::new(reason.span(), "`assume` needs a reason: why this field's type is plain data")); + return Err(syn::Error::new(reason.span(), format!("`{keyword}` needs a reason: why this field's type is plain data"))); } found = true; Ok(()) @@ -92,43 +122,24 @@ fn assumed(field: &syn::Field, name: &str) -> syn::Result { Ok(found) } -/// Whether `ty` names one of the type parameters `params`. -fn mentions(ty: &syn::Type, params: &[syn::Ident]) -> bool { - struct Finder<'p> { - params: &'p [syn::Ident], - found: bool, - } - impl<'ast> Visit<'ast> for Finder<'_> { - fn visit_path(&mut self, path: &'ast syn::Path) { - if path.leading_colon.is_none() && path.segments.first().is_some_and(|segment| self.params.contains(&segment.ident)) { - self.found = true; - } - syn::visit::visit_path(self, path); - } - } - let mut finder = Finder { params, found: false }; - finder.visit_type(ty); - finder.found -} - -/// The path of craft-tracked as the crate being compiled reaches it: the facade's `tracked` module, a direct -/// dependency (`::craft_tracked` in craft-tracked itself, which declares that name), or the framework's re-export in -/// `contract`. +/// The path of craft-tracked as the crate being compiled reaches it: a direct dependency (`::craft_tracked` in +/// craft-tracked itself, which declares that name), else the facade's `tracked` module, else the framework's +/// re-export in `contract`. fn tracked_crate() -> TokenStream { - match crate_name("craft") { - Ok(FoundCrate::Name(name)) => { - let name = format_ident!("{name}"); - return quote!(::#name::tracked); - } - Ok(FoundCrate::Itself) => return quote!(::craft::tracked), - Err(_) => {} - } match crate_name("craft-tracked") { Ok(FoundCrate::Name(name)) => { let name = format_ident!("{name}"); - quote!(::#name) + return quote!(::#name); } - Ok(FoundCrate::Itself) => quote!(::craft_tracked), + Ok(FoundCrate::Itself) => return quote!(::craft_tracked), + Err(_) => {} + } + match crate_name("craft") { + Ok(FoundCrate::Name(name)) => { + let name = format_ident!("{name}"); + quote!(::#name::tracked) + } + Ok(FoundCrate::Itself) => quote!(::craft::tracked), Err(_) => { let k = ui_crate(); quote!(#k::contract) @@ -141,7 +152,7 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { let input: DeriveInput = syn::parse2(input)?; let k = tracked_crate(); let trait_path = quote!(#k::PlainData); - let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some("plain_data"))?; + let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some(&Escape { attr: "plain_data", keyword: "assume" }))?; let ident = &input.ident; let (impl_generics, _, where_clause) = generics.split_for_impl(); let (_, type_generics, _) = input.generics.split_for_impl(); From 02b3ea4a342225a598a450dbfc1c240cef76e9c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:00:52 +0000 Subject: [PATCH 13/29] craft-ui: bind_tracked! binds several fields of one Tracked at once bind_tracked!(doc => title, style.size) splits the Tracked into its value and its write count (a Cell over the count) and gives each field path its own write-through binding, so the borrow checker rejects overlapping paths. A binding moves the count at each write that changes its field; making and reading bindings every pass leaves the revision. Bind::tracked, Field, Place, Projection and field! are gone: this is the one way to bind a tracked field. --- crates/tracked/src/lib.rs | 135 ++---------------- crates/ui-contract/src/contract/mod.rs | 3 +- crates/ui-contract/src/contract/values.rs | 97 ++++++++++--- .../tests/it/contract/tracked_bind.rs | 38 +++-- 4 files changed, 116 insertions(+), 157 deletions(-) diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs index b8aeba34f..17f12e09a 100644 --- a/crates/tracked/src/lib.rs +++ b/crates/tracked/src/lib.rs @@ -5,8 +5,8 @@ //! A reader that only needs to know whether the data changed compares the [`Revision`] (two integers) instead of the //! data. The revision is complete because the compiler sees every write: //! -//! - Every way to change the data goes through `&mut Tracked`: [`DerefMut`], [`Tracked::edit`] and a -//! [`Field`]'s writes, and each moves the revision. +//! - Every way to change the data goes through `&mut Tracked`: [`DerefMut`] and [`Tracked::edit`] move the +//! revision, and craft-ui's `bind_tracked!` binds fields that move it when an edit changes them. //! - `T` is [`PlainData`], so a shared reference can't change it: interior mutability, raw pointers, `dyn` objects //! and closures have no implementation, and a `Tracked` holding one does not compile. //! @@ -182,6 +182,7 @@ // The derive reaches this crate as `::craft_tracked`, here too. extern crate self as craft_tracked; +use std::cell::Cell; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -268,7 +269,7 @@ pub struct Revision { /// `T` with a revision that every write moves. /// -/// `Deref` reads; `DerefMut`, [`edit`](Self::edit) and a [`Field`]'s writes move the revision whether or not the +/// `Deref` reads; `DerefMut` and [`edit`](Self::edit) move the revision whether or not the /// write changes the data (a write with no change costs a reader one needless run, never a stale one). A clone is a /// new source: two clones written apart never share a revision. #[derive(Debug)] @@ -304,9 +305,13 @@ impl Tracked { f(&mut **self) } - /// One place inside the value, chosen with [`field!`]: reading it leaves the revision, writing it moves it. - pub fn field(&mut self, projection: Projection) -> Field<'_, T, U> { - Field { tracked: self, projection } + /// Called by craft-ui's `bind_tracked!` only: the value without moving the revision, and the write count. The + /// macro borrows each bound field from the value through a field path and gives the binding the count, which it + /// moves on every write that changes the field. A direct call can write any part of the value without moving the + /// revision, so readers keyed by it would miss the write; design-lint rejects direct calls in UI crates. + #[doc(hidden)] + pub fn __split_for_bind(&mut self) -> (&mut T, &Cell) { + (&mut self.value, Cell::from_mut(&mut self.revision.count)) } /// The value, leaving the tracking. @@ -336,116 +341,6 @@ impl DerefMut for Tracked { } } -/// The way to one field of an `M`, as a read and a write projection. Only [`field!`] builds one, from a field path, -/// so neither projection can do anything but select the field: the read projection leaves the revision, and only a -/// write runs the write projection. -pub struct Projection { - read: fn(&M) -> &U, - write: fn(&mut M) -> &mut U, -} - -impl Clone for Projection { - fn clone(&self) -> Self { - *self - } -} - -impl Copy for Projection {} - -impl Projection { - /// Called by [`field!`] only: a hand-written projection could write the value while selecting a field, and that - /// write would not move the revision. - #[doc(hidden)] - pub const fn __from_field_path(read: fn(&M) -> &U, write: fn(&mut M) -> &mut U) -> Self { - Projection { read, write } - } -} - -/// A [`Projection`] to the field at `path` (`field!(name)`, `field!(style.size)`, `field!(0.title)`): field names -/// and tuple indices only. -/// -/// ``` -/// use craft_tracked::{Tracked, field}; -/// # #[derive(craft_ui_macros::PlainData)] struct Style { size: f32 } -/// # #[derive(craft_ui_macros::PlainData)] struct Doc { style: Style } -/// let mut doc = Tracked::new(Doc { style: Style { size: 12.0 } }); -/// let before = doc.revision(); -/// let mut size = doc.field(field!(style.size)); -/// assert_eq!(*size.get(), 12.0); -/// size.set(14.0); -/// assert_ne!(doc.revision(), before); -/// ``` -/// -/// A method call or an index is not a field path: -/// -/// ```compile_fail -/// use craft_tracked::{Tracked, field}; -/// let mut names = Tracked::new(vec![String::new()]); -/// let _ = names.field(field!(first())); -/// ``` -#[macro_export] -macro_rules! field { - ($first:tt $(. $rest:tt)*) => { - $crate::Projection::__from_field_path(|m| &m.$first $(.$rest)*, |m| &mut m.$first $(.$rest)*) - }; -} - -/// One field inside a [`Tracked`]: reading it leaves the revision, writing it moves it. -pub struct Field<'a, M: PlainData, U> { - tracked: &'a mut Tracked, - projection: Projection, -} - -impl Field<'_, M, U> { - /// The field's value. - pub fn get(&self) -> &U { - (self.projection.read)(&self.tracked.value) - } - - /// Replaces the field's value and moves the revision. - pub fn set(&mut self, value: U) { - self.edit(|field| *field = value); - } - - /// Changes the field through `f` and moves the revision. - pub fn edit(&mut self, f: impl FnOnce(&mut U) -> R) -> R { - f((self.projection.write)(&mut **self.tracked)) - } - - /// The same field, borrowed for a shorter time. - pub fn reborrow(&mut self) -> Field<'_, M, U> { - Field { tracked: &mut *self.tracked, projection: self.projection } - } -} - -/// A field of some tracked value, for code that knows only the field's type (a value binding). -pub trait Place { - /// The field's value. - fn get(&self) -> &U; - /// Replaces the field's value and moves the revision. - fn set(&mut self, value: U); -} - -impl Place for Field<'_, M, U> { - fn get(&self) -> &U { - Field::get(self) - } - - fn set(&mut self, value: U) { - Field::set(self, value); - } -} - -impl + ?Sized> Place for &mut P { - fn get(&self) -> &U { - (**self).get() - } - - fn set(&mut self, value: U) { - (**self).set(value); - } -} - #[cfg(test)] mod tests { use super::Tracked; @@ -462,8 +357,7 @@ mod tests { let mut doc = Tracked::new(Doc { name: "a".into(), size: (1, 2) }); let start = doc.revision(); assert_eq!(doc.name, "a"); - let size = doc.field(field!(size.1)); - assert_eq!(*size.get(), 2); + assert_eq!(doc.size.1, 2); assert_eq!(doc.revision(), start, "reads leave the revision"); doc.name.push('b'); @@ -471,10 +365,7 @@ mod tests { assert_eq!(after_deref.count, start.count + 1, "a `&mut` access moves it"); doc.edit(|doc| doc.size.0 = 3); assert_eq!(doc.revision().count, start.count + 2, "an edit moves it"); - doc.field(field!(size.1)).set(4); - doc.field(field!(name)).edit(|name| name.clear()); - assert_eq!(doc.revision().count, start.count + 4, "a field's set and edit move it"); - assert_eq!((doc.size, doc.name.as_str()), ((3, 4), "")); + assert_eq!((doc.size, doc.name.as_str()), ((3, 2), "ab")); assert_eq!(doc.source(), start.source); let mut a = Tracked::new(1_u32); diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index b9f384e92..ed42534f6 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -38,6 +38,7 @@ pub mod toast; pub mod tooltip; mod values; +pub use crate::bind_tracked; pub use crate::layout::{BodyLayout, RowAlign}; pub use crate::primitives::FacesCx; pub use crate::runtime::access::{Access, FieldLabel, GridPlace, Name, Numeric, Politeness, PopupKind, Role, SetPosition, SubNode, announce}; @@ -66,7 +67,7 @@ pub use container::{ BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth, }; -pub use craft_tracked::{Field, Place, PlainData, Projection, Revision, Tracked, field}; +pub use craft_tracked::{PlainData, Revision, Tracked}; pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract}; #[doc(hidden)] pub use cx::THUMB; diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index d79ebd33c..ad257a04f 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -5,10 +5,10 @@ use crate::runtime::env::Message; use crate::runtime::memory::{MemoryStage, Savable, SaveKey, StageAccess}; use crate::runtime::reads::{self, BindKey}; use craft_behavior::{Applied, CanvasView, EditEvent, EditEvents, EditPolicy, Mixed, Value}; -use craft_tracked::{Place, PlainData, Projection, Tracked}; use egui::Id; use egui::Response; use std::any::TypeId; +use std::cell::Cell; use std::sync::Arc; /// What a check says about a value, with the message type of craft-ui. @@ -107,8 +107,9 @@ enum Source<'a, T> { Mut(&'a mut T), /// Write-through for a multi-selection field. MutMixed(&'a mut Mixed), - /// Write-through to a field of a `Tracked`, whose revision moves only when an edit changes the field. - Tracked(Box + 'a>), + /// Write-through to a field of a `Tracked` (`bind_tracked!`), whose write count moves only when an edit changes + /// the field. + Tracked { value: &'a mut T, count: &'a Cell }, /// No caller value: session memory under the component id, or the saved tier. Kept, } @@ -139,11 +140,11 @@ impl<'a, T: Value> Bind<'a, T> { Self::from_source(Source::MutMixed(v)) } - /// Edits write through to one field of `tracked`, chosen with `craft_tracked::field!` - /// (`Bind::tracked(&mut doc, field!(style.size))`). Making and reading the binding leaves the revision; only an - /// edit that changes the field moves it, so a binding made every pass does not invalidate the value's readers. - pub fn tracked(tracked: &'a mut Tracked, field: Projection) -> Self { - Self::from_source(Source::Tracked(Box::new(tracked.field(field)))) + /// Called by [`bind_tracked!`](crate::bind_tracked) only: edits write through to `value`, and an edit that + /// changes it moves `count`, the write count of the `Tracked` that holds it. + #[doc(hidden)] + pub fn __tracked(value: &'a mut T, count: &'a Cell) -> Self { + Self::from_source(Source::Tracked { value, count }) } /// No caller value: the component keeps it in session memory under its id. Until something is stored, it reads @@ -198,7 +199,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => Source::Given(value.clone()), Source::Mut(value) => Source::Mut(&mut **value), Source::MutMixed(value) => Source::MutMixed(&mut **value), - Source::Tracked(place) => Source::Tracked(Box::new(&mut **place)), + Source::Tracked { value, count } => Source::Tracked { value: &mut **value, count }, Source::Kept => Source::Kept, }; let check = self.check.as_deref().map(|check| Box::new(move |value: &T| check(value)) as Box>); @@ -222,7 +223,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(Mixed::Same(value)) => value == shown, Source::Mut(value) => **value == *shown, Source::MutMixed(Mixed::Same(value)) => value == shown, - Source::Tracked(place) => place.get() == shown, + Source::Tracked { value, .. } => **value == *shown, _ => false, } } @@ -233,7 +234,7 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => SourceMut::Given(value), Source::Mut(value) => SourceMut::Mut(&mut **value), Source::MutMixed(value) => SourceMut::MutMixed(&mut **value), - Source::Tracked(place) => SourceMut::Tracked(&mut **place), + Source::Tracked { value, count } => SourceMut::Tracked { value: &mut **value, count }, Source::Kept => SourceMut::Kept, }; BindMut { source, policy: self.policy, check: self.check.as_deref(), save: self.save.as_ref(), reset: self.reset.as_ref() } @@ -250,7 +251,7 @@ enum SourceMut<'a, T> { Given(&'a Mixed), Mut(&'a mut T), MutMixed(&'a mut Mixed), - Tracked(&'a mut dyn Place), + Tracked { value: &'a mut T, count: &'a Cell }, Kept, } @@ -272,7 +273,7 @@ impl BindMut<'_, T> { SourceMut::Given(value) => Some((*value).clone()), SourceMut::Mut(value) => Some(Mixed::Same((**value).clone())), SourceMut::MutMixed(value) => Some((**value).clone()), - SourceMut::Tracked(place) => Some(Mixed::Same(place.get().clone())), + SourceMut::Tracked { value, .. } => Some(Mixed::Same((**value).clone())), SourceMut::Kept => None, } } @@ -284,7 +285,7 @@ impl BindMut<'_, T> { SourceMut::Given(_) => None, SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::>(value) as usize, TypeId::of::>())), - SourceMut::Tracked(place) => Some(BindKey::Place(std::ptr::from_ref::(place.get()) as usize, TypeId::of::())), + SourceMut::Tracked { value, .. } => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), SourceMut::Kept => Some(match self.save { Some(save) => BindKey::Saved(Id::NULL.with(&save.key)), None => BindKey::Kept(id), @@ -306,7 +307,7 @@ impl BindMut<'_, T> { match &self.source { SourceMut::Given(Mixed::Same(value)) | SourceMut::MutMixed(Mixed::Same(value)) => value == shown, SourceMut::Mut(value) => **value == *shown, - SourceMut::Tracked(place) => place.get() == shown, + SourceMut::Tracked { value, .. } => **value == *shown, _ => false, } } @@ -405,7 +406,7 @@ impl BindMut<'_, T> { pub(crate) fn writes(&self, event: &EditEvent) -> bool { match self.source { SourceMut::Given(_) | SourceMut::Kept => false, - SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked(_) => { + SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked { .. } => { self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. }) } } @@ -420,12 +421,14 @@ impl BindMut<'_, T> { match &mut self.source { SourceMut::Mut(value) => event.apply(&mut **value), SourceMut::MutMixed(value) => event.apply_mixed(&mut **value), - // Applied to a copy, so an event that leaves the field as it was does not move the revision. - SourceMut::Tracked(place) => { - let mut value = place.get().clone(); - let applied = event.apply(&mut value); + SourceMut::Tracked { value, count } => { + // A gesture's start and a cancel with nothing to restore never write. + if matches!(event, EditEvent::Begin { .. } | EditEvent::Cancel { before: None, .. }) { + return Applied::Unchanged; + } + let applied = event.apply(&mut **value); if applied != Applied::Unchanged { - place.set(value); + count.set(count.get().wrapping_add(1)); } applied } @@ -594,3 +597,55 @@ pub(crate) enum Checked { /// A refused one-shot change reaches nothing. Drop, } + +/// Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` +/// gives one [`Bind`], `bind_tracked!(doc => title, style.size)` a tuple with one per field path (field names and +/// tuple indices only). Making and reading the bindings leaves the revision; an edit that changes a field moves it at +/// the write, so bindings made every pass don't invalidate the value's readers. Each binding borrows its own field, +/// so the paths must not overlap. +/// +/// ``` +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::{PlainData, Tracked, bind_tracked}; +/// +/// #[derive(PlainData)] +/// struct Doc { +/// title: String, +/// style: (f32, bool), +/// } +/// +/// let mut doc = Tracked::new(Doc { title: "a".into(), style: (12.0, false) }); +/// let (title, size) = bind_tracked!(doc => title, style.0); +/// # let _ = (title, size); +/// ``` +/// +/// Overlapping paths don't compile: +/// +/// ```compile_fail,E0499 +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::{Tracked, bind_tracked}; +/// let mut doc = Tracked::new((1_u32, 2_u32)); +/// let (a, b) = bind_tracked!(doc => 0, 0); +/// # let _ = (a, b); +/// ``` +/// +/// A method call is not a field path (a macro with no matching rule reports no error code): +/// +/// ```compile_fail +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::{Tracked, bind_tracked}; +/// let mut names = Tracked::new(vec![String::new()]); +/// let first = bind_tracked!(names => first()); +/// # let _ = first; +/// ``` +#[macro_export] +macro_rules! bind_tracked { + ($tracked:expr => $first:tt $(. $rest:tt)*) => {{ + let (model, count) = $tracked.__split_for_bind(); + $crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count) + }}; + ($tracked:expr => $($first:tt $(. $rest:tt)*),+ $(,)?) => {{ + let (model, count) = $tracked.__split_for_bind(); + ($($crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count),)+) + }}; +} diff --git a/crates/ui-contract/tests/it/contract/tracked_bind.rs b/crates/ui-contract/tests/it/contract/tracked_bind.rs index 1bab1ca19..38a5fab81 100644 --- a/crates/ui-contract/tests/it/contract/tracked_bind.rs +++ b/crates/ui-contract/tests/it/contract/tracked_bind.rs @@ -1,32 +1,44 @@ -//! A write-through binding to a field of a `Tracked` value. +//! Write-through bindings to fields of a `Tracked` value. use craft_behavior::{EditEvent, Mixed}; -use craft_ui::contract::{Bind, PlainData, Tracked, field}; +use craft_ui::contract::{PlainData, Tracked, bind_tracked}; use craft_ui::testing::trial; #[derive(PlainData)] struct Doc { title: String, + style: Style, +} + +#[derive(PlainData)] +struct Style { size: f32, } -/// Making and reading the binding every pass leaves the revision, and so does an edit to the value the field already -/// holds; an edit that changes the field moves it once and lands in the field. +/// Passes that bind two fields of one model and read them leave the revision, and so does an edit to the value a +/// field already holds; an edit that changes one field moves the revision once, at the write. #[trial] -fn a_tracked_binding_moves_the_revision_only_when_it_writes() { - let mut doc = Tracked::new(Doc { title: "a".into(), size: 12.0 }); +fn tracked_bindings_move_the_revision_only_when_an_edit_changes_a_field() { + let mut doc = Tracked::new(Doc { title: "a".into(), style: Style { size: 12.0 } }); let start = doc.revision(); for _ in 0..3 { - let mut bind = Bind::tracked(&mut doc, field!(size)); - assert_eq!(bind.reborrow().get(), Some(Mixed::Same(12.0))); + let (mut title, mut size) = bind_tracked!(doc => title, style.size); + assert_eq!(title.reborrow().get(), Some(Mixed::Same("a".to_owned()))); + assert_eq!(size.reborrow().get(), Some(Mixed::Same(12.0))); } - assert_eq!(doc.revision(), start, "bindings made and read every pass leave the revision"); + assert_eq!(doc.revision(), start, "two bindings made and read every pass, and written by neither, leave the revision"); let set = |after: f32| EditEvent::set(Mixed::Same(12.0), after, "Size".into(), None); - Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(12.0)); + { + let (_title, mut size) = bind_tracked!(doc => title, style.size); + size.reborrow().apply(&set(12.0)); + } assert_eq!(doc.revision(), start, "an edit to the value the field holds leaves the revision"); - Bind::tracked(&mut doc, field!(size)).reborrow().apply(&set(14.0)); - assert_eq!(doc.revision().count, start.count + 1, "a changing edit moves it once"); - assert_eq!((doc.size, doc.title.as_str()), (14.0, "a")); + { + let (_title, mut size) = bind_tracked!(doc => title, style.size); + size.reborrow().apply(&set(14.0)); + } + assert_eq!(doc.revision().count, start.count + 1, "a changing edit to one field moves it once"); + assert_eq!((doc.style.size, doc.title.as_str()), (14.0, "a")); } From a5a337466cd1b319ef0711a923ca0f3dc03bfb72 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:02:51 +0000 Subject: [PATCH 14/29] design-lint: no-global-state rejects __split_for_bind instead of __from_field_path (#2336) --- crates/design-lint/README.md | 2 +- crates/design-lint/src/contract/global_state.rs | 12 ++++++------ crates/design-lint/tests/contract_rules.rs | 2 +- .../contract-rules/reject/contract-global-state.rs | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index c3a66b336..817b02e7a 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__from_field_path` (only the `field!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs index f1791c0da..1da609cd7 100644 --- a/crates/design-lint/src/contract/global_state.rs +++ b/crates/design-lint/src/contract/global_state.rs @@ -24,8 +24,8 @@ const PATH_FS: [&str; 2] = ["std", "fs"]; const PLAIN_DATA: &str = "contract/no-global-state:plain-data"; const PROJECTION: &str = "contract/no-global-state:projection"; -/// The hidden constructor behind `field!`; the lint reads source before macro expansion, so every textual hit is a direct call. -const FROM_FIELD_PATH: &str = "__from_field_path"; +/// The hidden `Tracked::__split_for_bind`, called only by `bind_tracked!`; the lint reads source before macro expansion, so every textual hit is a direct call. +const SPLIT_FOR_BIND: &str = "__split_for_bind"; struct Hits { found: Vec<(proc_macro2::Span, String, String)>, @@ -52,7 +52,7 @@ fn static_names(tokens: proc_macro2::TokenStream, out: &mut Vec) { fn field_path_in(tokens: proc_macro2::TokenStream, out: &mut Vec) { for token in tokens { match token { - proc_macro2::TokenTree::Ident(i) if i == FROM_FIELD_PATH => out.push(i.span()), + proc_macro2::TokenTree::Ident(i) if i == SPLIT_FOR_BIND => out.push(i.span()), proc_macro2::TokenTree::Group(g) => field_path_in(g.stream(), out), _ => {} } @@ -131,8 +131,8 @@ impl Visit<'_> for Hits { } fn visit_ident(&mut self, node: &proc_macro2::Ident) { - if node == FROM_FIELD_PATH { - self.projection.push((node.span(), format!("`{FROM_FIELD_PATH}` is called by `field!` only"))); + if node == SPLIT_FOR_BIND { + self.projection.push((node.span(), format!("`{SPLIT_FOR_BIND}` is called by `bind_tracked!` only"))); } } @@ -140,7 +140,7 @@ impl Visit<'_> for Hits { let mut spans = Vec::new(); field_path_in(node.tokens.clone(), &mut spans); for span in spans { - self.projection.push((span, format!("`{FROM_FIELD_PATH}` is called by `field!` only"))); + self.projection.push((span, format!("`{SPLIT_FOR_BIND}` is called by `bind_tracked!` only"))); } visit::visit_macro(self, node); } diff --git a/crates/design-lint/tests/contract_rules.rs b/crates/design-lint/tests/contract_rules.rs index bd10dae4d..5d4354354 100644 --- a/crates/design-lint/tests/contract_rules.rs +++ b/crates/design-lint/tests/contract_rules.rs @@ -101,7 +101,7 @@ fn global_state_counts_every_form_and_honours_the_allowlist() { let src = fixture("reject", "contract-global-state.rs"); let found = analyze_contract(&src, Path::new(FAMILY), &scope(), false); // static, static mut, static OnceLock, thread_local!, impl MemoProps, a static in a fn, `use std::fs`, `std::fs::read`, - // and the two derive-only forms: impl PlainData and a direct `__from_field_path`. + // and the two derive-only forms: impl PlainData and a direct `__split_for_bind`. assert_eq!(found.iter().filter(|f| f.rule == "contract/no-global-state").count(), 10, "{found:?}"); // An entry names one item; the rest of the file is still flagged. The three derive-only forms have no entry. let mut allowed = StaticScope::new(); diff --git a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs index fafa76037..01b98cdac 100644 --- a/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs +++ b/crates/design-lint/tests/fixtures/contract-rules/reject/contract-global-state.rs @@ -16,8 +16,8 @@ impl MemoProps for Props {} impl PlainData for Props {} -fn project() -> Path { - Path::__from_field_path(&[]) +fn project() -> Tracked { + Tracked::__split_for_bind(&[]) } fn read(path: &str) -> Vec { From 94c912daa971b432affe89632a15e3874e18e191 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:08:11 +0000 Subject: [PATCH 15/29] design-lint: allow ui-contract's own MemoProps impls (#2336) --- crates/design-lint/src/workspace.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 17510ae8e..80d4f53f8 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -135,6 +135,8 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ /// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that /// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. const NO_GLOBAL_STATE: &[(&str, &str)] = &[ + // The trait's home crate: it implements `MemoProps` by hand for std and framework value types. + ("crates/ui-contract/src/contract/memo.rs", "MemoProps"), // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. ("crates/ui-contract/src/fonts/defaults.rs", "HACK"), ("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"), @@ -435,6 +437,10 @@ mod tests { #[test] fn no_global_state_allowlist_is_per_item() { + let memo = Path::new("crates/ui-contract/src/contract/memo.rs"); + assert!(no_global_state_allows("MemoProps", memo)); + assert!(!no_global_state_allows("MemoProps", Path::new("crates/ui-contract/src/contract/entry.rs"))); + assert!(!no_global_state_allows("SOMETHING", memo)); let file = Path::new("crates/imaging/src/ui/curve/preview.rs"); assert!(no_global_state_allows("IDENTITY", file)); assert!(!no_global_state_allows("SECOND", file), "a new static in an allowlisted file is flagged"); From 20287bf3fa157a97119639c51cd6991ba59db033 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:15:23 +0100 Subject: [PATCH 16/29] Index inspected elements for focus and labels --- crates/ui-contract/src/runtime/inspect.rs | 28 ++++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index 18e4138cf..d74c99414 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -307,8 +307,13 @@ fn finish(ctx: &Context, open: Open) -> Recorded { .into_iter() .map(|(owner, part, rect)| HitArea { owner, part, rect: from_screen * rect }) .collect(); + // Keep the first occurrence, matching the tree-order lookup when an id appears more than once. + let mut index = std::collections::HashMap::new(); + for (at, element) in elements.iter().enumerate() { + index.entry((element.id, element.part)).or_insert(at); + } for (node, label) in labels { - let facts = elements.iter_mut().find(|element| element.id == node && element.part.is_none()).and_then(|element| element.facts.as_mut()); + let facts = index.get(&(node, None)).and_then(|&at| elements[at].facts.as_mut()); if let Some(facts) = facts { facts.labelled_by.push(label); } @@ -320,20 +325,27 @@ fn finish(ctx: &Context, open: Open) -> Recorded { let key = |hit: &HitArea| (place.get(&hit.owner).copied(), hit.rect.min.y, hit.rect.min.x); key(a).partial_cmp(&key(b)).unwrap_or(std::cmp::Ordering::Equal) }); - for (at, (id, part)) in focus::tab_order(ctx, |id| ids.contains(&id)).into_iter().enumerate() { - let index = match elements.iter().position(|element| element.id == id && element.part == part) { - Some(index) => index, + for (stop, (id, part)) in focus::tab_order(ctx, |id| ids.contains(&id)).into_iter().enumerate() { + let at = match index.get(&(id, part)).copied() { + Some(at) => at, None => { // A part with no node of its own: listed after its component, where its hit area is. - let Some(owner) = elements.iter().position(|element| element.id == id && element.part.is_none()) else { continue }; + let Some(owner) = index.get(&(id, None)).copied() else { continue }; let rect = hits.iter().find(|hit| hit.owner == id && hit.part == part).map_or(elements[owner].rect, |hit| hit.rect); let depth = elements[owner].depth + 1; let element = Element { id, part, component: elements[owner].component, depth, rect, content: rect, facts: None, stop: None }; - elements.insert(owner + 1, element); - owner + 1 + let at = owner + 1; + elements.insert(at, element); + for old in index.values_mut() { + if *old >= at { + *old += 1; + } + } + index.insert((id, part), at); + at } }; - elements[index].stop = Some(at + 1); + elements[at].stop = Some(stop + 1); } Recorded { elements, hits } } From 5b12fdd273bdcc2b404f5aa20b401a6ec320a8d5 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:18:03 +0100 Subject: [PATCH 17/29] Skip undeclared parts outside declaration trials --- crates/ui-contract/src/contract/run.rs | 12 ++++-- crates/ui-contract/src/contract/steps.rs | 4 +- .../ui-contract/src/contract/steps/parts.rs | 1 + crates/ui-contract/src/testing/contract.rs | 30 ++++++++++++++ crates/ui-contract/src/testing/suite/shape.rs | 15 ++++++- crates/ui-contract/tests/it/contract/fixes.rs | 39 +++++++++++++++++++ 6 files changed, 96 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index fa0d9923d..95a70b207 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -939,16 +939,22 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e if !inert && facts.text() { parts.text.commit_now = focus::commit_now(&ctx) == Some(id); } - // A component that declares no parts skips the step; a debug build runs it anyway to check the declaration. let declares_parts = facts.parts || e.declares_parts(); - if !inert && (declares_parts || cfg!(debug_assertions)) { + #[cfg(feature = "testing")] + let checking_parts = !inert && !declares_parts && crate::testing::contract::checking_parts(); + #[cfg(not(feature = "testing"))] + let checking_parts = false; + if !inert && (declares_parts || checking_parts) { let input = MeasureIn { ui: &*ui, env, proposal: Proposal::Ideal, room: p.room }; e.parts(rect, flow, content_rect, &mut parts, &input, rtl); } + #[cfg(feature = "testing")] + if checking_parts && !declares_parts && !steps::declares_none(&parts) { + crate::testing::contract::bad_parts(facts.name); + } if facts.canvas_control && p.trace.recording() { inspect::canvas_control(&ctx, facts.name); } - debug_assert!(declares_parts || steps::declares_none(&parts), "`{}` sets `PARTS = false` and declares a part", facts.name); steps::check_parts(&ctx, facts.name, &parts); let keys = e.keys(); let (holder_widget, text_keys) = text_holder(&ctx, id, &parts, keys, &mut *e.core().memory); diff --git a/crates/ui-contract/src/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 3d4f3551e..6c8b9c22c 100644 --- a/crates/ui-contract/src/contract/steps.rs +++ b/crates/ui-contract/src/contract/steps.rs @@ -31,7 +31,9 @@ pub(crate) use id::{claim_id, draft, id, keeping_ids}; pub(crate) use label::scrub_by_label; pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx, padding, whole}; pub(crate) use paint::{Fade, UnderVeil, fade, next_shape, paint_focus, paint_part_layers, paint_surface, surface_ink, unfade}; -pub(crate) use parts::{PartsStep, check_parts, declares_none}; +#[cfg(feature = "testing")] +pub(crate) use parts::declares_none; +pub(crate) use parts::{PartsStep, check_parts}; pub(crate) use place::place; pub(crate) use report::{ReportIn, report, report_inert, report_parts, validity_of}; #[cfg(feature = "testing")] diff --git a/crates/ui-contract/src/contract/steps/parts.rs b/crates/ui-contract/src/contract/steps/parts.rs index 455ffc0d7..f09043f22 100644 --- a/crates/ui-contract/src/contract/steps/parts.rs +++ b/crates/ui-contract/src/contract/steps/parts.rs @@ -14,6 +14,7 @@ pub(crate) struct PartsStep { } /// Whether step 7 declared no parts, no roving group, no scroll part and no text, editor or selection part. +#[cfg(feature = "testing")] pub(crate) fn declares_none(parts: &PartsStep) -> bool { parts.decls.is_empty() && parts.rovings.is_empty() diff --git a/crates/ui-contract/src/testing/contract.rs b/crates/ui-contract/src/testing/contract.rs index f7c0ae238..d5631f3df 100644 --- a/crates/ui-contract/src/testing/contract.rs +++ b/crates/ui-contract/src/testing/contract.rs @@ -48,3 +48,33 @@ pub fn raw_widget(ui: &mut egui::Ui, rect: egui::Rect) { pub fn allocate(ui: &mut egui::Ui, size: egui::Vec2) { crate::runtime::egui::fixture::allocate_blocker(ui, size); } + +thread_local! { + static PARTS_CHECK: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Run a story with the parts declaration check enabled, and return any offending component types. +pub(crate) fn check_parts_declarations(run: impl FnOnce()) -> Vec<&'static str> { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + PARTS_CHECK.with(|check| *check.borrow_mut() = None); + } + } + PARTS_CHECK.with(|check| *check.borrow_mut() = Some(Vec::new())); + let _reset = Reset; + run(); + PARTS_CHECK.with(|check| check.borrow_mut().take().unwrap_or_default()) +} + +pub(crate) fn checking_parts() -> bool { + PARTS_CHECK.with(|check| check.borrow().is_some()) +} + +pub(crate) fn bad_parts(component: &'static str) { + PARTS_CHECK.with(|check| { + if let Some(bad) = check.borrow_mut().as_mut() { + bad.push(component); + } + }); +} diff --git a/crates/ui-contract/src/testing/suite/shape.rs b/crates/ui-contract/src/testing/suite/shape.rs index a2d80820b..0117b2474 100644 --- a/crates/ui-contract/src/testing/suite/shape.rs +++ b/crates/ui-contract/src/testing/suite/shape.rs @@ -4,7 +4,20 @@ use super::{ANY, Case, Subject}; use crate::testing::fixture::Fixture; use egui::{Rect, Vec2}; -pub(super) const CASES: &[Case] = &[Case::new("paints-inside", ANY, small_rooms_paint_inside_the_shown_rect)]; +pub(super) const CASES: &[Case] = + &[Case::new("paints-inside", ANY, small_rooms_paint_inside_the_shown_rect), Case::new("parts-declaration", ANY, parts_declaration)]; + +fn parts_declaration(subject: &Subject) -> Result<(), String> { + for story in &subject.stories { + let bad = crate::testing::contract::check_parts_declarations(|| { + Fixture::story(story).frame(Vec::new()); + }); + if !bad.is_empty() { + return Err(format!("{}: components with PARTS = false declared parts: {bad:?}", story.name)); + } + } + Ok(()) +} /// The slack between a painted bound and the shown rect: the rounding of the layout, as the layout cases allow. A /// shape's own slack adds half its stroke width. diff --git a/crates/ui-contract/tests/it/contract/fixes.rs b/crates/ui-contract/tests/it/contract/fixes.rs index fc1da8d47..1084dba64 100644 --- a/crates/ui-contract/tests/it/contract/fixes.rs +++ b/crates/ui-contract/tests/it/contract/fixes.rs @@ -237,3 +237,42 @@ fn the_step_log_is_kept_in_fixture_frames_only() { let id = seen.borrow().id.expect("the probe ran"); assert!(steps(&app.ctx, id).is_empty(), "an app frame records no steps"); } + +/// A component whose declaration says the pipeline need not run its parts hook. +#[derive(Component)] +struct NoParts<'a> { + #[common] + common: Common, + calls: &'a std::cell::Cell, +} + +impl Component for NoParts<'_> { + const ROLE: Role = Role::None; + const PARTS: bool = false; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: NoPartsStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn parts(&mut self, _: Rect, _: &mut PartsCx<'_, Self>) { + self.calls.set(self.calls.get() + 1); + } + + fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {} + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn a_component_declaring_no_parts_skips_the_parts_hook() { + let mut frames = Frames::new(); + let calls = std::cell::Cell::new(0); + frames.frame(vec![], |ui| { + NoParts { common: Common::new(), calls: &calls }.show(ui); + }); + assert_eq!(calls.get(), 0, "the parts hook is skipped on ordinary runs"); +} From 0489ea03bfffe838556b9b8b4316ce9ba3d90569 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:25:25 +0000 Subject: [PATCH 18/29] Keep the counters in pass-local state; mark Settle non_exhaustive --- crates/ui-contract/src/runtime/measure.rs | 13 +++++++------ crates/ui-contract/src/runtime/pass_state.rs | 4 ++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 85afc682f..912f37b57 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -309,6 +309,7 @@ pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { /// What a settling child's decision was. #[cfg(feature = "testing")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum Settle { /// The child ran. Ran, @@ -321,7 +322,7 @@ pub enum Settle { /// The settled-test decisions of one pass. #[cfg(feature = "testing")] #[derive(Default)] -struct SettleLog { +pub(crate) struct SettleLog { pass: u64, decisions: Vec<(Id, Settle)>, } @@ -331,7 +332,7 @@ struct SettleLog { #[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = SettleLog { pass, decisions: Vec::new() }; } @@ -343,13 +344,13 @@ pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { #[cfg(feature = "testing")] pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) + pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } /// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. #[cfg(feature = "testing")] #[derive(Default)] -struct PassTotals { +pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, @@ -359,7 +360,7 @@ struct PassTotals { #[cfg(feature = "testing")] fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = PassTotals { pass, ..PassTotals::default() }; } @@ -370,7 +371,7 @@ fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { #[cfg(feature = "testing")] fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 9e0fb9443..18f837d8d 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -113,6 +113,10 @@ pass_state! { style_record: crate::testing::style::StyleRecord, #[cfg(feature = "testing")] type_runs: crate::runtime::measure::TypeRuns, + #[cfg(feature = "testing")] + settle_log: crate::runtime::measure::SettleLog, + #[cfg(feature = "testing")] + pass_totals: crate::runtime::measure::PassTotals, } records { focus: crate::runtime::focus::State, From d7804c73c21a225a855469c7333f6e4d3f8ed987 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:41:02 +0000 Subject: [PATCH 19/29] access: the controls step reaches the tests through runtime::egui --- crates/ui-contract/src/runtime/egui/access.rs | 2 +- crates/ui-contract/src/testing/access.rs | 8 +------- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index f02dfc930..a996c6550 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -213,7 +213,7 @@ pub(crate) fn drop_dangling_relations(output: &mut FullOutput) { /// The step itself: every `controls` id of `update` that names no node of `update` is dropped. Other /// relations keep their ids: they are built from nodes this pass wrote. -pub(crate) fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { +pub fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { let ids: std::collections::HashSet = update.nodes.iter().map(|(id, _)| *id).collect(); for (_, node) in update.nodes.iter_mut() { if node.controls().iter().all(|id| ids.contains(id)) { diff --git a/crates/ui-contract/src/testing/access.rs b/crates/ui-contract/src/testing/access.rs index b1a80a5d5..2d05eb316 100644 --- a/crates/ui-contract/src/testing/access.rs +++ b/crates/ui-contract/src/testing/access.rs @@ -3,19 +3,13 @@ use crate::runtime::access::{FieldLabel, scope}; use egui::{Context, Id}; -pub use crate::runtime::egui::access::{AccessTree, Declared, NodeKey}; +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. pub fn tree_of(output: &mut crate::runtime::egui::fixture::FullOutput) -> AccessTree { crate::runtime::egui::access::tree_of(output).unwrap_or_else(AccessTree::none) } -/// Drops every `controls` id of `update` that names no node of `update`, as the runtime does to each -/// frame's AccessKit output. -pub fn prune_controls(update: &mut egui::accesskit::TreeUpdate) { - crate::runtime::egui::access::prune_controls(update); -} - /// Opens the label scope of `container` with `label`, as a field container's body step does; the container's /// report step closes it. pub fn begin_label_scope(ctx: &Context, container: Id, label: FieldLabel) { From ee0798cda02139617fddc089e0895be33cd7e463 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 08:04:36 +0000 Subject: [PATCH 20/29] craft: facade features table from the member manifests; PlainData derive reaches craft-tracked through contract --- crates/craft/Cargo.toml | 6 ++---- crates/ui-macros/src/plain.rs | 16 ++++------------ 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index b090960f8..3702f1ca9 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -218,8 +218,6 @@ craft-xfa = { workspace = true, optional = true } [features] ui = [ "dep:craft-ui", - # The framework's memoized views key app models by their `Tracked` revision. - "tracked", "dep:egui", "craft-automation?/ui", "craft-browse?/ui", @@ -842,14 +840,14 @@ theme-store = ["dep:craft-theme-store"] tiff = ["dep:craft-tiff"] -tracked = ["dep:craft-tracked"] - time = ["dep:craft-time"] timeline = ["dep:craft-timeline", "keymap"] timeline-otio = ["timeline", "craft-timeline/otio"] timeline-xml = ["timeline", "craft-timeline/xml"] +tracked = ["dep:craft-tracked"] + ui-app = ["ui", "craft-ui/app"] ui-cloud = ["ui", "craft-ui/cloud"] ui-color_fonts = ["ui", "craft-ui/color_fonts"] diff --git a/crates/ui-macros/src/plain.rs b/crates/ui-macros/src/plain.rs index e13425528..1416ce0b2 100644 --- a/crates/ui-macros/src/plain.rs +++ b/crates/ui-macros/src/plain.rs @@ -123,23 +123,15 @@ pub(crate) fn escaped(field: &syn::Field, escape: &Escape) -> syn::Result } /// The path of craft-tracked as the crate being compiled reaches it: a direct dependency (`::craft_tracked` in -/// craft-tracked itself, which declares that name), else the facade's `tracked` module, else the framework's -/// re-export in `contract`. +/// craft-tracked itself, which declares that name), else the framework's re-export in `contract`. Through the +/// facade that is `craft::ui::contract`, which every `ui` build has without the facade's `tracked` feature. fn tracked_crate() -> TokenStream { match crate_name("craft-tracked") { Ok(FoundCrate::Name(name)) => { let name = format_ident!("{name}"); - return quote!(::#name); + quote!(::#name) } - Ok(FoundCrate::Itself) => return quote!(::craft_tracked), - Err(_) => {} - } - match crate_name("craft") { - Ok(FoundCrate::Name(name)) => { - let name = format_ident!("{name}"); - quote!(::#name::tracked) - } - Ok(FoundCrate::Itself) => quote!(::craft::tracked), + Ok(FoundCrate::Itself) => quote!(::craft_tracked), Err(_) => { let k = ui_crate(); quote!(#k::contract) From 3a815c96573361cde272c3c3e679104aefd13fcb Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:02:29 +0000 Subject: [PATCH 21/29] ui-contract: MemoProps, MemoKey, Stateless and the MemoProps derive MemoProps keys every input of a memoized view. The derive builds on the plain-data field check, with #[memo_props(hash = "reason")] for foreign plain types and #[memo_props(stateless)] for the type parameter of a Stateless callback, which no fn item implements MemoProps for: the shared check takes an optional per-parameter escape beside the field escape, and PlainData passes none. FitKeep derives Hash. --- Cargo.lock | 2 + crates/behavior/src/fit.rs | 2 +- crates/ui-contract/Cargo.toml | 4 + crates/ui-contract/src/contract/memo.rs | 826 ++++++++++++++++++ crates/ui-contract/src/contract/mod.rs | 2 + .../ui-contract/src/contract/overlay/place.rs | 2 +- crates/ui-contract/src/primitives/icon.rs | 2 +- crates/ui-contract/src/style/key.rs | 2 +- crates/ui-contract/src/style/look.rs | 4 +- .../ui-contract/tests/it/contract/memo_key.rs | 133 +++ crates/ui-contract/tests/it/contract/mod.rs | 1 + crates/ui-macros/src/lib.rs | 17 +- crates/ui-macros/src/memo.rs | 94 ++ crates/ui-macros/src/plain.rs | 70 +- 14 files changed, 1148 insertions(+), 13 deletions(-) create mode 100644 crates/ui-contract/src/contract/memo.rs create mode 100644 crates/ui-contract/tests/it/contract/memo_key.rs create mode 100644 crates/ui-macros/src/memo.rs diff --git a/Cargo.lock b/Cargo.lock index f2351888f..efb9465f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4218,6 +4218,8 @@ dependencies = [ "log", "proc-macro2", "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", "smallvec", "syn 2.0.119", diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 8b57e2b93..0abbabacf 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -186,7 +186,7 @@ fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec< } /// Whether an item may move into the overflow menu, or lives there. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum FitKeep { /// The item leaves the strip when the room runs out, last item first. diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 07aa7ae2d..b96c932c0 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -36,6 +36,10 @@ craft-theme = { workspace = true } craft-ui-macros = { workspace = true } # `Tracked`: app models whose revision keys memoized views and write-through bindings. craft-tracked = { workspace = true } +# `MemoKey`: SipHash-1-3 with a 128-bit output. +siphasher = "1" +# `CommandRef.params`, which a memo key walks. +serde_json = { workspace = true } craft-settings = { workspace = true } toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } egui = { workspace = true } diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs new file mode 100644 index 000000000..3fe67ad42 --- /dev/null +++ b/crates/ui-contract/src/contract/memo.rs @@ -0,0 +1,826 @@ +//! `MemoProps` and `MemoKey`: every input of a memoized view, as one key the framework compares. +//! +//! A memoized view's content is a `fn` pointer, which captures nothing, and its props are its only argument besides the +//! `Ui`. `MemoProps` is implemented only for types that cannot change behind a shared reference and that the key can +//! feed completely: plain values, strings, containers of props, references to props, `Tracked` (by its revision), +//! callbacks as [`Stateless`] and the framework's value types. The types the plain-data derives reject (`Cell`, +//! `RefCell`, `OnceCell`, `OnceLock`, `Mutex`, `RwLock`, atomics, raw pointers, `dyn` trait objects, closures; the list +//! is on [`PlainData`](craft_tracked::PlainData)) have no implementation, so props holding one do not compile, and the +//! error points at the field: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::cell::Cell, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<'a> { +//! count: &'a std::cell::RefCell, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! name: std::cell::OnceCell, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! name: std::sync::OnceLock, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::sync::Mutex, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::sync::RwLock, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! count: std::sync::atomic::AtomicU32, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! at: *const u8, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<'a> { +//! label: &'a dyn Fn() -> String, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! label: Box String>, +//! } +//! ``` +//! +//! A closure, a field of a generic type and a field inside an enum variant are checked the same way: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! label: F, +//! } +//! let n = 3; +//! craft_ui::contract::MemoKey::of(&Props { label: move || n }); +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! value: T, +//! } +//! craft_ui::contract::MemoKey::of(&Props { value: std::cell::Cell::new(3) }); +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! enum Props { +//! Empty, +//! Count(std::cell::Cell), +//! } +//! ``` +//! +//! A field of a foreign plain type that has no implementation feeds the key through its `Hash`, with the reason it is +//! plain: `#[memo_props(hash = "why")]`. The type must be `Hash + Sync`, and its `Hash` must cover everything the view +//! shows and be prefix-free (two different values never feed bytes of which one starts the other). `Sync` keeps out +//! raw pointers, `NonNull`, `Cell` and `RefCell`, whose `Hash` (where they have one) says nothing about what they point +//! at or hold. A type without `Hash`, a raw pointer and a `NonNull` still fail: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! #[memo_props(hash = "an address")] +//! at: *const u8, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! #[memo_props(hash = "an address")] +//! at: std::ptr::NonNull, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props { +//! #[memo_props(hash = "a plain number")] +//! count: std::cell::Cell, +//! } +//! ``` +//! +//! A callback's type can't be named, so props holding a [`Stateless`] are generic over it. Its parameter is marked +//! `#[memo_props(stateless)]`, which bounds it by what `Stateless` needs instead of `MemoProps`: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps, Stateless}; +//! #[derive(MemoProps)] +//! struct Props<#[memo_props(stateless)] E> { +//! title: String, +//! english: Stateless, +//! } +//! fn english() -> &'static str { +//! "English" +//! } +//! let props = |title: &str| Props { title: title.to_owned(), english: Stateless::new(english) }; +//! assert_eq!(MemoKey::of(&props("a")), MemoKey::of(&props("a"))); +//! assert_ne!(MemoKey::of(&props("a")), MemoKey::of(&props("b"))); +//! ``` +//! +//! The mark only lifts the bound: a marked parameter held as a bare field is still checked, and an unmarked parameter +//! holding a fn item is not props: +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<#[memo_props(stateless)] E> { +//! english: E, +//! } +//! ``` +//! +//! ```compile_fail,E0277 +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps, Stateless}; +//! #[derive(MemoProps)] +//! struct Props { +//! english: Stateless, +//! } +//! fn english() -> &'static str { +//! "English" +//! } +//! MemoKey::of(&Props { english: Stateless::new(english) }); +//! ``` +//! +//! The mark is for type parameters only: +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Props<#[memo_props(stateless)] 'a> { +//! title: &'a str, +//! } +//! ``` +//! +//! Plain props derive, recursive types included: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps}; +//! #[derive(MemoProps)] +//! enum Node { +//! Leaf(String), +//! Branch(Vec), +//! } +//! let tree = |name: &str| Node::Branch(vec![Node::Leaf(name.to_owned())]); +//! assert_eq!(MemoKey::of(&tree("a")), MemoKey::of(&tree("a"))); +//! assert_ne!(MemoKey::of(&tree("a")), MemoKey::of(&tree("b"))); +//! ``` +//! +//! What the types cannot see: process-level state the `fn` or its callees read (`static`, `thread_local!`, `OnceLock`, +//! clocks, files, environment variables) and `unsafe` code. A design-lint rule covers UI crates and the replay audit +//! covers the rest. + +use std::any::TypeId; +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::{OsStr, OsString}; +use std::hash::{Hash, Hasher}; +use std::marker::PhantomData; +use std::num::{ + NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, + NonZeroUsize, +}; +use std::ops::{Range, RangeInclusive}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Duration; + +use craft_tracked::{PlainData, Revision, Tracked}; +use siphasher::sip128::{Hasher128, SipHasher13}; + +pub use craft_ui_macros::MemoProps; + +/// Every input a memoized view reads, fed into a [`MemoKey`]. Two equal keys mean equal inputs. +/// +/// Derive it (`#[derive(MemoProps)]`): the derive feeds every field in order and requires `MemoProps` of each, so a +/// field the view could read without the key seeing it does not compile. Implementations by hand belong to this crate +/// only. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be memo props", + label = "not memo props", + note = "memo props hold plain values, strings, containers and references of props, `Tracked` and framework value types; interior mutability (`Cell`, `RefCell`, `Mutex`, atomics), closures, `dyn` trait objects and raw pointers are rejected, because a memoized view could read them without its key seeing the change", + note = "large app data goes in `Tracked`, which keys by revision; a callback is a `Stateless` fn item or capture-free closure; a foreign plain type takes `#[memo_props(hash = \"why\")]`" +)] +pub trait MemoProps { + /// Feeds every input the view reads into `key`. + fn key(&self, key: &mut MemoKey); +} + +/// A 128-bit hash of a memoized view's props (SipHash-1-3 with a 128-bit output, a fixed key). A collision has a chance +/// of about 2⁻¹²⁸ per compare. A [`Stateless`] callback feeds the 64 bits its `TypeId` hashes, so two callbacks key +/// apart unless those collide. +#[derive(Clone, Debug, Default)] +pub struct MemoKey { + hasher: SipHasher13, + bytes: usize, +} + +impl MemoKey { + /// An empty key. + pub fn new() -> MemoKey { + MemoKey::default() + } + + /// The key of `props`. + pub fn of(props: &P) -> u128 { + let mut key = MemoKey::new(); + props.key(&mut key); + key.finish() + } + + /// Feeds `bytes`. + pub fn write(&mut self, bytes: &[u8]) { + self.hasher.write(bytes); + self.bytes += bytes.len(); + } + + /// Feeds a length or an enum variant's index. + pub fn write_u32(&mut self, value: u32) { + self.write(&value.to_le_bytes()); + } + + /// How many bytes fed the key: the view that takes the key adds them to the pass's key-byte count. + pub fn bytes(&self) -> usize { + self.bytes + } + + /// The key of everything fed so far. + pub fn finish(&self) -> u128 { + self.hasher.finish128().as_u128() + } + + /// Feeds `value` through its `Hash`: for a foreign plain type whose `Hash` is derived over every field (this + /// crate's implementations, and `#[memo_props(hash = "..")]` fields). `Sync` keeps out raw pointers, `NonNull`, + /// `Cell` and `RefCell`. + #[doc(hidden)] + pub fn feed_hash(&mut self, value: &T) { + value.hash(&mut Feed(self)); + } + + fn write_len(&mut self, len: usize) { + self.write(&(len as u64).to_le_bytes()); + } +} + +/// `Hasher` over a key, for [`MemoKey::feed_hash`]. +struct Feed<'k>(&'k mut MemoKey); + +impl Hasher for Feed<'_> { + fn finish(&self) -> u64 { + // Never read: the key finishes itself. + 0 + } + + fn write(&mut self, bytes: &[u8]) { + self.0.write(bytes); + } +} + +macro_rules! bytes { + ($($t:ty),* $(,)?) => { + $(impl MemoProps for $t { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_le_bytes()); + } + })* + }; +} + +bytes!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize); + +impl MemoProps for bool { + fn key(&self, key: &mut MemoKey) { + key.write(&[u8::from(*self)]); + } +} + +impl MemoProps for char { + fn key(&self, key: &mut MemoKey) { + key.write_u32(u32::from(*self)); + } +} + +impl MemoProps for f32 { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_bits().to_le_bytes()); + } +} + +impl MemoProps for f64 { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_bits().to_le_bytes()); + } +} + +impl MemoProps for () { + fn key(&self, _: &mut MemoKey) {} +} + +impl MemoProps for PhantomData { + fn key(&self, _: &mut MemoKey) {} +} + +impl MemoProps for str { + fn key(&self, key: &mut MemoKey) { + // The length first, so ("ab", "") and ("a", "b") differ. + key.write_len(self.len()); + key.write(self.as_bytes()); + } +} + +impl MemoProps for String { + fn key(&self, key: &mut MemoKey) { + self.as_str().key(key); + } +} + +impl MemoProps for Cow<'_, B> { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +impl MemoProps for &T { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +impl MemoProps for Box { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +/// By walking the value, as `Arc`: a large shared model goes in `Tracked`, which keys by revision. +impl MemoProps for Rc { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +/// By walking the value: a large shared model goes in `Tracked`, which keys by revision. +impl MemoProps for Arc { + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +impl MemoProps for Option { + fn key(&self, key: &mut MemoKey) { + match self { + None => key.write(&[0]), + Some(value) => { + key.write(&[1]); + value.key(key); + } + } + } +} + +impl MemoProps for Result { + fn key(&self, key: &mut MemoKey) { + match self { + Ok(value) => { + key.write(&[0]); + value.key(key); + } + Err(error) => { + key.write(&[1]); + error.key(key); + } + } + } +} + +impl MemoProps for Range { + fn key(&self, key: &mut MemoKey) { + let Range { start, end } = self; + start.key(key); + end.key(key); + } +} + +impl MemoProps for RangeInclusive { + fn key(&self, key: &mut MemoKey) { + self.start().key(key); + self.end().key(key); + // An iterated-out range is empty whatever its ends. + self.is_empty().key(key); + } +} + +impl MemoProps for Duration { + fn key(&self, key: &mut MemoKey) { + (self.as_secs(), self.subsec_nanos()).key(key); + } +} + +impl MemoProps for Ordering { + fn key(&self, key: &mut MemoKey) { + (*self as i8).key(key); + } +} + +macro_rules! non_zero { + ($($t:ty),* $(,)?) => { + $(impl MemoProps for $t { + fn key(&self, key: &mut MemoKey) { + self.get().key(key); + } + })* + }; +} + +non_zero!( + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + NonZeroU128, + NonZeroUsize, + NonZeroI8, + NonZeroI16, + NonZeroI32, + NonZeroI64, + NonZeroI128, + NonZeroIsize, +); + +/// Its bytes as the platform encodes them, length first. +impl MemoProps for OsStr { + fn key(&self, key: &mut MemoKey) { + let bytes = self.as_encoded_bytes(); + key.write_len(bytes.len()); + key.write(bytes); + } +} + +impl MemoProps for OsString { + fn key(&self, key: &mut MemoKey) { + self.as_os_str().key(key); + } +} + +impl MemoProps for Path { + fn key(&self, key: &mut MemoKey) { + self.as_os_str().key(key); + } +} + +impl MemoProps for PathBuf { + fn key(&self, key: &mut MemoKey) { + self.as_os_str().key(key); + } +} + +impl MemoProps for [T] { + fn key(&self, key: &mut MemoKey) { + key.write_len(self.len()); + for value in self { + value.key(key); + } + } +} + +impl MemoProps for [T; N] { + fn key(&self, key: &mut MemoKey) { + self.as_slice().key(key); + } +} + +impl MemoProps for Vec { + fn key(&self, key: &mut MemoKey) { + self.as_slice().key(key); + } +} + +impl MemoProps for BTreeMap { + fn key(&self, key: &mut MemoKey) { + key.write_len(self.len()); + for (k, v) in self { + k.key(key); + v.key(key); + } + } +} + +impl MemoProps for BTreeSet { + fn key(&self, key: &mut MemoKey) { + key.write_len(self.len()); + for value in self { + value.key(key); + } + } +} + +macro_rules! tuples { + ($(($($n:ident $i:tt),+)),* $(,)?) => { + $(impl<$($n: MemoProps),+> MemoProps for ($($n,)+) { + fn key(&self, key: &mut MemoKey) { + $(self.$i.key(key);)+ + } + })* + }; +} + +tuples!( + (A 0), + (A 0, B 1), + (A 0, B 1, C 2), + (A 0, B 1, C 2, D 3), + (A 0, B 1, C 2, D 3, E 4), + (A 0, B 1, C 2, D 3, E 4, F 5), + (A 0, B 1, C 2, D 3, E 4, F 5, G 6), + (A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7), +); + +impl MemoProps for Revision { + fn key(&self, key: &mut MemoKey) { + let Revision { source, count } = *self; + (source, count).key(key); + } +} + +/// By revision: equal revisions mean equal data. +impl MemoProps for Tracked { + fn key(&self, key: &mut MemoKey) { + self.revision().key(key); + } +} + +/// A callback in props: a fn item or a capture-free closure, which is zero-sized, so its type alone says what it +/// does, and its `TypeId` keys it. A capturing closure is not zero-sized and fails to build where `Stateless::new` is +/// called (not at `cargo check`: the assertion is evaluated when the call is compiled): +/// +/// ```compile_fail,E0080 +/// # extern crate craft_ui_contract as craft_ui; +/// let n = 3; +/// let _ = craft_ui::contract::Stateless::new(move || n); +/// ``` +/// +/// ``` +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::{MemoKey, Stateless}; +/// let three = Stateless::new(|| 3); +/// assert_eq!(three.get()(), 3); +/// assert_ne!(MemoKey::of(&three), MemoKey::of(&Stateless::new(|| 3))); +/// ``` +#[derive(Clone, Copy)] +pub struct Stateless(F); + +impl Stateless { + /// `f` as a prop; `f` must capture nothing. + pub const fn new(f: F) -> Stateless { + const { assert!(size_of::() == 0, "a Stateless callback captures nothing: pass a fn item or a capture-free closure") }; + Stateless(f) + } + + /// The callback. + pub fn get(&self) -> F { + self.0 + } +} + +impl std::fmt::Debug for Stateless { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(std::any::type_name::()) + } +} + +impl MemoProps for Stateless { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(&TypeId::of::()); + } +} + +// The framework's value types and the foreign plain types they hold. Structs are destructured without `..`, so a new +// field fails to build here until it feeds the key. Types this crate cannot destructure (`#[non_exhaustive]` types of +// other crates, private fields) feed their `Hash`, which each derives over every field. + +impl MemoProps for crate::runtime::env::Label { + fn key(&self, key: &mut MemoKey) { + use crate::runtime::env::Label; + // `Static` and `Shared` of the same text show the same. + match self { + Label::Empty => key.write_u32(0), + Label::Static(text) => { + key.write_u32(1); + text.key(key); + } + Label::Shared(text) => { + key.write_u32(1); + text.key(key); + } + Label::Word(word) => { + key.write_u32(2); + MemoProps::key(word, key); + } + } + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_i18n::Word { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for craft_keymap::CommandRef { + fn key(&self, key: &mut MemoKey) { + let craft_keymap::CommandRef { id, params } = self; + id.key(key); + params.key(key); + } +} + +/// Every value in order; an object's entries in the map's order. +impl MemoProps for serde_json::Value { + fn key(&self, key: &mut MemoKey) { + use serde_json::Value; + match self { + Value::Null => key.write_u32(0), + Value::Bool(value) => { + key.write_u32(1); + value.key(key); + } + Value::Number(number) => { + key.write_u32(2); + // A number is exactly one of these; its text keys it whole. + if let Some(value) = number.as_u64() { + key.write_u32(0); + value.key(key); + } else if let Some(value) = number.as_i64() { + key.write_u32(1); + value.key(key); + } else { + key.write_u32(2); + number.to_string().key(key); + } + } + Value::String(text) => { + key.write_u32(3); + text.key(key); + } + Value::Array(values) => { + key.write_u32(4); + values.key(key); + } + Value::Object(map) => { + key.write_u32(5); + key.write_len(map.len()); + for (name, value) in map { + name.key(key); + value.key(key); + } + } + } + } +} + +impl MemoProps for craft_keymap::Mods { + fn key(&self, key: &mut MemoKey) { + let craft_keymap::Mods { cmd, ctrl, alt, shift } = *self; + (cmd, ctrl, alt, shift).key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_keymap::Key { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for craft_keymap::Chord { + fn key(&self, key: &mut MemoKey) { + let craft_keymap::Chord { mods, key: pressed } = *self; + mods.key(key); + pressed.key(key); + } +} + +impl MemoProps for craft_theme::Srgba { + fn key(&self, key: &mut MemoKey) { + let craft_theme::Srgba { r, g, b, a } = *self; + (r, g, b, a).key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_theme::variant::Tone { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for craft_behavior::IconId { + fn key(&self, key: &mut MemoKey) { + // The name is the whole id. + self.name().key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_behavior::fit::FitKeep { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_host::target::WindowKind { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +/// Derived `Hash` (an opaque hash value). +impl MemoProps for egui::Id { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +impl MemoProps for egui::Vec2 { + fn key(&self, key: &mut MemoKey) { + let egui::Vec2 { x, y } = *self; + (x, y).key(key); + } +} + +impl MemoProps for egui::Pos2 { + fn key(&self, key: &mut MemoKey) { + let egui::Pos2 { x, y } = *self; + (x, y).key(key); + } +} + +impl MemoProps for egui::Rect { + fn key(&self, key: &mut MemoKey) { + let egui::Rect { min, max } = *self; + (min, max).key(key); + } +} + +impl MemoProps for egui::Color32 { + fn key(&self, key: &mut MemoKey) { + key.write(&self.to_array()); + } +} diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index ed42534f6..3b1a33cac 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -20,6 +20,7 @@ mod level; #[cfg(feature = "testing")] mod level_table; mod looks; +mod memo; mod mount; pub mod overlay; mod pages; @@ -92,6 +93,7 @@ pub use lazy::Lazy; #[cfg(feature = "testing")] pub use level::{Catalog, CatalogEntry, Level, StoryLayout, Surface, catalog, stale_table_rows, story_title}; pub use looks::Looks; +pub use memo::{MemoKey, MemoProps, Stateless}; pub use overlay::{Overlay, OverlayUi, Overlays, Popup, PopupHandle, SizeLimits, Trigger}; pub use pages::Pages; pub use paint_ui::PaintUi; diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index ac085d4ec..a0898aad6 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -164,7 +164,7 @@ impl ResizeEdges { /// producing inverted rects. A maximum constrains a pane when its sibling can take the remainder. A tab group takes /// the largest minimum and the largest maximum of its panels, so a panel without a maximum lifts the maximum of the /// panels it joins. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] pub struct SizeLimits { /// Smallest size. pub min: Vec2, diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 36d9a1b18..e11bb8b2e 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -12,7 +12,7 @@ use egui::{Color32, Painter, Rect, pos2, vec2}; pub use super::svg_set::IconSet; /// Whether a directional icon flips under right-to-left. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, crate::contract::MemoProps)] #[non_exhaustive] pub enum Mirror { /// Flips a directional icon under right-to-left. diff --git a/crates/ui-contract/src/style/key.rs b/crates/ui-contract/src/style/key.rs index 603da650d..dfc0e9429 100644 --- a/crates/ui-contract/src/style/key.rs +++ b/crates/ui-contract/src/style/key.rs @@ -11,7 +11,7 @@ use std::hash::{Hash, Hasher}; pub trait StyleKey: Copy + Eq + Hash + Send + Sync + 'static {} /// The text and icon colour that reads on a surface, resolved at step 12. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, crate::contract::MemoProps)] #[non_exhaustive] pub enum Ink { /// On panels, raised and sunken surfaces: the normal text colour. diff --git a/crates/ui-contract/src/style/look.rs b/crates/ui-contract/src/style/look.rs index 0bf3dfe9c..f0483fa00 100644 --- a/crates/ui-contract/src/style/look.rs +++ b/crates/ui-contract/src/style/look.rs @@ -7,7 +7,7 @@ use egui::{Color32, CornerRadius, Stroke}; /// A colour a style builder picked from tokens. `Draw` accepts only this or `DataColor`. It has no /// `From`: the one constructor is `StyleCx::color`. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct StyleColor(#[doc(hidden)] pub Color32); impl StyleColor { @@ -25,7 +25,7 @@ impl Mix for StyleColor { } /// A colour from data (a swatch, a layer label dot). -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct DataColor(#[doc(hidden)] pub Color32); impl DataColor { diff --git a/crates/ui-contract/tests/it/contract/memo_key.rs b/crates/ui-contract/tests/it/contract/memo_key.rs new file mode 100644 index 000000000..f4fb8f3fd --- /dev/null +++ b/crates/ui-contract/tests/it/contract/memo_key.rs @@ -0,0 +1,133 @@ +//! Memo keys: equal props key alike, and every input feeds the key. + +use craft_keymap::CommandRef; +use craft_ui::contract::{MemoKey, MemoProps, Stateless, Tracked}; +use craft_ui::runtime::env::Label; +use craft_ui::testing::trial; + +#[derive(Clone, MemoProps)] +struct Inner { + size: f32, + names: Vec, +} + +#[derive(Clone, MemoProps)] +struct Pair(u8, u8); + +#[derive(Clone, MemoProps)] +enum Mode { + Off, + Count(u32), + Range { from: u32, to: u32 }, +} + +#[derive(Clone, MemoProps)] +struct Props<'a, #[memo_props(stateless)] F> { + title: &'a str, + rest: &'a str, + shown: Option, + inner: Inner, + pair: Pair, + mode: Mode, + choice: Option, + grid: Vec>, + key: u32, + label: Label, + command: CommandRef, + model: &'a Tracked>, + path: std::path::PathBuf, + #[memo_props(hash = "four bytes; the derived Hash feeds them all")] + address: std::net::Ipv4Addr, + english: Stateless, +} + +fn english() -> &'static str { + "English" +} + +fn other() -> &'static str { + "Other" +} + +fn props<'a, F>(model: &'a Tracked>, english: Stateless) -> Props<'a, F> { + Props { + title: "ab", + rest: "", + shown: None, + inner: Inner { size: 1.0, names: vec!["x".to_owned()] }, + pair: Pair(1, 2), + mode: Mode::Count(3), + choice: Some(Mode::Off), + grid: vec![vec![1, 2], vec![3]], + key: 7, + label: Label::Static("Open"), + command: CommandRef::with_params("file.open", serde_json::json!({ "recent": 1 })), + model, + path: "a/b".into(), + address: std::net::Ipv4Addr::new(10, 0, 0, 1), + english, + } +} + +fn base(model: &Tracked>) -> Props<'_, impl Copy + 'static> { + props(model, Stateless::new(english)) +} + +/// Props built twice key alike; changing any one input, a nested field and an enum variant or its field included, gives +/// a key no other change gives. +#[trial] +fn equal_props_give_equal_keys_and_any_change_gives_a_new_key() { + let model = Tracked::new(vec!["a".to_owned()]); + let start = MemoKey::of(&base(&model)); + assert_eq!(MemoKey::of(&base(&model)), start, "equal props key alike"); + assert_eq!(MemoKey::of(&base(&model).clone()), start, "a clone keys alike"); + let mut shared = base(&model); + shared.label = Label::Shared("Open".into()); + assert_eq!(MemoKey::of(&shared), start, "a label keys by its text"); + + let mut keys = vec![start, MemoKey::of(&props(&model, Stateless::new(other)))]; + let mut changed = |change: &dyn Fn(&mut Props<'_, _>)| { + let mut props = base(&model); + change(&mut props); + keys.push(MemoKey::of(&props)); + }; + changed(&|props| props.title = "abc"); + changed(&|props| (props.title, props.rest) = ("a", "b")); + changed(&|props| props.shown = Some(0)); + changed(&|props| props.inner.size = 2.0); + changed(&|props| props.inner.names[0].push('y')); + changed(&|props| props.inner.names.push(String::new())); + changed(&|props| props.pair = Pair(2, 1)); + changed(&|props| props.mode = Mode::Count(4)); + changed(&|props| props.mode = Mode::Off); + changed(&|props| props.mode = Mode::Range { from: 3, to: 0 }); + changed(&|props| props.label = Label::Static("Close")); + changed(&|props| props.command = CommandRef::with_params("file.open", serde_json::json!({ "recent": 2 }))); + changed(&|props| props.command = CommandRef::new("file.open")); + changed(&|props| props.path = "a/c".into()); + changed(&|props| props.choice = None); + changed(&|props| props.choice = Some(Mode::Count(0))); + changed(&|props| props.choice = Some(Mode::Range { from: 0, to: 0 })); + changed(&|props| props.grid = vec![vec![1], vec![2, 3]]); + changed(&|props| props.grid = vec![vec![1, 2, 3]]); + changed(&|props| props.key = 8); + changed(&|props| props.address = std::net::Ipv4Addr::new(10, 0, 0, 2)); + + let mut written = model.clone(); + let cloned = MemoKey::of(&base(&written)); + written.push("b".to_owned()); + keys.extend([cloned, MemoKey::of(&base(&written))]); + + let mut distinct = keys.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert_eq!(distinct.len(), keys.len(), "every change gives its own key: {keys:x?}"); + + // Props key by their values only: two empty props types key alike. The memoized view's own key adds the props + // type's `TypeId`. + #[derive(MemoProps)] + struct Empty; + #[derive(MemoProps)] + struct Nothing {} + assert_eq!(MemoKey::of(&Empty), MemoKey::of(&Nothing {})); +} diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index b85c87339..3c39bfedc 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -3,6 +3,7 @@ mod fixes; mod gesture; mod hit_order; +mod memo_key; mod pages; mod pointer; mod style; diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 05958548b..7db0607d2 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -1,10 +1,11 @@ -//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue, PlainData)]`, +//! Macros of craft-ui: `#[derive(Component, Pattern, Props, ComponentStyle, TokenGroup, CommandSet, EnvValue, PlainData, MemoProps)]`, //! `words!`, `#[story]`, `#[craft_ui::testing::trial]` and `register_contract!`. #![warn(missing_docs)] mod command_set; mod component; mod env; +mod memo; mod pattern; mod plain; mod props; @@ -93,6 +94,20 @@ pub fn derive_plain_data(input: TokenStream) -> TokenStream { expanded(plain::derive(input.into())) } +/// Writes `MemoProps`: every field feeds the memo key, in order (an enum's variant index first), and every field's type +/// must implement `MemoProps`, so a field holding interior mutability, a closure, a trait object or a raw pointer is a +/// compile error at that field. Works on structs, tuple structs and enums. A field of a foreign plain type without an +/// implementation carries `#[memo_props(hash = "why the type is plain")]`: it feeds the key through its `Hash`, and its +/// type must be `Hash + Sync` (which keeps out raw pointers, `NonNull`, `Cell` and `RefCell`), with a `Hash` that covers +/// everything the view shows and is prefix-free (two different values never feed bytes of which one starts the +/// other); the reason is required. A type parameter is bound by `MemoProps`, except one marked +/// `#[memo_props(stateless)]`: the type of a callback held as `Stateless`, which no fn item or closure implements +/// `MemoProps` for, is bound by `'static` only (`struct Bar<#[memo_props(stateless)] E> { english: Stateless }`). +#[proc_macro_derive(MemoProps, attributes(memo_props))] +pub fn derive_memo_props(input: TokenStream) -> TokenStream { + expanded(memo::derive(input.into())) +} + /// Writes `ComponentStyle` from `#[style(surface)]`, `#[style(focus)]` and `#[style(metrics)]` fields (one each), /// any number of `#[style(text)]` (`TextLook`) and `#[style(icon)]` (`IconLook`) fields, and /// `#[style(variants = [..])]` on the type. diff --git a/crates/ui-macros/src/memo.rs b/crates/ui-macros/src/memo.rs new file mode 100644 index 000000000..2e7e3c859 --- /dev/null +++ b/crates/ui-macros/src/memo.rs @@ -0,0 +1,94 @@ +//! `#[derive(MemoProps)]`: every field feeds the key, in order, and every field must implement `MemoProps`. An enum +//! feeds its variant's index before the variant's fields. +//! +//! The bounds and the escape come from the shared field check ([`plain`](crate::plain)). Its check item is left out: +//! the key body already uses every field through `MemoProps` (or `Hash`, for an escaped field), at the field's binding, +//! so each rejected field gives one error that names it. + +use crate::plain::{Escape, FieldChecks, ParamEscape, escaped, field_checks}; +use crate::util::ui_crate; +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::spanned::Spanned; +use syn::{Data, DeriveInput, Fields}; + +/// The escape for a foreign plain type: the field feeds the key through its `Hash`. +const ESCAPE: Escape = Escape { attr: "memo_props", keyword: "hash" }; + +/// The escape for a callback's type parameter (`Stateless`): bound by what `Stateless: MemoProps` needs. +fn stateless() -> ParamEscape { + ParamEscape { attr: "memo_props", keyword: "stateless", bound: quote!('static) } +} + +/// The pattern binding every field of `fields` to a generated name (`{ a: __f0, b: __f1 }`, `(__f0, __f1)` or +/// nothing), so no field shadows the `key` parameter, and the statements feeding each. +fn feed(fields: &Fields, k: &TokenStream) -> syn::Result<(TokenStream, Vec)> { + // Spanned at the field's name, or a tuple field's type, so an error points at the field. + let names: Vec = fields + .iter() + .enumerate() + .map(|(at, field)| format_ident!("__f{at}", span = field.ident.as_ref().map_or_else(|| field.ty.span(), syn::Ident::span))) + .collect(); + let pattern = match fields { + Fields::Named(named) => { + let fields = named.named.iter().filter_map(|field| field.ident.as_ref()); + quote!({ #(#fields: #names),* }) + } + Fields::Unnamed(_) => quote!(( #(#names),* )), + Fields::Unit => quote!(), + }; + let mut statements = Vec::new(); + for (field, name) in fields.iter().zip(&names) { + statements.push(if escaped(field, &ESCAPE)? { quote!(key.feed_hash(#name);) } else { quote!(#k::contract::MemoProps::key(#name, key);) }); + } + Ok((pattern, statements)) +} + +pub(crate) fn derive(input: TokenStream) -> syn::Result { + let input: DeriveInput = syn::parse2(input)?; + let k = ui_crate(); + let trait_path = quote!(#k::contract::MemoProps); + let FieldChecks { generics, .. } = field_checks(&input, &trait_path, Some(&ESCAPE), Some(&stateless()))?; + let body = match &input.data { + Data::Struct(data) => { + let (pattern, statements) = feed(&data.fields, &k)?; + quote! { + let Self #pattern = self; + #(#statements)* + } + } + Data::Enum(data) => { + let mut arms = Vec::new(); + for (at, variant) in data.variants.iter().enumerate() { + let name = &variant.ident; + let (pattern, statements) = feed(&variant.fields, &k)?; + let at = u32::try_from(at).map_err(|_| syn::Error::new_spanned(name, "too many variants"))?; + arms.push(quote! { + Self::#name #pattern => { + key.write_u32(#at); + #(#statements)* + } + }); + } + quote! { + match self { + #(#arms)* + } + } + } + // `field_checks` rejects a union. + Data::Union(_) => quote!(), + }; + let ident = &input.ident; + let (impl_generics, _, where_clause) = generics.split_for_impl(); + let (_, type_generics, _) = input.generics.split_for_impl(); + Ok(quote! { + #[automatically_derived] + impl #impl_generics #trait_path for #ident #type_generics #where_clause { + #[allow(unused_variables)] + fn key(&self, key: &mut #k::contract::MemoKey) { + #body + } + } + }) +} diff --git a/crates/ui-macros/src/plain.rs b/crates/ui-macros/src/plain.rs index 1416ce0b2..1328b1415 100644 --- a/crates/ui-macros/src/plain.rs +++ b/crates/ui-macros/src/plain.rs @@ -39,23 +39,66 @@ pub(crate) struct Escape { pub(crate) keyword: &'static str, } +/// The escape a derive allows for one type parameter, `#[()]`: the parameter is bound by `bound` +/// instead of the derive's trait. +pub(crate) struct ParamEscape { + /// The attribute's name (`memo_props`). + pub(crate) attr: &'static str, + /// The one flag it takes (`stateless`). + pub(crate) keyword: &'static str, + /// What the parameter is bound by instead (`'static`). + pub(crate) bound: TokenStream, +} + /// Requires `trait_path` of every field of `input` (structs, tuple structs, enums; a union is an error). The impl /// bounds each type parameter by `trait_path`; every field is checked under those bounds by a generated /// `check::()` spanned at the field's type, so a rejected field (`Cell` included) is an error at the derive /// that names the field, and a recursive type (a node holding `Vec` or `Vec>`) does not make its impl /// require itself. A field type written with `Self` is checked as the type itself. A field carrying `escape` is not -/// checked. -pub(crate) fn field_checks(input: &DeriveInput, trait_path: &TokenStream, escape: Option<&Escape>) -> syn::Result { +/// checked. A type parameter carrying `param_escape` is bound by its `bound` instead of `trait_path`; its fields are +/// still checked under that bound. +pub(crate) fn field_checks( + input: &DeriveInput, + trait_path: &TokenStream, + escape: Option<&Escape>, + param_escape: Option<&ParamEscape>, +) -> syn::Result { let fields: Vec<&syn::Field> = match &input.data { Data::Struct(data) => data.fields.iter().collect(), Data::Enum(data) => data.variants.iter().flat_map(|variant| variant.fields.iter()).collect(), Data::Union(data) => return Err(syn::Error::new(data.union_token.span(), "a union cannot hold only plain data")), }; let mut generics = input.generics.clone(); - let params: Vec = input.generics.type_params().map(|param| param.ident.clone()).collect(); + if let Some(param_escape) = param_escape { + for param in &generics.params { + let attrs = match param { + syn::GenericParam::Type(_) => continue, + syn::GenericParam::Lifetime(param) => ¶m.attrs, + syn::GenericParam::Const(param) => ¶m.attrs, + }; + if let Some(attr) = attrs.iter().find(|attr| attr.path().is_ident(param_escape.attr)) { + let ParamEscape { attr: name, keyword, .. } = param_escape; + return Err(syn::Error::new_spanned(attr, format!("`#[{name}({keyword})]` marks a type parameter"))); + } + } + } + let mut bounds = Vec::new(); + for param in generics.type_params_mut() { + let escaped = match param_escape { + Some(param_escape) => param_escaped(param, param_escape)?, + None => false, + }; + // A derive's helper attributes are not attributes of the impl. + param.attrs.clear(); + let ident = ¶m.ident; + bounds.push(match param_escape { + Some(ParamEscape { bound, .. }) if escaped => quote!(#ident: #bound), + _ => quote!(#ident: #trait_path), + }); + } let where_clause = generics.make_where_clause(); - for param in ¶ms { - where_clause.predicates.push(syn::parse2(quote!(#param: #trait_path))?); + for bound in bounds { + where_clause.predicates.push(syn::parse2(bound)?); } let ident = &input.ident; let (_, type_generics, _) = input.generics.split_for_impl(); @@ -101,6 +144,21 @@ impl VisitMut for ReplaceSelf<'_> { } } +/// Whether `param` carries `#[()]`. Any other content of the attribute is an error. +fn param_escaped(param: &syn::TypeParam, escape: &ParamEscape) -> syn::Result { + let mut found = false; + for attr in param.attrs.iter().filter(|attr| attr.path().is_ident(escape.attr)) { + attr.parse_nested_meta(|meta| { + if !meta.path.is_ident(escape.keyword) { + return Err(meta.error(format!("expected `#[{}({})]`", escape.attr, escape.keyword))); + } + found = true; + Ok(()) + })?; + } + Ok(found) +} + /// Whether `field` carries `#[( = "reason")]`. Any other content of the attribute, or an empty /// reason, is an error. pub(crate) fn escaped(field: &syn::Field, escape: &Escape) -> syn::Result { @@ -144,7 +202,7 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { let input: DeriveInput = syn::parse2(input)?; let k = tracked_crate(); let trait_path = quote!(#k::PlainData); - let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some(&Escape { attr: "plain_data", keyword: "assume" }))?; + let FieldChecks { generics, checks } = field_checks(&input, &trait_path, Some(&Escape { attr: "plain_data", keyword: "assume" }), None)?; let ident = &input.ident; let (impl_generics, _, where_clause) = generics.split_for_impl(); let (_, type_generics, _) = input.generics.split_for_impl(); From d06fd33dfb967e28fc69e8692e41bf804c4658cb Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:39:51 +0000 Subject: [PATCH 22/29] Add count-trial counters for settling, text layout and measure asks, and an idle-frame trial --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 19 ++- crates/ui-contract/src/runtime/measure.rs | 116 ++++++++++++++++++ crates/ui-contract/src/testing/mod.rs | 5 +- crates/ui-widgets/tests/it/body/settle.rs | 72 +++++++---- 7 files changed, 190 insertions(+), 25 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6293bebde..856259c7a 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 0170bb71d..e75201bd6 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size))); diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 113581b1b..1d64bf0df 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 8cefd9fb5..7850311c1 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -240,7 +240,7 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { /// pass gets the same answer, so a measuring run and the real run lay out the same children. pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision { let targets = crate::runtime::focus::targets(ctx); - with(ctx, |store, pass_nr, frame| { + let decision = with(ctx, |store, pass_nr, frame| { let entry = store.touch(Some(view.owner), id, frame); let kind = usize::from(!sizing); // A child the other kind of run showed last takes that run's extent. @@ -255,7 +255,11 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - } }; if skip { Decision::Skip(size) } else { Decision::Run } - }) + }); + if matches!(decision, Decision::Skip(_)) { + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); + } + decision } /// Records what a run that showed the child `id` found: its extent in a run of this kind and, from a real run, what @@ -298,6 +302,17 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { + use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; + // The 8 bytes of a keyed call's content version are the key fed in. + if content.is_some() { + count_memo_key_bytes(ctx, 8); + } + let size = decide_settled(ctx, owner, id, sizing, place, content); + count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); + size +} + +fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index c281c04a5..5bed8a5e6 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -305,3 +305,119 @@ pub(crate) fn count_least(ctx: &Context, id: Id) { pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| log.runs.clone()) } + +/// What a settling child's decision was. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Settle { + /// The child ran. + Ran, + /// The child's last run was replayed in place of running. + Replayed, + /// The child is out of view and took its last extent without running. + OutOfView, +} + +/// The settled-test decisions of one pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct SettleLog { + pass: u64, + decisions: Vec<(Id, Settle)>, +} + +/// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and +/// `lazy::decide` (out of view); a rename of that decision point moves both calls. +pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { + #[cfg(feature = "testing")] + { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); + } + #[cfg(not(feature = "testing"))] + let _ = (ctx, id, what); +} + +/// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. +#[cfg(feature = "testing")] +pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) +} + +/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct PassTotals { + pass: u64, + key_bytes: usize, + text_layouts: u32, + asks: Vec<(&'static str, u32)>, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = PassTotals { pass, ..PassTotals::default() }; + } + f(log) + }) +} + +#[cfg(feature = "testing")] +fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) +} + +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.key_bytes += bytes); + #[cfg(not(feature = "testing"))] + let _ = (ctx, bytes); +} + +/// The bytes fed into memo keys in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { + last_totals(ctx, |log| log.key_bytes, 0) +} + +/// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +pub(crate) fn count_text_layout(ctx: &Context) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.text_layouts += 1); + #[cfg(not(feature = "testing"))] + let _ = ctx; +} + +/// The text layouts handed to egui in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_text_layouts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.text_layouts, 0) +} + +/// Counts a measure call of a leaf component of the type `name` in this pass. +pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { + #[cfg(feature = "testing")] + totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { + Some((_, count)) => *count += 1, + None => log.asks.push((name, 1)), + }); + #[cfg(not(feature = "testing"))] + let _ = (ctx, name); +} + +/// The leaf types that were asked to measure in the last pass, and how many times each. +#[cfg(feature = "testing")] +pub fn last_pass_measure_asks(ctx: &Context) -> Vec<(&'static str, u32)> { + last_totals(ctx, |log| log.asks.clone(), Vec::new()) +} diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 90ed467df..9dcb90e6a 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -41,8 +41,9 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ - active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, - last_pass_runs, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + Settle, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, + last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_runs, last_pass_settles, + last_pass_text_layouts, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index f7dae2c36..317b8d902 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -13,7 +13,7 @@ use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Comm use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; -use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial}; +use craft_ui::testing::{Fixture, Frames, Settle, last_pass_measuring_runs, last_pass_runs, last_pass_settles, last_pass_text_layouts, trial}; use egui::{Id, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -36,6 +36,8 @@ struct Scene { versions: [Cell>; 2], repaints: Cell, app_repaints: Cell, + /// Whether the scene shows only what is outside the settling children. + bare: Cell, runs: [Cell; 2], buttons: [Cell<(Id, Rect)>; 2], seen: Seen, @@ -51,6 +53,7 @@ impl Scene { versions: Default::default(), repaints: Cell::new(false), app_repaints: Cell::new(false), + bare: Cell::new(false), runs: Default::default(), buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))], seen: Seen::default(), @@ -73,28 +76,30 @@ impl Scene { if self.editor_first { self.editor(ui); } - in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { - self.child("reader", 0).show(ui, |ui| { - self.runs[0].set(self.runs[0].get() + 1); - let response = Button::new("Alpha").show(ui).response; - self.buttons[0].set((response.id, response.rect)); - Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); - }); - self.child("other", 1).show(ui, |ui| { - self.runs[1].set(self.runs[1].get() + 1); - if self.repaints.get() { - frame::request_repaint(ui.ctx()); - } - // In a body, whose measure a run that is not settled takes from what its last run kept. - Stack::new().show(ui, |ui, _| { - let response = Button::new("Beta").show(ui).response; - self.buttons[1].set((response.id, response.rect)); + if !self.bare.get() { + in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { + self.child("reader", 0).show(ui, |ui| { + self.runs[0].set(self.runs[0].get() + 1); + let response = Button::new("Alpha").show(ui).response; + self.buttons[0].set((response.id, response.rect)); + Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); + }); + self.child("other", 1).show(ui, |ui| { + self.runs[1].set(self.runs[1].get() + 1); + if self.repaints.get() { + frame::request_repaint(ui.ctx()); + } + // In a body, whose measure a run that is not settled takes from what its last run kept. + Stack::new().show(ui, |ui, _| { + let response = Button::new("Beta").show(ui).response; + self.buttons[1].set((response.id, response.rect)); + }); + if self.spinner { + Spinner::new().show(ui); + } }); - if self.spinner { - Spinner::new().show(ui); - } }); - }); + } if !self.editor_first { self.editor(ui); } @@ -146,6 +151,31 @@ fn a_settled_child_does_not_run_and_still_paints() { } } +/// After two warm-up frames, an idle frame with no input runs nothing that settles: every keyed child replays, the +/// components that run are those outside every settling child, the frame takes one pass and lays out no text. +#[trial] +fn an_idle_frame_runs_nothing_that_settles() { + let scene = Scene::new(false, false); + scene.versions.iter().for_each(|version| version.set(Some(1))); + let mut frames = Frames::new(); + scene.settle(&mut frames); + let reference = Scene::new(false, false); + reference.bare.set(true); + let mut bare = Frames::new(); + reference.settle(&mut bare); + let outside = { + reference.frame(&mut bare, vec![]); + last_pass_runs(&bare.ctx).iter().map(|(_, runs)| runs).sum::() + }; + let passes = frames.frame(vec![], |ui| scene.show(ui)); + let ran = last_pass_settles(&frames.ctx).into_iter().filter(|(_, what)| *what == Settle::Ran).count(); + let runs = last_pass_runs(&frames.ctx); + assert_eq!(ran, 0, "an idle frame ran keyed children: {:?}", last_pass_settles(&frames.ctx)); + assert_eq!(runs.iter().map(|(_, runs)| runs).sum::(), outside, "components ran inside settling children: {runs:?}"); + assert_eq!(passes, 1, "an idle frame takes one pass"); + assert_eq!(last_pass_text_layouts(&frames.ctx), 0, "an idle frame laid out text"); +} + /// The pointer over a settled child runs it, and only it, in the frame it arrives, from the measures its last run /// kept; leaving, the child runs until its hover has faded out, then settles again. #[trial] From ce3513f84a3a8fd2403298d5adfc0c0920f5d999 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:41:32 +0000 Subject: [PATCH 23/29] Gate the counters on the testing feature --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 23 ++++++------ crates/ui-contract/src/runtime/measure.rs | 35 +++++++------------ 5 files changed, 29 insertions(+), 32 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 856259c7a..6ccec0dbf 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + #[cfg(feature = "testing")] crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index e75201bd6..237e116be 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 1d64bf0df..d07364659 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 7850311c1..b6fd3756c 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -256,6 +256,7 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - }; if skip { Decision::Skip(size) } else { Decision::Run } }); + #[cfg(feature = "testing")] if matches!(decision, Decision::Skip(_)) { crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); } @@ -302,17 +303,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { - use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; - // The 8 bytes of a keyed call's content version are the key fed in. + // Keyed calls feed their 8-byte content version into the key. + #[cfg(feature = "testing")] if content.is_some() { - count_memo_key_bytes(ctx, 8); + crate::runtime::measure::count_memo_key_bytes(ctx, 8); } - let size = decide_settled(ctx, owner, id, sizing, place, content); - count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); - size -} - -fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); @@ -355,15 +350,23 @@ fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: settled.map(|settled| (entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(settled.rect.size()), settled)) }); // The pointer over it, or a press that started on it, is read outside the store. - let (size, settled) = settled?; + let Some((size, settled)) = settled else { + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); + return None; + }; if engaged(ctx, &settled) { with(ctx, |store, pass_nr, _| { if let Some(entry) = store.entries.get_mut(&id) { entry.replays = Some((pass_nr, false)); } }); + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); return None; } + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Replayed); Some(size) } diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 5bed8a5e6..85afc682f 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -328,19 +328,15 @@ struct SettleLog { /// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and /// `lazy::decide` (out of view); a rename of that decision point moves both calls. +#[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { - #[cfg(feature = "testing")] - { - let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { - if log.pass != pass { - *log = SettleLog { pass, decisions: Vec::new() }; - } - log.decisions.push((id, what)); - }); - } - #[cfg(not(feature = "testing"))] - let _ = (ctx, id, what); + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); } /// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. @@ -377,12 +373,11 @@ fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } -/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes +/// per call with a content version). +#[cfg(feature = "testing")] pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { - #[cfg(feature = "testing")] totals(ctx, |log| log.key_bytes += bytes); - #[cfg(not(feature = "testing"))] - let _ = (ctx, bytes); } /// The bytes fed into memo keys in the last pass. @@ -392,11 +387,9 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { } /// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_text_layout(ctx: &Context) { - #[cfg(feature = "testing")] totals(ctx, |log| log.text_layouts += 1); - #[cfg(not(feature = "testing"))] - let _ = ctx; } /// The text layouts handed to egui in the last pass. @@ -406,14 +399,12 @@ pub fn last_pass_text_layouts(ctx: &Context) -> u32 { } /// Counts a measure call of a leaf component of the type `name` in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { - #[cfg(feature = "testing")] totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { Some((_, count)) => *count += 1, None => log.asks.push((name, 1)), }); - #[cfg(not(feature = "testing"))] - let _ = (ctx, name); } /// The leaf types that were asked to measure in the last pass, and how many times each. From 972a86af6582034237877a0266097769f62b2baa Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:25:25 +0000 Subject: [PATCH 24/29] Keep the counters in pass-local state; mark Settle non_exhaustive --- crates/ui-contract/src/runtime/measure.rs | 13 +++++++------ crates/ui-contract/src/runtime/pass_state.rs | 4 ++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 85afc682f..912f37b57 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -309,6 +309,7 @@ pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { /// What a settling child's decision was. #[cfg(feature = "testing")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum Settle { /// The child ran. Ran, @@ -321,7 +322,7 @@ pub enum Settle { /// The settled-test decisions of one pass. #[cfg(feature = "testing")] #[derive(Default)] -struct SettleLog { +pub(crate) struct SettleLog { pass: u64, decisions: Vec<(Id, Settle)>, } @@ -331,7 +332,7 @@ struct SettleLog { #[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = SettleLog { pass, decisions: Vec::new() }; } @@ -343,13 +344,13 @@ pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { #[cfg(feature = "testing")] pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) + pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } /// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. #[cfg(feature = "testing")] #[derive(Default)] -struct PassTotals { +pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, @@ -359,7 +360,7 @@ struct PassTotals { #[cfg(feature = "testing")] fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = PassTotals { pass, ..PassTotals::default() }; } @@ -370,7 +371,7 @@ fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { #[cfg(feature = "testing")] fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 9e0fb9443..18f837d8d 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -113,6 +113,10 @@ pass_state! { style_record: crate::testing::style::StyleRecord, #[cfg(feature = "testing")] type_runs: crate::runtime::measure::TypeRuns, + #[cfg(feature = "testing")] + settle_log: crate::runtime::measure::SettleLog, + #[cfg(feature = "testing")] + pass_totals: crate::runtime::measure::PassTotals, } records { focus: crate::runtime::focus::State, From fc8f48ff967337636db58de10e5605f8013a852a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:31:24 +0000 Subject: [PATCH 25/29] Command board: maps for instances, modal roots and shown readers; node facts after the node check; chord texts from the keymap build --- .../ui-contract/src/contract/steps/report.rs | 72 ++++--- .../ui-contract/src/runtime/commands/board.rs | 190 ++++++++++++------ .../ui-contract/src/runtime/commands/mod.rs | 12 +- crates/ui-contract/src/runtime/measure.rs | 15 +- crates/ui-panels/src/rails/flyout.rs | 5 +- crates/ui-shell/tests/it/commands/board.rs | 61 +++++- crates/ui-shell/tests/it/commands/kit.rs | 31 +++ 7 files changed, 279 insertions(+), 107 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 2dd8a846d..7dafc2583 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -6,7 +6,7 @@ use crate::contract::cx::{CxCore, Decls}; use crate::contract::run::{ErasedPass, TypeFacts}; use crate::primitives::FaceRecord; use crate::runtime::access::{self, Access, FaceFacts, Own, Politeness, Role, SetPosition, SubDecl, SubNode, scope}; -use crate::runtime::commands::{self, ResolvedCommand}; +use crate::runtime::commands::ResolvedCommand; use crate::runtime::env::{Label, Message}; use crate::runtime::focus::{self}; use crate::runtime::keys; @@ -33,8 +33,15 @@ pub(crate) struct ReportIn<'a> { } /// The bound command's hint and shortcut text, which describe and key its node. -fn command_facts(command: &ResolvedCommand, platform: craft_keymap::Platform) -> (Option<&str>, Option) { - (command.hint.as_deref(), command.chord.as_ref().map(|chord| chord.display(platform))) +fn command_facts<'a>(ctx: &egui::Context, command: &'a ResolvedCommand) -> (Option<&'a str>, Option<&'a str>) { + let text = command.chord_text.as_deref(); + #[cfg(feature = "testing")] + if text.is_some() { + crate::runtime::measure::count_chord_text(ctx); + } + #[cfg(not(feature = "testing"))] + let _ = ctx; + (command.hint.as_deref(), text) } /// The message of a validity that warns, refuses or errs, and whether it warns. @@ -78,40 +85,10 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> } } *core.value_text.borrow_mut() = value_text; - for node in &mut access.nodes { - if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) { - node.expanded = Some(toggle.open); - } - } let role = access.role.unwrap_or(facts.role); - access.access_key = access.access_key.or(core.resolved.access_key); - if access.grid == access::GridPlace::default() { - access.grid = core.grid; - } debug_assert!(access.role.is_none_or(|alt| facts.alt_roles.contains(&alt)), "`Access::role` picks one of `ALT_ROLES`"); let flags = core.state.flags; let resolved = core.resolved; - let platform = commands::platform(ctx); - let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(command, platform)); - let shortcut = shortcut.as_deref(); - for (_, label) in &mut access.custom_actions { - *label = core.env.resolve(label); - } - let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text)); - let tooltip = tooltip_text.as_ref().map(Label::as_str); - if access.live.is_none() { - access.live = input.live; - } - if access.expanded.is_none() { - access.expanded = input.expanded; - } - if access.position.is_none() { - access.position = input.position; - } - if access.position.is_none() { - access.position = - input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); - } let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { @@ -132,6 +109,35 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> if !input.node { return; } + // Facts that only a node shows are built after the node check. + for node in &mut access.nodes { + if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) { + node.expanded = Some(toggle.open); + } + } + access.access_key = access.access_key.or(core.resolved.access_key); + if access.grid == access::GridPlace::default() { + access.grid = core.grid; + } + let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(ctx, command)); + for (_, label) in &mut access.custom_actions { + *label = core.env.resolve(label); + } + let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text)); + let tooltip = tooltip_text.as_ref().map(Label::as_str); + if access.live.is_none() { + access.live = input.live; + } + if access.expanded.is_none() { + access.expanded = input.expanded; + } + if access.position.is_none() { + access.position = input.position; + } + if access.position.is_none() { + access.position = + input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); + } let inner_of = access::fold::owner_of(ctx, id); let folded = access::fold::take(ctx, id); if access.value.is_none() { diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 0c3d7f8a7..ca350161d 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -32,6 +32,44 @@ enum Declaration { Focused { inactive: bool }, } +/// The registered instances in registration order, which `pick_instance` ranks by, with their positions by id. +#[derive(Default)] +struct Instances { + list: Vec, + at: HashMap, +} + +impl Instances { + fn get(&self, id: Id) -> Option<&Instance> { + self.at.get(&id).map(|at| &self.list[*at]) + } + + fn iter(&self) -> std::slice::Iter<'_, Instance> { + self.list.iter() + } + + /// Registers `instance`, keeping the place of one already registered under the same id. + fn upsert(&mut self, instance: Instance) { + match self.at.get(&instance.id) { + Some(at) => self.list[*at] = instance, + None => { + self.at.insert(instance.id, self.list.len()); + self.list.push(instance); + } + } + } + + /// Keeps the instances `keep` accepts, in their order. + fn retain(&mut self, mut keep: impl FnMut(&Instance) -> bool) { + self.list.retain(|instance| keep(instance)); + self.at = self.list.iter().enumerate().map(|(at, instance)| (instance.id, at)).collect(); + } + + fn contains(&self, id: Id) -> bool { + self.at.contains_key(&id) + } +} + /// A container instance that receives scoped commands. struct Instance { id: Id, @@ -54,6 +92,8 @@ struct KeymapCache { edit_chords: Arc<[(EditCommand, Chord)]>, /// The chords bound to the window's keys, which the input hook takes before any component. window_shortcuts: Arc<[(WindowShortcut, Chord)]>, + /// `BuiltKeymap::shown_text`. + shown_text: Arc>>, } /// A momentary command whose key is down: its release fires the command again. @@ -85,7 +125,7 @@ pub(crate) struct Board { out: Vec, /// The commands instances took since the last `FrameOutput`, in order. delivered: Vec, - instances: Vec, + instances: Instances, /// The focused component of each viewport's last step 12 and the instances around it. chains: HashMap, /// The focused component and its chain before the one in `chains`, per viewport; while the focus is in the menus @@ -98,7 +138,7 @@ pub(crate) struct Board { matcher: Matcher, held: Vec, /// The top modal layer's root container of each viewport that has one. - modal_roots: Vec<(ViewportId, Id)>, + modal_roots: HashMap, /// The states published this pass, and the pass before, by an instance inside the top modal layer. modal_published: HashSet, modal_published_last: HashSet, @@ -129,7 +169,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool { } /// Who read a command's resolution: the vantage `begin` resolves it from again. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Hash)] enum Reader { /// A surface with no component of its own (`resolve_global`): the key focus of the running pass. Global, @@ -142,21 +182,19 @@ enum Reader { InMenu(Id, CommandChain), } -/// What a reader was shown the last time it resolved a command. -struct Shown { - reader: Reader, - resolved: ResolvedCommand, -} - -/// The readers of each state key in each viewport. -type ShownMap = HashMap<(StateKey, ViewportId), Vec>; +/// What each reader was shown the last time it resolved a command, by the viewport and the state key it read. The +/// readers of a key stay in the order they first read it: the gate is app code, and `wake_shown` asks it in that order. +type ShownMap = HashMap>>; /// Keeps `resolved` as what `reader` of `viewport` was shown under `key`, in place of what it was shown before. fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader: Reader, resolved: &ResolvedCommand) { - let readers = shown.entry((key, viewport)).or_default(); - match readers.iter_mut().find(|entry| entry.reader == reader) { - Some(entry) => entry.resolved.clone_from(resolved), - None => readers.push(Shown { reader, resolved: resolved.clone() }), + keep_in(shown.entry(viewport).or_default().entry(key).or_default(), reader, resolved); +} + +fn keep_in(readers: &mut Vec<(Reader, ResolvedCommand)>, reader: Reader, resolved: &ResolvedCommand) { + match readers.iter_mut().find(|(kept, _)| *kept == reader) { + Some((_, kept)) => kept.clone_from(resolved), + None => readers.push((reader, resolved.clone())), } } @@ -238,7 +276,7 @@ impl Board { /// The instance of `scope` a command routed to `at` goes to: `at` when it is an instance of the scope itself (a /// canvas), else the innermost instance in `around`, the chain of the context `at` was shown in. fn instance_around(&self, at: Id, around: &CommandChain, scope: &str) -> Option { - let own = self.instances.iter().any(|i| i.id == at && self.within(i.scope.name(), scope)); + let own = self.instances.get(at).is_some_and(|i| self.within(i.scope.name(), scope)); if own { Some(at) } else { self.innermost(around, scope) } } @@ -262,7 +300,7 @@ impl Board { } fn is_live(&self, ctx: &Context, id: Id) -> bool { - self.instances.iter().any(|i| i.id == id && self.live(ctx, i)) + self.instances.get(id).is_some_and(|i| self.live(ctx, i)) } /// The definition of the command `id`: the linked sets', else the frame's app catalog's. @@ -301,7 +339,7 @@ impl Board { /// is declared inside, after its own. fn scopes_around(&self, chain: &[Id]) -> Vec<&'static str> { let mut scopes: Vec<&'static str> = Vec::new(); - for instance in chain.iter().rev().filter_map(|id| self.instances.iter().find(|i| i.id == *id)) { + for instance in chain.iter().rev().filter_map(|id| self.instances.get(*id)) { let lineage = self.lineage(instance.scope.name()); scopes.push(lineage[0]); let parents: Vec<&'static str> = lineage[1..].iter().copied().filter(|scope| !scopes.contains(scope)).collect(); @@ -318,7 +356,7 @@ impl Board { } fn is_modal_root(&self, id: Id) -> bool { - self.modal_roots.iter().any(|(_, root)| *root == id) + self.modal_roots.values().any(|root| *root == id) } /// Where `command` goes when a source with no component of its own fires it: `None` for an app-scope command, @@ -398,10 +436,12 @@ impl Board { }; let live = app || instance.is_some_and(|id| self.is_live(ctx, id)); let chord = self.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command)); + let chord_text = chord.and_then(|chord| self.keymap.as_ref()?.shown_text.get(&chord).cloned()); let resolved = ResolvedCommand { label: state.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))), icon: def.and_then(|def| def.icon.clone()), chord, + chord_text, enabled: flags.enabled && modal && live && !matches!(declaring, Some(Declaration::Focused { inactive: true })), checked: flags.checked, marked: state.is_some_and(CommandState::is_marked), @@ -464,6 +504,8 @@ struct BuiltKeymap { keymap: Arc, edit_chords: Arc<[(EditCommand, Chord)]>, window_shortcuts: Arc<[(WindowShortcut, Chord)]>, + /// The text of every chord the keymap shows, written once when the keymap is built. + shown_text: Arc>>, } /// The keymap of `defs` on `platform` under `overrides`. @@ -475,6 +517,19 @@ fn keymap_of(defs: Vec, scopes: Scopes, platform: Platform, override keymap } +#[cfg(feature = "testing")] +thread_local! { + static CHORD_TEXT_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many chord texts this thread's keymap builds have written: one per distinct shown chord per build, never one +/// per report. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn chord_text_builds() -> u64 { + CHORD_TEXT_BUILDS.with(std::cell::Cell::get) +} + #[cfg(feature = "testing")] thread_local! { static KEYMAP_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -558,7 +613,17 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.double).map(move |binding| (edit, binding.trigger.chord)) }) .collect(); - BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts } + let mut shown_text = HashMap::new(); + for def in keymap.catalog() { + if let Some(chord) = keymap.shown_chord(&def.command) { + shown_text.entry(chord).or_insert_with(|| { + #[cfg(feature = "testing")] + CHORD_TEXT_BUILDS.with(|builds| builds.set(builds.get() + 1)); + Arc::from(chord.display(platform)) + }); + } + } + BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts, shown_text: Arc::new(shown_text) } } /// The keymap of each shared registry (with or without the stories' sets) on each platform with no overrides. It @@ -596,7 +661,7 @@ pub(crate) fn innermost(ctx: &Context, chain: &CommandChain, scope: &str) -> Opt } /// The platform the keymap and the chords shown are read for. -pub(crate) fn platform(ctx: &Context) -> Platform { +fn platform(ctx: &Context) -> Platform { crate::runtime::windows::os_of(ctx) } @@ -630,9 +695,10 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { }); let mut shadowed = Vec::new(); if stale { - let BuiltKeymap { keymap, edit_chords, window_shortcuts } = + let BuiltKeymap { keymap, edit_chords, window_shortcuts, shown_text } = keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref()); - board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts }); + board.keymap = + Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text }); for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); @@ -699,15 +765,7 @@ fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_in(ctx, scope, id, layer)); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); - with(ctx, |board| match board.instances.iter_mut().find(|i| i.id == id) { - Some(instance) => { - instance.scope = scope; - instance.viewport = viewport; - instance.stamp = stamp; - instance.layer = layer; - } - None => board.instances.push(Instance { id, scope, viewport, stamp, layer }), - }); + with(ctx, |board| board.instances.upsert(Instance { id, scope, viewport, stamp, layer })); } /// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The @@ -731,14 +789,16 @@ pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) { pub(crate) fn set_modal_open(ctx: &Context, open: bool, viewport: ViewportId, root: Option) { with(ctx, |board| { board.here.modal_open = open; - board.modal_roots.retain(|(of, _)| *of != viewport); - board.modal_roots.extend(root.map(|root| (viewport, root))); + match root { + Some(root) => board.modal_roots.insert(viewport, root), + None => board.modal_roots.remove(&viewport), + }; }); } /// The root of the top modal layer of `viewport`, if one is open. pub(crate) fn modal_root(ctx: &Context, viewport: ViewportId) -> Option { - with(ctx, |board| board.modal_roots.iter().find(|(of, _)| *of == viewport).map(|(_, root)| *root)) + with(ctx, |board| board.modal_roots.get(&viewport).copied()) } /// Which instances a resolution counts as inside the top modal layer, where `ModalRule::InDialogs` and `Blocked` @@ -897,35 +957,35 @@ fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> /// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal /// layer it opened or closed), once. fn wake_shown(ctx: &Context, viewport: ViewportId) { - let mut shown = with(ctx, |board| std::mem::take(&mut board.shown)); + let mut table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default(); let mut changed = Vec::new(); - for ((key, of), readers) in &mut shown { - if *of != viewport { - continue; - } + for (key, readers) in &mut table { // A reader beneath a layer or inside a menu that is no longer shown is gone with it. - readers.retain(|entry| match entry.reader { - Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, layer), + readers.retain(|(reader, _)| match reader { + Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer), _ => true, }); - for entry in readers.iter_mut() { + for (reader, kept) in readers.iter_mut() { // The gate is app code and may resolve commands itself, so no board lock is held here. - let (resolved, _) = resolve_as(ctx, &entry.reader, &entry.resolved.command); - if resolved != entry.resolved { - entry.resolved = resolved; + let (resolved, _) = resolve_as(ctx, reader, &kept.command); + if resolved != *kept { + *kept = resolved; changed.push(*key); } } } - shown.retain(|_, readers| !readers.is_empty()); + table.retain(|_, readers| !readers.is_empty()); with(ctx, |board| { // Reads the gate made while the entries were out of the board. - let added = std::mem::replace(&mut board.shown, shown); - for ((key, of), readers) in added { - for entry in readers { - keep_shown(&mut board.shown, key, of, entry.reader, &entry.resolved); + let added = board.shown.remove(&viewport).unwrap_or_default(); + for (key, readers) in added { + for (reader, resolved) in readers { + keep_in(table.entry(key).or_default(), reader, &resolved); } } + if !table.is_empty() { + board.shown.insert(viewport, table); + } }); for (number, instance) in changed { lazy::note_edit(ctx, BindKey::Command(number, instance)); @@ -1197,8 +1257,8 @@ pub(crate) fn begin(ctx: &Context) { board.chains.get(&viewport).filter(|(id, _)| Some(*id) == focused).map(|(_, chain)| chain.ids().collect()).unwrap_or_default() }); // Nothing focused inside a modal: the modal's root takes the commands, as a plain Enter goes to its default button. - let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.iter().find(|(of, _)| *of == viewport)) { - (true, Some((_, root))) => vec![*root], + let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.get(&viewport)) { + (true, Some(root)) => vec![*root], _ => chain, }; if !chain.is_empty() { @@ -1218,7 +1278,7 @@ pub(crate) fn begin(ctx: &Context) { } let mut keys = board.key_scopes(&chain)?; // The held-open canvas's scope is around the focus for matching: its commands fire from the dialog. - let held_scope = held_open.and_then(|id| board.instances.iter().find(|i| i.id == id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope)); + let held_scope = held_open.and_then(|id| board.instances.get(id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope)); if let Some(scope) = held_scope && !keys.scopes.contains(&scope) { @@ -1295,7 +1355,7 @@ pub(crate) fn begin(ctx: &Context) { .iter() .filter(|fired| fired.phase == FirePhase::Press) .filter_map(|fired| fired.target) - .filter_map(|target| board.instances.iter().find(|instance| instance.id == target)?.layer) + .filter_map(|target| board.instances.get(target)?.layer) .collect() }); overlay::close_popups_outside(ctx, &inside); @@ -1313,18 +1373,22 @@ pub(crate) fn end(ctx: &Context) { let alive: Vec = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect(); let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); - let ids: Vec = board.instances.iter().map(|i| i.id).collect(); - board.queue.retain(|fired| fired.target.is_some_and(|id| ids.contains(&id))); - board.held.retain(|held| held.target.is_none_or(|id| ids.contains(&id))); + let instances = &board.instances; + let ids = |id: Id| instances.contains(id); + board.queue.retain(|fired| fired.target.is_some_and(ids)); + board.held.retain(|held| held.target.is_none_or(ids)); board.chains.retain(|viewport, _| live.contains(viewport)); board.before.retain(|viewport, _| live.contains(viewport)); board.here.focused.retain(|(viewport, _)| live.contains(viewport)); - board.shown.retain(|(_, viewport), readers| { - readers.retain(|entry| match &entry.reader { - Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(|id| ids.contains(&id)), - _ => true, + board.shown.retain(|viewport, table| { + table.retain(|_, readers| { + readers.retain(|(reader, _)| match reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids), + _ => true, + }); + !readers.is_empty() }); - live.contains(viewport) && !readers.is_empty() + live.contains(viewport) && !table.is_empty() }); }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 1570c4ae1..a4cf272e8 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -19,16 +19,16 @@ pub use registry::{SetEntry, sets}; pub use board::declare_child; #[doc(hidden)] pub use board::focus_within; -#[cfg(feature = "testing")] -#[doc(hidden)] -pub use board::keymap_builds; pub(crate) use board::publish as publish_for; pub(crate) use board::take as take_for_instance; pub(crate) use board::{ - begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_delivered, take_fired, window_shortcuts, + begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts, }; #[doc(hidden)] pub use board::{bound_around, take_around}; +#[cfg(feature = "testing")] +#[doc(hidden)] +pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; use craft_behavior::CommandFlags; @@ -261,6 +261,8 @@ pub struct ResolvedCommand { pub icon: Option>, /// The chord surfaces show: the first single-press binding that runs the command ([`chord`]). pub chord: Option, + /// `chord` as the platform writes it, from the table the keymap builds with its bindings. + pub chord_text: Option>, /// The state ANDed with the gate, the modal rule and the instance's liveness. pub enabled: bool, /// The checked state of a toggle or radio command. @@ -341,7 +343,7 @@ impl CommandInput { /// The chain of container instances that receive scoped commands, innermost last. A private inherited field of /// the env. #[doc(hidden)] -#[derive(Clone, Default, PartialEq, Eq)] +#[derive(Clone, Default, PartialEq, Eq, Hash)] pub struct CommandChain(Arc<[(CommandScope, Id)]>); impl CommandChain { diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 912f37b57..71e2cf685 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -285,6 +285,18 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) } +/// Counts a chord text an access report read for a node in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_chord_text(ctx: &Context) { + totals(ctx, |log| log.chord_texts += 1); +} + +/// The chord texts the access reports of the last pass read: one per command-bound node that exists. +#[cfg(feature = "testing")] +pub fn chord_texts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.chord_texts, 0) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { @@ -347,13 +359,14 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } -/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +/// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. #[cfg(feature = "testing")] #[derive(Default)] pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, + chord_texts: u32, asks: Vec<(&'static str, u32)>, } diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index 24d76a66d..dda5a9c5f 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -219,11 +219,10 @@ impl Component for FlyoutButton<'_, T> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let laid = self.resolve(cx); - let os = cx.env.shell().os; let face = cx.part(FACE, rect).priority(HitPriority::new(HitLevel::Body, 0)); if let Some(resolved) = self.lead(&laid) { - face.tooltip(match &resolved.chord { - Some(chord) => Label::from(format!("{} ({})", resolved.label, chord.display(os))), + face.tooltip(match &resolved.chord_text { + Some(chord) => Label::from(format!("{} ({chord})", resolved.label)), None => Label::Shared(resolved.label.clone()), }); } diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index 63dfc001e..d4bb19304 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,10 +1,11 @@ -use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Tap}; +use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap}; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft_ui::runtime::commands::{ - CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, fire, resolve, + CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve, }; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::frame::take_output; +use craft_ui::runtime::measure::chord_texts; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Frames, trial}; @@ -193,3 +194,59 @@ fn undo_in_a_dialog_reaches_the_dialog_and_not_the_application() { assert_eq!(undone.get(), 1, "the dialog took the undo"); assert!(take_output(&frames.ctx).fired.is_empty(), "the application's undo stays blocked"); } + +/// Count relation: an access report reads a chord text for each command-bound node that exists, at any number of nodes, +/// never for a component with no node, and writes none; the texts are written when the keymap is built. +#[trial] +fn access_reports_read_chord_texts_for_their_nodes_and_write_none() { + let mut frames = Frames::new(); + let mut built = 0; + for count in [6, 12] { + let mut show = |ui: &mut Ui| { + for salt in 0..count { + Tap::new().id_salt(salt).command(AppCommand::Save).show(ui); + } + Tap::new().id_salt("go").command(AppCommand::Go).show(ui); + Silent::new().id_salt("silent").command(AppCommand::Save).show(ui); + }; + frames.idle(3, &mut show); + if built == 0 { + built = chord_text_builds(); + } + frames.idle(3, &mut show); + assert_eq!(chord_text_builds(), built, "passes write no chord text"); + assert_eq!(chord_texts(&frames.ctx), count, "one read per node whose command has a chord, none for a component with no node"); + } +} + +/// An instance that stops registering and registers again goes last in registration order, which a non-component +/// source's pick follows (the first live instance); lookups by id stay right throughout. +#[trial] +fn a_re_registered_instance_goes_last_in_the_pick() { + let a_shown = Cell::new(true); + let taker = Cell::new(""); + let mut show = |ui: &mut Ui| { + for name in ["a", "b", "c"] { + if name == "a" && !a_shown.get() { + continue; + } + super::kit::Pane::new().id_salt(name).show(ui, |_, cx| { + if cx.take_command::().is_some() { + taker.set(name); + } + }); + } + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette)); + frames.idle(2, &mut show); + assert_eq!(taker.get(), "a", "registered first"); + a_shown.set(false); + frames.idle(3, &mut show); + a_shown.set(true); + frames.idle(3, &mut show); + assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette)); + frames.idle(2, &mut show); + assert_eq!(taker.get(), "b", "a registered again after b and c"); +} diff --git a/crates/ui-shell/tests/it/commands/kit.rs b/crates/ui-shell/tests/it/commands/kit.rs index 0530f8cd4..551c77024 100644 --- a/crates/ui-shell/tests/it/commands/kit.rs +++ b/crates/ui-shell/tests/it/commands/kit.rs @@ -89,6 +89,37 @@ impl Component for Tap<'_> { } } +/// A `Tap` whose role gives it no access node. +#[derive(Component)] +pub struct Silent { + #[common] + common: Common, +} + +impl Silent { + pub fn new() -> Self { + Silent { common: Common::new() } + } +} + +impl Component for Silent { + const ROLE: Role = Role::None; + type Style = FixedStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: SilentStyleKey) -> FixedStyle { + FixedStyle::default() + } + + fn measure(&mut self, _: &craft_ui::contract::MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(40.0, 20.0) + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + /// A container that is an instance of the `trial.pane` scope. #[derive(Component)] #[component(container)] From 0c076f890be0bfd5447563b9fc7a47e040df4077 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:19:37 +0100 Subject: [PATCH 26/29] ui-contract: record steps only inside an inspected region --- crates/ui-contract/src/contract/run.rs | 2 +- crates/ui-contract/src/runtime/inspect.rs | 20 ++++++++----------- crates/ui-contract/src/testing/contract.rs | 3 ++- crates/ui-contract/tests/it/contract/fixes.rs | 11 ++++++---- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 95a70b207..38c39078b 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -952,7 +952,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e if checking_parts && !declares_parts && !steps::declares_none(&parts) { crate::testing::contract::bad_parts(facts.name); } - if facts.canvas_control && p.trace.recording() { + if facts.canvas_control && !ui.is_sizing_pass() { inspect::canvas_control(&ctx, facts.name); } steps::check_parts(&ctx, facts.name, &parts); diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index d74c99414..07ae009fd 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -1,5 +1,5 @@ -//! Decision records and findings: what each pipeline step did, kept in frames a test fixture drives and inside an -//! inspected region ([`record`]). The region's record is what the debug inspector draws: every component shown in it +//! Decision records and findings. Inspected regions ([`record`]) collect pipeline steps. Fixture frames also collect +//! contract findings. The region's record is what the debug inspector draws: every component shown in it //! with its box and access facts, the hit areas the sensing core registered and the focus stops in Tab order. use crate::runtime::egui::areas; @@ -35,9 +35,9 @@ pub(crate) struct Log { kept: IdMap, } -/// Whether records are kept: in frames a test fixture drives, and inside an inspected region in any build. +/// Whether an explicit inspector region is collecting elements and their pipeline steps. pub(crate) fn recording(ctx: &Context) -> bool { - fixture_frame() || pass_state::with::(ctx, |log| !log.open.is_empty()) + pass_state::with::(ctx, |log| !log.open.is_empty()) } #[cfg(feature = "testing")] @@ -50,16 +50,12 @@ fn fixture_frame() -> bool { /// Starts the step record of `id` for a new show. pub(crate) fn begin(ctx: &Context, id: Id) { - if recording(ctx) { - pass_state::with::(ctx, |log| log.steps.insert(id, Vec::new())); - } + pass_state::with::(ctx, |log| log.steps.insert(id, Vec::new())); } /// Records that `step` ran for `id`. pub(crate) fn step(ctx: &Context, id: Id, step: &'static str) { - if recording(ctx) { - pass_state::with::(ctx, |log| log.steps.entry(id).or_default().push(step)); - } + pass_state::with::(ctx, |log| log.steps.entry(id).or_default().push(step)); } /// The steps the latest show of `id` ran, in order. @@ -70,7 +66,7 @@ pub(crate) fn steps_of(ctx: &Context, id: Id) -> Vec<&'static str> { /// Reports a finding. pub(crate) fn finding(ctx: &Context, finding: Finding) { - if !recording(ctx) { + if !fixture_frame() && !recording(ctx) { return; } pass_state::with::(ctx, |log| { @@ -89,7 +85,7 @@ pub(crate) fn findings(ctx: &Context) -> Vec { /// Records that the canvas control `type_name` showed in this pass, so the canvas-control cases can check that a /// press away from its parts reaches the tool. pub(crate) fn canvas_control(ctx: &Context, type_name: &'static str) { - if !recording(ctx) { + if !fixture_frame() && !recording(ctx) { return; } pass_state::with::(ctx, |log| { diff --git a/crates/ui-contract/src/testing/contract.rs b/crates/ui-contract/src/testing/contract.rs index d5631f3df..ee978c6af 100644 --- a/crates/ui-contract/src/testing/contract.rs +++ b/crates/ui-contract/src/testing/contract.rs @@ -3,7 +3,8 @@ use crate::runtime::inspect::{self, Finding}; use egui::{Context, Id}; -/// The steps the latest show of `id` ran, in order. +/// The steps the latest inspected show of `id` ran, in order. Wrap the show in +/// [`crate::runtime::inspect::record`] to collect its steps. pub fn steps(ctx: &Context, id: Id) -> Vec<&'static str> { inspect::steps_of(ctx, id) } diff --git a/crates/ui-contract/tests/it/contract/fixes.rs b/crates/ui-contract/tests/it/contract/fixes.rs index 1084dba64..cd8338733 100644 --- a/crates/ui-contract/tests/it/contract/fixes.rs +++ b/crates/ui-contract/tests/it/contract/fixes.rs @@ -216,17 +216,20 @@ fn a_style_value_set_in_content_env_changes_a_body_childs_style() { assert!(inside > outside, "the body's child read the body's value: {outside} -> {inside}"); } -/// The step log, a record only trials and the debug inspector read, is kept in frames a test fixture drives; a frame -/// an app drives itself, such as the gallery's, keeps none. +/// A fixture pays for pipeline step records only when the caller inspects a region. #[trial] -fn the_step_log_is_kept_in_fixture_frames_only() { +fn the_step_log_is_kept_only_for_an_inspected_region() { let mut fixture = Frames::new(); let seen = RefCell::new(Seen::default()); fixture.frame(Vec::new(), |ui| { Probe::new(&seen).show(ui); }); let id = seen.borrow().id.expect("the probe ran"); - assert!(!steps(&fixture.ctx, id).is_empty(), "a fixture frame records the probe's steps"); + assert!(steps(&fixture.ctx, id).is_empty(), "an ordinary fixture frame has no step log"); + fixture.frame(Vec::new(), |ui| { + craft_ui::runtime::inspect::record(ui, egui::Id::unique("inspect probe"), |ui| Probe::new(&seen).show(ui)); + }); + assert!(!steps(&fixture.ctx, seen.borrow().id.expect("the inspected probe ran")).is_empty()); let app = Frames::new(); let seen = RefCell::new(Seen::default()); From 50812ec37cb2453a6b1d175ada33c39cad7f726a Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:58:09 +0100 Subject: [PATCH 27/29] Use the declarations slice for the suite assertion --- crates/ui-contract/src/contract/cx/parts.rs | 4 ---- crates/ui-contract/src/contract/steps/parts.rs | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/ui-contract/src/contract/cx/parts.rs b/crates/ui-contract/src/contract/cx/parts.rs index 61c358b8b..50b702c77 100644 --- a/crates/ui-contract/src/contract/cx/parts.rs +++ b/crates/ui-contract/src/contract/cx/parts.rs @@ -52,10 +52,6 @@ impl Decls { &self.parts } - pub(crate) fn is_empty(&self) -> bool { - self.parts.is_empty() - } - pub(crate) fn iter(&self) -> std::iter::Zip, std::slice::Iter<'_, PartExtras>> { self.parts.iter().zip(&self.extras) } diff --git a/crates/ui-contract/src/contract/steps/parts.rs b/crates/ui-contract/src/contract/steps/parts.rs index f09043f22..4e1dc0e0d 100644 --- a/crates/ui-contract/src/contract/steps/parts.rs +++ b/crates/ui-contract/src/contract/steps/parts.rs @@ -16,7 +16,7 @@ pub(crate) struct PartsStep { /// Whether step 7 declared no parts, no roving group, no scroll part and no text, editor or selection part. #[cfg(feature = "testing")] pub(crate) fn declares_none(parts: &PartsStep) -> bool { - parts.decls.is_empty() + parts.decls.parts().is_empty() && parts.rovings.is_empty() && parts.scrolls.is_empty() && parts.text.decl.is_none() From 448e8d4bfca8ffeed8547f97668b02844ddaa28e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 14:44:36 +0100 Subject: [PATCH 28/29] Test parts declaration guard and inspector focus order --- crates/ui-contract/src/testing/contract.rs | 10 +-- crates/ui-contract/tests/it/contract/fixes.rs | 87 ++++++++++++++++++- 2 files changed, 89 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/testing/contract.rs b/crates/ui-contract/src/testing/contract.rs index ee978c6af..4daf52d18 100644 --- a/crates/ui-contract/src/testing/contract.rs +++ b/crates/ui-contract/src/testing/contract.rs @@ -55,15 +55,15 @@ thread_local! { } /// Run a story with the parts declaration check enabled, and return any offending component types. -pub(crate) fn check_parts_declarations(run: impl FnOnce()) -> Vec<&'static str> { - struct Reset; +pub fn check_parts_declarations(run: impl FnOnce()) -> Vec<&'static str> { + struct Reset(Option>); impl Drop for Reset { fn drop(&mut self) { - PARTS_CHECK.with(|check| *check.borrow_mut() = None); + PARTS_CHECK.with(|check| *check.borrow_mut() = self.0.take()); } } - PARTS_CHECK.with(|check| *check.borrow_mut() = Some(Vec::new())); - let _reset = Reset; + let previous = PARTS_CHECK.with(|check| check.replace(Some(Vec::new()))); + let _reset = Reset(previous); run(); PARTS_CHECK.with(|check| check.borrow_mut().take().unwrap_or_default()) } diff --git a/crates/ui-contract/tests/it/contract/fixes.rs b/crates/ui-contract/tests/it/contract/fixes.rs index cd8338733..dccd6512b 100644 --- a/crates/ui-contract/tests/it/contract/fixes.rs +++ b/crates/ui-contract/tests/it/contract/fixes.rs @@ -247,6 +247,7 @@ struct NoParts<'a> { #[common] common: Common, calls: &'a std::cell::Cell, + declare: bool, } impl Component for NoParts<'_> { @@ -256,11 +257,14 @@ impl Component for NoParts<'_> { type Output = Response; fn style(_: &StyleCx<'_>, _: NoPartsStyleKey) -> PlainStyle { - PlainStyle::default() + PlainStyle::min(Vec2::splat(20.0)) } - fn parts(&mut self, _: Rect, _: &mut PartsCx<'_, Self>) { + fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { self.calls.set(self.calls.get() + 1); + if self.declare { + cx.part(craft_behavior::PartKey::new("unexpected"), rect); + } } fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {} @@ -275,7 +279,84 @@ fn a_component_declaring_no_parts_skips_the_parts_hook() { let mut frames = Frames::new(); let calls = std::cell::Cell::new(0); frames.frame(vec![], |ui| { - NoParts { common: Common::new(), calls: &calls }.show(ui); + NoParts { common: Common::new(), calls: &calls, declare: false }.show(ui); }); assert_eq!(calls.get(), 0, "the parts hook is skipped on ordinary runs"); } + +#[trial] +fn parts_declaration_checks_report_bad_components_and_restore_nested_checks() { + use craft_ui::testing::contract::check_parts_declarations; + let calls = std::cell::Cell::new(0); + let show = || { + Frames::new().frame(vec![], |ui| { + NoParts { common: Common::new(), calls: &calls, declare: true }.show(ui); + }); + }; + let outer = check_parts_declarations(|| { + show(); + let inner = check_parts_declarations(show); + assert!(inner.iter().any(|name| name.contains("NoParts")), "{inner:?}"); + show(); + }); + assert!(outer.len() >= 2 && outer.iter().all(|name| name.contains("NoParts")), "{outer:?}"); + + let panic = std::panic::catch_unwind(|| check_parts_declarations(|| panic!("guard test"))); + assert!(panic.is_err()); + let before = calls.get(); + show(); + assert_eq!(calls.get(), before, "the check is disabled after unwinding"); +} + +#[derive(Component)] +struct FocusParts { + #[common] + common: Common, +} + +impl Component for FocusParts { + const ROLE: Role = Role::None; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: FocusPartsStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::splat(20.0)) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { + cx.part(craft_behavior::PartKey::new("first"), rect).focusable(); + cx.part(craft_behavior::PartKey::new("second"), rect).focusable(); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn inspector_places_synthetic_focus_parts_after_each_owner() { + let mut frames = Frames::new(); + let mut recorded = None; + let mut ids = Vec::new(); + frames.frame(vec![], |ui| { + let (shown, record) = craft_ui::runtime::inspect::record(ui, named_id("focus-region"), |ui| { + ["one", "two"].map(|salt| FocusParts { common: Common::new() }.id_salt(salt).show(ui).id) + }); + ids = shown.to_vec(); + recorded = record; + }); + let record = recorded.expect("real pass was recorded"); + let mut stops = Vec::new(); + for id in ids { + let owner = record.elements.iter().position(|element| element.id == id && element.part.is_none()).unwrap(); + let parts = &record.elements[owner + 1..owner + 3]; + assert!(parts.iter().all(|part| part.id == id && part.part.is_some() && part.facts.is_none()), "{parts:?}"); + stops.extend(parts.iter().map(|part| part.stop.expect("part is a focus stop"))); + } + stops.sort_unstable(); + assert_eq!(stops, [1, 2, 3, 4]); +} From 2287e9f3d17d59784718b89f0166eb06040f742e Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 14:59:11 +0000 Subject: [PATCH 29/29] design-lint: bind_tracked!'s own definition is not a call of __split_for_bind --- crates/design-lint/src/contract/global_state.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/design-lint/src/contract/global_state.rs b/crates/design-lint/src/contract/global_state.rs index 1da609cd7..75208f2ec 100644 --- a/crates/design-lint/src/contract/global_state.rs +++ b/crates/design-lint/src/contract/global_state.rs @@ -24,8 +24,10 @@ const PATH_FS: [&str; 2] = ["std", "fs"]; const PLAIN_DATA: &str = "contract/no-global-state:plain-data"; const PROJECTION: &str = "contract/no-global-state:projection"; -/// The hidden `Tracked::__split_for_bind`, called only by `bind_tracked!`; the lint reads source before macro expansion, so every textual hit is a direct call. +/// The hidden `Tracked::__split_for_bind`, called only by `bind_tracked!`; the lint reads source before macro expansion, so every textual hit outside its definition is a direct call. const SPLIT_FOR_BIND: &str = "__split_for_bind"; +/// The macro that calls [`SPLIT_FOR_BIND`]; its definition is not a call site. +const BIND_TRACKED: &str = "bind_tracked"; struct Hits { found: Vec<(proc_macro2::Span, String, String)>, @@ -110,6 +112,10 @@ impl Visit<'_> for Hits { } fn visit_item_macro(&mut self, node: &ItemMacro) { + // `bind_tracked!`'s own definition is the one place that names the hidden call. + if node.mac.path.is_ident("macro_rules") && node.ident.as_ref().is_some_and(|i| i == BIND_TRACKED) { + return; + } self.macro_path(&node.mac); visit::visit_item_macro(self, node); }