Merge next into DPX/Cineon decode memory change

This commit is contained in:
yoriswind
2026-11-19 08:28:47 -08:00
68 changed files with 2709 additions and 111 deletions
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.
+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)
}
@@ -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)]
+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()
+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,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)
}
+108
View File
@@ -305,3 +305,111 @@ 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 and measure asks of that pass.
#[cfg(feature = "testing")]
#[derive(Default)]
pub(crate) struct PassTotals {
pass: u64,
key_bytes: usize,
text_layouts: 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 {
+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.
+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
})
}
@@ -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 {
+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]