Merge remote-tracking branch 'upstream/next' into memo-records

# Conflicts:
#	crates/ui-contract/src/runtime/commands/mod.rs
This commit is contained in:
aiongg committed 2026-11-19 17:43:02 +00:00
commit 4f697dbc70
82 files changed
+3164 -238

No files matched your search

Generated
+11
View File
@@ -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",
@@ -4209,6 +4218,8 @@ dependencies = [
"log",
"proc-macro2",
"serde",
"serde_json",
"siphasher",
"skrifa 0.44.0",
"smallvec",
"syn 2.0.119",
+1
View File
@@ -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" }
+1 -1
View File
@@ -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.
+31 -7
View File
@@ -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<Pos2>,
/// 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<Pos2>),
@@ -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<Pos2>, 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<Pos2>, 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);
}
}
}
+4 -4
View File
@@ -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) {
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 {
+3
View File
@@ -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 }
@@ -845,6 +846,8 @@ 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"]
+2
View File
@@ -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")]
+1
View File
@@ -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` 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.
@@ -0,0 +1,212 @@
//! `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";
/// 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.
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 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)>,
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<String>) {
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<proc_macro2::Span>) {
for token in tokens {
match token {
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),
_ => {}
}
}
}
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<String>, out: &mut Vec<(proc_macro2::Span, Vec<String>)>) {
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),
node.ident.to_string(),
));
visit::visit_item_static(self, node);
}
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);
}
fn visit_stmt_macro(&mut self, node: &syn::StmtMacro) {
self.macro_path(&node.mac);
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, FS_MESSAGE.to_owned(), FS.to_owned()));
}
}
visit::visit_item_use(self, node);
}
fn visit_ident(&mut self, node: &proc_macro2::Ident) {
if node == SPLIT_FOR_BIND {
self.projection.push((node.span(), format!("`{SPLIT_FOR_BIND}` is called by `bind_tracked!` 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!("`{SPLIT_FOR_BIND}` is called by `bind_tracked!` only")));
}
visit::visit_macro(self, node);
}
fn visit_path(&mut self, node: &SynPath) {
let names: Vec<String> = node.segments.iter().map(|s| s.ident.to_string()).collect();
if names_fs(&names) {
self.found.push((node.segments[0].ident.span(), FS_MESSAGE.to_owned(), FS.to_owned()));
}
visit::visit_path(self, node);
}
fn visit_item_impl(&mut self, node: &ItemImpl) {
if let Some((_, path, _)) = &node.trait_
&& let Some(name) = path.segments.last().map(|s| s.ident.to_string()).filter(|n| n == "MemoProps" || n == "PlainData")
{
let message = format!("`{name}` is implemented by the derive only");
if name == "MemoProps" {
self.found.push((node.impl_token.span, message, name));
} else {
self.derive_only.push((node.impl_token.span, message));
}
}
visit::visit_item_impl(self, node);
}
}
impl Hits {
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")
{
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,
));
}
}
}
}
pub(super) fn check(cx: &Cx<'_>, out: &mut Vec<Finding>) {
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(), derive_only: Vec::new(), projection: Vec::new() };
hits.visit_file(cx.file);
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);
}
for (span, message) in hits.projection {
cx.flag_span(out, ID, PROJECTION, span, message);
}
}
+6 -2
View File
@@ -10,6 +10,8 @@ mod egui_import;
mod egui_widget;
mod entry;
mod facts;
mod global_state;
pub(crate) use global_state::FS;
mod keys;
mod layers;
mod memory;
@@ -39,7 +41,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 +81,13 @@ pub(crate) const IDS: [&str; 39] = [
shape::OVERLAY_FLAG,
shape::REGISTRATION,
unsafe_allow::ID,
global_state::ID,
];
type Check = fn(&Cx<'_>, &mut Vec<Finding>);
/// 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 +109,7 @@ const REGISTRY: [Check; 21] = [
entry::check,
shape::check,
unsafe_allow::check,
global_state::check,
];
/// One file as the rules see it.
+8 -2
View File
@@ -16,12 +16,18 @@ pub(super) fn check(cx: &Cx<'_>, out: &mut Vec<Finding>) {
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("::")),
);
}
}
}
+114 -1
View File
@@ -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,6 +120,99 @@ fn places(key: &str) -> Vec<Place> {
}
}
/// 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)] = &[
// 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"),
("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/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", "APPS"),
// Settled fact: the thumbnail texture cache, keyed by its content.
("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", "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", "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", FS),
// Settled fact: the fallback text format, computed once from constants and immutable after init.
("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", "IDENTITY"),
// Settled fact: the default layer-style draft and its preview paint, computed once from constants.
("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", FS),
// later task of #2336: the dock node id counter is hidden state.
("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", "NEXT_ID"),
// later task of #2336: the outline hover generation counter is hidden state.
("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", "SERIAL"),
// later task of #2336: the mock image read cache is hidden state.
("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", "CACHE"),
// later task of #2336: the face loader reads file sizes during the pass.
("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", "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",
];
/// 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 {
name: String,
dir: PathBuf,
@@ -287,6 +380,12 @@ 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 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"));
}
@@ -336,6 +435,20 @@ 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 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");
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(","))
}
+25 -2
View File
@@ -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,25 @@ 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`,
// 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();
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(), 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}");
}
}
+2 -1
View File
@@ -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"),
@@ -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<u32> = std::sync::Mutex::new(0);
}
@@ -0,0 +1,26 @@
use std::cell::RefCell;
use std::fs;
use std::sync::{Mutex, OnceLock};
static COUNTER: Mutex<u32> = Mutex::new(0);
static mut RAW: u32 = 0;
static CACHE: OnceLock<String> = OnceLock::new();
thread_local! {
static LOCAL: RefCell<u32> = const { RefCell::new(0) };
}
struct Props;
impl MemoProps for Props {}
impl PlainData for Props {}
fn project() -> Tracked {
Tracked::__split_for_bind(&[])
}
fn read(path: &str) -> Vec<u8> {
static INNER: Mutex<u32> = Mutex::new(0);
std::fs::read(path).unwrap_or_default()
}
@@ -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;
@@ -0,0 +1,3 @@
fn f(cell: &std::sync::OnceLock<std::time::Instant>) -> std::time::Instant {
*cell.get_or_init(std::time::Instant::now)
}
+19 -9
View File
@@ -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,14 +71,14 @@ 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. A press on an anchor or a shown handle selects and drags it as
/// [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it alone), and a click on empty canvas
/// deselects the anchors and keeps the path. With ⌥ a click on a segment selects its whole subpath and a drag moves a
/// copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on
/// an anchor does nothing. Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+";
/// over an anchor the arrow; with ⌥ no mark and the arrow with "+"; 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. A press on an anchor or a shown
/// handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it
/// alone), and a click on empty canvas deselects the anchors and keeps the path. With ⌥ a click on a segment selects
/// its whole subpath and a drag moves a copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that
/// takes no copies), and a press on an anchor does nothing. Hover: the segment mark with the anchor a click adds
/// ([`HitMark`]) and the pen with "+"; over an anchor the arrow; with ⌥ no mark and the arrow with "+"; 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.
@@ -508,13 +513,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,
@@ -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)]
+57
View File
@@ -919,6 +919,63 @@ fn add_anchor_selects_and_edits_existing_anchors_and_handles() {
}
}
// 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 (with "+" under ⌥, PhotoCraft #12709), the pen
// with "-" for Delete Anchor, the Convert Point icon, the arrow for Direct Selection and under ⌘, the crosshair when
+1 -1
View File
@@ -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 };
+1 -1
View File
@@ -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) {
+1 -1
View File
@@ -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<Catalog>, Arc<Catalog>);
+1 -1
View File
@@ -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<R>(ui: &mut Ui, dark: bool, mut content: impl FnMut(&mut Ui) -> R) -> Option<R> {
+1 -1
View File
@@ -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) {
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -135,7 +135,7 @@ const TRACKING_RANGE: RangeInclusive<f64> = -1000.0..=10000.0;
/// The range of the scale fields, percent.
const SCALE_RANGE: RangeInclusive<f64> = 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")]
+17
View File
@@ -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<T>: 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 }
+378
View File
@@ -0,0 +1,378 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
//! `Tracked<T>`: 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<T>`: [`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.
//!
//! ```
//! 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<Node> },
//! }
//!
//! let tree = Tracked::new(Node::Group { name: "root".into(), children: vec![Node::Leaf("a".into())] });
//! # 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<T> {
//! value: T,
//! children: Vec<Tree<T>>,
//! }
//!
//! #[derive(PlainData)]
//! struct List {
//! name: String,
//! next: Option<Box<Self>>,
//! }
//!
//! #[derive(PlainData)]
//! struct Id<T> {
//! raw: u64,
//! kind: PhantomData<T>,
//! }
//!
//! 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::<List> { 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:
//!
//! - **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. 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;
//! 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<T>`, 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::<u32>::new());
//! ```
//!
//! ```compile_fail,E0277
//! let _ = craft_tracked::Tracked::new(std::ptr::null::<u8>());
//! ```
//!
//! ```compile_fail,E0277
//! let _ = craft_tracked::Tracked::new(Box::new(|| 1) as Box<dyn Fn() -> 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<u32>,
//! }
//! ```
//!
//! 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<T> {
//! hits: std::cell::Cell<T>,
//! }
//! ```
//!
//! A generic derived type used with a rejected parameter:
//!
//! ```compile_fail,E0277
//! #[derive(craft_ui_macros::PlainData)]
//! struct Wrap<T>(T);
//! let _ = craft_tracked::Tracked::new(Wrap(std::cell::Cell::new(1)));
//! ```
//!
//! An `assume` without a reason (the derive reports it with `compile_error!`, which has no error code):
//!
//! ```compile_fail
//! #[derive(craft_ui_macros::PlainData)]
//! struct Panel {
//! #[plain_data(assume = "")]
//! rect: std::cell::Cell<u32>,
//! }
//! ```
// 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};
/// 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<T: PlainData + ?Sized> PlainData for &T {}
impl<T: PlainData + ?Sized> PlainData for Box<T> {}
impl<T: PlainData + ?Sized> PlainData for std::sync::Arc<T> {}
impl<T: PlainData + ?Sized> PlainData for std::rc::Rc<T> {}
impl<B: PlainData + ToOwned + ?Sized> PlainData for std::borrow::Cow<'_, B> where B::Owned: PlainData {}
impl<T: PlainData> PlainData for Option<T> {}
impl<T: PlainData, E: PlainData> PlainData for Result<T, E> {}
impl<T: PlainData> PlainData for Vec<T> {}
impl<T: PlainData> PlainData for [T] {}
impl<T: PlainData, const N: usize> PlainData for [T; N] {}
impl<T: PlainData> PlainData for std::ops::Range<T> {}
impl<T: PlainData> PlainData for std::ops::RangeInclusive<T> {}
impl<T: PlainData> PlainData for std::collections::VecDeque<T> {}
impl<T: PlainData> PlainData for std::collections::BinaryHeap<T> {}
impl<K: PlainData, V: PlainData, S: PlainData> PlainData for std::collections::HashMap<K, V, S> {}
impl<K: PlainData, S: PlainData> PlainData for std::collections::HashSet<K, S> {}
impl<K: PlainData, V: PlainData> PlainData for std::collections::BTreeMap<K, V> {}
impl<K: PlainData> PlainData for std::collections::BTreeSet<K> {}
impl<H> PlainData for std::hash::BuildHasherDefault<H> {}
impl<T: ?Sized> PlainData for std::marker::PhantomData<T> {}
impl<T: PlainData> PlainData for Tracked<T> {}
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` 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)]
pub struct Tracked<T: PlainData> {
value: T,
revision: Revision,
}
impl<T: PlainData + Default> Default for Tracked<T> {
fn default() -> Tracked<T> {
Tracked::new(T::default())
}
}
impl<T: PlainData> Tracked<T> {
/// `value`, as a new source at count 0.
pub fn new(value: T) -> Tracked<T> {
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<R>(&mut self, f: impl FnOnce(&mut T) -> R) -> R {
f(&mut **self)
}
/// 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<u64>) {
(&mut self.value, Cell::from_mut(&mut self.revision.count))
}
/// The value, leaving the tracking.
pub fn into_inner(self) -> T {
self.value
}
}
impl<T: PlainData + Clone> Clone for Tracked<T> {
fn clone(&self) -> Tracked<T> {
Tracked::new(self.value.clone())
}
}
impl<T: PlainData> Deref for Tracked<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T: PlainData> DerefMut for Tracked<T> {
fn deref_mut(&mut self) -> &mut T {
self.revision.count = self.revision.count.wrapping_add(1);
&mut self.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");
assert_eq!(doc.size.1, 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");
assert_eq!((doc.size, doc.name.as_str()), ((3, 2), "ab"));
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");
}
}
@@ -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);
+6
View File
@@ -34,6 +34,12 @@ 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 }
# `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 }
@@ -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<'_, PartDecl>, std::slice::Iter<'_, PartExtras>> {
self.parts.iter().zip(&self.extras)
}
+1 -1
View File
@@ -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.
+826
View File
@@ -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<T>` (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<u32>,
//! }
//! ```
//!
//! ```compile_fail,E0277
//! # extern crate craft_ui_contract as craft_ui;
//! #[derive(craft_ui::contract::MemoProps)]
//! struct Props<'a> {
//! count: &'a std::cell::RefCell<u32>,
//! }
//! ```
//!
//! ```compile_fail,E0277
//! # extern crate craft_ui_contract as craft_ui;
//! #[derive(craft_ui::contract::MemoProps)]
//! struct Props {
//! name: std::cell::OnceCell<String>,
//! }
//! ```
//!
//! ```compile_fail,E0277
//! # extern crate craft_ui_contract as craft_ui;
//! #[derive(craft_ui::contract::MemoProps)]
//! struct Props {
//! name: std::sync::OnceLock<String>,
//! }
//! ```
//!
//! ```compile_fail,E0277
//! # extern crate craft_ui_contract as craft_ui;
//! #[derive(craft_ui::contract::MemoProps)]
//! struct Props {
//! count: std::sync::Mutex<u32>,
//! }
//! ```
//!
//! ```compile_fail,E0277
//! # extern crate craft_ui_contract as craft_ui;
//! #[derive(craft_ui::contract::MemoProps)]
//! struct Props {
//! count: std::sync::RwLock<u32>,
//! }
//! ```
//!
//! ```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<dyn Fn() -> 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<F> {
//! 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<T> {
//! 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<u32>),
//! }
//! ```
//!
//! 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<u8>,
//! }
//! ```
//!
//! ```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<u32>,
//! }
//! ```
//!
//! 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<E>,
//! }
//! 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<E: 'static> {
//! english: Stateless<E>,
//! }
//! 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<Node>),
//! }
//! 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<T>` 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<T>`, 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<P: MemoProps + ?Sized>(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<T: Hash + Sync + ?Sized>(&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<T: ?Sized> MemoProps for PhantomData<T> {
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<B: MemoProps + ToOwned + ?Sized> MemoProps for Cow<'_, B> {
fn key(&self, key: &mut MemoKey) {
(**self).key(key);
}
}
impl<T: MemoProps + ?Sized> MemoProps for &T {
fn key(&self, key: &mut MemoKey) {
(**self).key(key);
}
}
impl<T: MemoProps + ?Sized> MemoProps for Box<T> {
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<T: MemoProps + ?Sized> MemoProps for Rc<T> {
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<T: MemoProps + ?Sized> MemoProps for Arc<T> {
fn key(&self, key: &mut MemoKey) {
(**self).key(key);
}
}
impl<T: MemoProps> MemoProps for Option<T> {
fn key(&self, key: &mut MemoKey) {
match self {
None => key.write(&[0]),
Some(value) => {
key.write(&[1]);
value.key(key);
}
}
}
}
impl<T: MemoProps, E: MemoProps> MemoProps for Result<T, E> {
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<T: MemoProps> MemoProps for Range<T> {
fn key(&self, key: &mut MemoKey) {
let Range { start, end } = self;
start.key(key);
end.key(key);
}
}
impl<T: MemoProps + PartialOrd> MemoProps for RangeInclusive<T> {
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<T: MemoProps> MemoProps for [T] {
fn key(&self, key: &mut MemoKey) {
key.write_len(self.len());
for value in self {
value.key(key);
}
}
}
impl<T: MemoProps, const N: usize> MemoProps for [T; N] {
fn key(&self, key: &mut MemoKey) {
self.as_slice().key(key);
}
}
impl<T: MemoProps> MemoProps for Vec<T> {
fn key(&self, key: &mut MemoKey) {
self.as_slice().key(key);
}
}
impl<K: MemoProps, V: MemoProps> MemoProps for BTreeMap<K, V> {
fn key(&self, key: &mut MemoKey) {
key.write_len(self.len());
for (k, v) in self {
k.key(key);
v.key(key);
}
}
}
impl<T: MemoProps> MemoProps for BTreeSet<T> {
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<T: PlainData> MemoProps for Tracked<T> {
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>(F);
impl<F: Copy + 'static> Stateless<F> {
/// `f` as a prop; `f` must capture nothing.
pub const fn new(f: F) -> Stateless<F> {
const { assert!(size_of::<F>() == 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<F> std::fmt::Debug for Stateless<F> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(std::any::type_name::<F>())
}
}
impl<F: 'static> MemoProps for Stateless<F> {
fn key(&self, key: &mut MemoKey) {
key.feed_hash(&TypeId::of::<F>());
}
}
// 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());
}
}
+5 -1
View File
@@ -20,6 +20,7 @@ mod level;
#[cfg(feature = "testing")]
mod level_table;
mod looks;
mod memo;
mod mount;
pub mod overlay;
mod pages;
@@ -38,6 +39,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 +68,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::{PlainData, Revision, Tracked};
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
#[doc(hidden)]
pub use cx::THUMB;
pub use cx::{
@@ -90,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;
@@ -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,
+10 -4
View File
@@ -939,16 +939,22 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, 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);
}
if facts.canvas_control && p.trace.recording() {
#[cfg(feature = "testing")]
if checking_parts && !declares_parts && !steps::declares_none(&parts) {
crate::testing::contract::bad_parts(facts.name);
}
if facts.canvas_control && !ui.is_sizing_pass() {
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);
+3 -1
View File
@@ -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")]
@@ -27,6 +27,8 @@ pub(crate) fn measure_content<C: Component>(
value: Option<&ValueOf<C>>,
) -> (Vec2, Inputs) {
let cx = measure_cx::<C>(input, style, resolved, value);
#[cfg(feature = "testing")]
crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::<C>());
layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx))
}
@@ -14,8 +14,9 @@ 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()
+39 -33
View File
@@ -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<String>) {
(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() {
+84 -1
View File
@@ -8,6 +8,7 @@ use craft_behavior::{Applied, CanvasView, EditEvent, EditEvents, EditPolicy, Mix
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.
@@ -106,6 +107,9 @@ enum Source<'a, T> {
Mut(&'a mut T),
/// Write-through for a multi-selection field.
MutMixed(&'a mut Mixed<T>),
/// 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<u64> },
/// No caller value: session memory under the component id, or the saved tier.
Kept,
}
@@ -136,6 +140,13 @@ impl<'a, T: Value> Bind<'a, T> {
Self::from_source(Source::MutMixed(v))
}
/// 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<u64>) -> 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
/// as the [`reset`](Self::reset) value when one is given, else as nothing.
pub fn kept() -> Self {
@@ -188,6 +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 { 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<Check<'_, T>>);
@@ -211,6 +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 { value, .. } => **value == *shown,
_ => false,
}
}
@@ -221,6 +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 { 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() }
@@ -237,6 +251,7 @@ enum SourceMut<'a, T> {
Given(&'a Mixed<T>),
Mut(&'a mut T),
MutMixed(&'a mut Mixed<T>),
Tracked { value: &'a mut T, count: &'a Cell<u64> },
Kept,
}
@@ -258,6 +273,7 @@ impl<T: Value> BindMut<'_, T> {
SourceMut::Given(value) => Some((*value).clone()),
SourceMut::Mut(value) => Some(Mixed::Same((**value).clone())),
SourceMut::MutMixed(value) => Some((**value).clone()),
SourceMut::Tracked { value, .. } => Some(Mixed::Same((**value).clone())),
SourceMut::Kept => None,
}
}
@@ -269,6 +285,7 @@ impl<T: Value> BindMut<'_, T> {
SourceMut::Given(_) => None,
SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::<T>(value) as usize, TypeId::of::<T>())),
SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::<Mixed<T>>(value) as usize, TypeId::of::<Mixed<T>>())),
SourceMut::Tracked { value, .. } => Some(BindKey::Place(std::ptr::from_ref::<T>(value) as usize, TypeId::of::<T>())),
SourceMut::Kept => Some(match self.save {
Some(save) => BindKey::Saved(Id::NULL.with(&save.key)),
None => BindKey::Kept(id),
@@ -290,6 +307,7 @@ impl<T: Value> BindMut<'_, T> {
match &self.source {
SourceMut::Given(Mixed::Same(value)) | SourceMut::MutMixed(Mixed::Same(value)) => value == shown,
SourceMut::Mut(value) => **value == *shown,
SourceMut::Tracked { value, .. } => **value == *shown,
_ => false,
}
}
@@ -388,7 +406,9 @@ impl<T: Value> BindMut<'_, T> {
pub(crate) fn writes(&self, event: &EditEvent<T>) -> 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 +421,17 @@ impl<T: Value> BindMut<'_, T> {
match &mut self.source {
SourceMut::Mut(value) => event.apply(&mut **value),
SourceMut::MutMixed(value) => event.apply_mixed(&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 {
count.set(count.get().wrapping_add(1));
}
applied
}
SourceMut::Given(_) | SourceMut::Kept => Applied::Unchanged,
}
}
@@ -566,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),)+)
}};
}
+1 -1
View File
@@ -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.
+127 -63
View File
@@ -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<Instance>,
at: HashMap<Id, usize>,
}
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<HashMap<Chord, Arc<str>>>,
}
/// A momentary command whose key is down: its release fires the command again.
@@ -85,7 +125,7 @@ pub(crate) struct Board {
out: Vec<Fired>,
/// The commands instances took since the last `FrameOutput`, in order.
delivered: Vec<Fired>,
instances: Vec<Instance>,
instances: Instances,
/// The focused component of each viewport's last step 12 and the instances around it.
chains: HashMap<ViewportId, (Id, CommandChain)>,
/// 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<Held>,
/// The top modal layer's root container of each viewport that has one.
modal_roots: Vec<(ViewportId, Id)>,
modal_roots: HashMap<ViewportId, Id>,
/// The states published this pass, and the pass before, by an instance inside the top modal layer.
modal_published: HashSet<StateKey>,
modal_published_last: HashSet<StateKey>,
@@ -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<Shown>>;
/// 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<ViewportId, HashMap<StateKey, Vec<(Reader, ResolvedCommand)>>>;
/// 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<Id> {
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<Keymap>,
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<HashMap<Chord, Arc<str>>>,
}
/// The keymap of `defs` on `platform` under `overrides`.
@@ -475,6 +517,19 @@ fn keymap_of(defs: Vec<CommandDef>, scopes: Scopes, platform: Platform, override
keymap
}
#[cfg(feature = "testing")]
thread_local! {
static CHORD_TEXT_BUILDS: std::cell::Cell<u64> = 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<u64> = const { std::cell::Cell::new(0) };
@@ -558,7 +613,17 @@ fn build_keymap(registry: &registry::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<Id>) {
crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| 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<Id>) {
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<Id> {
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));
@@ -1198,8 +1258,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() {
@@ -1219,7 +1279,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)
{
@@ -1296,7 +1356,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);
@@ -1314,18 +1374,22 @@ pub(crate) fn end(ctx: &Context) {
let alive: Vec<bool> = 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<Id> = 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()
});
});
}
@@ -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<Cow<'static, str>>,
/// The chord surfaces show: the first single-press binding that runs the command ([`chord`]).
pub chord: Option<Chord>,
/// `chord` as the platform writes it, from the table the keymap builds with its bindings.
pub chord_text: Option<Arc<str>>,
/// 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, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct CommandChain(Arc<[(CommandScope, Id)]>);
impl CommandChain {
+26 -3
View File
@@ -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,28 @@ fn hide_behind_modal(ctx: &Context, viewport: ViewportId, written: &IdSet) {
pub(crate) fn tree_of(output: &mut FullOutput) -> Option<AccessTree> {
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: 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 fn prune_controls(update: &mut egui::accesskit::TreeUpdate) {
let ids: std::collections::HashSet<egui::accesskit::NodeId> = 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<egui::accesskit::NodeId> = node.controls().iter().copied().filter(|id| ids.contains(id)).collect();
node.set_controls(kept);
}
}
@@ -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);
}
@@ -127,6 +127,8 @@ 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))
};
let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size)));
@@ -10,6 +10,8 @@ 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<Galley> {
#[cfg(feature = "testing")]
crate::runtime::measure::count_text_layout(ctx);
ctx.fonts_mut(|fonts| layout_with(fonts, job))
}
+28 -20
View File
@@ -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<Kept>,
}
/// 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::<Log, _>(ctx, |log| !log.open.is_empty())
pass_state::with::<Log, _>(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::<Log, _>(ctx, |log| log.steps.insert(id, Vec::new()));
}
pass_state::with::<Log, _>(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::<Log, _>(ctx, |log| log.steps.entry(id).or_default().push(step));
}
pass_state::with::<Log, _>(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::<Log, _>(ctx, |log| {
@@ -89,7 +85,7 @@ pub(crate) fn findings(ctx: &Context) -> Vec<Finding> {
/// 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::<Log, _>(ctx, |log| {
@@ -307,8 +303,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 +321,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 }
}
+21 -3
View File
@@ -240,7 +240,7 @@ fn with<R>(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,12 @@ 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);
}
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 +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: Id, sizing: bool, place: Option<Place>, content: Option<u64>) -> Option<Vec2> {
// Keyed calls feed their 8-byte content version into the key.
#[cfg(feature = "testing")]
if content.is_some() {
crate::runtime::measure::count_memo_key_bytes(ctx, 8);
}
let input = ctx.input(|input| {
input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone))
});
@@ -340,15 +350,23 @@ pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, pl
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)
}
+121
View File
@@ -285,6 +285,18 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> {
store::with::<RowMeasures, _>(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) {
@@ -305,3 +317,112 @@ pub(crate) fn count_least(ctx: &Context, id: Id) {
pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> {
store::with::<LeastRuns, _>(ctx, |log| log.runs.clone())
}
/// 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,
/// 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)]
pub(crate) 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.
#[cfg(feature = "testing")]
pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) {
let pass = ctx.cumulative_pass_nr();
pass_state::with::<SettleLog, _>(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.
#[cfg(feature = "testing")]
pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> {
let last = ctx.cumulative_pass_nr().saturating_sub(1);
pass_state::with::<SettleLog, _>(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() })
}
/// 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)>,
}
#[cfg(feature = "testing")]
fn totals<R>(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R {
let pass = ctx.cumulative_pass_nr();
pass_state::with::<PassTotals, _>(ctx, |log| {
if log.pass != pass {
*log = PassTotals { pass, ..PassTotals::default() };
}
f(log)
})
}
#[cfg(feature = "testing")]
fn last_totals<R>(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R {
let last = ctx.cumulative_pass_nr().saturating_sub(1);
pass_state::with::<PassTotals, _>(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
/// per call with a content version).
#[cfg(feature = "testing")]
pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) {
totals(ctx, |log| log.key_bytes += 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.
#[cfg(feature = "testing")]
pub(crate) fn count_text_layout(ctx: &Context) {
totals(ctx, |log| log.text_layouts += 1);
}
/// 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.
#[cfg(feature = "testing")]
pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) {
totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) {
Some((_, count)) => *count += 1,
None => log.asks.push((name, 1)),
});
}
/// 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())
}
@@ -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,
+1 -1
View File
@@ -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.
+2 -2
View File
@@ -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<Color32>`: 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 {
+1 -1
View File
@@ -3,7 +3,7 @@
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 {
+32 -1
View File
@@ -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)
}
@@ -48,3 +49,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<Option<Vec<&'static str>>> = const { std::cell::RefCell::new(None) };
}
/// Run a story with the parts declaration check enabled, and return any offending component types.
pub fn check_parts_declarations(run: impl FnOnce()) -> Vec<&'static str> {
struct Reset(Option<Vec<&'static str>>);
impl Drop for Reset {
fn drop(&mut self) {
PARTS_CHECK.with(|check| *check.borrow_mut() = self.0.take());
}
}
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())
}
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);
}
});
}
@@ -17,8 +17,8 @@ const DISC: &[u8] = b"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24
const SQUARE: &[u8] =
b"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" fill=\"black\"/></svg>";
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<SvgIcon> {
let tokens = style::tokens(Mode::Light, Contrast::Standard);
+3 -2
View File
@@ -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};
+14 -1
View File
@@ -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.
@@ -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<NodeId>, carried: Vec<NodeId>) -> 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<NodeId> {
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)]);
}
@@ -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;
+127 -4
View File
@@ -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());
@@ -237,3 +240,123 @@ 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<usize>,
declare: bool,
}
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::min(Vec2::splat(20.0))
}
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>) {}
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, 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]);
}
@@ -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<String>,
}
#[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<u32>,
inner: Inner,
pair: Pair,
mode: Mode,
choice: Option<Mode>,
grid: Vec<Vec<u8>>,
key: u32,
label: Label,
command: CommandRef,
model: &'a Tracked<Vec<String>>,
path: std::path::PathBuf,
#[memo_props(hash = "four bytes; the derived Hash feeds them all")]
address: std::net::Ipv4Addr,
english: Stateless<F>,
}
fn english() -> &'static str {
"English"
}
fn other() -> &'static str {
"Other"
}
fn props<'a, F>(model: &'a Tracked<Vec<String>>, english: Stateless<F>) -> 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<Vec<String>>) -> 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 {}));
}
@@ -3,7 +3,9 @@
mod fixes;
mod gesture;
mod hit_order;
mod memo_key;
mod pages;
mod pointer;
mod style;
mod tracked_bind;
mod visited_type;
@@ -0,0 +1,44 @@
//! Write-through bindings to fields of a `Tracked` value.
use craft_behavior::{EditEvent, Mixed};
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,
}
/// 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 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 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, "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);
{
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");
{
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"));
}
+1 -1
View File
@@ -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.
+27 -1
View File
@@ -1,11 +1,13 @@
//! 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, 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;
mod style;
mod token_group;
@@ -82,6 +84,30 @@ 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 `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<E>`, which no fn item or closure implements
/// `MemoProps` for, is bound by `'static` only (`struct Bar<#[memo_props(stateless)] E> { english: Stateless<E> }`).
#[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.
+94
View File
@@ -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<E>`): bound by what `Stateless<E>: 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<TokenStream>)> {
// Spanned at the field's name, or a tuple field's type, so an error points at the field.
let names: Vec<syn::Ident> = 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<TokenStream> {
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
}
}
})
}
+215
View File
@@ -0,0 +1,215 @@
//! 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<dyn Fn()>` and every other) and closures
//! - containers and smart pointers of any of these (`Arc<Mutex<T>>`, `Vec<Cell<u8>>`)
//!
//! 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_mut::VisitMut;
use syn::{Data, DeriveInput};
/// 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,
}
/// The escape a derive allows for one field: `#[<attr>(<keyword> = "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,
}
/// The escape a derive allows for one type parameter, `#[<attr>(<keyword>)]`: 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::<Field>()` spanned at the field's type, so a rejected field (`Cell<T>` included) is an error at the derive
/// that names the field, and a recursive type (a node holding `Vec<Self>` or `Vec<Node<T>>`) 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. 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<FieldChecks> {
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();
if let Some(param_escape) = param_escape {
for param in &generics.params {
let attrs = match param {
syn::GenericParam::Type(_) => continue,
syn::GenericParam::Lifetime(param) => &param.attrs,
syn::GenericParam::Const(param) => &param.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 = &param.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 bound in bounds {
where_clause.predicates.push(syn::parse2(bound)?);
}
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(escape) = escape
&& escaped(field, escape)?
{
continue;
}
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 checks = quote! {
const _: () = {
#[allow(dead_code, clippy::extra_unused_type_parameters)]
fn check<T: ?Sized + #trait_path>() {}
#[allow(dead_code)]
fn fields #impl_generics () #where_clause {
#(#checked)*
}
};
};
Ok(FieldChecks { generics, checks })
}
/// 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 `param` carries `#[<attr>(<keyword>)]`. Any other content of the attribute is an error.
fn param_escaped(param: &syn::TypeParam, escape: &ParamEscape) -> syn::Result<bool> {
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 `#[<attr>(<keyword> = "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<bool> {
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(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(), format!("`{keyword}` needs a reason: why this field's type is plain data")));
}
found = true;
Ok(())
})?;
}
Ok(found)
}
/// 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 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}");
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<TokenStream> {
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" }), None)?;
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
})
}
+2 -3
View File
@@ -219,11 +219,10 @@ impl<T: Value + 'static> 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()),
});
}
@@ -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 {
+59 -2
View File
@@ -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::<PaneCommand>().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");
}
+31
View File
@@ -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)]
+3 -3
View File
@@ -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.
@@ -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 {
+1 -1
View File
@@ -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<E: 'static> NodeKind<E> for Mix {
fn title(&self) -> &str {
@@ -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 = [])]
+51 -21
View File
@@ -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<Option<u64>>; 2],
repaints: Cell<bool>,
app_repaints: Cell<bool>,
/// Whether the scene shows only what is outside the settling children.
bare: Cell<bool>,
runs: [Cell<usize>; 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::<u32>()
};
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::<u32>(), 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]