From 1851f6984fbcfc7c72009fad452c3842f036037c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 17:33:27 +0000 Subject: [PATCH 01/89] Component constants: one-component values live in the component's file A dimension that belongs to one component's own drawing is a documented constant in that component's file; layout sizes stay semantic tokens, and no size-preset token exists for one component (craft-framework.md 5.4). - Spec: 5.4 rule 3 reworded; Appendix A, 4.6 (the component-token rung goes, no such tokens exist), 8.3, porting.md and the theme README agree. - design-lint: literal-size/* treats a module- or impl-level const with a doc comment as a named value: a name that resolves to it is not flagged, and its initializer is its definition. Fn-local and undocumented consts and call-site literals stay flagged. Nine markers that only covered such consts are removed. - Ruler ticks: size.ruler.tick.* leaves the size presets; kit.rs draws TICK_MID = 6 and TICK_MINOR = 3 points in every density, as the old library and the apps' rulers do. Comfortable ticks go back to 6 / 3 (from 9 / 4.5); Compact is unchanged. - size.scroll_fade becomes FADE_LENGTH in scroll_bar.rs, size.notice.width CARD_WIDTH in notice.rs, and size.story.* multiples of size.control.md in testing/stage.rs (15, 10 and 30 control heights: today's values in both densities). pointer_tip, checker, thumb.sample.*, the card gaps and icon.glyph_md stay tokens: each has more than one user. --- crates/design-lint/README.md | 2 +- crates/design-lint/src/rules.rs | 86 ++++++++++++++++--- crates/design-lint/tests/rules.rs | 14 +++ crates/draw/src/ui/pen/anchor_tool.rs | 1 - crates/pages/src/ui/page_rulers/stories.rs | 1 - crates/print/src/ui/dialog.rs | 2 - crates/theme/README.md | 6 +- crates/theme/sizes/comfortable.json | 15 ---- crates/theme/sizes/compact.json | 15 ---- crates/theme/src/dump.rs | 21 +---- crates/theme/src/lib.rs | 6 +- crates/theme/src/sizes.rs | 7 -- crates/theme/src/tokens/size.rs | 42 --------- .../tokens/adwaita-dark-high-comfortable.txt | 7 -- .../tokens/adwaita-dark-high-compact.txt | 7 -- .../adwaita-dark-standard-comfortable.txt | 7 -- .../tokens/adwaita-dark-standard-compact.txt | 7 -- .../tokens/adwaita-light-high-comfortable.txt | 7 -- .../tokens/adwaita-light-high-compact.txt | 7 -- .../adwaita-light-standard-comfortable.txt | 7 -- .../tokens/adwaita-light-standard-compact.txt | 7 -- .../tokens/artcraft-dark-high-comfortable.txt | 7 -- .../tokens/artcraft-dark-high-compact.txt | 7 -- .../artcraft-dark-standard-comfortable.txt | 7 -- .../tokens/artcraft-dark-standard-compact.txt | 7 -- .../artcraft-light-high-comfortable.txt | 7 -- .../tokens/artcraft-light-high-compact.txt | 7 -- .../artcraft-light-standard-comfortable.txt | 7 -- .../artcraft-light-standard-compact.txt | 7 -- .../tokens/breeze-dark-high-comfortable.txt | 7 -- .../dumps/tokens/breeze-dark-high-compact.txt | 7 -- .../breeze-dark-standard-comfortable.txt | 7 -- .../tokens/breeze-dark-standard-compact.txt | 7 -- .../tokens/breeze-light-high-comfortable.txt | 7 -- .../tokens/breeze-light-high-compact.txt | 7 -- .../breeze-light-standard-comfortable.txt | 7 -- .../tokens/breeze-light-standard-compact.txt | 7 -- .../tokens/classic-light-high-comfortable.txt | 7 -- .../tokens/classic-light-high-compact.txt | 7 -- .../classic-light-standard-comfortable.txt | 7 -- .../tokens/classic-light-standard-compact.txt | 7 -- .../tokens/graphite-dark-high-comfortable.txt | 7 -- .../tokens/graphite-dark-high-compact.txt | 7 -- .../graphite-dark-standard-comfortable.txt | 7 -- .../tokens/graphite-dark-standard-compact.txt | 7 -- .../graphite-light-high-comfortable.txt | 7 -- .../tokens/graphite-light-high-compact.txt | 7 -- .../graphite-light-standard-comfortable.txt | 7 -- .../graphite-light-standard-compact.txt | 7 -- .../tokens/pro-dark-high-comfortable.txt | 7 -- .../dumps/tokens/pro-dark-high-compact.txt | 7 -- ...ro-dark-standard-comfortable-app-sizes.txt | 7 -- .../tokens/pro-dark-standard-comfortable.txt | 7 -- .../tokens/pro-dark-standard-compact.txt | 7 -- .../pro-light-gray-light-high-comfortable.txt | 7 -- .../pro-light-gray-light-high-compact.txt | 7 -- ...-light-gray-light-standard-comfortable.txt | 7 -- .../pro-light-gray-light-standard-compact.txt | 7 -- .../tokens/pro-light-high-comfortable.txt | 7 -- .../dumps/tokens/pro-light-high-compact.txt | 7 -- .../tokens/pro-light-standard-comfortable.txt | 7 -- .../tokens/pro-light-standard-compact.txt | 7 -- .../tokens/soft-dark-high-comfortable.txt | 7 -- .../dumps/tokens/soft-dark-high-compact.txt | 7 -- .../tokens/soft-dark-standard-comfortable.txt | 7 -- .../tokens/soft-dark-standard-compact.txt | 7 -- .../tokens/soft-light-high-comfortable.txt | 7 -- .../dumps/tokens/soft-light-high-compact.txt | 7 -- .../soft-light-standard-comfortable.txt | 7 -- .../tokens/soft-light-standard-compact.txt | 7 -- .../solarized-dark-dark-high-comfortable.txt | 7 -- .../solarized-dark-dark-high-compact.txt | 7 -- ...larized-dark-dark-standard-comfortable.txt | 7 -- .../solarized-dark-dark-standard-compact.txt | 7 -- .../tokens/studio-dark-high-comfortable.txt | 7 -- .../dumps/tokens/studio-dark-high-compact.txt | 7 -- .../studio-dark-standard-comfortable.txt | 7 -- .../tokens/studio-dark-standard-compact.txt | 7 -- .../tokens/studio-light-high-comfortable.txt | 7 -- .../tokens/studio-light-high-compact.txt | 7 -- .../studio-light-standard-comfortable.txt | 7 -- .../tokens/studio-light-standard-compact.txt | 7 -- crates/ui-canvas/src/canvas/tools.rs | 4 +- .../ui-contract/src/contract/body/scroll.rs | 2 +- .../ui-contract/src/contract/items/hooks.rs | 2 +- crates/ui-contract/src/primitives/kit.rs | 21 +++-- .../ui-contract/src/primitives/pointer_art.rs | 1 - .../ui-contract/src/primitives/scroll_bar.rs | 11 ++- crates/ui-contract/src/style/paint.rs | 3 - crates/ui-contract/src/testing/mod.rs | 2 +- crates/ui-contract/src/testing/stage.rs | 30 +++++-- crates/ui-gallery/src/chrome/card.rs | 4 +- crates/ui-gallery/src/chrome/overview.rs | 4 +- .../src/patterns/preferences/window.rs | 4 +- crates/ui-widgets/src/notices/notice.rs | 8 +- docs/craft-framework.md | 20 ++--- docs/porting.md | 6 +- migration/api-map/canvas-core.toml | 2 +- 98 files changed, 169 insertions(+), 656 deletions(-) diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 817b02e7a..7751a0f6c 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -81,7 +81,7 @@ Egui paths are resolved through the file's `use` items (one table per file, grou Names are resolved through the file's `use` items, per module scope: grouped imports, renames (`use egui::Margin as M`), module aliases (`use crate::theme as t`) and glob imports (`use crate::theme::*`) all reach the rule table, so `margin(4.0)` is flagged after `use crate::theme::margin`. A bare name that a fn in the same module defines is not extended through globs. Imports in a module do not apply in sibling modules. -A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero. +A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value, unless it is a component constant: a module- or impl-level `const` with a doc comment, the named place for a dimension of one component's own drawing (craft-framework.md 5.4). A name that resolves to a component constant is not a literal size, and its initializer is its definition, so the literals in it are not flagged either. A `const` inside a fn body, a `static` and an undocumented `const` are flagged as literals. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero. ## Markers diff --git a/crates/design-lint/src/rules.rs b/crates/design-lint/src/rules.rs index 58720f847..d3dec56b4 100644 --- a/crates/design-lint/src/rules.rs +++ b/crates/design-lint/src/rules.rs @@ -150,6 +150,7 @@ pub(crate) fn analyze_file(src: &str, file: &syn::File, include_tests: bool) -> imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), + in_named_const: false, out: Analysis::default(), include_tests, }; @@ -184,6 +185,9 @@ struct ConstDef { line: usize, expr: Expr, value: Option, + /// A component constant: a module- or impl-level `const` with a doc comment. A name that resolves to it is not a + /// literal size, and its initializer is its definition, not a call site. + named: bool, } /// A `use` declaration: `alias` is the name it brings in, `None` for a glob (`path::*`). @@ -202,6 +206,8 @@ struct Linter<'a> { fns: Vec<(Vec, String)>, /// The modules and impl blocks around the item being visited. scope: Vec, + /// Inside the initializer of a named const, where `literal-size/*` does not apply. + in_named_const: bool, out: Analysis, include_tests: bool, } @@ -212,17 +218,21 @@ struct ConstCollector { imports: Vec, fns: Vec<(Vec, String)>, scope: Vec, + /// How many fn bodies enclose the item being visited. + fn_depth: usize, include_tests: bool, } impl ConstCollector { - fn add(&mut self, name: &syn::Ident, expr: &Expr) { + /// Records a const or static; `documented` is whether it is a `const` with a doc comment. + fn add(&mut self, name: &syn::Ident, expr: &Expr, documented: bool) { self.defs.push(ConstDef { scope: self.scope.clone(), name: name.to_string(), line: name.span().start().line, expr: expr.clone(), value: None, + named: documented && self.fn_depth == 0, }); } @@ -256,9 +266,21 @@ impl<'ast> Visit<'ast> for ConstCollector { fn visit_item_fn(&mut self, i: &'ast syn::ItemFn) { if !self.skipped(&i.attrs) { self.fns.push((module_scope(&self.scope).to_vec(), i.sig.ident.to_string())); + self.fn_depth += 1; visit::visit_item_fn(self, i); + self.fn_depth -= 1; } } + fn visit_impl_item_fn(&mut self, i: &'ast syn::ImplItemFn) { + self.fn_depth += 1; + visit::visit_impl_item_fn(self, i); + self.fn_depth -= 1; + } + fn visit_trait_item_fn(&mut self, i: &'ast syn::TraitItemFn) { + self.fn_depth += 1; + visit::visit_trait_item_fn(self, i); + self.fn_depth -= 1; + } fn visit_item_use(&mut self, i: &'ast syn::ItemUse) { if !self.skipped(&i.attrs) { let mut found = Vec::new(); @@ -268,15 +290,15 @@ impl<'ast> Visit<'ast> for ConstCollector { } } fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, has_doc(&i.attrs)); visit::visit_item_const(self, i); } fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, false); visit::visit_item_static(self, i); } fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, has_doc(&i.attrs)); visit::visit_impl_item_const(self, i); } } @@ -349,6 +371,11 @@ fn last_ident(path: &syn::Path) -> Option { path.segments.last().map(|s| s.ident.to_string()) } +/// Whether an item carries a doc comment (`///` or `#[doc = ...]`). +fn has_doc(attrs: &[Attribute]) -> bool { + attrs.iter().any(|a| a.path().is_ident("doc")) +} + fn cfg_is_test(meta: &Meta) -> bool { match meta { Meta::Path(p) => p.is_ident("test"), @@ -420,8 +447,14 @@ impl Linter<'_> { } fn resolve_consts(&mut self, file: &syn::File) { - let mut collector = - ConstCollector { defs: Vec::new(), imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), include_tests: self.include_tests }; + let mut collector = ConstCollector { + defs: Vec::new(), + imports: Vec::new(), + fns: Vec::new(), + scope: Vec::new(), + fn_depth: 0, + include_tests: self.include_tests, + }; collector.visit_file(file); self.defs = collector.defs; self.imports = collector.imports; @@ -431,7 +464,8 @@ impl Linter<'_> { .defs .iter() .enumerate() - .filter(|(_, d)| d.value.is_none()) + // A named const keeps no literal value: a name that resolves to it reads like a token. + .filter(|(_, d)| d.value.is_none() && !d.named) .filter_map(|(i, d)| self.eval_in(&d.expr, &d.scope).map(|v| (i, v))) .collect(); if resolved.is_empty() { @@ -552,12 +586,21 @@ impl Linter<'_> { Some((shown, def.line)) } + /// Whether the const item named `ident` is a named const (`ConstDef::named`). + fn is_named_const(&self, ident: &syn::Ident) -> bool { + let line = ident.span().start().line; + self.defs.iter().any(|d| d.named && d.line == line && *ident == d.name) + } + fn is_flagged_size(&self, e: &Expr) -> bool { self.eval(e).is_some_and(|v| v != 0.0) } /// Reports `what` when any of `args` is a non-zero literal size. fn size_rule<'e>(&mut self, rule: &'static str, what: proc_macro2::Span, args: impl IntoIterator) { + if self.in_named_const { + return; + } let args: Vec<&Expr> = args.into_iter().collect(); // A vector of literal -1, 0 and 1 is a direction, not a size. if rule == VEC2 && args.iter().all(|a| is_unit_literal(a)) { @@ -726,11 +769,21 @@ fn is_unit_literal(e: &Expr) -> bool { fn hint(rule: &str) -> &'static str { match rule { - VEC2 => "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`) or mark `// design: allow()`", - ADD_SPACE => "use a spacing token (`Tokens::of(ui).space.gap.inline`) or mark `// design: allow()`", - CORNER_RADIUS => "use a radius token from `Tokens::of(ui)` or mark `// design: allow()`", - STROKE => "use a stroke width token from `Tokens::of(ui)` or mark `// design: allow()`", - MARGIN => "use a spacing token (`Tokens::of(ui).space`) or mark `// design: allow()`", + VEC2 => { + "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + ADD_SPACE => { + "use a spacing token (`Tokens::of(ui).space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + CORNER_RADIUS => { + "use a radius token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + STROKE => { + "use a stroke width token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + MARGIN => { + "use a spacing token (`Tokens::of(ui).space`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } TOOLTIP => "use `craft_ui::contract::Props::tooltip` or `craft_ui::contract::Show::show_with_tip` or mark `// design: allow()`", STYLE_MUTATION => "set styles through the theme (craft-ui installs them from the tokens) or mark `// design: allow()`", _ => "use a type-size token from `Tokens::of(ui)` or mark `// design: allow()`", @@ -774,9 +827,18 @@ impl<'ast> Visit<'ast> for Linter<'_> { } fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { if !self.skips(&i.attrs, i.span()) { + let named = self.in_named_const || self.is_named_const(&i.ident); + let outer = std::mem::replace(&mut self.in_named_const, named); visit::visit_item_const(self, i); + self.in_named_const = outer; } } + fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) { + let named = self.in_named_const || self.is_named_const(&i.ident); + let outer = std::mem::replace(&mut self.in_named_const, named); + visit::visit_impl_item_const(self, i); + self.in_named_const = outer; + } fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { if !self.skips(&i.attrs, i.span()) { visit::visit_item_static(self, i); diff --git a/crates/design-lint/tests/rules.rs b/crates/design-lint/tests/rules.rs index 11b6b8efc..cba0e2fe9 100644 --- a/crates/design-lint/tests/rules.rs +++ b/crates/design-lint/tests/rules.rs @@ -67,6 +67,20 @@ fn consts_resolve_by_module_and_impl_scope() { assert_eq!(run(src).len(), 3); } +#[test] +fn documented_consts_are_component_constants() { + // A documented module or impl const is a named value, its initializer included; arithmetic on it reads like a token. + let src = "/// The tick.\nconst TICK: f32 = 3.0;\n/// The room.\nconst ROOM: Vec2 = vec2(30.0, 40.0);\nstruct A;\nimpl A {\n /// The pad.\n const PAD: f32 = 6.0;\n fn f(&self, ui: &mut Ui) { ui.add_space(Self::PAD); ui.add_space(TICK * 2.0); let v = vec2(TICK, ROOM.y); }\n}\n"; + assert!(clean(src)); + + // An undocumented const, a documented const in a fn body and a literal stay flagged. + let src = "const GAP: f32 = 4.0;\nfn f(ui: &mut Ui) { ui.add_space(GAP); }\nfn g(ui: &mut Ui) {\n /// The gap.\n const LOCAL: f32 = 4.0;\n ui.add_space(LOCAL);\n}\nfn h(ui: &mut Ui) { ui.add_space(4.0); }\n"; + assert_eq!(run(src).iter().map(|f| f.line).collect::>(), [2, 6, 8]); + + // The initializer of an undocumented const is a call site. + assert!(flagged("const ROOM: Vec2 = vec2(30.0, 40.0);\n", "literal-size/vec2")); +} + #[test] fn clippy_allow_attributes_are_counted_and_inner_ones_flagged() { let src = "#![allow(clippy::disallowed_methods, reason = \"stock widgets\")]\n#[expect(clippy::disallowed_types)]\nstruct S;\n#[allow(clippy::too_many_arguments)]\nfn f() {}\nmod m {\n #![expect(clippy::disallowed_methods)]\n}\n"; diff --git a/crates/draw/src/ui/pen/anchor_tool.rs b/crates/draw/src/ui/pen/anchor_tool.rs index 41cb41592..6a97242d4 100644 --- a/crates/draw/src/ui/pen/anchor_tool.rs +++ b/crates/draw/src/ui/pen/anchor_tool.rs @@ -10,7 +10,6 @@ use craft_ui::primitives::{Draw, ToolIcon}; use egui::Vec2; /// The apex of the Convert Point icon's caret, in the units of the icon's box. -// design: allow[literal-size/vec2](the cursor art's hot spot offset in icon units, not a layout size) const CONVERT_TIP: Vec2 = Vec2::new(ICON_BOX / 2.0, 5.5); /// The canvas tool of Add Anchor Point, Delete Anchor Point, Convert Point and Direct Selection. Every press of these diff --git a/crates/pages/src/ui/page_rulers/stories.rs b/crates/pages/src/ui/page_rulers/stories.rs index 7cdf4a66c..5afae5d28 100644 --- a/crates/pages/src/ui/page_rulers/stories.rs +++ b/crates/pages/src/ui/page_rulers/stories.rs @@ -41,7 +41,6 @@ fn inches() -> DocUnit { fn vertical(ui: &mut Ui, rows: &[f32], text: Option) -> StoryOutput { let full = craft_ui::testing::stage(ui); let page = demo_placed(1, pos2(full.min.x + STRIP, full.min.y + PAGE_TOP)).remove(0); - // design: allow[literal-size/vec2](the strip is the demo page margin in document points, story data) let strip = Rect::from_min_size(full.min, vec2(STRIP, full.height())); let mut ruler = VerticalRuler::new("Vertical ruler", &page).unit(inches()).rows(rows); if let Some(range) = text { diff --git a/crates/print/src/ui/dialog.rs b/crates/print/src/ui/dialog.rs index 85aeb96cf..df832b256 100644 --- a/crates/print/src/ui/dialog.rs +++ b/crates/print/src/ui/dialog.rs @@ -311,13 +311,11 @@ impl Component for PrintPreview<'_> { } // The description and the labels are text of the printed page; the preview shows where each stands. if marks.description { - // design: allow[literal-size/vec2](printer's marks are page geometry in points, not UI sizes) let from = paper.left_bottom() + vec2(MARK_GAP, -MARK_GAP); // design: allow[literal-size/vec2](printer's marks are page geometry in points, not UI sizes) rule(RuleKind::Edge, from, from + vec2(MARK_LEN * 3.0, 0.0)); } if marks.labels { - // design: allow[literal-size/vec2](printer's marks are page geometry in points, not UI sizes) let from = paper.left_top() + vec2(MARK_GAP, MARK_GAP); // design: allow[literal-size/vec2](printer's marks are page geometry in points, not UI sizes) rule(RuleKind::Edge, from, from + vec2(MARK_LEN * 3.0, 0.0)); diff --git a/crates/theme/README.md b/crates/theme/README.md index 483655170..a75dccadb 100644 --- a/crates/theme/README.md +++ b/crates/theme/README.md @@ -20,17 +20,15 @@ let resolved = resolve(theme, appearance, None); ## Tokens -Three layers, each derived from the one before: +Two layers, the second derived from the first: 1. **Primitives**: sRGB and OKLCH colour, WCAG contrast, 12-step colour ramps, fixed scales (space, radius, stroke, opacity, duration, easing, elevation). 2. **Semantic tokens**: surface, text, line, state, accent, status, overlay, data and caption colours; shape, size, space, motion and type tokens. Seeds (neutral, accent, four status colours) generate ramps, and ramps fill the tokens. -3. **Component tokens**: one struct per component family (button, badge, check box, radio button and switch, text and number field, guide, handle, icon button, kbd, list box, marquee, progress bar, readout, ruler, segmented control, slider, swatch, toggle button, tooltip), with curated overrides. -A theme sets **seeds** and may **pin** any colour token (`"surface.panel": "#F0F0F0"`), or a -component field, per mode. Pins win over derivation. Apps can pin per app (`apps.`). +A theme sets **seeds** and may **pin** any colour token (`"surface.panel": "#F0F0F0"`) per mode. Pins win over derivation. Apps can pin per app (`apps.`). ## Contrast diff --git a/crates/theme/sizes/comfortable.json b/crates/theme/sizes/comfortable.json index 02c680a30..49353b25f 100644 --- a/crates/theme/sizes/comfortable.json +++ b/crates/theme/sizes/comfortable.json @@ -69,9 +69,6 @@ "short": 120.0, "track": 144.0 }, - "notice": { - "width": 360.0 - }, "pane": { "least": 50.0 }, @@ -96,18 +93,6 @@ "row": { "text": 21.0 }, - "ruler": { - "tick": { - "mid": 9.0, - "minor": 4.5 - } - }, - "scroll_fade": 20.0, - "story": { - "height": 450.0, - "width_max": 900.0, - "width_min": 300.0 - }, "thumb": { "card": 160.0, "lg": 48.0, diff --git a/crates/theme/sizes/compact.json b/crates/theme/sizes/compact.json index b54e86102..1d2cc8a06 100644 --- a/crates/theme/sizes/compact.json +++ b/crates/theme/sizes/compact.json @@ -69,9 +69,6 @@ "short": 96.0, "track": 128.0 }, - "notice": { - "width": 360.0 - }, "pane": { "least": 40.0 }, @@ -96,18 +93,6 @@ "row": { "text": 18.0 }, - "ruler": { - "tick": { - "mid": 6.0, - "minor": 3.0 - } - }, - "scroll_fade": 20.0, - "story": { - "height": 360.0, - "width_max": 720.0, - "width_min": 240.0 - }, "thumb": { "card": 128.0, "lg": 48.0, diff --git a/crates/theme/src/dump.rs b/crates/theme/src/dump.rs index 0805e416f..a37895275 100644 --- a/crates/theme/src/dump.rs +++ b/crates/theme/src/dump.rs @@ -7,9 +7,9 @@ use std::fmt::Write as _; use crate::{ BarSizes, ColorToken, ControlSizes, DialogSizes, DockColumnSizes, Easing, Edge, Elevation, ElevationTokens, FloatSizes, FontSlot, Gaps, - HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, Motion, MotionTokens, NoticeSizes, Pads, PaneSizes, PlotSizes, RadiusSet, - RailSizes, RampSizes, Rgba, RowSizes, RulerSizes, RulerTickSizes, ShapeTokens, SizeTokens, SpaceTokens, StorySizes, StrokeTokens, ThumbSamples, - ThumbSizes, Tokens, TypeStyle, TypeTokens, WellShape, WindowSizes, + HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, Motion, MotionTokens, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, + RampSizes, Rgba, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StrokeTokens, ThumbSamples, ThumbSizes, Tokens, TypeStyle, TypeTokens, + WellShape, WindowSizes, }; /// The text of every token, one `key = value` line each, in a fixed order. @@ -116,7 +116,6 @@ fn size_lines(out: &mut Lines, size: &SizeTokens) { bar, panel_header, popup_min, - scroll_fade, thumb: thumbs, handle, hit, @@ -130,11 +129,8 @@ fn size_lines(out: &mut Lines, size: &SizeTokens) { float, window, pane, - ruler, dock, - notice, dialog, - story, } = size; let ControlSizes { sm, md } = control; out.line("size.control.sm", len(*sm)); @@ -154,7 +150,6 @@ fn size_lines(out: &mut Lines, size: &SizeTokens) { } out.line("size.panel_header", len(*panel_header)); out.line("size.popup_min", len(*popup_min)); - out.line("size.scroll_fade", len(*scroll_fade)); let ThumbSizes { sm, md, lg, card, sample } = thumbs; out.line("size.thumb.sm", len(*sm)); out.line("size.thumb.md", len(*md)); @@ -198,23 +193,13 @@ fn size_lines(out: &mut Lines, size: &SizeTokens) { out.line("size.window.cascade", len(*cascade)); let PaneSizes { least } = pane; out.line("size.pane.least", len(*least)); - let RulerSizes { tick } = ruler; - let RulerTickSizes { mid, minor } = tick; - out.line("size.ruler.tick.mid", len(*mid)); - out.line("size.ruler.tick.minor", len(*minor)); let DockColumnSizes { column } = dock; out.line("size.dock.column", len(*column)); - let NoticeSizes { width } = notice; - out.line("size.notice.width", len(*width)); let DialogSizes { least, wrap, button, side_button } = dialog; out.line("size.dialog.least", len(*least)); out.line("size.dialog.wrap", len(*wrap)); out.line("size.dialog.button", len(*button)); out.line("size.dialog.side_button", len(*side_button)); - let StorySizes { height, width_min, width_max } = story; - out.line("size.story.height", len(*height)); - out.line("size.story.width_min", len(*width_min)); - out.line("size.story.width_max", len(*width_max)); } fn slot(s: FontSlot) -> &'static str { diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index 57e85bce2..3bed2c09f 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -98,9 +98,9 @@ pub use token_group::{GroupValues, TokenGroup}; pub use tokens::{ AccentColors, BarSizes, CaptionColors, ColorToken, ColorTokens, ControlSizes, DataColors, DialogSizes, DockColumnSizes, Edge, EdgeColors, ElevationTokens, FloatSizes, FontSlot, Gaps, HandleSizes, HitSizes, IconSizes, Insets, KnobShape, LengthSizes, LineColors, Motion, MotionTokens, - NoticeSizes, OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, RulerSizes, RulerTickSizes, ShapeTokens, - SizeTokens, SpaceTokens, StateColors, Status, StatusColors, StatusKind, StorySizes, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, - ThumbSizes, Tokens, TypeRole, TypeStyle, TypeTokens, WellShape, WindowSizes, + OverlayColors, Pads, PaneSizes, PlotSizes, RadiusSet, RailSizes, RampSizes, RowSizes, ShapeTokens, SizeTokens, SpaceTokens, StateColors, Status, + StatusColors, StatusKind, StrokeTokens, SurfaceColors, TextColors, ThumbSamples, ThumbSizes, Tokens, TypeRole, TypeStyle, TypeTokens, WellShape, + WindowSizes, }; pub use values::ColorSource; pub use variant::{CustomVariant, Emphasis, RadiusStep, Variant, VariantLook}; diff --git a/crates/theme/src/sizes.rs b/crates/theme/src/sizes.rs index a6adbf00b..6464ecb67 100644 --- a/crates/theme/src/sizes.rs +++ b/crates/theme/src/sizes.rs @@ -107,7 +107,6 @@ pub(crate) fn leaves(b: &mut Preset) -> Vec> { "base.size.bar.options_narrow" Num 16.0..=80.0 => s.bar.options_narrow; "base.size.panel_header" Num 16.0..=64.0 => s.panel_header; "base.size.popup_min" Num 64.0..=640.0 => s.popup_min; - "base.size.scroll_fade" Num 4.0..=64.0 => s.scroll_fade; "base.size.thumb.sm" Num 12.0..=96.0 => s.thumb.sm; "base.size.thumb.md" Num 12.0..=96.0 => s.thumb.md; "base.size.thumb.lg" Num 12.0..=96.0 => s.thumb.lg; @@ -140,13 +139,7 @@ pub(crate) fn leaves(b: &mut Preset) -> Vec> { "base.size.float.height" Num 48.0..=1024.0 => s.float.height; "base.size.window.cascade" Num 8.0..=96.0 => s.window.cascade; "base.size.pane.least" Num 16.0..=128.0 => s.pane.least; - "base.size.ruler.tick.mid" Num 1.0..=32.0 => s.ruler.tick.mid; - "base.size.ruler.tick.minor" Num 1.0..=32.0 => s.ruler.tick.minor; - "base.size.story.height" Num 120.0..=1024.0 => s.story.height; - "base.size.story.width_min" Num 120.0..=1024.0 => s.story.width_min; - "base.size.story.width_max" Num 120.0..=2048.0 => s.story.width_max; "base.size.dock.column" Num 120.0..=640.0 => s.dock.column; - "base.size.notice.width" Num 120.0..=1024.0 => s.notice.width; "base.size.dialog.least" Num 120.0..=1024.0 => s.dialog.least; "base.size.dialog.wrap" Num 120.0..=1024.0 => s.dialog.wrap; "base.size.dialog.button" Num 24.0..=240.0 => s.dialog.button; diff --git a/crates/theme/src/tokens/size.rs b/crates/theme/src/tokens/size.rs index 461a4fd21..65456f785 100644 --- a/crates/theme/src/tokens/size.rs +++ b/crates/theme/src/tokens/size.rs @@ -202,8 +202,6 @@ pub struct SizeTokens { pub panel_header: f32, /// Least width of a popup surface: a menu or a popup list. pub popup_min: f32, - /// The length of the fade at an edge of a scroll region past which its content continues. - pub scroll_fade: f32, /// Thumbnail sides. pub thumb: ThumbSizes, /// Canvas drag handles. @@ -233,41 +231,8 @@ pub struct SizeTokens { pub pane: PaneSizes, /// The docks' columns. pub dock: DockColumnSizes, - /// Notice cards: toasts. - pub notice: NoticeSizes, /// Dialogs: their content width and their buttons. pub dialog: DialogSizes, - /// The rulers of a canvas. - pub ruler: RulerSizes, - /// The stage a story draws on. - pub story: StorySizes, -} - -/// The stage a story draws on, in logical pixels: a story of a canvas control, and each column of a story grid. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct StorySizes { - /// The height of the stage a story of a canvas control shows its canvas on. - pub height: f32, - /// The least width of a story: of that stage, and of a column of a story grid. - pub width_min: f32, - /// The greatest width of that stage. - pub width_max: f32, -} - -/// The sizes of a canvas ruler, in logical pixels. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct RulerSizes { - /// The tick marks. - pub tick: RulerTickSizes, -} - -/// The lengths of a ruler's tick marks, in logical pixels. The major tick spans the ruler's depth. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct RulerTickSizes { - /// The tick halfway between two labelled ticks. - pub mid: f32, - /// The tick between two other ticks. - pub minor: f32, } /// The sizes of the panes of a dock's split, in logical pixels. @@ -286,13 +251,6 @@ pub struct DockColumnSizes { pub column: f32, } -/// The sizes of a notice card, in logical pixels. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct NoticeSizes { - /// The width every card of a toast stack has where the room allows. - pub width: f32, -} - /// The sizes of a dialog, in logical pixels. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct DialogSizes { diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt index e1e34bf96..f6f0f889d 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt index 234c614fd..baa136a14 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt index 3ef6d8504..07a2b182b 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt index a9aba5082..663d9aa56 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt index 2af6bbff1..30791b515 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt index d1648993d..0dbad648c 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt index b320cc27d..97f26b5b8 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt index 1e29c9a77..6afca472b 100644 --- a/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/adwaita-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt index 70b095cf4..290bfbd69 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt index ae6cd9e19..08cb3121d 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt index e1f8c22a7..0edf137d8 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt index 4f76678e5..98cfdf3ca 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt index 00a1091c9..4ef00d6e6 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt index bfb368afb..bfc96544d 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt index 55f702a1f..7af4ea988 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt index 6ebe57241..c8f3f50a3 100644 --- a/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/artcraft-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt index 709e21b2a..9095b81a2 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt index 352f425c3..69a5660f7 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt index 777b6c368..cef377c1a 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt index 39337fa26..a8ca13233 100644 --- a/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt index d815f8260..7292f9c95 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt b/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt index 3a3de563a..03870d5cd 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt index 1c1046d51..2663a322b 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt index d28858afa..1d486baed 100644 --- a/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/breeze-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt index 0a8745f5e..c2b224cad 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt b/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt index 6ded2511a..21eb18c2f 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt index 64a72cd99..d13e565b2 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt index 475e84eb3..75df34571 100644 --- a/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/classic-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt index ed62a4f67..1903a0cab 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt index ed6911bd1..7749259d4 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt index cb1c644a7..5048aad6e 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt index fd85432e1..10b953f21 100644 --- a/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt index 086e42f22..00ffcfed9 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt b/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt index 20062381c..f960fdee2 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt index ac916ce09..2e6c3882c 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt index c7e474ea1..9a62914d3 100644 --- a/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/graphite-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt index a653473ad..a1fbfdc45 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt index 6c8c0dfee..e2fcea5f2 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt index a2fc1f7d2..7e441df23 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable-app-sizes.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt index c1cc33b3e..251190a64 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt index 1964a740c..72ddc45e9 100644 --- a/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt index f161ee554..8367df0dc 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt index 32bf9b423..9ed556dab 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt index 284bb93e2..ba9f4e843 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt index 4dfa8b047..4aa509b95 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-gray-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt index 257a367dd..ce1af43c1 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt index 68cdaad75..bed4e1f79 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt index 1b2bc5507..01b5b2a57 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt index b4bbf55d3..3c1537b6f 100644 --- a/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/pro-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt index ad8f3275d..1f5a590c3 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt index 17d472b79..db070fb55 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt index 7b167d2e2..66d7444ae 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt index 857b91ed1..88b92b44c 100644 --- a/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt index a2e781704..bb1b7b1b7 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt b/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt index a96f66c16..652cf8299 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt index e113483a0..08a58ef9e 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt index 838825074..0586c0f88 100644 --- a/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/soft-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt index 1a92c8898..40beff6ae 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt index 36e54c9db..aa973e000 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt index a6d0d66c2..3695878d6 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt index 50b6a2dd9..1db2e75b0 100644 --- a/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/solarized-dark-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt index 70ec56153..5f2710e90 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt b/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt index ac2fc9e97..57b5d112d 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt index 800b1a04d..1826e99ea 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt b/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt index 6d573d055..51a7034df 100644 --- a/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-dark-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt index 310de3b24..e9c49c1af 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-high-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt b/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt index 2b734d0c3..ae6eb3217 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-high-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt b/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt index 9daaaa4c8..f2c8e0554 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-standard-comfortable.txt @@ -144,7 +144,6 @@ size.bar.options = 42 size.bar.options_narrow = 36 size.panel_header = 34 size.popup_min = 240 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 34 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 240 size.float.height = 300 size.window.cascade = 38 size.pane.least = 50 -size.ruler.tick.mid = 9 -size.ruler.tick.minor = 4.5 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 450 -size.story.width_min = 300 -size.story.width_max = 900 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt b/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt index e3baee9f6..6e62a52b3 100644 --- a/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt +++ b/crates/theme/tests/dumps/tokens/studio-light-standard-compact.txt @@ -144,7 +144,6 @@ size.bar.options = 36 size.bar.options_narrow = 28 size.panel_header = 28 size.popup_min = 192 -size.scroll_fade = 20 size.thumb.sm = 18 size.thumb.md = 24 size.thumb.lg = 48 @@ -177,17 +176,11 @@ size.float.width = 192 size.float.height = 240 size.window.cascade = 32 size.pane.least = 40 -size.ruler.tick.mid = 6 -size.ruler.tick.minor = 3 size.dock.column = 340 -size.notice.width = 360 size.dialog.least = 380 size.dialog.wrap = 440 size.dialog.button = 84 size.dialog.side_button = 96 -size.story.height = 360 -size.story.width_min = 240 -size.story.width_max = 720 stroke.thin = 1 stroke.medium = 1.5 stroke.thick = 2 diff --git a/crates/ui-canvas/src/canvas/tools.rs b/crates/ui-canvas/src/canvas/tools.rs index 28e021518..1e1feaa27 100644 --- a/crates/ui-canvas/src/canvas/tools.rs +++ b/crates/ui-canvas/src/canvas/tools.rs @@ -24,10 +24,10 @@ const ROTATE_STEP_DEG: f64 = 15.0; /// The room Fit Artboard on Screen leaves around the board, in points: at the sides, and above and below (the board's /// name sits above it). -const ARTBOARD_MARGIN: Vec2 = Vec2::new(30.0, 40.0); // design: allow[literal-size/vec2](view-fit room in screen points, not a look) +const ARTBOARD_MARGIN: Vec2 = Vec2::new(30.0, 40.0); /// The room Fit Layers on Screen leaves around the layers' bounds, in points. -const LAYERS_MARGIN: Vec2 = Vec2::new(20.0, 20.0); // design: allow[literal-size/vec2](view-fit room in screen points, not a look) +const LAYERS_MARGIN: Vec2 = Vec2::new(20.0, 20.0); /// The room Fit on Screen leaves around the document on each side, in points. const FIT_MARGIN: f64 = 20.0; diff --git a/crates/ui-contract/src/contract/body/scroll.rs b/crates/ui-contract/src/contract/body/scroll.rs index c1d1ba13c..d83bb4afb 100644 --- a/crates/ui-contract/src/contract/body/scroll.rs +++ b/crates/ui-contract/src/contract/body/scroll.rs @@ -187,7 +187,7 @@ impl BodyHooks<'_> { let content = Vec2::new(if scroll.horizontal_on() { ex } else { view.width() }, if scroll.vertical_on() { ey } else { view.height() }); let offset = Vec2::new(self.offset.x as f32, self.offset.y as f32); let background = surface_style(tokens, SurfaceKind::under(own_surface(props, cx), env.surface)).fill; - ui.painter().extend(ScrollBar::fades(&look, view, HiddenContent::new(content, view.size(), offset, rtl), background)); + ui.painter().extend(ScrollBar::fades(view, HiddenContent::new(content, view.size(), offset, rtl), background)); } if let Some(view) = self.view { use crate::contract::Pointer as _; diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 49729416d..1f8f7507c 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -745,7 +745,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { // The rows blend into the surface they sit on. let background = surface_style(&env.tokens, SurfaceKind::under(own, env.surface)).fill; let hidden = HiddenContent::new(self.content, rect.size(), Vec2::new(self.offset_x as f32, self.offset as f32), rtl); - ui.painter().extend(ScrollBar::fades(&look, rect, hidden, background)); + ui.painter().extend(ScrollBar::fades(rect, hidden, background)); if self.shows_bar(rect) { let track = bar_track(rect, look.thickness, rtl); let content = f64::from(self.content.y); diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index f53b7b778..a6a95abf5 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -34,14 +34,20 @@ pub enum TickEdge { #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum TickRank { - /// The shortest, `size.ruler.tick.minor`. + /// The shortest, `TICK_MINOR` long. Minor, - /// Halfway between two major ticks, `size.ruler.tick.mid`. + /// Halfway between two major ticks, `TICK_MID` long. Mid, - /// The longest, `space.gap.inline`. + /// The longest, across the ruler's depth. Major, } +/// The length of a minor tick, in points. The same in every density, as in the apps' rulers. +const TICK_MINOR: f32 = 3.0; + +/// The length of the tick halfway between two major ticks, in points, in every density. +const TICK_MID: f32 = 6.0; + /// One tick: where it sits along its edge and how long it is. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -619,21 +625,20 @@ pub fn grid_lines_with(look: &GridLook, grid: &GridLines, ink: &GridInk, pixels_ } /// The tick marks of `ticks` on one edge of `rect` that `clip` shows, `stroke.thin` lines of `text.faint`: minor ones -/// `size.ruler.tick.minor` long, mid ones `size.ruler.tick.mid`, major ones across the whole depth of `rect`, beside their labels. +/// `TICK_MINOR` long, mid ones `TICK_MID`, major ones across the whole depth of `rect`, beside their labels. pub fn ticks(tokens: &UiTokens, rect: Rect, edge: TickEdge, ticks: &[Tick], clip: Rect, pixels_per_point: f32) -> Vec { let look = RuleLook { color: rgba_color(tokens.color.text.faint), width: RuleWidth::Points(tokens.stroke.thin) }; let depth = match edge { TickEdge::Bottom | TickEdge::Top => rect.height(), TickEdge::Left | TickEdge::Right => rect.width(), }; - let (minor, mid, major) = (tokens.size.ruler.tick.minor, tokens.size.ruler.tick.mid, depth); ticks .iter() .filter_map(|tick| { let length = match tick.rank { - TickRank::Minor => minor, - TickRank::Mid => mid, - TickRank::Major => major, + TickRank::Minor => TICK_MINOR, + TickRank::Mid => TICK_MID, + TickRank::Major => depth, }; let (from, to) = match edge { TickEdge::Bottom => (pos2(rect.left() + tick.at, rect.bottom()), pos2(rect.left() + tick.at, rect.bottom() - length)), diff --git a/crates/ui-contract/src/primitives/pointer_art.rs b/crates/ui-contract/src/primitives/pointer_art.rs index 0fd7be528..412666dde 100644 --- a/crates/ui-contract/src/primitives/pointer_art.rs +++ b/crates/ui-contract/src/primitives/pointer_art.rs @@ -412,7 +412,6 @@ pub(crate) fn type_on(pen: &Pen, path: bool) { /// The locator: a square frame centred on the pointer between halo frames a hairline outside and inside it. pub(crate) fn locator(pen: &Pen) { - // design: allow[literal-size/vec2](pointer art is a fixed bitmap-like drawing around the hotspot, not a layout size) let rect = Rect::from_center_size(Pos2::ZERO, Vec2::splat(LOCATOR_SIDE)); let halo = Stroke::new(pen.thin, pen.halo); pen.push(Mark::Frame(rect.expand(pen.thin), halo)); diff --git a/crates/ui-contract/src/primitives/scroll_bar.rs b/crates/ui-contract/src/primitives/scroll_bar.rs index f0c62a441..8027b18d5 100644 --- a/crates/ui-contract/src/primitives/scroll_bar.rs +++ b/crates/ui-contract/src/primitives/scroll_bar.rs @@ -11,6 +11,9 @@ pub struct ScrollBar; /// The opacity of an edge fade at the view's edge, once at least the fade's length of content is hidden past it. const FADE_STRENGTH: f32 = 0.5; +/// The length of an edge fade, in points, in every density. +const FADE_LENGTH: f32 = 20.0; + /// How far a scroll view's content runs past each of its edges, in points. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] @@ -62,13 +65,13 @@ impl ScrollBar { } } - /// The fades over `view` at each edge past which content is hidden: `look.fade` long, from `background` at the + /// The fades over `view` at each edge past which content is hidden: `FADE_LENGTH` long, from `background` at the /// edge to clear inward, the more opaque the more is hidden, up to `FADE_STRENGTH` once a fade's length is. - pub fn fades(look: &ScrollBarLook, view: Rect, hidden: HiddenContent, background: Color32) -> Vec { + pub fn fades(view: Rect, hidden: HiddenContent, background: Color32) -> Vec { let across = |hidden: f32, extent: f32, edge: fn(Rect, f32) -> Rect, direction: Direction| { - let length = look.fade.min(extent); + let length = FADE_LENGTH.min(extent); (hidden > 0.0 && length > 0.0).then(|| { - let at = background.gamma_multiply((hidden / look.fade).clamp(0.0, 1.0) * FADE_STRENGTH); + let at = background.gamma_multiply((hidden / FADE_LENGTH).clamp(0.0, 1.0) * FADE_STRENGTH); Shape::gradient_rect(edge(view, length), direction, [at, Color32::TRANSPARENT]) }) }; diff --git a/crates/ui-contract/src/style/paint.rs b/crates/ui-contract/src/style/paint.rs index 73db34566..59066a5a9 100644 --- a/crates/ui-contract/src/style/paint.rs +++ b/crates/ui-contract/src/style/paint.rs @@ -199,8 +199,6 @@ pub struct ScrollBarLook { pub thumb_width: Stateful, /// The shortest the thumb gets along the bar. pub min_thumb: f32, - /// The length of the fade at an edge past which content is hidden. - pub fade: f32, } /// The shortest a scroll bar's thumb gets along the bar, whatever the bar's kind. @@ -245,7 +243,6 @@ pub(crate) fn scroll_bar_look_of(tokens: &UiTokens, kind: ScrollBarKind) -> Scro thickness, thumb_width: Stateful::new(rest).off(craft_theme::States::new(rest, thickness, thickness, rest)), min_thumb: min_thumb(tokens), - fade: tokens.size.scroll_fade, } } diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index a4dc0c3f4..f6993ccd3 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -51,7 +51,7 @@ pub use crate::runtime::measure::{ pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; pub use frames::Frames; -pub use stage::{room_height, stage, stage_fitting, stage_width}; +pub use stage::{least_stage_width, room_height, stage, stage_fitting, stage_width}; #[doc(hidden)] pub use story::{ CollectionKind, Drive, EditKind, Grip, Required, Story, StoryData, StoryOutput, StoryRegistration, StorySnapshot, show_as_only_item, stories, diff --git a/crates/ui-contract/src/testing/stage.rs b/crates/ui-contract/src/testing/stage.rs index 89759f814..c295901d2 100644 --- a/crates/ui-contract/src/testing/stage.rs +++ b/crates/ui-contract/src/testing/stage.rs @@ -2,13 +2,33 @@ use crate::layout::flow_room; use crate::runtime::env::Env; +use craft_theme::Tokens; use egui::{Rect, Ui}; +/// The stage's height, in control heights (`size.control.md`): 360 in Compact. +const HEIGHT_IN_CONTROLS: f32 = 15.0; + +/// The stage's least width, in control heights: 240 in Compact. +const WIDTH_MIN_IN_CONTROLS: f32 = 10.0; + +/// The stage's greatest width, in control heights: 720 in Compact. +const WIDTH_MAX_IN_CONTROLS: f32 = 30.0; + +/// The height of a story's stage. +fn stage_height(tokens: &Tokens) -> f32 { + HEIGHT_IN_CONTROLS * tokens.size.control.md +} + +/// The least width of a story's stage, which is also the least width of a column of a story grid. +pub fn least_stage_width(tokens: &Tokens) -> f32 { + WIDTH_MIN_IN_CONTROLS * tokens.size.control.md +} + /// Allocates the stage of a story of a canvas control or a root that fills both axes, and returns its rect: the width -/// left in `ui` between the least and greatest stage width, and the stage height, all from the size tokens. Show the +/// left in `ui` between the least and greatest stage width, and the stage height, all in control heights. Show the /// story's root over it with `show_at`. pub fn stage(ui: &mut Ui) -> Rect { - let height = Env::of(ui).tokens.tokens().size.story.height; + let height = stage_height(&Env::of(ui).tokens); stage_fitting(ui, |_| height) } @@ -16,7 +36,7 @@ pub fn stage(ui: &mut Ui) -> Rect { /// canvas): the room its card's view gives, or the stage height where the room is unbounded. pub fn room_height(ui: &Ui) -> f32 { let room = flow_room(ui).y; - if room.is_finite() { room } else { Env::of(ui).tokens.tokens().size.story.height } + if room.is_finite() { room } else { stage_height(&Env::of(ui).tokens) } } /// Allocates a stage as wide as [`stage`]'s and as tall as the story's content at that width, which `height` gives, @@ -29,8 +49,8 @@ pub fn stage_fitting(ui: &mut Ui, height: impl FnOnce(f32) -> f32) -> Rect { /// The width of the stage [`stage_fitting`] allocates: the width left in `ui` between the least and greatest stage /// width. A story whose content measures itself at a width (through `ui`) reads it before allocating. pub fn stage_width(ui: &Ui) -> f32 { - let story = Env::of(ui).tokens.tokens().size.story; + let tokens = &Env::of(ui).tokens; let room = flow_room(ui).x; let room = if room.is_finite() { room } else { ui.available_width() }; - room.clamp(story.width_min, story.width_max) + room.clamp(least_stage_width(tokens), WIDTH_MAX_IN_CONTROLS * tokens.size.control.md) } diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index 578b33e42..ced8c50c8 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -20,7 +20,7 @@ use craft_ui::runtime::inspect::{self, Recorded}; use craft_ui::runtime::layout_memory; use craft_ui::sections::{HeaderCommand, HeaderStrength, Panel}; use craft_ui::style::SurfaceKind; -use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration}; +use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration, least_stage_width}; /// A story's show function. type StoryFn = fn(&mut Ui, &mut StoryData) -> StoryOutput; @@ -198,7 +198,7 @@ impl Card<'_> { let gap = Gap::Item.points(ui); // The narrowest a column of stories may be is the least story width, as the old gallery's grids kept // their cases. - let least = Env::of(ui).tokens.size.story.width_min; + let least = least_stage_width(&Env::of(ui).tokens); let fit = ((ui.available_width() + gap) / (least + gap)).floor() as usize; let columns = fit.clamp(1, usize::from(most).clamp(1, COLUMNS.len())); Grid::new(&COLUMNS[..columns]).gap(Gap::Item).fill_width().show(ui, |ui, _| { diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs index f9892f4bd..9960c64b4 100644 --- a/crates/ui-gallery/src/chrome/overview.rs +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -16,7 +16,7 @@ use craft_ui::pickers::Select; use craft_ui::runtime::env::{Env, WindowKey}; use craft_ui::shell::AppShell; use craft_ui::style::SurfaceKind; -use craft_ui::testing::StoryRegistration; +use craft_ui::testing::{StoryRegistration, least_stage_width}; use egui::Ui; /// A card's story row before it ran, in standard control heights (120 at a 24 control). @@ -24,7 +24,7 @@ const STORY_ROW_IN_CONTROLS: f32 = 5.0; /// The narrowest a card may be before the cards go to one column: a story at its least width inside the card's padding. fn card_min_width(tokens: &Tokens) -> f32 { - tokens.size.story.width_min + 2.0 * tokens.space.pad.regular + least_stage_width(tokens) + 2.0 * tokens.space.pad.regular } const ONE: &[ColumnWidth] = &[ColumnWidth::fill(1.0)]; diff --git a/crates/ui-patterns/src/patterns/preferences/window.rs b/crates/ui-patterns/src/patterns/preferences/window.rs index c056738dc..f78ef4648 100644 --- a/crates/ui-patterns/src/patterns/preferences/window.rs +++ b/crates/ui-patterns/src/patterns/preferences/window.rs @@ -24,9 +24,9 @@ use std::cell::RefCell; use std::sync::Arc; /// The size the window opens at until the user resizes it. -pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0); // design: allow[literal-size/vec2](the window's own opening size in points) +pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0); /// The least size the window may be resized to. -pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0); // design: allow[literal-size/vec2](the window's own least size in points) +pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0); /// What the window keeps between passes; the host owns it and binds it with [`PreferencesWindow::new`]. #[derive(Clone, Debug, Default, PartialEq)] diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index 9c3bdce04..2c5f794d9 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -155,8 +155,6 @@ pub struct NoticeStyle { /// The icon's side and colour. #[style(icon)] icon: IconLook, - /// The width of every card, padding included, where the room allows. - card_width: f32, /// The widest column of the centred layout. reading_width: f32, } @@ -165,6 +163,9 @@ pub struct NoticeStyle { /// column in the source apps. const READING_IN_BODY_SIZES: f32 = 38.5; +/// The width of every card of a toast stack, padding included, where the room allows, in points, in every density. +const CARD_WIDTH: f32 = 360.0; + /// A message in a tone. The tone picks the icon and the colours; the neutral tone reads muted and has no icon. The /// message is the label; a title above it is optional. A centred notice can host the app's own leaves under its /// actions (a drop hint, "No recent files"). Actions read as links (as buttons in the centred layout) and @@ -541,7 +542,6 @@ impl Component for Notice<'_> { line, more, icon: IconLook::new(control.icon, stateful(tone)), - card_width: cx.tokens.size.notice.width, reading_width: cx.tokens.typography.get(TypeRole::Body).size * READING_IN_BODY_SIZES, } } @@ -554,7 +554,7 @@ impl Component for Notice<'_> { // The card is the card width wide, its padding included, where the room allows. (NoticeLayout::Card, room) => { let padding = cx.style.metrics.padding; - let width = cx.style.card_width - padding.start - padding.end; + let width = CARD_WIDTH - padding.start - padding.end; room.map_or(width, |room| width.min(room)) } (NoticeLayout::Centred, None) => natural.min(cx.style.reading_width), diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 18697afe7..13a4a1d5f 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -440,11 +440,10 @@ An app has one layout in every theme and size. A theme never changes the layout. Use the first step that works. 1. **Density.** Compact or Comfortable. -2. **Size overrides.** The app ships a `sizes.json` that overrides base sizes (for example `size.control.md`). A base override carries to every size derived from it. To change one component, pin that component's token. Overrides stay within the validator's limits. -3. **Component tokens.** One named value changes a component app-wide. -4. **Builder options.** Options cover structural differences. A new need gets a new option, not a new component. -5. **Per-app colour overrides.** A theme file can carry a section per app. Values are theme roles or literal colours, so themes, dark mode and high contrast keep working. -6. **One-off app components.** A last resort, built from shared pieces. Allowed and not policed. +2. **Size overrides.** The app ships a `sizes.json` that overrides base sizes (for example `size.control.md`). A base override carries to every size derived from it. Overrides stay within the validator's limits. +3. **Builder options.** Options cover structural differences. A new need gets a new option, not a new component. +4. **Per-app colour overrides.** A theme file can carry a section per app. Values are theme roles or literal colours, so themes, dark mode and high contrast keep working. +5. **One-off app components.** A last resort, built from shared pieces. Allowed and not policed. ### 4.7 Themes @@ -501,9 +500,9 @@ Sizes are runtime tokens. The rule runs from the general to the specific: 1. A **scale** holds the allowed values: spacing 0, 2, 4, 6, 8, 12, 16, 20, 24, 32; radius 0, 2, 3, 4, 6, 8, 12 and full; strokes hairline, 1, 1.5, 2, 3. 2. **Semantic role tokens** pick from the scale by meaning: control height, icon size, gap, padding, radius, bar height. -3. **Components** derive their own dimensions from the role tokens in their style: a role, or a role times a ratio named in the component's style with the rule it comes from. There are no component-specific theme values. +3. **Components** take their layout sizes (heights, widths, padding, gaps between parts) from role tokens. A dimension that belongs to one component's own drawing, such as tick lengths, glyph geometry, a notch or an inset inside its art, is a named constant in the component's file with a doc comment (a ruler's `TICK_MINOR`), never a literal at the draw site. When it must follow density, the constant is a ratio of a role token (a story stage is 15 control heights tall). No theme or size-preset token exists for one component. -Components name semantic tokens and never a pixel value or shape of their own. [Appendix A](#appendix-a-component-tokens) says which component takes which role. Only drawing details (stroke widths, chevron geometry, dash lengths) stay constants. +[Appendix A](#appendix-a-component-tokens) says which component takes which role. **Semantic role tokens (pt).** @@ -686,6 +685,7 @@ How to run each locally, and which of them CI runs, is in [development.md](devel ### 8.3 Design lint - Rules: `literal-size/*`, `raw-colour/const`, `style-mutation`, `tooltip/stock`, `clippy/inner-allow`. +- `literal-size/*` flags literal sizes at a call site and names of consts with literal values, except a module- or impl-level `const` with a doc comment: that is a component constant ([5.4](#54-dimensions)), and its initializer is its definition. - Exemption marker: `// design: allow(reason)`. Empty, invalid and unused markers are findings. - Baselines and `--deny-unused` are supported. - Exit 0 clean, 1 findings, 2 error. @@ -893,7 +893,7 @@ The library replaces upstream's `craft-ui` crate, and changes public items in `c ## Appendix A. Component tokens -Maintainer reference. The rule is in [5.4 Dimensions](#54-dimensions): components name semantic tokens, and semantic tokens pick from the scale. This page lists which role each component takes. +Maintainer reference. The rule is in [5.4 Dimensions](#54-dimensions): components take their layout sizes from semantic tokens, semantic tokens pick from the scale, and a dimension of one component's own drawing is a constant in its file. This page lists which role each component takes. ### Semantic colour tokens @@ -990,7 +990,6 @@ A theme with its own shape replaces the radii or adds an offset to control, surf | `size.bar.title`, `size.bar.tab`, `size.bar.status`, `size.bar.options`, `size.bar.options_narrow` | Title bar, document tab bar, status bar, options bar | | `size.panel_header` | Panel headers | | `size.popup_min` | Least width of a popup surface (menus only; popup lists such as Select and ComboBox take their anchor's width) | -| `size.scroll_fade` | Length of the fade at an edge of a scroll region past which its content continues | | `size.groove` | Groove of a value track | | `size.ramp.bar` | Colour band: a gradient ramp drawn as a bar of its own (levels output bar, gradient thumb row) or as the face of a triangle-pointer channel slider | | `size.ramp.groove` | Gradient drawn as the groove of a value track (faced sliders) and the span between two thumbs of a gradient's thumb row | @@ -999,10 +998,8 @@ A theme with its own shape replaces the radii or adds an offset to control, surf | `size.length.number.sm`, `size.length.number.md` | Number field and the number cell over a slider, one width per control size | | `size.length.track`, `size.length.short` | Value track, short field | | `size.row.text` | A row that shows text only: one body line and `space.gap.tight`; read-only display tables take it, lists the user picks from keep control-high rows | -| `size.notice.width` | Width of a toast card where the room allows | | `size.dialog.least`, `size.dialog.wrap` | A dialog's content: the least width it opens at, and the line length its paragraphs wrap at (`LeastWidth::Dialog`, `WrapWidth::Dialog`); content that cannot wrap widens it past that | | `size.dialog.button`, `size.dialog.side_button` | Least width of a dialog's footer button and of a button in its column beside the body | -| `size.story.height`, `size.story.width_min`, `size.story.width_max` | The stage a story of a canvas control draws its canvas on: its height and the range of its width; `width_min` is also the least width of a column of a story grid | | `size.hit.edge` | The band inside the edge of a canvas's view in which a tool that autoscrolls on hover scrolls the view (a Polygonal Lasso's rubber band), at most a quarter of the view's shorter side | | `size.thumb.card` | The picture side of a tile card at zoom 1 (tile grids, preset browsers, the start screen) | | `size.thumb.sample.sm`, `size.thumb.sample.md`, `size.thumb.sample.lg` | The sample beside each thumbnail size choice in a panel's options dialog (Layers, Channels, Paths): larger than the panel's thumbnails, so the choices read apart (`PictureSize::Sample`) | @@ -1631,7 +1628,6 @@ The theme model: colour, scale and token primitives, semantic tokens, contrast r | `app_sizes` | An app's size overrides (`sizes.json`) | exists | | `builtins` | The ten built-in themes | exists | | `color`, `color_model` | sRGB, OKLab and OKLCH with gamut mapping; colour models a picker edits in; hex helpers | exists | -| `components` | Component tokens, one struct per family | exists | | `contrast` | WCAG contrast and repair | exists | | `derive`, `ramp` | Seeds to ramps to tokens; 12-step ramps | exists | | `dump`, `explain`, `report` | Token text dump, why each colour has its value, contrast sweep | exists | diff --git a/docs/porting.md b/docs/porting.md index 7bb144add..f7a03e41b 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -65,9 +65,9 @@ Before marking a part `missing component`, walk this ladder and stop at the firs 1. **An existing component as is.** Search components-index.md by purpose and by shape, and look at the component's stories in the gallery. 2. **An existing component with a new story or variant.** If the component already does the job and only lacks a shown state, add the story (authoring.md, "Stories"). A story is a state of an existing type, not a new type. -3. **A builder option on an existing component.** A structural difference gets a new option on the component, not a new component (craft-framework.md 4.6, step 4). -4. **Density, size overrides or component tokens.** Visual differences an app needs are tokens and size overrides, never component-specific theme values (craft-framework.md 4.6, steps 1–3). -5. **Per-app colour overrides** in the theme file (craft-framework.md 4.6, step 5). +3. **A builder option on an existing component.** A structural difference gets a new option on the component, not a new component (craft-framework.md 4.6, step 3). +4. **Density or size overrides.** Visual differences an app needs are tokens and size overrides, never a theme value for one component (craft-framework.md 4.6, steps 1–2). +5. **Per-app colour overrides** in the theme file (craft-framework.md 4.6, step 4). 6. **A family component** in the crate that owns the document concept, when the part names one (layer, colour model, path): craft-framework.md 4.3. 7. **A new library component**, when its inputs are general data and no existing component fits. Place it in the lowest crate of its layer (craft-framework.md 4.3). 8. **A one-off app component**, built from shared pieces, as a last resort. diff --git a/migration/api-map/canvas-core.toml b/migration/api-map/canvas-core.toml index 5529bc472..c885251da 100644 --- a/migration/api-map/canvas-core.toml +++ b/migration/api-map/canvas-core.toml @@ -152,7 +152,7 @@ name = "RulerTick" old = "craft_ui::canvas::rulers::RulerTick" new = "craft_ui::canvas::RulerTick" status = "moved" -note = "`RulerTick { value, rank: primitives::TickRank, step }`: the label text is written at paint time from `RulerText::tick_label`, and the rank is Major at a labelled step, Mid halfway between labels in an even subdivision, Minor otherwise (`primitives::ticks` draws the length by rank; the mid length is the token `size.ruler.tick.mid`)." +note = "`RulerTick { value, rank: primitives::TickRank, step }`: the label text is written at paint time from `RulerText::tick_label`, and the rank is Major at a labelled step, Mid halfway between labels in an even subdivision, Minor otherwise (`primitives::ticks` draws the length by rank; the minor and mid lengths are the constants `TICK_MINOR` and `TICK_MID` in `primitives/kit.rs`)." [[type]] name = "TickRule" From c9d84670b064883d18856b49ca41cdc97a850b8a Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 17:39:51 +0000 Subject: [PATCH 02/89] design-lint: drop the exception entries the component-constant rule leaves stale --- design/exceptions/craft-draw/crate.toml | 8 -------- design/exceptions/craft-pages/stories.toml | 9 --------- design/exceptions/craft-print/crate.toml | 2 +- design/exceptions/craft-ui-canvas/canvas.toml | 9 --------- design/exceptions/craft-ui-contract/primitives.toml | 2 +- design/exceptions/craft-ui-patterns/preferences.toml | 9 --------- 6 files changed, 2 insertions(+), 37 deletions(-) delete mode 100644 design/exceptions/craft-pages/stories.toml delete mode 100644 design/exceptions/craft-ui-canvas/canvas.toml delete mode 100644 design/exceptions/craft-ui-patterns/preferences.toml diff --git a/design/exceptions/craft-draw/crate.toml b/design/exceptions/craft-draw/crate.toml index 74c710de8..f283a2909 100644 --- a/design/exceptions/craft-draw/crate.toml +++ b/design/exceptions/craft-draw/crate.toml @@ -7,11 +7,3 @@ rule = "raw-colour/const" path = "crates/draw/src/ui/artboard/stories.rs" reason = "The artboard background is document data in a story, not a UI colour." count = 2 - -[[exception]] -name = "convert-point-cursor-tip" -kind = "marker" -rule = "literal-size/vec2" -path = "crates/draw/src/ui/pen/anchor_tool.rs" -reason = "The cursor art's hot spot offset is in icon units, not a layout size." -count = 1 diff --git a/design/exceptions/craft-pages/stories.toml b/design/exceptions/craft-pages/stories.toml deleted file mode 100644 index 2c3c1d481..000000000 --- a/design/exceptions/craft-pages/stories.toml +++ /dev/null @@ -1,9 +0,0 @@ -config_version = 1 - -[[exception]] -name = "page-rulers-story-strip" -kind = "marker" -rule = "literal-size/vec2" -path = "crates/pages/src/ui/page_rulers/stories.rs" -reason = "The strip is the demo page margin in document points, story data." -count = 1 diff --git a/design/exceptions/craft-print/crate.toml b/design/exceptions/craft-print/crate.toml index aa4a9c243..abd78ce16 100644 --- a/design/exceptions/craft-print/crate.toml +++ b/design/exceptions/craft-print/crate.toml @@ -6,7 +6,7 @@ kind = "marker" rule = "literal-size/vec2" path = "crates/print/src/ui/dialog.rs" reason = "Printer's marks are page geometry in points, not UI sizes." -count = 4 +count = 2 [[exception]] name = "print-story-page-sizes" diff --git a/design/exceptions/craft-ui-canvas/canvas.toml b/design/exceptions/craft-ui-canvas/canvas.toml deleted file mode 100644 index 27a7d94cd..000000000 --- a/design/exceptions/craft-ui-canvas/canvas.toml +++ /dev/null @@ -1,9 +0,0 @@ -config_version = 1 - -[[exception]] -name = "view-fit-margins" -kind = "marker" -rule = "literal-size/vec2" -path = "crates/ui-canvas/src/canvas/tools.rs" -reason = "The room a view fit leaves around the document is in screen points, not a look." -count = 2 diff --git a/design/exceptions/craft-ui-contract/primitives.toml b/design/exceptions/craft-ui-contract/primitives.toml index 8c9d73b21..c4865a434 100644 --- a/design/exceptions/craft-ui-contract/primitives.toml +++ b/design/exceptions/craft-ui-contract/primitives.toml @@ -6,7 +6,7 @@ kind = "marker" rule = "literal-size/vec2" path = "crates/ui-contract/src/primitives/pointer_art.rs" reason = "Painted pointers are drawn in points around the hotspot like an OS cursor bitmap; their sides are art data, not layout sizes." -count = 2 +count = 1 [[exception]] name = "icon-fixed-layer-tint" diff --git a/design/exceptions/craft-ui-patterns/preferences.toml b/design/exceptions/craft-ui-patterns/preferences.toml deleted file mode 100644 index b1d675b49..000000000 --- a/design/exceptions/craft-ui-patterns/preferences.toml +++ /dev/null @@ -1,9 +0,0 @@ -config_version = 1 - -[[exception]] -name = "preferences-window-sizes" -kind = "marker" -rule = "literal-size/vec2" -path = "crates/ui-patterns/src/patterns/preferences/window.rs" -reason = "The window opens at and shrinks to sizes of its own, in points." -count = 2 From 48cef3fa60e2e9ecf7bff32acf0328a0c246a2ed Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 17:42:03 +0000 Subject: [PATCH 03/89] contract-api.md: ScrollBarLook without its fade length --- docs/contract-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index 006b1c940..276d6607d 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -3902,7 +3902,7 @@ The style layer: the state set and its resolver, style parts and `ComponentStyle - `pub fn pixels(self, pixels_per_point: f32) -> f32`. The width in whole physical pixels on a display of `pixels_per_point`. - `pub fn points(self, pixels_per_point: f32) -> f32`. The width in points on a display of `pixels_per_point`. - `craft_ui::style::ScrollBarKind`: `pub enum ScrollBarKind { Overlay, Docked }`. Where a scroll bar sits. -- `craft_ui::style::ScrollBarLook`: `pub struct ScrollBarLook { pub kind: ScrollBarKind, pub track: Stateful, pub thumb: Stateful, pub thickness: f32, pub min_thumb: f32, pub inset: f32, pub edge: Option, pub fade: f32 }`. A scroll bar's track and thumb. +- `craft_ui::style::ScrollBarLook`: `pub struct ScrollBarLook { pub kind: ScrollBarKind, pub track: Stateful, pub thumb: Stateful, pub thickness: f32, pub min_thumb: f32, pub inset: f32, pub edge: Option }`. A scroll bar's track and thumb. - `craft_ui::style::State`: re-export of `craft_theme::State` (outside these crates). - `craft_ui::style::StateMix`: re-export of `craft_theme::StateMix` (outside these crates). - `craft_ui::style::StateSet`: `pub struct StateSet { pub state: State, pub flags: Flags, pub t: StateMix }`. The state of a component or one of its parts at step 12: the interaction state, the value flags and the From ea48749d346991e189687250290cbcb998821556 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 12:26:24 +0000 Subject: [PATCH 04/89] Derived: a value kept per component id and rebuilt only when its key changes `runtime::derived::derived(ctx, id, &key, build)` (and `BodyCx::derived`) keeps one value per id and value type. The key is `MemoProps`, so it holds only checked inputs. A value no pass asks for is dropped by the memo rule for absent entries, which moves into one helper both stores call. `testing::last_pass_derived_builds` counts builds. Part of #2336. --- crates/ui-contract/src/contract/cx/body.rs | 6 ++ crates/ui-contract/src/runtime/derived.rs | 75 +++++++++++++++++++ .../ui-contract/src/runtime/layout_memory.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 28 ++++--- crates/ui-contract/src/runtime/measure.rs | 34 +++++++++ crates/ui-contract/src/runtime/mod.rs | 1 + crates/ui-contract/src/runtime/pass_state.rs | 3 + crates/ui-contract/src/testing/mod.rs | 5 +- .../ui-contract/tests/it/runtime/derived.rs | 62 +++++++++++++++ crates/ui-contract/tests/it/runtime/mod.rs | 1 + 10 files changed, 205 insertions(+), 11 deletions(-) create mode 100644 crates/ui-contract/src/runtime/derived.rs create mode 100644 crates/ui-contract/tests/it/runtime/derived.rs diff --git a/crates/ui-contract/src/contract/cx/body.rs b/crates/ui-contract/src/contract/cx/body.rs index 14f0080ca..ac8624c33 100644 --- a/crates/ui-contract/src/contract/cx/body.rs +++ b/crates/ui-contract/src/contract/cx/body.rs @@ -203,6 +203,12 @@ impl<'a> BodyCx<'a> { } impl BodyCx<'_> { + /// The value this body derives from `key`: kept while `key` is unchanged, else built by `build` + /// ([`runtime::derived`](crate::runtime::derived::derived), under the body's id). + pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc { + crate::runtime::derived::derived(self.memory.ctx(), self.id, key, build) + } + /// Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it /// is empty. `true` once per Escape; the enclosing scope (a dialog, a popover) then does not act on it. /// Components shown earlier in the body have run by the time the body asks. diff --git a/crates/ui-contract/src/runtime/derived.rs b/crates/ui-contract/src/runtime/derived.rs new file mode 100644 index 000000000..3334103ef --- /dev/null +++ b/crates/ui-contract/src/runtime/derived.rs @@ -0,0 +1,75 @@ +//! Derived values: data a component computes from its inputs and keeps across passes. [`derived`] keeps one value per +//! component id and value type, and builds it again only when its key changes. The key implements +//! [`MemoProps`](crate::contract::MemoProps), so it can only be made of checked inputs (`Tracked` revisions, framework +//! revisions, plain values), and a kept value is never stale while the key compiles. +//! +//! A value no pass asks for is dropped by the rule memoized views follow for absent entries (`lazy::absent_past_room`). + +use crate::contract::{MemoKey, MemoProps}; +use crate::runtime::egui::pass; +use crate::runtime::frame::PerViewport; +use egui::{Context, Id, IdMap}; +use std::any::{Any, TypeId}; +use std::sync::Arc; + +/// A kept value: the key it was built from and the frame a pass last asked for it. +struct Entry { + key: u128, + value: Arc, + touched: u64, +} + +/// The kept values of one viewport. +#[derive(Default)] +pub(crate) struct Store { + entries: IdMap, + /// The frame the entries were last pruned in. + pruned: u64, +} + +impl Store { + /// Drops the absent entries past the memo rule's room, once per frame. An entry asked for in this frame or the one + /// before is shown. + fn prune(&mut self, frame: u64) { + if self.pruned == frame { + return; + } + self.pruned = frame; + let shown = self.entries.values().filter(|entry| entry.touched + 1 >= frame).count(); + let absent = self.entries.iter().filter(|(_, entry)| entry.touched + 1 < frame).map(|(id, entry)| (entry.touched, *id)); + for id in super::lazy::absent_past_room(shown, absent) { + self.entries.remove(&id); + } + } +} + +/// The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else +/// `build`'s, which is kept in its place. One value is kept per id and value type `V`; a component that derives two +/// values of one type gives each its own id. +pub fn derived(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc { + let mut memo = MemoKey::of_view(ctx); + memo.feed_hash(&K::identity()); + key.key(&mut memo); + #[cfg(feature = "testing")] + crate::runtime::measure::count_memo_key_bytes(ctx, memo.bytes()); + let key = memo.finish(); + let slot = id.with(TypeId::of::()); + let viewport = pass::current_viewport(ctx); + let frame = pass::frame_nr(ctx, viewport); + let kept = PerViewport::::with(ctx, viewport, |store| { + store.prune(frame); + let entry = store.entries.get_mut(&slot).filter(|entry| entry.key == key)?; + entry.touched = frame; + Arc::clone(&entry.value).downcast::().ok() + }); + if let Some(value) = kept { + return value; + } + #[cfg(feature = "testing")] + crate::runtime::measure::count_derived(ctx, id); + // Built outside the store, so a build may derive values of its own. + let value = Arc::new(build()); + let entry = Entry { key, value: Arc::clone(&value) as Arc, touched: frame }; + PerViewport::::with(ctx, viewport, |store| store.entries.insert(slot, entry)); + value +} diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 4da3ef9fc..dce40db69 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1270,6 +1270,7 @@ pub(crate) mod guard { "runtime::lazy::Store", "lazy extents: the kept extent of content out of view, its own mechanism; a pass a kept transcript serves decides in its real run, which compares each row by its backstop", ), + ("runtime::derived::Store", "derived values: a pure function of their key, so a value a measuring run builds is the one a real run builds"), ("contract::steps::scroll_owner::", "scroll reveals and moves: read; taken through take_queued"), ("contract::body::scroll::Jumps", "scroll jumps: taken through take_queued"), ("runtime::edit::CancelAll", "edit cancels: read; a measuring run ends nothing"), diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 3a46b3231..19b1b46e3 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -335,6 +335,20 @@ impl Store { } } +/// The memo rule for absent entries, shared by every memo store (memoized views, `runtime::derived`): an entry +/// outlives its absence while the absent ones are at most twice as many as the shown ones, the longest absent dropped +/// first. Takes the absent entries as (frame last touched, id) and returns the ones to drop. +pub(crate) fn absent_past_room(shown: usize, absent: impl IntoIterator) -> Vec { + let mut absent: Vec<(u64, Id)> = absent.into_iter().collect(); + let room = 2 * shown; + if absent.len() <= room { + return Vec::new(); + } + absent.sort_unstable_by_key(|(touched, _)| *touched); + absent.truncate(absent.len() - room); + absent.into_iter().map(|(_, id)| id).collect() +} + fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { let viewport = pass::current_viewport(ctx); let (pass_nr, frame) = (pass::pass_nr(ctx, viewport), pass::frame_nr(ctx, viewport)); @@ -345,16 +359,12 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { store.pruned = frame; let reached = &store.reached; store.entries.retain(|_, entry| entry.memo() || entry.live(frame, reached)); - // A memoized view's entry outlives its absence while the absent ones are at most twice as many as the shown - // ones, the longest absent dropped first: a view shown again with the same props replays. + // A memoized view's entry outlives its absence by the memo rule: a view shown again with the same props + // replays. let shown = store.entries.values().filter(|entry| entry.memo() && entry.live(frame, reached)).count(); - let mut absent: Vec<(u64, Id)> = - store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)).collect(); - if absent.len() > 2 * shown { - absent.sort_unstable_by_key(|(touched, _)| *touched); - for (_, id) in &absent[..absent.len() - 2 * shown] { - store.entries.remove(id); - } + let absent = store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)); + for id in absent_past_room(shown, absent) { + store.entries.remove(&id); } let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect(); store.reached.retain(|owner, _| owners.contains(owner)); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 6a789786a..8fd0fc014 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -52,6 +52,14 @@ struct BodyRuns { runs: Vec<(Id, u32)>, } +/// The derived values built in a pass, by component id, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +pub(crate) struct DerivedBuilds { + pass: u64, + builds: Vec<(Id, u32)>, +} + /// How many contributions the measuring runs of a pass made that stand, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -540,6 +548,32 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { last_totals(ctx, |log| log.key_bytes, 0) } +/// Counts a build of a derived value of the component `id` in this pass (`runtime::derived`). +#[cfg(feature = "testing")] +pub(crate) fn count_derived(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } + let pass = ctx.cumulative_pass_nr(); + pass_state::with::(ctx, |log| { + if log.pass != pass { + *log = DerivedBuilds { pass, builds: Vec::new() }; + } + match log.builds.iter_mut().find(|(of, _)| *of == id) { + Some((_, count)) => *count += 1, + None => log.builds.push((id, 1)), + } + }); +} + +/// The components that built a derived value in the last pass, and how many builds each; empty when that pass built +/// none. +#[cfg(feature = "testing")] +pub fn last_pass_derived_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + pass_state::with::(ctx, |log| if log.pass == last { log.builds.clone() } else { Vec::new() }) +} + /// 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) { diff --git a/crates/ui-contract/src/runtime/mod.rs b/crates/ui-contract/src/runtime/mod.rs index 74870f6bb..168e97e3e 100644 --- a/crates/ui-contract/src/runtime/mod.rs +++ b/crates/ui-contract/src/runtime/mod.rs @@ -5,6 +5,7 @@ pub mod access; pub(crate) mod audit; pub mod commands; pub mod cursor; +pub mod derived; pub mod drag; pub mod edit; pub mod egui; diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 47a8da311..a2fbf0034 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -119,6 +119,8 @@ pass_state! { memo_log: crate::runtime::measure::MemoLog, #[cfg(feature = "testing")] pass_totals: crate::runtime::measure::PassTotals, + #[cfg(feature = "testing")] + derived_builds: crate::runtime::measure::DerivedBuilds, } records { focus: crate::runtime::focus::State, @@ -126,6 +128,7 @@ pass_state! { cursor: crate::runtime::cursor::State, layout: crate::runtime::layout_memory::Entries, lazy: crate::runtime::lazy::Store, + derived: crate::runtime::derived::Store, arenas: crate::primitives::sensing::Arenas, envs: crate::runtime::env::ViewportEnvs, pointer: crate::runtime::pointer::Memory, diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 27c05cfeb..32977778f 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -46,8 +46,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs, - last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, - last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, + last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, + last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, + widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-contract/tests/it/runtime/derived.rs b/crates/ui-contract/tests/it/runtime/derived.rs new file mode 100644 index 000000000..dbb8343de --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/derived.rs @@ -0,0 +1,62 @@ +//! Derived values: built once per key, kept while the key is unchanged, and dropped by the memo rule once absent. + +use craft_ui::runtime::derived::derived; +use craft_ui::testing::{Fixture, last_pass_derived_builds, trial}; +use egui::Id; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +/// A fixture whose pass derives a value under each id `ids` holds, keyed by `key`; `seen` collects the values. +fn deriving(ids: Rc>>, key: Rc>, seen: Rc>>>) -> Fixture { + Fixture::new(move |ui| { + seen.borrow_mut().clear(); + for id in ids.borrow().iter() { + let value = derived(ui.ctx(), Id::NULL.with(("derived", *id)), &key.get(), || format!("{id} at {}", key.get())); + seen.borrow_mut().push(value); + } + }) +} + +/// The number of builds in the last pass. +fn builds(fixture: &Fixture) -> u32 { + last_pass_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum() +} + +/// An unchanged key returns the kept value without a build; a changed key builds once, then keeps that. +#[trial] +fn a_derived_value_builds_once_per_key() { + let (ids, key, seen) = (Rc::new(RefCell::new(vec![1])), Rc::new(Cell::new(7)), Rc::default()); + let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen)); + fixture.frame(Vec::new()); + let first = Arc::clone(&seen.borrow()[0]); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "an unchanged key builds nothing"); + assert!(Arc::ptr_eq(&seen.borrow()[0], &first), "and returns the kept value"); + } + key.set(8); + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 1, "a changed key builds once"); + assert_eq!(*seen.borrow()[0], "1 at 8"); + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "then keeps the new value"); +} + +/// A value no pass asks for is kept while the absent ones are at most twice the shown ones, and dropped past that. +#[trial] +fn an_absent_derived_value_is_dropped_by_the_memo_rule() { + let (ids, key, seen) = (Rc::new(RefCell::new(vec![1, 2, 3])), Rc::new(Cell::new(0)), Rc::default()); + let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen)); + fixture.frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1]; + fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1, 2, 3]; + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "two absent values beside one shown are kept"); + *ids.borrow_mut() = Vec::new(); + fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1]; + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 1, "with none shown, every absent value was dropped"); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 44af1552c..d24b2afb1 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -4,6 +4,7 @@ mod chord_fallthrough; mod clipboard; mod control_click; mod cursor; +mod derived; mod elapsed; mod env; mod frame; From 42739aaa2d2a2e2f3f24f76c7e59a60bc5661a3f Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 12:26:24 +0000 Subject: [PATCH 05/89] Dock on Derived: tracked panel specs, workspace revisions, layout-owned window ids - `Workspace` fields are private. `revision()` moves with every write (a clone is a new source); `generation()` moves only on `replace` and ends drags as the old revision did. A trial walks every `&mut self` method, read from the source. - Panel specs and permissions leave `DockPanels` for `PanelSpecs`, a plain-data model the host keeps in a `Tracked`. `DockArea` binds `Arc` and derives specs, permissions and keys from the workspace revision, the specs revision and the lock: an idle pass reads no spec, read-only docks included. - `DockGrid::rail(cells)` is sized by the dock from its own tokens. - Floating window ids come from a counter the layout owns; `replace` gives incoming windows ids the replaced layout never gave out. The dock's global id counter and its `no-global-state` allowlist entry are gone. Part of #2336. --- crates/behavior/src/dock/edit.rs | 9 +- crates/behavior/src/dock/layout.rs | 43 +++- crates/behavior/src/dock/node.rs | 78 +++---- crates/behavior/src/dock/policy.rs | 2 +- crates/behavior/src/dock/workspace.rs | 108 ++++++++-- crates/behavior/src/dock/workspaces.rs | 4 +- crates/behavior/tests/dock.rs | 9 +- crates/behavior/tests/dock_apply.rs | 195 +++++++++++++----- crates/cloud-ui/src/esign/mod.rs | 10 +- crates/design-lint/src/workspace.rs | 2 - crates/ui-gallery/src/chrome/dock.rs | 10 +- crates/ui-gallery/src/chrome/mod.rs | 1 + crates/ui-gallery/src/chrome/shell.rs | 22 +- crates/ui-gallery/src/mock/editor.rs | 29 +-- crates/ui-gallery/src/mock/model.rs | 10 +- crates/ui-gallery/src/mock/panels.rs | 14 +- crates/ui-gallery/src/viewer/layout.rs | 4 +- crates/ui-gallery/src/viewer/state.rs | 27 ++- crates/ui-gallery/tests/it/viewer.rs | 4 +- crates/ui-panels/src/docking/drop.rs | 8 +- crates/ui-panels/src/docking/mod.rs | 2 +- crates/ui-panels/src/docking/panels.rs | 59 ++++-- crates/ui-panels/src/docking/spec.rs | 53 ++++- crates/ui-panels/src/docking/stories.rs | 11 +- crates/ui-panels/src/docking/targets.rs | 7 + crates/ui-panels/src/docking/window_menu.rs | 15 +- crates/ui-panels/src/rails/tool.rs | 16 +- crates/ui-patterns/src/patterns/dock/area.rs | 195 +++++++++++------- .../src/patterns/dock/area/stories.rs | 25 ++- .../ui-patterns/tests/it/docking/columns.rs | 52 ++--- .../ui-patterns/tests/it/docking/dock_back.rs | 2 +- crates/ui-patterns/tests/it/docking/drop.rs | 2 +- .../tests/it/docking/drop_preview.rs | 20 +- .../tests/it/docking/floating_area.rs | 113 +++++----- .../tests/it/docking/group_view.rs | 19 +- crates/ui-patterns/tests/it/docking/hidden.rs | 21 +- crates/ui-patterns/tests/it/docking/mod.rs | 10 + crates/ui-patterns/tests/it/docking/native.rs | 173 +++++++++------- .../tests/it/docking/panel_menu.rs | 35 ++-- crates/ui-patterns/tests/it/docking/runs.rs | 136 ++++++++---- docs/ui-docking.md | 24 ++- 41 files changed, 1017 insertions(+), 562 deletions(-) diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 8d116bd79..b8572fcd0 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -330,6 +330,7 @@ impl Layout

{ .iter() .map(|w| Floating { column: column_shape(&w.column), rect: Rect::ZERO, native: None, edge: None, ..w.clone() }) .collect(), + next_window: self.next_window, } } @@ -512,9 +513,13 @@ impl Layout

{ return Err(DockError::InvalidGeometry); } // A window's width is its rect's; only a collapsed column keeps to an edge of its own. - let window = Floating::new(Column { width: None, ..moving.column }, rect); + let id = match moving.id { + Some(id) => id, + None => self.fresh_window_id(), + }; + let window = Floating::new(id, Column { width: None, ..moving.column }, rect); let edge = edge.filter(|_| window.column.iconic); - self.floating.push(Floating { id: moving.id.unwrap_or(window.id), edge, ..window }); + self.floating.push(Floating { edge, ..window }); Ok(()) } Target::NewDock { side } => { diff --git a/crates/behavior/src/dock/layout.rs b/crates/behavior/src/dock/layout.rs index ec3d68d10..f5b13eef7 100644 --- a/crates/behavior/src/dock/layout.rs +++ b/crates/behavior/src/dock/layout.rs @@ -19,7 +19,9 @@ use super::{ }; /// The panels of a workspace: a docked tree plus floating windows. Every panel occurs once. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +/// +/// Equality compares the tree and the windows, not the window id counter. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub struct Layout

{ /// The docked layout; `None` when nothing is docked. @@ -27,18 +29,53 @@ pub struct Layout

{ /// Floating windows, with unique ids. #[serde(deserialize_with = "super::node::floating_serde::unique_ids")] pub floating: Vec>, + /// The least id [`Self::fresh_window_id`] may draw: above every id this layout has drawn, and above every id + /// the layouts it replaced held. Not saved. + #[serde(skip)] + pub(super) next_window: u64, +} + +impl PartialEq for Layout

{ + fn eq(&self, other: &Self) -> bool { + self.root == other.root && self.floating == other.floating + } } impl

Default for Layout

{ fn default() -> Self { - Self { root: None, floating: Vec::new() } + Self { root: None, floating: Vec::new(), next_window: 0 } } } impl

Layout

{ /// A layout with the docked tree `root` and the floating windows `floating`. pub fn new(root: Option>, floating: Vec>) -> Self { - Self { root, floating } + Self { root, floating, next_window: 0 } + } + + /// An id for a new floating window: above every window id the layout holds or has drawn, so an id, and the OS + /// window it names, is never given to another window while the layout lives. + pub fn fresh_window_id(&mut self) -> u64 { + let id = self.window_floor(); + self.next_window = id.saturating_add(1); + id + } + + /// The least id no window of the layout holds or has held. + fn window_floor(&self) -> u64 { + self.floating.iter().map(|window| window.id.saturating_add(1)).fold(self.next_window, u64::max) + } + + /// Takes the windows of `incoming`, which replaces this layout, onto ids this layout never gave out: a window + /// whose id is below this layout's floor gets a fresh one, and the counter keeps growing from both. + pub(super) fn hand_ids_to(&self, incoming: &mut Layout

) { + let floor = self.window_floor(); + incoming.next_window = incoming.window_floor().max(floor); + let stale: Vec = incoming.floating.iter().enumerate().filter(|(_, window)| window.id < floor).map(|(at, _)| at).collect(); + for at in stale { + let id = incoming.fresh_window_id(); + incoming.floating[at].id = id; + } } } diff --git a/crates/behavior/src/dock/node.rs b/crates/behavior/src/dock/node.rs index b9b2f68cc..1d0a0bfd8 100644 --- a/crates/behavior/src/dock/node.rs +++ b/crates/behavior/src/dock/node.rs @@ -126,35 +126,20 @@ impl

StackEntry

{ } } -/// A window id no other window of this process has drawn, from a random start so ids saved -/// by earlier runs are unlikely to repeat. -pub(super) fn fresh_window_id() -> u64 { - use std::hash::{BuildHasher, Hasher}; - use std::sync::{ - OnceLock, - atomic::{AtomicU64, Ordering}, - }; - static NEXT: OnceLock = OnceLock::new(); - let next = NEXT.get_or_init(|| AtomicU64::new(std::collections::hash_map::RandomState::new().build_hasher().finish() >> 1)); - next.fetch_add(1, Ordering::Relaxed) -} - impl

Floating

{ - /// A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build - /// a layout once and keep it, or give its windows ids with [`Self::with_id`]. A layout - /// built anew each frame without them opens new OS windows each frame. - pub fn new(column: Column

, rect: Rect) -> Self { - Self { id: fresh_window_id(), column, rect, native: None, edge: None } + /// The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id + /// from [`Layout::fresh_window_id`](super::Layout::fresh_window_id). The same id is the same window, and the same + /// OS window, on every frame. + pub fn new(id: u64, column: Column

, rect: Rect) -> Self { + Self { id, column, rect, native: None, edge: None } } - /// A window with one group. Each call makes a new window, as [`Self::new`] does. - pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self { - Self::new(Column::new(vec![Group::new(panels, active)]), rect) + /// The window `id` with one group. + pub fn single(id: u64, panels: Vec

, active: usize, rect: Rect) -> Self { + Self::new(id, Column::new(vec![Group::new(panels, active)]), rect) } - /// The window with `id`, for a layout the app builds in code, such as a default layout: - /// built with the same id, it is the same window, and the same OS window, on every frame. - /// Ids must be unique within a layout. + /// The window with `id` in place of its own. Ids must be unique within a layout. pub fn with_id(mut self, id: u64) -> Self { self.id = id; self @@ -165,10 +150,9 @@ impl

Floating

{ self.column.panels() } - /// A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, - /// as [`Self::new`] does. - pub fn stack(groups: Vec>, rect: Rect) -> Option { - (!groups.is_empty()).then(|| Self::new(Column::new(groups), rect)) + /// The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups. + pub fn stack(id: u64, groups: Vec>, rect: Rect) -> Option { + (!groups.is_empty()).then(|| Self::new(id, Column::new(groups), rect)) } /// The window's groups, top to bottom. @@ -202,7 +186,7 @@ pub(super) mod floating_serde { use serde::de::IgnoredAny; use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use super::{Column, DockEdge, Floating, Group, Node, fresh_window_id}; + use super::{Column, DockEdge, Floating, Group, Node}; use crate::dock::limits::MAX_NODES; use crate::dock::rect_serde::{from_array, to_array}; use crate::dock::split::SplitSize; @@ -339,9 +323,13 @@ pub(super) mod floating_serde { } } + /// A window as read, with the id it was saved with, if any. + type Saved

= (Option, Floating

); + impl

Repr

{ - /// The windows the saved window becomes, first to last. - fn into_windows(self) -> Result>, E> { + /// The windows the saved window becomes, first to last, each with its saved id: the first keeps the saved + /// window's, the others have none. + fn into_windows(self) -> Result>, E> { let Repr { id, column, root, groups, panels, active, rect, native, minimized, edge } = self; let rect = from_array(rect.ok_or_else(|| E::missing_field("rect"))?); let columns = match (column, root, groups, panels) { @@ -367,11 +355,8 @@ pub(super) mod floating_serde { return Err(E::invalid_length(0, &"at least one group")); } let native = native.and_then(|native| native.repaired()); - let mut id = Some(id.unwrap_or_else(fresh_window_id)); - Ok(columns - .into_iter() - .map(|(column, rect)| Floating { id: id.take().unwrap_or_else(fresh_window_id), column, rect, native: native.clone(), edge }) - .collect()) + let mut id = id; + Ok(columns.into_iter().map(|(column, rect)| (id.take(), Floating { id: 0, column, rect, native: native.clone(), edge })).collect()) } } @@ -419,20 +404,25 @@ pub(super) mod floating_serde { groups } - /// Floating windows as saved, each read into the windows it becomes, with a fresh id for each one whose id an - /// earlier window took. + /// Floating windows as saved, each read into the windows it becomes. A window keeps its saved id unless an + /// earlier window took it; one without an id, or with a taken one, gets the next id above every saved one. pub(in crate::dock) fn unique_ids<'de, D: Deserializer<'de>, P: Deserialize<'de>>(deserializer: D) -> Result>, D::Error> { let mut windows = Vec::new(); for saved in Vec::>::deserialize(deserializer)? { windows.extend(saved.into_windows::()?); } + let mut next = windows.iter().filter_map(|(id, _)| *id).max().map_or(0, |id| id.saturating_add(1)); let mut seen = std::collections::HashSet::new(); - for window in &mut windows { - while !seen.insert(window.id) { - window.id = fresh_window_id(); - } - } - Ok(windows) + Ok(windows + .into_iter() + .map(|(id, window)| { + let id = id.filter(|id| seen.insert(*id)).unwrap_or_else(|| { + next += 1; + next - 1 + }); + Floating { id, ..window } + }) + .collect()) } } diff --git a/crates/behavior/src/dock/policy.rs b/crates/behavior/src/dock/policy.rs index 629008c34..2d30965a9 100644 --- a/crates/behavior/src/dock/policy.rs +++ b/crates/behavior/src/dock/policy.rs @@ -5,7 +5,7 @@ use std::fmt; /// What may happen to a panel. `Layout::apply_with_permissions` enforces these for every /// action, whoever issues it. They also decide which gestures and menu items the renderer /// offers; a renderer hides the built-in close controls of a panel that stays closable by command. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] #[non_exhaustive] pub struct Permissions { /// The panel may be moved. diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index d261427ce..ddaed82c0 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -6,6 +6,8 @@ use std::{collections::HashSet, hash::Hash}; +use craft_tracked::{Revision, Tracked}; + use super::{ DockSide, action::{Action, DockPlacement, Location}, @@ -19,10 +21,12 @@ use super::{ /// A saved arrangement of panels: the [`Layout`] and the closed panels' former places. /// -/// Its [`revision`](Self::revision) changes when another arrangement replaces it (switch, reset, load): replace a +/// Two signals name its state. [`revision`](Self::revision) moves with every write: the fields are private and every +/// method that writes moves it, and a clone is a new source, so two workspace values never share a revision. +/// [`generation`](Self::generation) moves only when another arrangement replaces it (switch, reset, load): replace a /// shown workspace with [`replace`](Self::replace) or the [`WorkspaceSet`](super::WorkspaceSet) operations, never by /// assignment, so a running drag on it ends. Edits ([`apply`](Self::apply), [`set_visible`](Self::set_visible), the -/// dock's own) keep the revision. +/// dock's own) keep the generation. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(bound(deserialize = "P: serde::Deserialize<'de>"))] #[non_exhaustive] @@ -30,25 +34,29 @@ pub struct Workspace

{ /// Format version; files without one are v1 (`{layout, hidden}`). Always written as /// [`Workspace::VERSION`]. #[serde(default = "first_version", serialize_with = "write_version")] - pub version: u32, + version: u32, /// The current arrangement, changes included. A save without one is no workspace: it does not load. - pub layout: Layout

, + layout: Layout

, /// Closed panels, and panels the application does not register now, with where each one /// goes back. #[serde(default)] - pub hidden: Vec<(P, Location

)>, + hidden: Vec<(P, Location

)>, /// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the /// workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub floated: Vec<(P, Location

)>, + floated: Vec<(P, Location

)>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. #[serde(skip)] - revision: u64, + generation: u64, + /// Moves with every write; a clone is a new source. Not saved, and not part of equality. + #[serde(skip)] + revision: Tracked<()>, } impl PartialEq for Workspace

{ fn eq(&self, other: &Self) -> bool { - self.version == other.version && self.layout == other.layout && self.hidden == other.hidden && self.floated == other.floated + self.revision.revision() == other.revision.revision() + || (self.version == other.version && self.layout == other.layout && self.hidden == other.hidden && self.floated == other.floated) } } @@ -73,18 +81,75 @@ impl

Workspace

{ /// A workspace of `layout`, with no hidden panels. pub fn new(layout: Layout

) -> Self { - Self { version: Self::VERSION, layout, hidden: Vec::new(), floated: Vec::new(), revision: 0 } + Self::from_parts(layout, Vec::new(), Vec::new()) } - /// The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else. - pub fn revision(&self) -> u64 { - self.revision + /// A workspace of `layout` with the closed panels' places `hidden` and the floating panels' docked places + /// `floated`, unchecked, as a saved one loads; [`validate`](Self::validate) checks it. + pub fn from_parts(layout: Layout

, hidden: Vec<(P, Location

)>, floated: Vec<(P, Location

)>) -> Self { + Self { version: Self::VERSION, layout, hidden, floated, generation: 0, revision: Tracked::default() } } - /// Replaces the arrangement with `with` and moves to the next revision. + /// The format version the workspace was read with. + pub fn version(&self) -> u32 { + self.version + } + + /// The current arrangement. + pub fn layout(&self) -> &Layout

{ + &self.layout + } + + /// The closed panels, and panels the application does not register now, with where each one goes back. + pub fn hidden(&self) -> &[(P, Location

)] { + &self.hidden + } + + /// The floating panels with the docked location each one left. + pub fn floated(&self) -> &[(P, Location

)] { + &self.floated + } + + /// The revision of this workspace value: it moves with every write, and no other value has it. + pub fn revision(&self) -> Revision { + self.revision.revision() + } + + /// The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. + pub fn generation(&self) -> u64 { + self.generation + } + + /// The workspace with its arrangement replaced by `layout`, for a stored set whose saved arrangement is kept apart. + pub(super) fn with_layout(mut self, layout: Layout

) -> Self { + self.layout = layout; + self.touch(); + self + } + + /// Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. + pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool) { + let before = self.hidden.len(); + self.hidden.retain(|(panel, _)| !forget(panel)); + if self.hidden.len() != before { + self.touch(); + } + } + + /// Moves the revision. Every method that writes the workspace calls it. + fn touch(&mut self) { + self.revision.edit(|()| ()); + } + + /// Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this + /// workspace never gave out, so no OS window passes to another window. pub fn replace(&mut self, with: Workspace

) { - let revision = self.revision.wrapping_add(1); - *self = Workspace { revision, ..with }; + let generation = self.generation.wrapping_add(1); + let revision = std::mem::take(&mut self.revision); + let mut with = with; + self.layout.hand_ids_to(&mut with.layout); + *self = Workspace { generation, revision, ..with }; + self.touch(); } } @@ -168,7 +233,9 @@ impl Workspace

{ let mut seen = HashSet::new(); all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone())); proposed.validate()?; - *self = proposed; + let Workspace { layout, hidden, floated, .. } = proposed; + (self.layout, self.hidden, self.floated) = (layout, hidden, floated); + self.touch(); Ok(all_closed) } @@ -291,6 +358,15 @@ impl Workspace

{ /// [`Permissions::locked`] ones. /// `hidden` keeps at most [`MAX_PANELS`] entries, dropping the oldest unregistered ones first. pub fn reconcile(&mut self, registered: impl Fn(&P) -> bool, permissions: impl Fn(&P) -> Permissions, default: &Workspace

) { + let before = self.clone(); + self.reconcile_parts(registered, permissions, default); + if *self != before { + self.touch(); + } + } + + /// [`Self::reconcile`]'s work, which leaves the revision to it. + fn reconcile_parts(&mut self, registered: impl Fn(&P) -> bool, permissions: impl Fn(&P) -> Permissions, default: &Workspace

) { if self.validate().is_err() { self.replace(default.clone()); } diff --git a/crates/behavior/src/dock/workspaces.rs b/crates/behavior/src/dock/workspaces.rs index 04535bb53..3d84d1bb3 100644 --- a/crates/behavior/src/dock/workspaces.rs +++ b/crates/behavior/src/dock/workspaces.rs @@ -286,7 +286,7 @@ impl

From> for WorkspaceSet

{ let StoredWorkspace { mut workspace, locked: lock, saved } = named.layout; locked |= lock; if let Some(layout) = saved { - workspace.layout = layout; + workspace = workspace.with_layout(layout); } NamedWorkspace { id: named.id, name: named.name, layout: workspace, chrome: named.chrome, keeps: named.keeps } }) @@ -297,7 +297,7 @@ impl

From> for WorkspaceSet

{ if let Some(layout) = stored.saved && let Some(named) = saved.iter_mut().find(|w| w.id == id) { - named.layout.layout = layout; + named.layout = std::mem::take(&mut named.layout).with_layout(layout); } edited.insert(id, stored.workspace); } diff --git a/crates/behavior/tests/dock.rs b/crates/behavior/tests/dock.rs index e9d825400..2858bb282 100644 --- a/crates/behavior/tests/dock.rs +++ b/crates/behavior/tests/dock.rs @@ -32,7 +32,10 @@ fn docked() -> Layout { DockEdge::End, vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)]).with_width(180.0), Column::new(vec![g(&[5], 0)]).with_width(120.0)], ); - Layout::new(Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], WINDOW).unwrap()]) + Layout::new( + Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), + vec![Floating::stack(100, vec![g(&[6, 7], 1), g(&[8], 0)], WINDOW).unwrap()], + ) } fn with_column(column: Column) -> Layout { @@ -165,7 +168,7 @@ fn without(skip: Option) -> Layout { let windows: Vec> = [group(&[6], 0), tall].into_iter().flatten().collect(); Layout::new( Some(hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end)), - vec![Floating::stack(windows, area(10.0, 10.0, 200.0, 300.0)).unwrap()], + vec![Floating::stack(101, windows, area(10.0, 10.0, 200.0, 300.0)).unwrap()], ) } @@ -203,7 +206,7 @@ fn a_layout_saved_with_the_physical_names_loads_and_writes_back_in_reading_order tabs(&[1, 2], 1), Node::dock(DockEdge::End, vec![Column::new(vec![g(&[3], 0)]).with_width(180.0)]), )), - vec![Floating::single(vec![4], 0, area(1.0, 2.0, 300.0, 200.0)).with_id(5)], + vec![Floating::single(5, vec![4], 0, area(1.0, 2.0, 300.0, 200.0))], ); assert_eq!(layout, expected); let written = serde_json::to_value(&layout).unwrap(); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 59d764ad3..af2d0eae2 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -32,7 +32,7 @@ fn docked() -> Layout { vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)]).with_width(180.0), Column::new(vec![g(&[5], 0)]).with_width(120.0)], ); let root = Node::split(Axis::X, SplitSize::FixedSecond(300.0), middle, dock); - Layout::new(Some(root), vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], window()).unwrap()]) + Layout::new(Some(root), vec![Floating::stack(100, vec![g(&[6, 7], 1), g(&[8], 0)], window()).unwrap()]) } const ALL: [u32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12]; @@ -79,32 +79,33 @@ fn apply_all_changes_everything_or_nothing_and_reports_the_closed_panels() { #[test] fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() { let default = Workspace::new(docked()); - let mut workspace = default.clone(); - workspace.layout.apply(Action::close(5)).unwrap(); - workspace.layout.apply(Action::close(12)).unwrap(); - workspace.layout.apply(Action::open_at(99, 2, DockPlacement::tab(None))).unwrap(); - let stray = workspace.layout.location(&99).unwrap(); - workspace.hidden.push((98, stray)); + let mut layout = docked(); + layout.apply(Action::close(5)).unwrap(); + layout.apply(Action::close(12)).unwrap(); + layout.apply(Action::open_at(99, 2, DockPlacement::tab(None))).unwrap(); + let stray = layout.location(&99).unwrap(); + let mut workspace = Workspace::from_parts(layout, vec![(98, stray)], Vec::new()); let registered = |p: &u32| *p < 90; workspace.reconcile(registered, allow, &default); workspace.validate().unwrap(); // Unregistered panels wait in `hidden` and come back once registered. - assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [98, 99]); - assert_eq!(sorted(&workspace.layout), ALL); + assert_eq!(workspace.hidden().iter().map(|(p, _)| *p).collect::>(), [98, 99]); + assert_eq!(sorted(workspace.layout()), ALL); workspace.set_visible(99, true, None, false, allow).unwrap(); - assert_eq!(group_members(&workspace.layout, 2), [2, 3, 99]); - assert_eq!(end_dock(&workspace.layout).len(), 2); - assert_eq!(group_members(&workspace.layout, 11), [11, 12]); + assert_eq!(group_members(workspace.layout(), 2), [2, 3, 99]); + assert_eq!(end_dock(workspace.layout()).len(), 2); + assert_eq!(group_members(workspace.layout(), 11), [11, 12]); - let mut broken = default.clone(); - broken.layout.floating[0].rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(-1.0, 400.0)); + let mut layout = docked(); + layout.floating[0].rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(-1.0, 400.0)); + let mut broken = Workspace::new(layout); broken.reconcile(registered, allow, &default); - assert_eq!(broken.layout, default.layout); + assert_eq!(broken.layout(), default.layout()); } #[test] fn a_workspace_set_with_a_floating_group_round_trips_through_json() { - let layout = Layout::new(Some(Node::tabs(vec![1u32, 2], 0)), vec![Floating::single(vec![3u32], 0, rect(1.0, 2.0, 300.0, 200.0)).with_id(5)]); + let layout = Layout::new(Some(Node::tabs(vec![1u32, 2], 0)), vec![Floating::single(5, vec![3u32], 0, rect(1.0, 2.0, 300.0, 200.0))]); let mut set = WorkspaceSet::new(vec![NamedWorkspace::new("essentials", "Essentials", Workspace::default())]); set.save("Mine", Workspace::new(layout), WorkspaceChrome::default(), WorkspaceKeeps::new(false, true, true)).unwrap(); let saved = serde_json::to_string(&set).unwrap(); @@ -134,18 +135,18 @@ fn a_workspace_with_a_bottom_pane_opens_and_closes_it_on_switch() { ]); let mut live = photography; set.select("motion", &mut live).unwrap(); - let bottom = live.layout.place(&TIMELINE).unwrap(); + let bottom = live.layout().place(&TIMELINE).unwrap(); assert_eq!(bottom, PanelPlace::Node(vec![true]), "the Timeline is the second (bottom) frame of the split"); set.select("photography", &mut live).unwrap(); - assert!(!live.layout.contains(&TIMELINE), "leaving Motion closes the Timeline"); + assert!(!live.layout().contains(&TIMELINE), "leaving Motion closes the Timeline"); set.select("motion", &mut live).unwrap(); - assert!(live.layout.contains(&TIMELINE), "coming back opens it again"); + assert!(live.layout().contains(&TIMELINE), "coming back opens it again"); } -/// Switching and resetting replace the live workspace and move it to a new revision; edits and selecting the shown -/// workspace keep it, and the revision is neither saved nor compared. +/// Switching and resetting replace the live workspace and move it to a new generation; edits and selecting the shown +/// workspace keep it, and the generation is neither saved nor compared. #[test] -fn only_a_replacement_changes_the_live_revision() { +fn only_a_replacement_changes_the_live_generation() { let essentials = Workspace::new(Layout::new(Some(tabs(&[1, 2], 0)), Vec::new())); let painting = Workspace::new(Layout::new(Some(tabs(&[3], 0)), Vec::new())); let mut set = WorkspaceSet::new(vec![ @@ -153,20 +154,20 @@ fn only_a_replacement_changes_the_live_revision() { NamedWorkspace::new("painting", "Painting", painting), ]); let mut live = essentials.clone(); - let start = live.revision(); + let start = live.generation(); live.apply(Action::activate(2), false, allow).unwrap(); live.set_visible(1, false, None, false, allow).unwrap(); set.select("essentials", &mut live).unwrap(); - assert_eq!(live.revision(), start, "edits and selecting the shown workspace keep the revision"); + assert_eq!(live.generation(), start, "edits and selecting the shown workspace keep the generation"); set.select("painting", &mut live).unwrap(); - let switched = live.revision(); - assert!(switched != start && live.layout.contains(&3), "a switch replaces the live workspace"); + let switched = live.generation(); + assert!(switched != start && live.layout().contains(&3), "a switch replaces the live workspace"); set.reset(&mut live).unwrap(); - assert!(live.revision() != switched, "a reset replaces it again"); + assert!(live.generation() != switched, "a reset replaces it again"); set.select("essentials", &mut live).unwrap(); - assert!(!live.layout.contains(&1), "the switch back shows the edited essentials"); + assert!(!live.layout().contains(&1), "the switch back shows the edited essentials"); let loaded: Workspace = serde_json::from_str(&serde_json::to_string(&live).unwrap()).unwrap(); - assert_eq!(loaded, live, "the revision is not saved and not part of equality"); + assert_eq!(loaded, live, "the generation is not saved and not part of equality"); } /// Open of a hidden panel follows its record: a floating panel returns to its window; a record whose anchor is gone @@ -175,39 +176,39 @@ fn only_a_replacement_changes_the_live_revision() { fn opening_a_closed_floating_panel_restores_its_window_place() { let mut workspace = Workspace::new(docked()); workspace.apply(Action::close(8), false, allow).unwrap(); - assert!(workspace.layout.place(&8).is_none()); + assert!(workspace.layout().place(&8).is_none()); workspace.apply(Action::open(8, Some(11)), false, allow).unwrap(); - assert!(matches!(workspace.layout.place(&8), Some(PanelPlace::Floating { .. })), "back in its window"); - assert!(workspace.hidden.is_empty()); + assert!(matches!(workspace.layout().place(&8), Some(PanelPlace::Floating { .. })), "back in its window"); + assert!(workspace.hidden().is_empty()); - let mut stray = workspace.layout.location(&5).unwrap(); + let mut stray = workspace.layout().location(&5).unwrap(); stray.anchor = Some(99); - workspace.hidden.push((50, stray)); + let mut workspace = Workspace::from_parts(workspace.layout().clone(), vec![(50, stray)], Vec::new()); workspace.apply(Action::open(50, Some(11)), false, allow).unwrap(); - assert_eq!(group_members(&workspace.layout, 11), [11, 12, 50]); + assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]); } /// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first. #[test] fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { let mut workspace = Workspace::new(docked()); - let docked_at = workspace.layout.location(&2).unwrap(); + let docked_at = workspace.layout().location(&2).unwrap(); workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated, [(2, docked_at.clone())]); + assert_eq!(workspace.floated(), [(2, docked_at.clone())]); workspace.apply(Action::float(2, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated, [(2, docked_at)], "floating again from the float keeps the first record"); + assert_eq!(workspace.floated(), [(2, docked_at)], "floating again from the float keeps the first record"); workspace.apply(Action::move_beside(2, 11, DockPlacement::tab(None)), false, allow).unwrap(); - assert!(workspace.floated.is_empty(), "docking drops the record"); + assert!(workspace.floated().is_empty(), "docking drops the record"); workspace.apply(Action::float(3, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated.len(), 1); + assert_eq!(workspace.floated().len(), 1); workspace.apply(Action::close(3), false, allow).unwrap(); - assert!(workspace.floated.is_empty(), "closing drops the record"); + assert!(workspace.floated().is_empty(), "closing drops the record"); } /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); - Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(vec![6], 0, window())]) + Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(101, vec![6], 0, window())]) } fn floats(layout: &Layout, panel: u32) -> bool { @@ -318,12 +319,13 @@ fn a_panel_that_does_not_collapse_keeps_its_column_expanded() { layout.apply_with_permissions(Action::set_iconic(3, false), rigid).unwrap(); layout.apply_with_permissions(Action::move_group(2, Target::at(3, DockPlacement::group(true, None))), rigid).unwrap(); - let mut saved = Workspace::new(columns()); - saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); - assert!(column_of(&saved.layout, 2).iconic); + let mut layout = columns(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + let mut saved = Workspace::new(layout); + assert!(column_of(saved.layout(), 2).iconic); saved.reconcile(|_| true, rigid, &Workspace::new(columns())); - assert!(!column_of(&saved.layout, 2).iconic, "reconcile expands the column"); - assert_eq!(group_members(&saved.layout, 2), [2]); + assert!(!column_of(saved.layout(), 2).iconic, "reconcile expands the column"); + assert_eq!(group_members(saved.layout(), 2), [2]); } /// A panel that shares no column (a toolbar) refuses every placement that puts it beside other panels in a column @@ -348,11 +350,12 @@ fn a_panel_that_shares_no_column_moves_only_to_a_column_of_its_own() { assert_eq!(column_of(&moved, 2).panels().count(), 1, "{to:?}"); } - let mut saved = Workspace::new(columns()); - saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + let mut layout = columns(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + let mut saved = Workspace::new(layout); saved.reconcile(|_| true, alone, &Workspace::new(columns())); - assert_eq!(column_of(&saved.layout, 2).panels().collect::>(), [&2], "reconcile gives it a column of its own"); - assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]); + assert_eq!(column_of(saved.layout(), 2).panels().collect::>(), [&2], "reconcile gives it a column of its own"); + assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]); } /// A panel that docks only in dock columns (a toolbar, photocraft#12517) refuses every placement that leaves it in a @@ -395,9 +398,9 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() { other.apply_with_permissions(Action::move_group(6, Target::at(3, DockPlacement::column(false))), strip).unwrap(); let mut saved = Workspace::new(split); saved.reconcile(|_| true, strip, &Workspace::new(columns())); - assert!(matches!(saved.layout.place(&2), Some(PanelPlace::Dock { .. })), "reconcile docks it in a column: {:?}", saved.layout); - assert_eq!(column_of(&saved.layout, 2).panels().collect::>(), [&2]); - assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]); + assert!(matches!(saved.layout().place(&2), Some(PanelPlace::Dock { .. })), "reconcile docks it in a column: {:?}", saved.layout()); + assert_eq!(column_of(saved.layout(), 2).panels().collect::>(), [&2]); + assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]); } /// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only @@ -420,3 +423,87 @@ fn a_stepped_column_keeps_its_step_count_and_refuses_a_width() { let saved: Layout = serde_json::from_str(&serde_json::to_string(&layout).unwrap()).unwrap(); assert_eq!(saved, layout); } + +/// The names of the `pub fn` methods in `source` whose receiver is `&mut self`. +fn mutating_methods(source: &str) -> Vec<&str> { + let mut names: Vec<&str> = source + .split("pub fn ") + .skip(1) + .filter_map(|rest| { + let name = &rest[..rest.find(|c: char| !(c.is_alphanumeric() || c == '_'))?]; + let receiver = rest[rest.find('(')? + 1..].trim_start(); + receiver.starts_with("&mut self").then_some(name) + }) + .collect(); + names.sort_unstable(); + names +} + +/// Every method that writes a workspace moves its revision, and only `replace` moves its generation. The trial reads +/// the workspace's source for its `&mut self` methods, so a new one fails here until it is walked. +#[test] +fn every_workspace_mutator_moves_the_revision() { + let mut walked: Vec<&str> = Vec::new(); + let mut moves = |name: &'static str, edit: &dyn Fn(&mut Workspace)| { + let mut workspace = Workspace::new(docked()); + let (revision, generation) = (workspace.revision(), workspace.generation()); + edit(&mut workspace); + assert_ne!(workspace.revision(), revision, "`{name}` moves the revision"); + assert_eq!(workspace.generation() != generation, name == "replace", "only `replace` moves the generation, `{name}` included"); + walked.push(name); + }; + moves("replace", &|workspace| workspace.replace(Workspace::new(columns()))); + moves("apply", &|workspace| drop(workspace.apply(Action::activate(6), false, allow).unwrap())); + moves("apply_all", &|workspace| drop(workspace.apply_all([Action::close(5), Action::close(4)], false, allow).unwrap())); + moves("set_visible", &|workspace| workspace.set_visible(5, false, None, false, allow).unwrap()); + moves("reconcile", &|workspace| workspace.reconcile(|panel| *panel != 5, allow, &Workspace::new(docked()))); + moves("forget_hidden", &|workspace| { + workspace.apply(Action::close(5), false, allow).unwrap(); + let revision = workspace.revision(); + workspace.forget_hidden(|panel| *panel == 5); + assert_ne!(workspace.revision(), revision, "`forget_hidden` moves the revision by itself"); + }); + walked.sort_unstable(); + assert_eq!(walked, mutating_methods(include_str!("../src/dock/workspace.rs")), "every `&mut self` method of `Workspace` is walked"); + + let workspace = Workspace::new(docked()); + assert_ne!(workspace.clone().revision(), workspace.revision(), "a clone is a new source"); + let mut settled = Workspace::new(docked()); + let revision = settled.revision(); + settled.reconcile(|_| true, allow, &Workspace::new(docked())); + assert_eq!(settled.revision(), revision, "a reconcile that changes nothing keeps the revision"); +} + +fn window_ids(workspace: &Workspace) -> Vec { + workspace.layout().floating.iter().map(|window| window.id).collect() +} + +/// Window ids come from a counter each layout owns: two workspaces edited side by side each keep their windows' ids +/// unique, a closed window's id is never drawn again, and a replacement's windows take ids the old layout never gave. +#[test] +fn window_ids_stay_unique_within_each_layout_and_are_never_reused() { + let (mut a, mut b) = (Workspace::new(docked()), Workspace::new(docked())); + for workspace in [&mut a, &mut b] { + workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + workspace.apply(Action::float(5, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap(); + let mut ids = window_ids(workspace); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3, "three windows, three ids: {:?}", window_ids(workspace)); + } + + let seen = window_ids(&a); + a.apply(Action::close(5), false, allow).unwrap(); + a.apply(Action::float(3, rect(50.0, 50.0, 200.0, 200.0)), false, allow).unwrap(); + let fresh: Vec = window_ids(&a).into_iter().filter(|id| !seen.contains(id)).collect(); + assert!(fresh.len() == 1 && fresh[0] > seen.iter().copied().max().unwrap(), "a new window takes a new id: {fresh:?} after {seen:?}"); + + let held: Vec = seen.iter().chain(&fresh).copied().collect(); + a.replace(Workspace::new(docked())); + let replaced = window_ids(&a); + assert!(replaced.iter().all(|id| !held.contains(id)), "the replacement's window takes an id no earlier window had: {replaced:?} after {held:?}"); + + let saved = r#"{"layout":{"root":null,"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":7,"panels":[2],"active":0,"rect":[0,0,100,100]},{"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#; + let loaded: Workspace = serde_json::from_str(saved).unwrap(); + assert_eq!(window_ids(&loaded), [7, 8, 9], "a load keeps the first of a duplicate id and numbers the rest above every saved id"); +} diff --git a/crates/cloud-ui/src/esign/mod.rs b/crates/cloud-ui/src/esign/mod.rs index 64087bbd5..e574a7c67 100644 --- a/crates/cloud-ui/src/esign/mod.rs +++ b/crates/cloud-ui/src/esign/mod.rs @@ -240,11 +240,11 @@ impl Default for EsignDialog { } /// A send operation id no other send in this process has used, from a random -/// start so one saved by an earlier process is unlikely to repeat either. -/// Mirrors `docking::model::fresh_window_id`: a counter kept on one -/// [`EsignDialog`] repeats across two dialog instances (two windows, or one -/// replaced after a document closes), and two sends sharing an idempotency -/// key have a conforming provider return the first envelope for the second. +/// start so one saved by an earlier process is unlikely to repeat either. A +/// counter kept on one [`EsignDialog`] would repeat across two dialog instances +/// (two windows, or one replaced after a document closes), and two sends +/// sharing an idempotency key have a conforming provider return the first +/// envelope for the second. fn fresh_send_id() -> u64 { use std::hash::{BuildHasher, Hasher}; use std::sync::OnceLock; diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index fe66419a0..baf44abc9 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -195,8 +195,6 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ ("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. diff --git a/crates/ui-gallery/src/chrome/dock.rs b/crates/ui-gallery/src/chrome/dock.rs index dac9db2fc..ddc4e6ce0 100644 --- a/crates/ui-gallery/src/chrome/dock.rs +++ b/crates/ui-gallery/src/chrome/dock.rs @@ -10,7 +10,7 @@ use craft_theme::variant::Tone; use craft_ui::contract::Show as _; use craft_ui::contract::{BodyCx, Outbox, SizeLimits, Tracked}; use craft_ui::display::InspectLayers; -use craft_ui::docking::{DockHeights, DockPanels, PanelSpec}; +use craft_ui::docking::{DockHeights, DockPanels, PanelSpec, PanelSpecs}; use craft_ui::menu::PanelRow; use craft_ui::notices::Notice; use craft_window::policy::WindowKind; @@ -62,7 +62,11 @@ impl GalleryDock<'_> { } } -impl DockPanels for GalleryDock<'_> { +/// The gallery's panel specs: each panel's follow from its id. +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::PlainData)] +pub struct GallerySpecs; + +impl PanelSpecs for GallerySpecs { fn spec(&self, panel: &PanelId) -> PanelSpec { let spec = PanelSpec::new(panel.title()).limits(SizeLimits::default()); match panel { @@ -78,7 +82,9 @@ impl DockPanels for GalleryDock<'_> { fn permissions(&self, panel: &PanelId) -> Permissions { panel.permissions() } +} +impl DockPanels for GalleryDock<'_> { fn body(&mut self, panel: &PanelId, ui: &mut Ui, _: &mut BodyCx<'_>) { match (panel, self.preview) { (PanelId::Preview, Preview::App) => { diff --git a/crates/ui-gallery/src/chrome/mod.rs b/crates/ui-gallery/src/chrome/mod.rs index acb1e7e0a..ee6b5b9c6 100644 --- a/crates/ui-gallery/src/chrome/mod.rs +++ b/crates/ui-gallery/src/chrome/mod.rs @@ -12,6 +12,7 @@ mod shell; mod variants; pub use card::{BodyShown, Card, CardEvents, CardStory, Look, StoryBody}; +pub use dock::GallerySpecs; pub use inspect::{Inspect, Inspected, region_key}; pub use options::options_bar; pub use overview::{Spec, SpecStory, overview_card}; diff --git a/crates/ui-gallery/src/chrome/shell.rs b/crates/ui-gallery/src/chrome/shell.rs index 42ae35c83..33b731f2c 100644 --- a/crates/ui-gallery/src/chrome/shell.rs +++ b/crates/ui-gallery/src/chrome/shell.rs @@ -25,6 +25,7 @@ use craft_ui::shell::app::ShellApp; use craft_ui::shell::embed::CloseDecision; use egui::Ui; use std::collections::HashSet; +use std::sync::Arc; use web_time::Instant; /// The viewer as the root window's app. @@ -84,7 +85,7 @@ fn read_dropped(file: &OsFile) -> Result { /// The registered name of the component whose tab is in front and selected in the shown workspace's dock. fn front_component(viewer: &Viewer) -> Option<&'static str> { let dock = if viewer.workspace == Workspace::Theme { &viewer.theme_dock } else { &viewer.dock }; - viewer.browser.selected_type().filter(|type_name| dock.layout.panel_state(&PanelId::component(type_name)) == PanelState::Front) + viewer.browser.selected_type().filter(|type_name| dock.layout().panel_state(&PanelId::component(type_name)) == PanelState::Front) } /// Gives an open Variants view its centre tab: the front centre tab of the components workspace when the view opens, @@ -92,12 +93,12 @@ fn front_component(viewer: &Viewer) -> Option<&'static str> { /// runs. fn place_variants(viewer: &mut Viewer) { let front = - |panel: &PanelId| matches!(panel, PanelId::Overview | PanelId::Component(_)) && viewer.dock.layout.panel_state(panel) == PanelState::Front; + |panel: &PanelId| matches!(panel, PanelId::Overview | PanelId::Component(_)) && viewer.dock.layout().panel_state(panel) == PanelState::Front; let owner = match (&viewer.variants, &viewer.variants_tab) { (None, _) => None, (Some(_), Some(tab)) if front(tab) => Some(tab.clone()), (Some(_), Some(_)) => None, - (Some(_), None) => viewer.dock.layout.panels().into_iter().find(|panel| front(panel)).cloned(), + (Some(_), None) => viewer.dock.layout().panels().into_iter().find(|panel| front(panel)).cloned(), }; if owner.is_none() { viewer.variants = None; @@ -109,12 +110,12 @@ fn place_variants(viewer: &mut Viewer) { fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) { place_variants(viewer); let selected = front_component(viewer).map(PanelId::component); - let Viewer { env, workspace, preview, browser, dock, themes, theme_dock, mock, variants, variants_tab, inspect_layers, .. } = viewer; + let Viewer { env, workspace, preview, browser, dock, themes, theme_dock, specs, mock, variants, variants_tab, inspect_layers, .. } = viewer; let appearance = env.appearance(ui.ctx()); let subject = ThemeSubject::new(theme_of(env.theme_id()), appearance); let in_theme = *workspace == Workspace::Theme; - let dock: &mut Dock<_> = if in_theme { theme_dock } else { dock }; - let front = |panel: &PanelId| dock.layout.panel_state(panel) == PanelState::Front; + let dock: &mut Arc> = if in_theme { theme_dock } else { dock }; + let front = |panel: &PanelId| dock.layout().panel_state(panel) == PanelState::Front; let inspect = Inspect { on: !in_theme && variants.is_none() && front(&PanelId::Inspect), front: [Some(PanelId::Overview), selected].into_iter().flatten().filter(|panel| front(panel)).collect(), @@ -134,10 +135,10 @@ fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) { }; // Component tabs are documents: they close from their ×. let config = DockConfig::default().tab_close_buttons(true); - DockArea::new(if in_theme { "Theme dock" } else { "Components dock" }, Bind::bound(&mut *dock), &mut content, config).show(ui); + DockArea::new(if in_theme { "Theme dock" } else { "Components dock" }, Bind::bound(&mut *dock), specs, &mut content, config).show(ui); let GalleryDock { opened, variants_out, .. } = content; for type_name in opened { - let _ = dock.set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions()); + let _ = Arc::make_mut(dock).set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions()); } for event in variants_out { if let VariantsEvent::Use(look) = event { @@ -151,7 +152,10 @@ fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) { *variants = None; } // A closed component tab does not come back from the layout's record of closed panels. - dock.hidden.retain(|(panel, _)| !matches!(panel, PanelId::Component(_))); + let component = |panel: &PanelId| matches!(panel, PanelId::Component(_)); + if dock.hidden().iter().any(|(panel, _)| component(panel)) { + Arc::make_mut(dock).forget_hidden(component); + } } impl ShellApp for Gallery { diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index 5b17f1e8b..b381a6057 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -14,7 +14,7 @@ use craft_ui::canvas::{PickStep, ViewCommands}; use craft_ui::contract::{Bind, BodyCx, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _}; use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; use craft_ui::display::{Divider, Text}; -use craft_ui::docking::{DockConfig, DockEvent, DockPanels as _}; +use craft_ui::docking::{DockConfig, DockEvent, PanelSpecs as _}; use craft_ui::menu::{Menu, MenuBar, MenuItem, MenuTitle}; use craft_ui::patterns::dock::DockArea; use craft_ui::patterns::form_dialogs::{ @@ -25,6 +25,7 @@ use craft_ui::runtime::env::{Env, Label, WindowKey}; use craft_ui::shell::{AppShell, AppShellOutput, CaptionFamily, Captions, Frame, ScreenMode, ShellDialogsCx as _, Title, TitleBar}; use craft_window::Layout; use egui::{Rect, Ui}; +use std::sync::Arc; /// The parameters of Gaussian Blur. const BLUR: &str = r#"{"radius":0.1..1000=1}"#; @@ -94,13 +95,12 @@ impl<'a> EditorMock<'a> { /// The dock, then the commands and dialog answers of this pass. fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { let mut tools = cx.keep::().clone(); - let ctx = ui.ctx().clone(); let (events, picked) = { - let mut panels = - Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, last_used: &mut state.last_used, picked: None, ctx: &ctx }; + let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, last_used: &mut state.last_used, picked: None }; // The mock app is a preview inside the gallery's page: its floats stay in it. - let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default().native_windows(false)) - .flyout(Bind::bound(&mut state.flyout)); + let mut area = + DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default().native_windows(false)) + .flyout(Bind::bound(&mut state.flyout)); if let Some(panel) = state.maximized { area = area.maximized(panel); } @@ -138,20 +138,13 @@ fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { for command in asked { if let Some(panel) = command.panel() { // A panel in a column collapsed to icons shows in its flyout: the command opens or closes that. - if state.workspace.layout.opens_in_flyout(&panel) { + if state.workspace.layout().opens_in_flyout(&panel) { state.flyout = if state.flyout == Some(panel) { None } else { Some(panel) }; continue; } - let shown = state.workspace.layout.panel_state(&panel) != PanelState::Hidden; - let panels = Panels { - document: &mut state.document, - tool: state.tool, - tools: &mut tools, - last_used: &mut state.last_used, - picked: None, - ctx: &ctx, - }; - let _ = state.workspace.set_visible(panel, !shown, None, false, |panel| panels.permissions(panel)); + let shown = state.workspace.layout().panel_state(&panel) != PanelState::Hidden; + let specs = &state.specs; + let _ = Arc::make_mut(&mut state.workspace).set_visible(panel, !shown, None, false, |panel| specs.permissions(panel)); continue; } match command { @@ -266,7 +259,7 @@ fn title_bar(ui: &mut Ui, state: &MockState) { }), MenuTitle::new("&Window", |ui| { for panel in Panel::ALL { - let layout = &state.workspace.layout; + let layout = state.workspace.layout(); let shown = if layout.opens_in_flyout(&panel) { state.flyout == Some(panel) } else { diff --git a/crates/ui-gallery/src/mock/model.rs b/crates/ui-gallery/src/mock/model.rs index b0d491640..691d3a8f1 100644 --- a/crates/ui-gallery/src/mock/model.rs +++ b/crates/ui-gallery/src/mock/model.rs @@ -12,6 +12,9 @@ use craft_ui::contract::{CommandSet, Tracked}; use craft_ui::rails::{LastUsed, RailTool, SlotId, ToolSlot}; use craft_ui::runtime::env::UnitKind; use egui::{Color32, Rect}; +use std::sync::Arc; + +use super::panels::MockSpecs; /// The width of the dock column at the end edge. const SIDE_WIDTH: f32 = 220.0; @@ -403,7 +406,9 @@ impl Document { #[non_exhaustive] pub struct MockState { /// The dock's panels and where they sit. - pub workspace: Workspace, + pub workspace: Arc>, + /// The dock's panel specs. + pub specs: Tracked, /// The open document. pub document: Document, /// The current tool. @@ -433,7 +438,8 @@ impl Default for MockState { Node::split(Axis::X, SplitSize::Ratio(CANVAS_SHARE), Node::tabs(vec![Panel::Canvas], 0), Node::dock(DockEdge::End, vec![side, icons])); let root = Node::split(Axis::X, SplitSize::FixedFirst(TOOLS_DOCK_WIDTH), Node::dock(DockEdge::Start, vec![tools]), canvas); MockState { - workspace: Workspace::new(Layout::new(Some(root), Vec::new())), + workspace: Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))), + specs: Tracked::new(MockSpecs), document: Document::default(), tool: Tool::Move, last_used: LastUsed::default(), diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index 11f5b9cdd..1a8d3434f 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -18,7 +18,7 @@ use craft_ui::contract::{ Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, MemoProps, MemoView, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SweepApply, SweepStep, ToggleColumn, WordSetCx as _, }; -use craft_ui::docking::{DockPanels, GroupAt, PanelSpec}; +use craft_ui::docking::{DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs}; use craft_ui::list::{ListRow, ToggleCell}; use craft_ui::patterns::canvas::NavigatorPanel; use craft_ui::primitives::textures::Revision; @@ -48,10 +48,12 @@ pub(super) struct Panels<'a> { pub(super) last_used: &'a mut LastUsed, /// The tool the toolbar picked in this pass. pub(super) picked: Option, - /// The context the toolbar's grid is measured in. - pub(super) ctx: &'a egui::Context, } +/// The dock's panel specs: fixed for the mock's four panels. +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::PlainData)] +pub struct MockSpecs; + impl Panels<'_> { /// The toolbar's rail in the rect the dock gives it, or its height at a width: as many tool columns as the width /// holds. The rail's own padding surrounds the buttons, so no group padding applies. @@ -92,13 +94,13 @@ fn name(panel: Panel) -> &'static str { } } -impl DockPanels for Panels<'_> { +impl PanelSpecs for MockSpecs { fn spec(&self, panel: &Panel) -> PanelSpec { let spec = PanelSpec::new(name(*panel)).limits(SizeLimits::default()); match panel { Panel::Canvas => spec.canvas(), // The toolbar's column is whole tool columns wide. - Panel::Tools => spec.grid(ToolRail::::dock_grid(self.ctx, Tool::slots().len())), + Panel::Tools => spec.grid(DockGrid::rail(Tool::slots().len())), _ => spec, } } @@ -111,7 +113,9 @@ impl DockPanels for Panels<'_> { _ => Permissions::ALL, } } +} +impl DockPanels for Panels<'_> { fn body(&mut self, panel: &Panel, ui: &mut Ui, cx: &mut BodyCx<'_>) { match panel { Panel::Navigator => { diff --git a/crates/ui-gallery/src/viewer/layout.rs b/crates/ui-gallery/src/viewer/layout.rs index 12780ff69..aec99739f 100644 --- a/crates/ui-gallery/src/viewer/layout.rs +++ b/crates/ui-gallery/src/viewer/layout.rs @@ -167,7 +167,7 @@ pub fn reconciled(mut saved: Dock, workspace: Workspace, catalog: &Cata } }; saved.reconcile(registered, PanelId::permissions, &default_for(workspace)); - saved.hidden.retain(|(panel, _)| registered(panel)); + saved.forget_hidden(|panel| !registered(panel)); saved } @@ -185,7 +185,7 @@ pub fn load(text: &str, workspace: Workspace, catalog: &Catalog) -> Dock) -> Vec { layout - .layout + .layout() .panels() .into_iter() .filter_map(|panel| match panel { diff --git a/crates/ui-gallery/src/viewer/state.rs b/crates/ui-gallery/src/viewer/state.rs index d6d9a1479..c7fb67de4 100644 --- a/crates/ui-gallery/src/viewer/state.rs +++ b/crates/ui-gallery/src/viewer/state.rs @@ -8,6 +8,7 @@ use super::layout::{self, PanelId}; use super::picks::Cells; use super::settings::GallerySettings; use super::tree::{self, TreeKey}; +use crate::chrome::GallerySpecs; use crate::mock::MockState; use craft_behavior::Selection; use craft_behavior::dock::Workspace as Dock; @@ -90,9 +91,11 @@ pub struct Viewer { /// What the theme panels share. pub themes: ThemeWorkspace, /// The components workspace's dock layout. - pub dock: Dock, + pub dock: Arc>, /// The theme workspace's dock layout. - pub theme_dock: Dock, + pub theme_dock: Arc>, + /// The panel specs both docks show. + pub specs: Tracked, /// The mock application the theme workspace's App preview shows. pub mock: MockState, /// The drawings the inspector shows over the selected card's stories. @@ -125,8 +128,9 @@ impl Viewer { more_open: false, browser, themes: ThemeWorkspace::new(), - dock: layout::default_components(), - theme_dock: layout::default_theme(), + dock: Arc::new(layout::default_components()), + theme_dock: Arc::new(layout::default_theme()), + specs: Tracked::new(GallerySpecs), mock: MockState::default(), inspect_layers: Tracked::new(InspectLayers::default()), sizes_synced: None, @@ -154,8 +158,8 @@ impl Viewer { *browser.tree_seen = Some(browser.selected_type()); browser.level.edit(|level| level.clone_from(&settings.level)); *browser.story_of = settings.story_of(&browser.catalog); - self.dock = layout::load(&settings.dock, Workspace::Components, &browser.catalog); - self.theme_dock = layout::load(&settings.theme_dock, Workspace::Theme, &browser.catalog); + Arc::make_mut(&mut self.dock).replace(layout::load(&settings.dock, Workspace::Components, &browser.catalog)); + Arc::make_mut(&mut self.theme_dock).replace(layout::load(&settings.theme_dock, Workspace::Theme, &browser.catalog)); } /// Makes the root's app sizes the theme workspace's app layer, when the layer was edited since the last sync. @@ -181,26 +185,27 @@ impl Viewer { /// The dock layout of the shown workspace. pub fn dock_mut(&mut self) -> &mut Dock { match self.workspace { - Workspace::Components => &mut self.dock, - Workspace::Theme => &mut self.theme_dock, + Workspace::Components => Arc::make_mut(&mut self.dock), + Workspace::Theme => Arc::make_mut(&mut self.theme_dock), } } /// Opens the tab of the component registered as `type_name` beside the Overview and shows it. pub fn open_component(&mut self, type_name: &str) { - let _ = self.dock.set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions()); + let _ = Arc::make_mut(&mut self.dock) + .set_visible(PanelId::component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions()); } /// Puts the shown workspace's panels back at their default places. The open component tabs are documents and stay. pub fn reset_layout(&mut self) { let workspace = self.workspace; let tabs = layout::open_tabs(&self.dock); - *self.dock_mut() = layout::default_for(workspace); + self.dock_mut().replace(layout::default_for(workspace)); if workspace == Workspace::Components { for tab in tabs { self.open_component(&tab); } - let _ = self.dock.set_visible(PanelId::Overview, true, None, false, |panel| panel.permissions()); + let _ = Arc::make_mut(&mut self.dock).set_visible(PanelId::Overview, true, None, false, |panel| panel.permissions()); } } diff --git a/crates/ui-gallery/tests/it/viewer.rs b/crates/ui-gallery/tests/it/viewer.rs index c3e5a4bd8..5d8a7ca0f 100644 --- a/crates/ui-gallery/tests/it/viewer.rs +++ b/crates/ui-gallery/tests/it/viewer.rs @@ -15,7 +15,7 @@ fn each_default_layout_is_valid_and_holds_exactly_its_workspaces_panels() { let layout = default_for(workspace); assert_eq!(layout.validate(), Ok(())); for panel in COMPONENTS.iter().chain(&THEME) { - assert_eq!(layout.layout.contains(panel), panels.contains(panel), "{workspace:?} {panel:?}"); + assert_eq!(layout.layout().contains(panel), panels.contains(panel), "{workspace:?} {panel:?}"); } } } @@ -59,7 +59,7 @@ fn the_overview_is_pinned_and_a_component_tab_is_not() { let tab = PanelId::component("craft_ui::buttons::link::Link"); let mut dock = default_for(Workspace::Components); let _ = dock.set_visible(tab.clone(), true, Some(PanelId::Overview), false, |panel| panel.permissions()); - assert!(dock.layout.contains(&tab), "the component tab opens beside the Overview"); + assert!(dock.layout().contains(&tab), "the component tab opens beside the Overview"); let refused = [ Action::float(PanelId::Overview, rect), Action::close(PanelId::Overview), diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 44fe2eb95..c3b9a874c 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -409,12 +409,12 @@ impl DropTarget> for DockDro } } -/// The arrangement a dock drag started on: the dock area and the revision of the workspace it showed. +/// The arrangement a dock drag started on: the dock area and the generation of the workspace it showed. #[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct Arrangement { pub dock: Id, - pub revision: u64, + pub generation: u64, } /// The env value a dock area puts into its body: the arrangement it shows. `None` outside a dock area. @@ -463,9 +463,9 @@ where cx.start_drag(GroupDrag { unit, active, source: None, strip: Some(strip), started }, DragPreview::Named(label)); } -/// Ends a running tab or group drag that started on `shown`'s dock under another revision: another arrangement +/// Ends a running tab or group drag that started on `shown`'s dock under another generation: another arrangement /// replaced the workspace, and the panel or group the drag names may be gone or elsewhere. The dock's own edits keep -/// the revision, and so the drag. +/// the generation, and so the drag. #[doc(hidden)] pub fn end_replaced_drags(ctx: &Context, shown: Arrangement) { let replaced = |started: Option| started.is_some_and(|started| started.dock == shown.dock && started != shown); diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 6f5c0a214..1ce3cab72 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -38,7 +38,7 @@ pub use event::{DockEvent, FloatSpace, HidePanels}; pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook, MenuRows}; pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, WindowColumn}; -pub use panels::{DockPanels, request_actions}; +pub use panels::{DockPanels, PanelSpecs, SpecSource, request_actions}; #[doc(hidden)] pub use panels::{close_requests, open_requests}; pub use placed::{Placing, placed_rect, with_area_rules}; diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index bdcd51b00..69530973f 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -2,13 +2,56 @@ use super::flyout::GroupAt; use super::spec::PanelSpec; -use crate::contract::BodyCx; +use crate::contract::{BodyCx, PlainData, Revision, Tracked}; use crate::menu::PanelRow; use crate::runtime::memory; use craft_behavior::dock::{Action, Permissions}; use egui::{Context, Id, Ui}; -/// The host's panels. A dock calls, in one pass and for each group it shows: +/// What a dock reads of the host's panels: each panel's spec and permissions. The host keeps an implementation in a +/// [`Tracked`] and gives the dock a reference to it; the dock reads it only when the `Tracked`'s revision or the +/// workspace changed, and keeps what it read otherwise. A host changes a label or a limit by editing its spec model, +/// which moves the revision. The model is plain data, so nothing it answers can change without that edit; a spec +/// needs no style either (a tool rail's grid is [`DockGrid::rail`](super::DockGrid::rail), which the dock sizes). +pub trait PanelSpecs

: PlainData { + /// What the dock reads of `panel`. + fn spec(&self, panel: &P) -> PanelSpec; + + /// What may happen to `panel`: whether it moves, floats, closes and takes tabs and splits (the default allows + /// everything). A canvas is `Permissions::PROTECTED`. A locked workspace narrows these itself. + fn permissions(&self, _panel: &P) -> Permissions { + Permissions::ALL + } +} + +/// A host's [`PanelSpecs`] in its [`Tracked`], as a dock holds it: the revision keys what the dock derives from the +/// specs. Implemented for `Tracked` of every `S: PanelSpecs

`. +pub trait SpecSource

{ + /// The revision of the spec model. + fn revision(&self) -> Revision; + + /// What the dock reads of `panel` ([`PanelSpecs::spec`]). + fn spec(&self, panel: &P) -> PanelSpec; + + /// What may happen to `panel` ([`PanelSpecs::permissions`]). + fn permissions(&self, panel: &P) -> Permissions; +} + +impl> SpecSource

for Tracked { + fn revision(&self) -> Revision { + Tracked::revision(self) + } + + fn spec(&self, panel: &P) -> PanelSpec { + PanelSpecs::spec(&**self, panel) + } + + fn permissions(&self, panel: &P) -> Permissions { + PanelSpecs::permissions(&**self, panel) + } +} + +/// The host's panel views. A dock calls, in one pass and for each group it shows: /// /// 1. `group_view`, with the group's panels and where the group goes. When it returns a height the host took the group /// itself: the dock shows no tab strip and no panel body for that group, and calls neither `group_header` nor `body` @@ -19,20 +62,10 @@ use egui::{Context, Id, Ui}; /// Each of these runs every pass the group shows. A host memoizes inside them: a body or view shown through a /// [`MemoView`](crate::contract::MemoView) runs only when its props changed or input reached it, and otherwise repaints /// its last run. The dock's own chrome (each group's tab row, each column's bar) is memoized on what it shows: the -/// panels' specs, the arrangement and the look. +/// panels' specs ([`PanelSpecs`]), the arrangement and the look. /// -/// A panel's `spec` and `permissions` are read every pass, so a host may change a label or a limit between passes. /// `panel_rows` is read while the group's menu is open. The dock's actions name a group by one of its panels. pub trait DockPanels

{ - /// What the dock reads of `panel`. - fn spec(&self, panel: &P) -> PanelSpec; - - /// What may happen to `panel`: whether it moves, floats, closes and takes tabs and splits (the default allows - /// everything). A canvas is `Permissions::PROTECTED`. A locked workspace narrows these itself. - fn permissions(&self, _panel: &P) -> Permissions { - Permissions::ALL - } - /// Shows `panel`'s body in `ui`: the group's body, inset from its edges by the panel padding. The group is the /// body's panel and its tab the body's title, so the body shows no framework `Panel` or padding of its own; content /// taller than the group scrolls in the body's own scrolling container. A document panel's body diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index b395cd6f0..6af8a0ac2 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -1,5 +1,6 @@ //! `PanelSpec`: what the dock asks of a panel before it shows its body. +use super::DockSizes; use crate::contract::SizeLimits; use crate::primitives::IconSpec; use crate::runtime::env::Label; @@ -52,26 +53,61 @@ impl DockHeights { /// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as /// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag /// of the column's edge sets whole steps; the content lays out as many columns as fit the width it gets. +/// +/// A tool rail's grid is [`DockGrid::rail`]: the dock computes its widths from its own style +/// ([`resolved`](Self::resolved)), so the grid follows the theme and density without the panel's spec reading them. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct DockGrid { - /// The content's width at one column: a cell and the content's own padding on both sides. - pub first: f32, - /// The width each further column adds: a cell and the gap before it. - pub step: f32, + widths: GridWidths, /// The most columns the content fills, its cell count: more steps show it no wider. pub most: u16, } +/// The widths of a [`DockGrid`]'s columns. +#[derive(Clone, Copy, Debug, PartialEq)] +enum GridWidths { + /// `first`: the content's width at one column, a cell and the content's own padding on both sides; `step`: the + /// width each further column adds, a cell and the gap before it. + Points { first: f32, step: f32 }, + /// A tool rail's cells, sized by the dock's style. + Rail, +} + impl DockGrid { /// A grid `first` wide at one column, `step` wider for each further column, up to `most` columns. pub const fn new(first: f32, step: f32, most: u16) -> Self { - DockGrid { first, step, most } + DockGrid { widths: GridWidths::Points { first, step }, most } } - /// Whether the widths are finite and positive and the grid has a column. + /// The grid of a tool rail of `cells` cells: a rail button and the control padding on both sides at one column, + /// a button and the tight gap for each further column, in the style the dock shows it in. + pub fn rail(cells: usize) -> Self { + DockGrid { widths: GridWidths::Rail, most: u16::try_from(cells).unwrap_or(u16::MAX).max(1) } + } + + /// The grid with its widths in points: a [`rail`](Self::rail) grid takes the rail widths of `sizes`. + pub fn resolved(self, sizes: &DockSizes) -> Self { + match self.widths { + GridWidths::Points { .. } => self, + GridWidths::Rail => DockGrid::new(sizes.rail_first, sizes.rail_step, self.most), + } + } + + /// The content's width at one column and the width each further column adds; zero for a rail grid not yet + /// [`resolved`](Self::resolved). + fn first_step(self) -> (f32, f32) { + match self.widths { + GridWidths::Points { first, step } => (first, step), + GridWidths::Rail => (0.0, 0.0), + } + } + + /// Whether the widths are finite and positive and the grid has a column. A rail grid not yet + /// [`resolved`](Self::resolved) is not. pub fn valid(self) -> bool { - self.first.is_finite() && self.first > 0.0 && self.step.is_finite() && self.step > 0.0 && self.most > 0 + let (first, step) = self.first_step(); + first.is_finite() && first > 0.0 && step.is_finite() && step > 0.0 && self.most > 0 } /// `steps` kept between one column and [`most`](Self::most). @@ -81,7 +117,8 @@ impl DockGrid { /// The content's width at `steps` columns, kept within the grid's columns. pub fn width(self, steps: u16) -> f32 { - self.first + f32::from(self.clamp(steps) - 1) * self.step + let (first, step) = self.first_step(); + first + f32::from(self.clamp(steps) - 1) * step } /// The most columns whose width fits `width`, at least one. diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 71b53c765..14415863f 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -4,9 +4,9 @@ use super::SplitFramesCx as _; use super::group::MENU; use super::stack::{StackSection, StackSections}; use super::tree::FrameRules; -use super::{DockCommands, DockGroup, DockPanels, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelTitle, SplitArea, Splitter, WindowMenuRows}; +use super::{DockCommands, DockGroup, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelSpecs, PanelTitle, SplitArea, Splitter, WindowMenuRows}; use crate::contract::SizeLimits; -use crate::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, Validity}; +use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Tracked, Validity}; use crate::menu::{Menu, PanelRow}; use crate::runtime::commands::CommandRef; use crate::runtime::env::Message; @@ -130,21 +130,20 @@ fn between_sections(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } /// The panels of the Window menu story: each labelled by its number. +#[derive(crate::contract::PlainData)] struct NumberedPanels; -impl DockPanels for NumberedPanels { +impl PanelSpecs for NumberedPanels { fn spec(&self, panel: &u32) -> PanelSpec { PanelSpec::new(format!("Panel {panel}")) } - - fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} } #[story(WindowMenuRows<'static, u32>, covers = [Default], drive = Drive::Never)] fn window_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let layout = Layout::new(Some(Node::tabs(vec![1], 0)), Vec::new()); let menu = Menu::new("Window").open(data.bind("open", true)).show(ui, |ui, _| { - WindowMenuRows::new(&layout, &NumberedPanels, &[1, 2]).show(ui); + WindowMenuRows::new(&layout, &Tracked::new(NumberedPanels), &[1, 2]).show(ui); }); StoryOutput::from(menu.output) } diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 358e6b0b5..20f26a4a2 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -66,6 +66,11 @@ pub struct DockSizes { pub iconic_least: f32, /// The width of an expanded column the user has not resized (the dock column width). pub column: f32, + /// A tool rail's width at one column: a rail button and the control padding on both sides + /// ([`DockGrid::rail`](super::DockGrid::rail)). + pub rail_first: f32, + /// The width each further column of a tool rail adds: a rail button and the tight gap before it. + pub rail_step: f32, } impl DockSizes { @@ -99,6 +104,8 @@ impl DockSizes { jump: cx.control().height, iconic_least: size.rail.width, column: size.dock.column, + rail_first: size.rail.button + 2.0 * cx.tokens.space.pad.control, + rail_step: size.rail.button + cx.tokens.space.gap.tight, } } diff --git a/crates/ui-panels/src/docking/window_menu.rs b/crates/ui-panels/src/docking/window_menu.rs index 054037daa..8a0d29a51 100644 --- a/crates/ui-panels/src/docking/window_menu.rs +++ b/crates/ui-panels/src/docking/window_menu.rs @@ -1,6 +1,6 @@ //! `WindowMenuRows`: the Window menu's check row for every panel of an app. -use super::DockPanels; +use super::SpecSource; use crate::contract::Show as _; use crate::menu::MenuItem; use craft_behavior::dock::{Action, Layout, PanelState}; @@ -8,7 +8,7 @@ use egui::Ui; use std::hash::Hash; /// One check row per panel in the order the app gives, for a Window menu. A row is checked while its panel is in the -/// layout (closed panels are not), and its label and icon come from [`DockPanels::spec`]. A pick returns the action +/// layout (closed panels are not), and its label and icon come from the panels' specs ([`PanelSpecs::spec`](super::PanelSpecs::spec)). A pick returns the action /// that shows the panel (open a closed one, bring a panel behind another tab to the front) or closes it (a panel /// showing); the app applies it through the same path as the actions of a `DockArea`. A Hidden pick's `Action::open` /// restores the panel's last place through `Workspace::apply_all`. @@ -20,7 +20,7 @@ use std::hash::Hash; #[pattern(probe(WindowMenuRows<'static, u32>))] pub struct WindowMenuRows<'a, P> { layout: &'a Layout

, - panels: &'a dyn DockPanels

, + specs: &'a dyn SpecSource

, order: &'a [P], flyout: Option<&'a P>, } @@ -37,9 +37,10 @@ pub struct WindowMenuRowsOutput

{ } impl<'a, P: Clone + Eq + Hash> WindowMenuRows<'a, P> { - /// Rows for `order` (every panel the app has, open or not), checked from `layout`, labelled by `panels`. - pub fn new(layout: &'a Layout

, panels: &'a dyn DockPanels

, order: &'a [P]) -> Self { - WindowMenuRows { layout, panels, order, flyout: None } + /// Rows for `order` (every panel the app has, open or not), checked from `layout`, labelled by `specs`, the + /// host's spec model the dock shows ([`DockArea::new`](crate::docking)). + pub fn new(layout: &'a Layout

, specs: &'a dyn SpecSource

, order: &'a [P]) -> Self { + WindowMenuRows { layout, specs, order, flyout: None } } /// The panel whose flyout is open: the value of the binding the app gives `DockArea::flyout`. @@ -53,7 +54,7 @@ impl<'a, P: Clone + Eq + Hash> WindowMenuRows<'a, P> { pub fn show(self, ui: &mut Ui) -> WindowMenuRowsOutput

{ let (mut action, mut flyout) = (None, None); for panel in self.order { - let spec = self.panels.spec(panel); + let spec = self.specs.spec(panel); let state = self.layout.panel_state(panel); let in_flyout = self.layout.opens_in_flyout(panel); let open = self.flyout == Some(panel); diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 99e0f0f9a..4d7491a80 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -92,7 +92,7 @@ type FooterFn<'a> = Box; /// The rail of tool slots, laid out in a grid of columns: one `FlyoutButton` per visible slot showing the slot's shown /// tool, the slot with the current tool toggled on. A click selects the shown tool, a row of the flyout selects that /// tool. The rail takes as many columns as the width it gets holds, the most whole columns that fit -/// ([`dock_grid`](ToolRail::dock_grid)): it is `first` wide at one column and `step` wider for each further column, +/// ([`dock_grid`](ToolRail::dock_grid)): it is a button and the control padding wide at one column and a button and the tight gap wider for each further column, /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button /// follows the last slot; the host's footer stays in view under the slots, which scroll when the room is short under @@ -156,15 +156,11 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { .label(label) } - /// The grid of a rail of `cells` cells (its visible slots and the Edit Toolbar button) as its dock column sizes - /// it ([`PanelSpec::grid`](crate::docking::PanelSpec::grid)): `first` is a button and the control padding on both - /// sides, `step` a button and the tight gap before it, and `most` the cells. + /// The grid of a rail of `cells` cells (its visible slots and the Edit Toolbar button) in the root style: + /// [`DockGrid::rail`] resolved there. A panel's spec gives the unresolved [`DockGrid::rail`], which its dock + /// resolves in its own style. pub fn dock_grid(ctx: &egui::Context, cells: usize) -> DockGrid { - StyleCx::with_root(ctx, |cx| { - let button = cx.tokens.size.rail.button; - let most = u16::try_from(cells).unwrap_or(u16::MAX).max(1); - DockGrid::new(button + 2.0 * cx.tokens.space.pad.control, button + cx.tokens.space.gap.tight, most) - }) + DockGrid::rail(cells).resolved(&crate::docking::DockSizes::of(ctx)) } /// The cells the rail lays out: its visible slots and the Edit Toolbar button. @@ -311,7 +307,7 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { /// Shows the rail one column wide, for a host that lays it at the start of a row (the full-window workspaces' /// tool strips): the width `ui` has left belongs to what follows it in the row. pub fn show_column(self, ui: &mut Ui, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput { - let one = Self::dock_grid(ui.ctx(), 1).first; + let one = Self::dock_grid(ui.ctx(), 1).width(1); self.show_within(ui, one, footer) } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 4401d77be..156944aa4 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -4,7 +4,7 @@ use super::hide::{self, Shown}; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, Tracked, WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; @@ -12,11 +12,12 @@ use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_dra use crate::docking::{ ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, - IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, Placing, SplitArea, WindowColumn, actions, column_cells, dock_states, - frame, move_actions, stepped, with_area_rules, + IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, WindowColumn, actions, + column_cells, dock_states, frame, move_actions, stepped, with_area_rules, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within}; +use crate::runtime::derived::derived; use crate::runtime::drag; use crate::runtime::env::{Env, Label, RevealEdge, ShellCx, ShellEntry}; use crate::runtime::memory::Remember as _; @@ -70,7 +71,7 @@ pub struct DockAreaOutput

{ /// The edits of the whole workspace this pass, in order: a split divider's size, a floating window's move, and the /// applied `actions` as one undo step. A workspace bound by reference takes them itself; a given one needs the host /// to apply them. - pub edit: EditEvents>, + pub edit: EditEvents>>, /// Where commands float a panel, group or column: the area's float bounds and the sizes of what it drew. pub float_space: Option>, /// Where each dock column was placed this pass, named by a panel of its first group, in the area's layer space. @@ -108,13 +109,17 @@ impl

Outcome for DockAreaOutput

{ /// so does a release no spot takes, with `DockConfig::float_on_empty_drop`. /// - State: the open flyout (unless the host binds it with [`flyout`](DockArea::flyout)) lives in the area's root /// container. -/// - Replacement: a tab or group drag records the workspace revision it started under; when another arrangement +/// - Replacement: a tab or group drag records the workspace generation it started under; when another arrangement /// replaces the workspace ([`Workspace::replace`]), the drag ends without a drop. +/// - Specs: the panels' specs and permissions come from the host's [`PanelSpecs`] in a `Tracked`. The area reads them +/// only when that revision, the workspace's revision or the lock changed ([`derived`]), and keeps what it read +/// otherwise: an idle pass reads no spec. #[derive(crate::contract::Pattern, crate::contract::Props)] #[pattern(probe(DockArea<'static, usize>))] pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { label: Label, - workspace: Bind<'a, Workspace

>, + workspace: Bind<'a, Arc>>, + specs: &'a dyn SpecSource

, panels: &'a mut dyn DockPanels

, config: DockConfig, /// Which panels the host hides. @@ -138,13 +143,20 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { } impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { - /// A dock area named `label` over `workspace`, with its panels from `panels` and its behaviour from `config`. The - /// root's id comes from the label under the parent's id, and inside an `AppShell` from the window too, so two - /// windows' docks never share state. - pub fn new(label: impl Into

>, panels: &'a mut dyn DockPanels

, config: DockConfig) -> Self { + /// A dock area named `label` over `workspace`, with its panels' specs from `specs`, their views from `panels` and + /// its behaviour from `config`. The root's id comes from the label under the parent's id, and inside an `AppShell` + /// from the window too, so two windows' docks never share state. + pub fn new + 'a>( + label: impl Into

, + config: DockConfig, + ) -> Self { DockArea { label: label.into(), workspace, + specs, panels, config, hide: HidePanels::None, @@ -155,10 +167,16 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { } } - /// A dock area over a layout that is only shown: a given workspace without hidden panels, locked, so nothing - /// moves, floats or closes. - pub fn read_only(label: impl Into

, panels: &'a mut dyn DockPanels

, config: DockConfig) -> Self { - DockArea { locked: true, ..Self::new(label, Bind::given(Workspace::new(layout.clone())), panels, config) } + /// A dock area that only shows `workspace`: given, and locked, so nothing moves, floats or closes. It keys what it + /// derives on the workspace's revision, so an idle pass reads no spec. + pub fn read_only + 'a>( + label: impl Into

, + config: DockConfig, + ) -> Self { + DockArea { locked: true, ..Self::new(label, Bind::given(Arc::clone(workspace)), specs, panels, config) } } } @@ -175,7 +193,7 @@ struct AreaMemory

{ #[derive(Clone)] struct Moving

{ id: GestureId, - before: Workspace

, + before: Arc>, } impl

Default for AreaMemory

{ @@ -205,7 +223,7 @@ impl Drops<'_, P> { let shell = cx.env.get::().0; let bounds = shell.as_ref().map_or(cx.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, self.config, self.specs); - let spec = |panel: &P| spec_in(self.specs, panel); + let spec = |panel: &P| spec_in(self.specs, &sizes, panel); let protected = |panel: &P| (self.permissions)(panel).is_protected(); let (hide, _) = hide::resolved(self.hide, shell.as_ref()); let mut target = DockDropTarget::new(&ctx, self.dock, self.layout, self.permissions); @@ -249,14 +267,46 @@ struct Scene<'s, P> { floated: &'s [(P, Location

)], } -/// The spec of `panel` in `specs`, or an unnamed one. -fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec { - specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) +/// The spec of `panel` in `specs`, or an unnamed one, with its grid in the dock's `sizes`. +fn spec_in(specs: &HashMap, sizes: &DockSizes, panel: &P) -> PanelSpec { + let mut spec = specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())); + spec.grid = spec.grid.map(|grid| grid.resolved(sizes)); + spec +} + +/// What an area derives from its workspace, its panels' specs and its lock, kept while none of them changes: whether +/// the workspace is valid, and for each panel in its layout the spec, the permissions (narrowed when locked) and the +/// key. +struct DockModel

{ + error: Option, + specs: HashMap, + rights: HashMap, + keys: HashMap, +} + +impl DockModel

{ + fn of(workspace: &Workspace

, specs: &dyn SpecSource

, locked: bool) -> Self { + let error = workspace.validate().err().map(|error| InvalidGeometry { error }); + let panels = if error.is_none() { workspace.layout().panels() } else { Vec::new() }; + let rights = panels + .iter() + .map(|panel| { + let rights = specs.permissions(panel); + ((*panel).clone(), if locked { rights.locked() } else { rights }) + }) + .collect(); + DockModel { + error, + specs: panels.iter().map(|panel| ((*panel).clone(), specs.spec(panel))).collect(), + rights, + keys: panels.iter().map(|panel| (PanelKey::of(*panel), (*panel).clone())).collect(), + } + } } impl Scene<'_, P> { fn spec(&self, panel: &P) -> PanelSpec { - spec_in(self.specs, panel) + spec_in(self.specs, &self.sizes, panel) } fn permissions(&self, panel: &P) -> Permissions { @@ -277,7 +327,7 @@ struct Passed

{ events: Vec>, focused: Option

, picked: Option

, - edit: EditEvents>, + edit: EditEvents>>, space: Option>, columns: Vec<(P, Rect)>, windows: Vec<(P, ViewportId)>, @@ -346,7 +396,7 @@ struct Pass<'s, P> { impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { /// Shows the area across the room offered. pub fn show(self, ui: &mut Ui) -> DockAreaOutput

{ - let DockArea { label, mut workspace, panels, config, hide, maximized, auto_collapse, locked, mut flyout } = self; + let DockArea { label, mut workspace, specs, panels, config, hide, maximized, auto_collapse, locked, mut flyout } = self; let ctx = ui.ctx().clone(); let (rtl, window) = { let env = Env::of(ui); @@ -355,34 +405,24 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { let id = ui.scope_id().with(("dock area", label.as_str(), window)); let held = match workspace.reborrow().get() { Some(Mixed::Same(held)) => held, - _ => Workspace::default(), + _ => Arc::default(), }; - let (current, error) = match held.validate() { - Ok(()) => (held, None), - Err(error) => (Workspace::default(), Some(InvalidGeometry { error })), - }; - let rights: HashMap = current - .layout - .panels() - .into_iter() - .map(|panel| { - let rights = panels.permissions(panel); - (panel.clone(), if locked { rights.locked() } else { rights }) - }) - .collect(); + let model = derived(&ctx, id, &(held.revision(), specs.revision(), locked), || DockModel::of(&held, specs, locked)); + let error = model.error.clone(); + let current = if error.is_none() { held } else { Arc::default() }; + let rights = &model.rights; let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL); - let specs: HashMap = current.layout.panels().into_iter().map(|panel| (panel.clone(), panels.spec(panel))).collect(); let drops = Drops { dock: id, - layout: ¤t.layout, + layout: current.layout(), permissions: &policy, config: &config, - specs: &specs, + specs: &model.specs, hide, maximized: maximized.as_ref(), rtl, }; - let shows = Arrangement { dock: id, revision: current.revision() }; + let shows = Arrangement { dock: id, generation: current.generation() }; end_replaced_drags::

(&ctx, shows); let dropped: RefCell>> = RefCell::new(None); let root = DockRoot::new(|cx| { @@ -402,21 +442,22 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { ctx: &ctx, current: ¤t, config: &config, - specs: &specs, + specs: &model.specs, + keys: &model.keys, hide, maximized: maximized.as_ref(), auto_collapse, sizes, rtl, }; - let mut result = show_area(ui, body, &input, &rights, &mut *panels, flyout.as_mut()); + let mut result = show_area(ui, body, &input, rights, &mut *panels, flyout.as_mut()); for edit in &result.edit { workspace.reborrow().write(body, edit); } result.actions.extend(dropped.take()); if !result.actions.is_empty() { let proposed = std::mem::take(&mut result.actions); - let applied = apply_actions(body, workspace.reborrow(), ¤t, &*panels, locked, &label, proposed); + let applied = apply_actions(body, workspace.reborrow(), ¤t, specs, locked, &label, proposed); result.actions = applied.actions; result.edit.extend(applied.edit); } @@ -459,27 +500,28 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { /// What the workspace took of a pass's actions. struct Applied

{ actions: Vec>, - edit: Option>>, + edit: Option>>>, } -/// Applies `proposed` in order to the workspace the binding holds, with the panels' permissions (narrowed when -/// `locked`). A refused action changes nothing and is left out of the result. The accepted ones are written as one -/// edit, which a given workspace does not take. `current` is the workspace as the pass started. +/// Applies `proposed` in order to the workspace the binding holds, with the panels' permissions from `specs` (narrowed +/// when `locked`; an action may open a panel the layout does not hold). A refused action changes nothing and is left +/// out of the result. The accepted ones are written as one edit, which a given workspace does not take. `current` is +/// the workspace as the pass started. fn apply_actions( body: &mut BodyCx<'_>, - mut workspace: BindMut<'_, Workspace

>, - current: &Workspace

, - panels: &dyn DockPanels

, + mut workspace: BindMut<'_, Arc>>, + current: &Arc>, + specs: &dyn SpecSource

, locked: bool, label: &Label, proposed: Vec>, ) -> Applied

{ let before = match workspace.read(body) { Some(Mixed::Same(held)) => held, - _ => current.clone(), + _ => Arc::clone(current), }; - let permissions = |panel: &P| panels.permissions(panel); - let mut next = before.clone(); + let permissions = |panel: &P| specs.permissions(panel); + let mut next = Workspace::clone(&before); let mut actions = Vec::new(); for action in proposed { if next.apply(action.clone(), locked, permissions).is_ok() { @@ -489,7 +531,7 @@ fn apply_actions( if actions.is_empty() { return Applied { actions, edit: None }; } - let edit = EditEvent::set(Mixed::Same(before), next, Arc::from(label.as_str()), None); + let edit = EditEvent::set(Mixed::Same(before), Arc::new(next), Arc::from(label.as_str()), None); workspace.write(body, &edit); Applied { actions, edit: Some(edit) } } @@ -498,9 +540,10 @@ fn apply_actions( struct Input<'i, P> { id: Id, ctx: &'i Context, - current: &'i Workspace

, + current: &'i Arc>, config: &'i DockConfig, specs: &'i HashMap, + keys: &'i HashMap, hide: HidePanels<'i, P>, maximized: Option<&'i P>, auto_collapse: bool, @@ -530,12 +573,11 @@ fn show_area( panels: &mut dyn DockPanels

, mut flyout: Option<&mut Bind<'_, Option

>>, ) -> Passed

{ - let Input { id, ctx, current, config, specs, hide, maximized, auto_collapse, sizes, rtl } = *input; + let Input { id, ctx, current, config, specs, keys, hide, maximized, auto_collapse, sizes, rtl } = *input; let shell = body.shell(); let mut memory = body.memory::>().clone(); - let keys: HashMap = current.layout.panels().into_iter().map(|panel| (PanelKey::of(panel), panel.clone())).collect(); let protected = |panel: &P| rights.get(panel).is_some_and(|rights| rights.is_protected()); - let Shown { view, floating } = hide::shown(¤t.layout, maximized, hide, shell.as_ref(), &protected); + let Shown { view, floating } = hide::shown(current.layout(), maximized, hide, shell.as_ref(), &protected); let layout: &Layout

= &view.layout; let bounds = shell.as_ref().map_or(body.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, config, specs); @@ -546,12 +588,12 @@ fn show_area( layout, specs, permissions: rights, - keys: &keys, + keys, space: &space, bounds, auto_collapse, rtl, - floated: ¤t.floated, + floated: current.floated(), }; let open = open_of(&mut flyout, body, &memory); let mut pass = Pass { @@ -597,16 +639,23 @@ fn show_area( }) }); let mut edit = area.output.edit.events.map(|edited| { - let mut next = current.clone(); - view.write_back(&edited, &mut next.layout); - next + let mut layout = current.layout().clone(); + view.write_back(&edited, &mut layout); + let resized = match (current.layout().root.as_ref(), layout.root.as_ref()) { + (Some(from), Some(to)) => split_changes(from, to).into_iter().map(|(path, size)| Action::resize_split(path, size)).collect(), + _ => Vec::new(), + }; + let mut next = Workspace::clone(current); + // A divider drag only resizes splits, which no permission or lock refuses. + let _ = next.apply_all(resized, false, |_| Permissions::ALL); + Arc::new(next) }); - let mut geometry: Vec> = match (current.layout.root.as_ref(), edit.landed().and_then(|landed| landed.layout.root.as_ref())) { + let mut geometry: Vec> = match (current.layout().root.as_ref(), edit.landed().and_then(|landed| landed.layout().root.as_ref())) { (Some(from), Some(to)) => split_changes(from, to).into_iter().map(|(path, size)| Action::resize_split(path, size)).collect(), _ => Vec::new(), }; register_bands(&scene, ctx, body.rect, &leaves); - let started = memory.moving.as_ref().map(|moving| &moving.before.layout); + let started = memory.moving.as_ref().map(|moving| moving.before.layout()); let moved = if floating { pass.windows(ui, body, &open, started) } else { None }; let mut report = pass.report; let label: Arc = Arc::from(body.words::().move_window.as_str()); @@ -623,7 +672,7 @@ fn show_area( { let place_in = |layout: &Layout

| layout.floating.iter().find(|window| window.contains(&anchor)).map(|window| (window.rect, window.edge)); if let Some((rect, edge)) = - event.landed().and_then(|landed| place_in(&landed.layout)).filter(|place| Some(*place) != place_in(¤t.layout)) + event.landed().and_then(|landed| place_in(landed.layout())).filter(|place| Some(*place) != place_in(current.layout())) { geometry.push(Action::move_floating_with_edge(anchor.clone(), rect, edge)); } @@ -1377,22 +1426,22 @@ fn split_changes

(from: &Node

, to: &Node

) -> Vec<(Vec, SplitSize)> /// permissions with the lock applied, which refuse the move of a locked workspace. fn window_edit( ctx: &Context, - current: &Workspace

, + current: &Arc>, rights: &HashMap, moving: &mut Option>, phase: GesturePhase, action: Action

, label: Arc, -) -> Option>> { +) -> Option>>> { let moved = || { - let mut next = current.clone(); + let mut next = Workspace::clone(current); let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL); - next.apply(action.clone(), false, policy).ok().map(|_| next) + next.apply(action.clone(), false, policy).ok().map(|_| Arc::new(next)) }; let begin = |moving: &mut Option>| { let id = crate::runtime::edit::next_gesture_id(ctx); - *moving = Some(Moving { id, before: current.clone() }); - EditEvent::begin(id, Mixed::Same(current.clone()), Arc::clone(&label), None) + *moving = Some(Moving { id, before: Arc::clone(current) }); + EditEvent::begin(id, Mixed::Same(Arc::clone(current)), Arc::clone(&label), None) }; match phase { GesturePhase::Begin => Some(begin(moving)), @@ -1402,7 +1451,7 @@ fn window_edit( }, GesturePhase::Commit => match moving.take() { Some(held) => Some(EditEvent::commit(held.id, Mixed::Same(held.before), moved()?)), - None => Some(EditEvent::set(Mixed::Same(current.clone()), moved()?, label, None)), + None => Some(EditEvent::set(Mixed::Same(Arc::clone(current)), moved()?, label, None)), }, _ => moving.take().map(|held| EditEvent::cancel(held.id, CancelReason::Dismissed, Some(Mixed::Same(held.before)))), } diff --git a/crates/ui-patterns/src/patterns/dock/area/stories.rs b/crates/ui-patterns/src/patterns/dock/area/stories.rs index 7d798c226..4a5d2abeb 100644 --- a/crates/ui-patterns/src/patterns/dock/area/stories.rs +++ b/crates/ui-patterns/src/patterns/dock/area/stories.rs @@ -2,15 +2,16 @@ use super::DockArea; use crate::contract::SizeLimits; -use crate::contract::{BodyCx, Show as _}; +use crate::contract::{BodyCx, Show as _, Tracked}; use crate::display::Text; -use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, PanelSpec}; +use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs}; use crate::menu::PanelRow; use crate::patterns::presets::{PresetPanelMenu, PresetView}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; use craft_behavior::{Axis, Proposal}; use egui::{Pos2, Rect, Ui}; +use std::sync::{Arc, LazyLock}; const LAYERS: usize = 0; const CHANNELS: usize = 1; @@ -47,7 +48,11 @@ fn name(panel: usize) -> &'static str { } } -impl DockPanels for Demo { +/// The demo panels' specs: fixed by panel. +#[derive(Clone, Debug, Default, PartialEq, crate::contract::PlainData)] +struct DemoSpecs; + +impl PanelSpecs for DemoSpecs { fn spec(&self, panel: &usize) -> PanelSpec { let spec = PanelSpec::new(name(*panel)).limits(SizeLimits::default()); match *panel { @@ -64,7 +69,9 @@ impl DockPanels for Demo { _ => Permissions::ALL, } } +} +impl DockPanels for Demo { fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { Text::new(name(*panel)).show(ui); } @@ -90,22 +97,24 @@ impl DockPanels for Demo { /// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the /// end, with one floating group and one floating window collapsed to icons. -fn workspace() -> Workspace { +fn workspace() -> Arc> { let tools = Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1); let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS], 0), Group::new(vec![PROPERTIES], 0)]).with_width(SIDE); let mut icons = Column::new(vec![Group::new(vec![SWATCHES], 0)]).with_width(SIDE); icons.iconic = true; let centre = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![icons])); let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![tools, side]), centre); - let window = Floating::single(vec![HISTORY], 0, WINDOW).with_id(1); - let mut collapsed = Floating::single(vec![NAVIGATOR], 0, COLLAPSED_WINDOW).with_id(2); + let window = Floating::single(1, vec![HISTORY], 0, WINDOW); + let mut collapsed = Floating::single(2, vec![NAVIGATOR], 0, COLLAPSED_WINDOW); collapsed.column.iconic = true; - Workspace::new(Layout::new(Some(root), vec![window, collapsed])) + Arc::new(Workspace::new(Layout::new(Some(root), vec![window, collapsed]))) } fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput { + /// One spec model for every story, so its revision stays put across frames. + static SPECS: LazyLock> = LazyLock::new(|| Tracked::new(DemoSpecs)); let (workspace, workspace_at) = data.value_at("workspace", workspace()); - DockArea::new("Dock", workspace_at.bind(&mut *workspace), demo, DockConfig::default()).show(ui).into() + DockArea::new("Dock", workspace_at.bind(&mut *workspace), &*SPECS, demo, DockConfig::default()).show(ui).into() } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index d335a4bd6..d5c0f4809 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -2,14 +2,15 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; -use craft_ui::contract::{Bind, BodyCx, Role, Show as _, SizeLimits}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Role, Show as _, SizeLimits, Tracked}; use craft_ui::display::Text; -use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, GroupSize, PanelSpec, group_heights}; +use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, GroupSize, PanelSpec, PanelSpecs, group_heights}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; const STRIP: f32 = 20.0; const MIN: f32 = 60.0; @@ -82,9 +83,9 @@ fn a_dock_sides_total_width_scales_its_columns_within_their_bounds() { let sizes = super::sizes(4.0, 100.0, STRIP); let spec: &dyn Fn(&u32) -> PanelSpec = &spec; let mut live = Workspace::new(end_dock_layout()); - let widths = |live: &Workspace| end_columns(&live.layout).iter().map(|column| sizes.width(column, spec)).collect::>(); + let widths = |live: &Workspace| end_columns(live.layout()).iter().map(|column| sizes.width(column, spec)).collect::>(); let within = |live: &Workspace| { - end_columns(&live.layout).iter().zip(widths(live)).all(|(column, width)| { + end_columns(live.layout()).iter().zip(widths(live)).all(|(column, width)| { let (lo, hi) = sizes.shown_bounds(column, spec); (lo - 0.01..=hi + 0.01).contains(&width) }) @@ -92,20 +93,20 @@ fn a_dock_sides_total_width_scales_its_columns_within_their_bounds() { let start = widths(&live); for total in [sum(&start) + 120.0, sum(&start) - 60.0] { - let actions = sizes.resize_side(&live.layout, DockEdge::End, spec, total); + let actions = sizes.resize_side(live.layout(), DockEdge::End, spec, total); live.apply_all(actions, true, |_| Permissions::ALL).expect("resizing works while the workspace is locked"); assert!((sum(&widths(&live)) - total).abs() < 0.5, "the columns add up to {total}: {:?}", widths(&live)); assert!(within(&live), "every column stays within its bounds: {:?}", widths(&live)); } - let actions = sizes.resize_side(&live.layout, DockEdge::End, spec, 10.0); + let actions = sizes.resize_side(live.layout(), DockEdge::End, spec, 10.0); live.apply_all(actions, false, |_| Permissions::ALL).unwrap(); - let least: f32 = end_columns(&live.layout).iter().map(|column| sizes.shown_bounds(column, spec).0).sum(); + let least: f32 = end_columns(live.layout()).iter().map(|column| sizes.shown_bounds(column, spec).0).sum(); assert!((sum(&widths(&live)) - least).abs() < 0.5, "a total below the bounds stops at their sum"); - let iconic = &end_columns(&live.layout)[2]; + let iconic = &end_columns(live.layout())[2]; assert_eq!(iconic.width, Some(300.0), "an iconic column keeps the width it expands to"); - assert!(sizes.resize_side(&live.layout, DockEdge::End, spec, least).is_empty(), "the width it has asks for nothing"); - assert!(sizes.resize_side(&live.layout, DockEdge::Start, spec, 500.0).is_empty(), "a side without a dock asks for nothing"); + assert!(sizes.resize_side(live.layout(), DockEdge::End, spec, least).is_empty(), "the width it has asks for nothing"); + assert!(sizes.resize_side(live.layout(), DockEdge::Start, spec, 500.0).is_empty(), "a side without a dock asks for nothing"); } /// The panel that lays its content in a grid, as a toolbar does. @@ -125,10 +126,10 @@ fn a_stepped_column_keeps_its_width_while_the_others_scale() { let columns = vec![Column::new(vec![Group::new(vec![2], 0)]).with_width(250.0), Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(2)]; let root = Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, columns)); let mut live = Workspace::new(Layout::new(Some(root), Vec::new())); - let widths = |live: &Workspace| end_columns(&live.layout).iter().map(|column| sizes.width(column, spec)).collect::>(); + let widths = |live: &Workspace| end_columns(live.layout()).iter().map(|column| sizes.width(column, spec)).collect::>(); let before = widths(&live); assert_eq!(before[1], grid().width(2), "a stepped column is as wide as its steps"); - let actions = sizes.resize_side(&live.layout, DockEdge::End, spec, sum(&before) + 80.0); + let actions = sizes.resize_side(live.layout(), DockEdge::End, spec, sum(&before) + 80.0); let touches_tools = |action: &Action| matches!(action, Action::ResizeColumn { panel: TOOLS, .. } | Action::SetColumnSteps { .. }); assert!(!actions.iter().any(touches_tools), "the side's width leaves the stepped column alone: {actions:?}"); live.apply_all(actions, false, |_| Permissions::ALL).expect("the side resizes"); @@ -144,9 +145,10 @@ fn a_stepped_column_keeps_its_width_while_the_others_scale() { } /// A toolbar: a panel whose two lines of content lay out in a grid and never collapse. +#[derive(PlainData)] struct Tools; -impl DockPanels for Tools { +impl PanelSpecs for Tools { fn spec(&self, panel: &u32) -> PanelSpec { if *panel == TOOLS { PanelSpec::new("Tools").grid(grid()) } else { PanelSpec::new("Canvas") } } @@ -154,7 +156,9 @@ impl DockPanels for Tools { fn permissions(&self, panel: &u32) -> Permissions { if *panel == TOOLS { Permissions::ALL.collapses(false) } else { Permissions::ALL } } +} +impl DockPanels for Tools { fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { if *panel == TOOLS { Text::new("One").show(ui); @@ -169,12 +173,12 @@ impl DockPanels for Tools { fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_and_two_steps() { let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1)]); let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0)); - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); let placed: Rc>> = Rc::default(); - let (held, seen) = (Rc::clone(&workspace), Rc::clone(&placed)); + let (held, seen, specs) = (Rc::clone(&workspace), Rc::clone(&placed), Tracked::new(Tools)); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); - let out = DockArea::new("Stepped dock", Bind::bound(&mut workspace), &mut Tools, DockConfig::default()).show(ui); + let out = DockArea::new("Stepped dock", Bind::bound(&mut workspace), &specs, &mut Tools, DockConfig::default()).show(ui); *held.borrow_mut() = workspace; *seen.borrow_mut() = out.columns; }); @@ -184,7 +188,7 @@ fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_an fixture.by_role(Role::TAB_PANEL).into_iter().map(|group| group.rect).find(|rect| !tools.contains_rect(*rect)).expect("the canvas shows"); assert!(tools.bottom() < canvas.bottom() - 10.0, "the column ends below its content, above the dock's foot: {tools:?}, canvas {canvas:?}"); - let steps = |workspace: &Workspace| match &workspace.layout.root { + let steps = |workspace: &Workspace| match &workspace.layout().root { Some(Node::Split { first, .. }) => match first.as_ref() { Node::Dock { columns, .. } => columns[0].steps, other => panic!("{other:?}"), @@ -204,13 +208,13 @@ fn a_docked_stepped_column_fits_its_content_and_its_double_arrow_switches_one_an } /// A dock area showing only a floating window at `at` with the toolbar in a column of one step. -fn floating_tools(at: Rect) -> (Fixture, Rc>>) { - let window = Floating::new(Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1), at); - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(None, vec![window])))); - let held = Rc::clone(&workspace); +fn floating_tools(at: Rect) -> (Fixture, Rc>>>) { + let window = Floating::new(100, Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1), at); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(None, vec![window]))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Tools)); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); - DockArea::new("Floating tools", Bind::bound(&mut workspace), &mut Tools, DockConfig::default()).show(ui); + DockArea::new("Floating tools", Bind::bound(&mut workspace), &specs, &mut Tools, DockConfig::default()).show(ui); *held.borrow_mut() = workspace; }); fixture.settle(); @@ -230,9 +234,9 @@ fn a_floating_stepped_windows_left_and_top_edge_drags_keep_the_opposite_edge() { let (mut fixture, workspace) = floating_tools(at); let before = shown_tools(&fixture); // The left grip straddles the window's left edge, which is its rect's. - fixture.drag_at(Pos2::new(at.left(), before.center().y), Vec2::new(-1.5 * grid().step, 0.0)).settle(); + fixture.drag_at(Pos2::new(at.left(), before.center().y), Vec2::new(-1.5 * (grid().width(2) - grid().width(1)), 0.0)).settle(); let after = shown_tools(&fixture); - let steps = workspace.borrow().layout.floating[0].column.steps; + let steps = workspace.borrow().layout().floating[0].column.steps; assert!(steps.is_some_and(|steps| steps > 1), "the drag widened the window by whole steps: {steps:?}"); assert!((after.right() - before.right()).abs() <= 1.5, "the right edge stays: {before:?}, then {after:?}"); assert!(after.left() < before.left(), "the window grew to the left: {before:?}, then {after:?}"); diff --git a/crates/ui-patterns/tests/it/docking/dock_back.rs b/crates/ui-patterns/tests/it/docking/dock_back.rs index cad0462e1..1c10260cf 100644 --- a/crates/ui-patterns/tests/it/docking/dock_back.rs +++ b/crates/ui-patterns/tests/it/docking/dock_back.rs @@ -25,7 +25,7 @@ fn layout() -> Layout { let end = Node::dock(DockEdge::End, vec![Column::new(vec![Group::new(vec![LAYERS], 0)])]); let root = Node::split(Axis::X, SplitSize::Ratio(0.2), start, Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![CANVAS], 0), end)); let window = Rect::from_min_size(Pos2::new(100.0, 100.0), egui::vec2(200.0, 150.0)); - Layout::new(Some(root), vec![Floating::single(vec![FLOATED], 0, window)]) + Layout::new(Some(root), vec![Floating::single(100, vec![FLOATED], 0, window)]) } #[trial] diff --git a/crates/ui-patterns/tests/it/docking/drop.rs b/crates/ui-patterns/tests/it/docking/drop.rs index f490138ab..715ddbfa7 100644 --- a/crates/ui-patterns/tests/it/docking/drop.rs +++ b/crates/ui-patterns/tests/it/docking/drop.rs @@ -18,7 +18,7 @@ const COLUMN_WIDTH: f32 = 200.0; fn layout() -> Layout { let column = Column::new(vec![Group::new(vec![TOP_GROUP, TOP_SECOND_TAB], 0), Group::new(vec![LOWER_GROUP], 0)]).with_width(COLUMN_WIDTH); let dock = Node::dock(DockEdge::Start, vec![column]); - let window = Floating::single(vec![WINDOW], 0, Rect::from_min_size(at(500.0, 0.0), Vec2::new(200.0, 150.0))); + let window = Floating::single(100, vec![WINDOW], 0, Rect::from_min_size(at(500.0, 0.0), Vec2::new(200.0, 150.0))); Layout::new(Some(Node::split(Axis::X, SplitSize::FixedFirst(COLUMN_WIDTH), dock, Node::tabs(vec![CANVAS], 0))), vec![window]) } diff --git a/crates/ui-patterns/tests/it/docking/drop_preview.rs b/crates/ui-patterns/tests/it/docking/drop_preview.rs index a22d63744..021ccf828 100644 --- a/crates/ui-patterns/tests/it/docking/drop_preview.rs +++ b/crates/ui-patterns/tests/it/docking/drop_preview.rs @@ -1,9 +1,10 @@ //! A dock drop's mark is the region the dragged panel takes once dropped: the rect the area then gives its group. +use super::Numbered; use craft_behavior::Axis; use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx, Role}; -use craft_ui::docking::{DockConfig, DockPanels, DragUnit, FloatSpace, GroupAt, PanelSpec, float_drop}; +use craft_ui::contract::{Bind, BodyCx, Role, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, DragUnit, FloatSpace, GroupAt, float_drop}; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag::{self, DropMark}; use craft_ui::testing::pointer::{moved, press, release}; @@ -12,6 +13,7 @@ use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; +use std::sync::Arc; const ROOM: Vec2 = Vec2::new(800.0, 500.0); const SLACK: f32 = 0.5; @@ -25,10 +27,6 @@ struct Panels { } impl DockPanels for Panels { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { @@ -41,7 +39,7 @@ impl DockPanels for Panels { struct Bed { fixture: Fixture, - workspace: Rc>>, + workspace: Rc>>>, shown: Shown, } @@ -56,13 +54,13 @@ fn bed() -> Bed { } fn bed_on(root: Node) -> Bed { - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); let shown: Shown = Rc::default(); - let (held, seen) = (Rc::clone(&workspace), Rc::clone(&shown)); + let (held, seen, specs) = (Rc::clone(&workspace), Rc::clone(&shown), Tracked::new(Numbered)); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); let mut panels = Panels { shown: Rc::clone(&seen) }; - DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); *held.borrow_mut() = workspace; }); fixture.room(ROOM).settle(); @@ -97,7 +95,7 @@ fn drop_tab(bed: &mut Bed, panel: usize, to: Pos2) -> DropMark { /// The rect the area shows the group of `panel` in. fn group_rect(bed: &Bed, panel: usize) -> Rect { - let layout = bed.workspace.borrow().layout.clone(); + let layout = bed.workspace.borrow().layout().clone(); let place = layout.place(&panel).expect("the panel is docked"); let Some(Node::Tabs { panels, .. }) = layout.node_of(&place) else { panic!("panel {panel} is in a tab group") }; *bed.shown.borrow().get(panels).unwrap_or_else(|| panic!("the group {panels:?} was shown")) diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 4ea3299d4..1802c945c 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -1,10 +1,11 @@ //! Floating windows of a `DockArea`: a drop over a window lands on it. +use super::Numbered; use craft_behavior::Axis; use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx, Role, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, BodyCx, Role, Show as _, ShowContainer as _, Tracked}; use craft_ui::display::Text; -use craft_ui::docking::{DockConfig, DockPanels, GroupDrag, PanelSpec, request_actions}; +use craft_ui::docking::{DockConfig, DockPanels, GroupDrag, request_actions}; use craft_ui::layout_components::Stack; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag::{self, DropMark}; @@ -13,6 +14,7 @@ use craft_ui::testing::{Fixture, trial}; use egui::{Modifiers, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; const DOCKED: usize = 1; const WINDOW: usize = 2; @@ -29,19 +31,9 @@ fn title(panel: usize) -> String { format!("Panel {panel}") } -struct Panels { - rights: fn(&usize) -> Permissions, -} +struct Panels; impl DockPanels for Panels { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(title(*panel)) - } - - fn permissions(&self, panel: &usize) -> Permissions { - (self.rights)(panel) - } - fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { match *panel { SHORT => { @@ -62,7 +54,7 @@ impl DockPanels for Panels { /// while `second` is set. struct Bed { fixture: Fixture, - workspace: Rc>>, + workspace: Rc>>>, actions: Rc>>>, second: Rc>, /// The tallest a floated panel opens (`FloatSpace::default_size`), as the area reported it. @@ -71,19 +63,20 @@ struct Bed { title_row: Rc>, } -fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { - let workspace = Rc::new(RefCell::new(Workspace::new(layout))); +fn bed(layout: Layout) -> Bed { + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout)))); let actions: Rc>>> = Rc::default(); let second = Rc::new(Cell::new(false)); let float_height = Rc::new(Cell::new(0.0)); let title_row = Rc::new(Cell::new(0.0)); let (held, seen_actions, shows_second, seen_height) = (Rc::clone(&workspace), Rc::clone(&actions), Rc::clone(&second), Rc::clone(&float_height)); let seen_title_row = Rc::clone(&title_row); - let mut other = Workspace::new(Layout::new(Some(Node::tabs(vec![SECOND], 0)), Vec::new())); + let mut other = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![SECOND], 0)), Vec::new()))); + let specs = Tracked::new(Numbered); let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); - let mut panels = Panels { rights }; - let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + let mut panels = Panels; + let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); *held.borrow_mut() = workspace; seen_actions.borrow_mut().extend(out.actions); if let Some(space) = out.float_space { @@ -91,7 +84,7 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { seen_title_row.set(space.title_row); } if shows_second.get() { - DockArea::new("Second dock", Bind::bound(&mut other), &mut panels, DockConfig::default()).show(ui); + DockArea::new("Second dock", Bind::bound(&mut other), &specs, &mut panels, DockConfig::default()).show(ui); } }); fixture.settle(); @@ -108,7 +101,7 @@ fn dragging(bed: &Bed) -> bool { } fn with_window(root: Option>) -> Layout { - Layout::new(root, vec![Floating::single(vec![WINDOW], 0, WINDOW_AT)]) + Layout::new(root, vec![Floating::single(100, vec![WINDOW], 0, WINDOW_AT)]) } fn press_and_move(fixture: &mut Fixture, from: Pos2, by: Vec2) { @@ -121,7 +114,7 @@ fn press_and_move(fixture: &mut Fixture, from: Pos2, by: Vec2) { #[trial] fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))), |_| Permissions::ALL); + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0)))); let tabs = bed.fixture.by_role(Role::TAB); let mut docked: Vec<_> = tabs.iter().filter(|tab| !WINDOW_AT.contains(tab.center())).copied().collect(); docked.sort_by(|a, b| a.rect.min.x.total_cmp(&b.rect.min.x)); @@ -139,7 +132,7 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { assert!(!points.is_empty() && points.iter().all(|point| WINDOW_AT.expand(SLACK).contains(*point)), "the mark is the window's: {mark:?}"); bed.fixture.frame(vec![release(over)]); bed.fixture.settle(); - let layout = bed.workspace.borrow().layout.clone(); + let layout = bed.workspace.borrow().layout().clone(); let window = layout.floating.first().expect("the window stays"); assert!(window.panels().any(|panel| *panel == SECOND), "the tab joined the window: {:?}", bed.actions.borrow()); } @@ -148,12 +141,12 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { /// ends the drag, and the release drops nothing. #[trial] fn a_replaced_workspace_ends_the_drag_that_the_areas_own_edits_keep() { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); let by = Vec2::new(-40.0, 30.0); press_and_move(&mut bed.fixture, window_title(), by); - let moved_to = bed.workspace.borrow().layout.floating[0].rect; + let moved_to = bed.workspace.borrow().layout().floating[0].rect; assert!(dragging(&bed) && moved_to != WINDOW_AT, "the window moves under its drag: {moved_to:?}"); - bed.workspace.borrow_mut().replace(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))))); + Arc::make_mut(&mut bed.workspace.borrow_mut()).replace(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))))); bed.fixture.frame(vec![moved(window_title() + by * 1.25)]); assert!(!dragging(&bed), "the replacement ended the drag"); bed.fixture.frame(vec![release(window_title() + by * 1.25)]); @@ -166,10 +159,6 @@ fn a_replaced_workspace_ends_the_drag_that_the_areas_own_edits_keep() { struct Requesting; impl DockPanels for Requesting { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(title(*panel)) - } - fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { assert!(request_actions(ui.ctx(), vec![Action::activate(*panel)]).is_ok(), "the running pass takes the request"); } @@ -179,14 +168,14 @@ impl DockPanels for Requesting { /// and its bodies' requests unapplied beside them. #[trial] fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { - let workspace = Rc::new(RefCell::new(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED], 0)))))); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED], 0))))))); let requested: Rc>>> = Rc::default(); - let (held, seen) = (Rc::clone(&workspace), Rc::clone(&requested)); + let (held, seen, specs) = (Rc::clone(&workspace), Rc::clone(&requested), Tracked::new(Numbered)); let mut fixture = Fixture::new(move |ui| { let given = held.borrow().clone(); let mut panels = Requesting; - let out = DockArea::new("Given dock", Bind::given(given), &mut panels, DockConfig::default()).show(ui); - held.borrow_mut().apply_all(out.actions, false, |_| Permissions::ALL).expect("the area's actions apply"); + let out = DockArea::new("Given dock", Bind::given(given), &specs, &mut panels, DockConfig::default()).show(ui); + Arc::make_mut(&mut held.borrow_mut()).apply_all(out.actions, false, |_| Permissions::ALL).expect("the area's actions apply"); seen.borrow_mut().extend(out.requested); }); fixture.settle(); @@ -194,16 +183,16 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let asked = requested.borrow().clone(); let own = |action: &Action| *action == Action::activate(DOCKED) || *action == Action::activate(WINDOW); assert!(!asked.is_empty() && asked.iter().all(own), "each body's request came back: {asked:?}"); - assert_eq!(workspace.borrow().layout.floating[0].rect, WINDOW_AT, "nothing moved yet"); + assert_eq!(workspace.borrow().layout().floating[0].rect, WINDOW_AT, "nothing moved yet"); press_and_move(&mut fixture, window_title(), Vec2::new(-40.0, 30.0)); - let moved_to = workspace.borrow().layout.floating[0].rect; + let moved_to = workspace.borrow().layout().floating[0].rect; assert!(moved_to != WINDOW_AT, "the host's copy took the window's move: {moved_to:?}"); } /// A dock area's first pass leaves a drag running in another area alone. #[trial] fn an_areas_first_pass_keeps_a_running_drag() { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); press_and_move(&mut bed.fixture, window_title(), Vec2::new(-40.0, 30.0)); assert!(dragging(&bed), "the window drag runs"); bed.second.set(true); @@ -215,7 +204,7 @@ fn an_areas_first_pass_keeps_a_running_drag() { #[trial] fn a_floating_window_leaves_the_docked_tree_its_room() { let docked_bottom = |layout: Layout| { - let bed = bed(layout, |_| Permissions::ALL); + let bed = bed(layout); let panels = bed.fixture.by_role(Role::TAB_PANEL); let docked: Vec = panels.iter().filter(|panel| !WINDOW_AT.expand(SLACK).contains_rect(panel.rect)).map(|panel| panel.rect.bottom()).collect(); @@ -230,7 +219,7 @@ fn a_floating_window_leaves_the_docked_tree_its_room() { /// A floating window's drag bar shows no title: its tab is the one place the panel's name shows in the window. #[trial] fn a_floating_windows_drag_bar_shows_no_title() { - let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); let named = bed.fixture.texts().iter().filter(|text| text.text == title(WINDOW) && WINDOW_AT.contains_rect(text.rect)).count(); assert_eq!(named, 1, "only the tab names the panel: {:?}", bed.fixture.texts()); } @@ -239,7 +228,7 @@ fn a_floating_windows_drag_bar_shows_no_title() { /// one the window draws: the window's group starts right under it. #[trial] fn a_floating_windows_group_starts_under_the_title_row_the_area_sizes_windows_by() { - let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); let group = bed .fixture .by_role(Role::TAB_PANEL) @@ -261,14 +250,14 @@ fn a_floating_windows_group_starts_under_the_title_row_the_area_sizes_windows_by #[trial] fn a_floated_panel_fits_its_content_up_to_the_float_height() { let floated = |bed: &Bed, panel: usize| { - let layout = bed.workspace.borrow().layout.clone(); + let layout = bed.workspace.borrow().layout().clone(); let window = layout.floating.iter().find(|window| window.contains(&panel)).map(|window| window.rect); window.unwrap_or_else(|| panic!("panel {panel} floats: {:?}", bed.actions.borrow())) }; // Torn out of the window: the filling panel floats at the group's width and the cap, which a measure of its // content alone would not reach. - let mut torn = bed(Layout::new(Some(Node::tabs(vec![FILL, SHORT], 0)), Vec::new()), |_| Permissions::ALL); + let mut torn = bed(Layout::new(Some(Node::tabs(vec![FILL, SHORT], 0)), Vec::new())); let group = torn.fixture.by_role(Role::TAB_PANEL).first().expect("the docked group shows").rect; let tab = torn.fixture.by_role(Role::TAB).into_iter().min_by(|a, b| a.rect.min.x.total_cmp(&b.rect.min.x)).expect("FILL's tab shows").rect; let outside = Pos2::new(group.center().x, -40.0); @@ -285,7 +274,7 @@ fn a_floated_panel_fits_its_content_up_to_the_float_height() { // drag carries the measure the area added in the pass it started, and the short panel floats at its content's // height. let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![SHORT], 0), Node::tabs(vec![DOCKED], 0)); - let mut dragged = bed(Layout::new(Some(root), Vec::new()), |_| Permissions::ALL); + let mut dragged = bed(Layout::new(Some(root), Vec::new())); let tab = dragged.fixture.by_role(Role::TAB).into_iter().min_by(|a, b| a.rect.min.x.total_cmp(&b.rect.min.x)).expect("the tab shows").rect; let group = dragged.fixture.by_role(Role::TAB_PANEL).into_iter().find(|group| group.rect.contains(tab.center())).expect("its group shows").rect; assert!(cap < group.height() - SLACK, "the cap {cap} is below the docked group {group:?}"); @@ -308,7 +297,7 @@ fn a_floated_panel_fits_its_content_up_to_the_float_height() { /// the window in place of the groups, and expands it again; the window keeps its expanded rect throughout. #[trial] fn a_floating_windows_double_arrow_collapses_its_column_to_icons_and_expands_it() { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); let button = |bed: &Bed, name: &str| { let tree = bed.fixture.tree(); bed.fixture @@ -322,7 +311,7 @@ fn a_floating_windows_double_arrow_collapses_its_column_to_icons_and_expands_it( let collapse = button(&bed, "Collapse column to icons").expect("the title row shows the column's double arrow"); bed.fixture.click(&collapse); bed.fixture.settle(); - let window = bed.workspace.borrow().layout.floating[0].clone(); + let window = bed.workspace.borrow().layout().floating[0].clone(); assert!(window.column.iconic, "the window's column collapsed: {:?}", bed.actions.borrow()); assert_eq!(window.rect, WINDOW_AT, "the window keeps its expanded rect"); assert_eq!(in_window(&bed), 0, "the collapsed window shows no group"); @@ -331,14 +320,14 @@ fn a_floating_windows_double_arrow_collapses_its_column_to_icons_and_expands_it( let expand = button(&bed, "Expand column").expect("the collapsed window's title row shows the double arrow"); bed.fixture.click(&expand); bed.fixture.settle(); - let window = bed.workspace.borrow().layout.floating[0].clone(); + let window = bed.workspace.borrow().layout().floating[0].clone(); assert!(!window.column.iconic && window.rect == WINDOW_AT, "the column expanded at its rect: {window:?}"); assert_eq!(in_window(&bed), 1, "the expanded window shows its group again"); } /// The window of `with_window` at `rect` with its column collapsed to icons, and no docked tree under it. fn collapsed_at(rect: Rect) -> Layout { - let mut window = Floating::single(vec![WINDOW], 0, rect); + let mut window = Floating::single(101, vec![WINDOW], 0, rect); window.column.iconic = true; Layout::new(None, vec![window]) } @@ -361,7 +350,7 @@ fn a_collapsed_window_dragged_across_the_middle_keeps_its_strip_under_the_pointe // Across the middle; then to the strip's centre just past the middle of the 400-point room, on the end side, // while the expanded rect hanging from it reaches past the middle to the start side. for middle in [None, Some(210.0)] { - let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); + let mut bed = bed(collapsed_at(WINDOW_AT)); let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); let by = Vec2::new(middle.map_or(-250.0, |x: f32| x - icon.center().x), 0.0); // The title row's band, clear of the double arrow at the end the window keeps to. @@ -373,7 +362,7 @@ fn a_collapsed_window_dragged_across_the_middle_keeps_its_strip_under_the_pointe bed.fixture.idle(3); let dropped = button_rect(&bed, &title(WINDOW)).expect("the icon shows after the move"); assert!((dropped.left() - held.left()).abs() <= SLACK, "by {by:?}: the strip stays where it was dropped: {held:?}, then {dropped:?}"); - let window = bed.workspace.borrow().layout.floating[0].clone(); + let window = bed.workspace.borrow().layout().floating[0].clone(); assert!(window.column.iconic && window.edge.is_some(), "by {by:?}: the window stays collapsed and keeps its edge: {window:?}"); } } @@ -385,7 +374,7 @@ fn an_icon_floated_in_the_middle_band_lands_collapsed_under_the_pointer() { let mut column = Column::new(vec![Group::new(vec![WINDOW], 0)]); column.iconic = true; let root = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![DOCKED], 0), Node::dock(DockEdge::End, vec![column])); - let mut bed = bed(Layout::new(Some(root), Vec::new()), |_| Permissions::ALL); + let mut bed = bed(Layout::new(Some(root), Vec::new())); let icon = button_rect(&bed, &title(WINDOW)).expect("the docked collapsed column shows its icon"); // Just past the middle of the 400-point room: the strip is nearer the end edge, a window of the float width // around it the start edge. @@ -397,7 +386,7 @@ fn an_icon_floated_in_the_middle_band_lands_collapsed_under_the_pointer() { bed.fixture.frame(vec![release(at)]); bed.fixture.hold(Modifiers::NONE); bed.fixture.settle(); - let window = bed.workspace.borrow().layout.floating.first().cloned(); + let window = bed.workspace.borrow().layout().floating.first().cloned(); let window = window.unwrap_or_else(|| panic!("the icon floats: {:?}", bed.actions.borrow())); assert!(window.column.iconic && window.edge.is_some(), "it floats collapsed, keeping to the edge its strip was dropped near: {window:?}"); let floated = button_rect(&bed, &title(WINDOW)).expect("the floating window shows its icon"); @@ -412,7 +401,7 @@ fn an_icon_floated_in_the_middle_band_lands_collapsed_under_the_pointer() { fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { // In the end half of the area, then in the start half. for (rect, opens_right) in [(WINDOW_AT, false), (WINDOW_AT.translate(Vec2::new(-110.0, 0.0)), true)] { - let mut bed = bed(collapsed_at(rect), |_| Permissions::ALL); + let mut bed = bed(collapsed_at(rect)); let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); bed.fixture.click_at(icon.center()).settle(); let flyout = bed.fixture.by_role(Role::TAB_PANEL).first().map(|group| group.rect).expect("the flyout shows the panel's group"); @@ -425,16 +414,16 @@ fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { /// double click on the collapsed window's band expands it again; the groups keep their state. #[trial] fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column() { - let mut bed = bed(with_window(None), |_| Permissions::ALL); + let mut bed = bed(with_window(None)); let band = Pos2::new(WINDOW_AT.left() + 40.0, WINDOW_AT.top() + 6.0); bed.fixture.click_at(band).click_at(band).settle(); - let window = bed.workspace.borrow().layout.floating[0].clone(); + let window = bed.workspace.borrow().layout().floating[0].clone(); assert!(window.column.iconic, "the band's double click collapsed the column: {:?}", bed.actions.borrow()); assert!(window.groups().iter().all(|group| !group.minimized), "no group minimized"); let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); let band = Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0); bed.fixture.click_at(band).click_at(band).settle(); - assert!(!bed.workspace.borrow().layout.floating[0].column.iconic, "a second double click expanded it: {:?}", bed.actions.borrow()); + assert!(!bed.workspace.borrow().layout().floating[0].column.iconic, "a second double click expanded it: {:?}", bed.actions.borrow()); } /// A floating window's title row is its column's bar, with the double arrow and Close and no menu button: a context @@ -442,7 +431,7 @@ fn a_double_click_on_a_floating_windows_band_collapses_and_expands_its_column() #[trial] fn a_context_request_on_a_windows_band_opens_its_menu_and_close_closes_it() { for collapsed in [true, false] { - let mut bed = if collapsed { bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL) } else { bed(with_window(None), |_| Permissions::ALL) }; + let mut bed = if collapsed { bed(collapsed_at(WINDOW_AT)) } else { bed(with_window(None)) }; let band = if collapsed { let icon = button_rect(&bed, &title(WINDOW)).expect("the collapsed window shows its icon"); Pos2::new(icon.left() + 4.0, WINDOW_AT.top() + 6.0) @@ -461,7 +450,7 @@ fn a_context_request_on_a_windows_band_opens_its_menu_and_close_closes_it() { let close = close.unwrap_or_else(|| panic!("collapsed {collapsed}: the band's context request opens the window's menu: {names:?}")); bed.fixture.click(&close); bed.fixture.settle(); - assert!(bed.workspace.borrow().layout.floating.is_empty(), "collapsed {collapsed}: Close closed the window: {:?}", bed.actions.borrow()); + assert!(bed.workspace.borrow().layout().floating.is_empty(), "collapsed {collapsed}: Close closed the window: {:?}", bed.actions.borrow()); } } @@ -475,7 +464,7 @@ fn a_drag_over_a_floating_window_joins_or_stacks_and_never_splits() { docked.sort_by(|a, b| a.min.x.total_cmp(&b.min.x)); docked.last().copied().expect("the second docked tab shows") }; - let mut expanded = bed(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))), |_| Permissions::ALL); + let mut expanded = bed(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0)))); let tab = docked_tab(&expanded); let side = Pos2::new(WINDOW_AT.left() + 6.0, WINDOW_AT.center().y + 20.0); press_and_move(&mut expanded.fixture, tab.center(), side - tab.center()); @@ -484,15 +473,15 @@ fn a_drag_over_a_floating_window_joins_or_stacks_and_never_splits() { assert!(matches!(mark, DropMark::Region { .. }), "the start side of a floating group joins it: {mark:?}"); expanded.fixture.frame(vec![release(side)]).settle(); - let mut window = Floating::single(vec![WINDOW], 0, WINDOW_AT); + let mut window = Floating::single(102, vec![WINDOW], 0, WINDOW_AT); window.column.iconic = true; - let mut collapsed = bed(Layout::new(Some(Node::tabs(vec![DOCKED, SECOND], 0)), vec![window]), |_| Permissions::ALL); + let mut collapsed = bed(Layout::new(Some(Node::tabs(vec![DOCKED, SECOND], 0)), vec![window])); let tab = docked_tab(&collapsed); let icon = button_rect(&collapsed, &title(WINDOW)).expect("the collapsed window shows its icon"); press_and_move(&mut collapsed.fixture, tab.center(), icon.center() - tab.center()); collapsed.fixture.frame(Vec::new()); collapsed.fixture.frame(vec![release(icon.center())]).settle(); - let window = collapsed.workspace.borrow().layout.floating[0].clone(); + let window = collapsed.workspace.borrow().layout().floating[0].clone(); assert!(window.groups().len() == 1 && window.contains(&SECOND), "the tab joined the icon's group: {:?}", collapsed.actions.borrow()); assert!(window.column.iconic, "the window stays collapsed"); } @@ -501,7 +490,7 @@ fn a_drag_over_a_floating_window_joins_or_stacks_and_never_splits() { #[trial] fn a_settled_collapsed_window_runs_no_more_passes_than_an_expanded_one() { let passes = |layout: Layout| { - let mut bed = bed(layout, |_| Permissions::ALL); + let mut bed = bed(layout); bed.fixture.idle(3); bed.fixture.passes() }; diff --git a/crates/ui-patterns/tests/it/docking/group_view.rs b/crates/ui-patterns/tests/it/docking/group_view.rs index a92f50c55..62d980cc5 100644 --- a/crates/ui-patterns/tests/it/docking/group_view.rs +++ b/crates/ui-patterns/tests/it/docking/group_view.rs @@ -2,25 +2,32 @@ use craft_behavior::Axis; use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx}; -use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Ui, Vec2}; use std::cell::Cell; use std::rc::Rc; +use std::sync::Arc; /// Panel 0 is a canvas the host draws in its group's place; it records the group's rect and the `Ui` it was given. struct Panels { seen: Rc>>, } -impl DockPanels for Panels { +/// Panel 0 is a canvas. +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { fn spec(&self, panel: &usize) -> PanelSpec { let spec = PanelSpec::new(format!("Panel {panel}")); if *panel == 0 { spec.canvas() } else { spec } } +} +impl DockPanels for Panels { fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} fn group_view(&mut self, panels: &[usize], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { @@ -41,10 +48,10 @@ impl DockPanels for Panels { fn a_group_view_lays_out_and_clips_to_its_group_rect() { let seen = Rc::new(Cell::new(None)); let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0)); - let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); - let mut panels = Panels { seen: seen.clone() }; + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (Panels { seen: seen.clone() }, Tracked::new(Specs)); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(1200.0, 600.0)).settle(); let (rect, room, clip) = seen.get().expect("the canvas group was shown"); diff --git a/crates/ui-patterns/tests/it/docking/hidden.rs b/crates/ui-patterns/tests/it/docking/hidden.rs index dcc2cfc09..64cfec75e 100644 --- a/crates/ui-patterns/tests/it/docking/hidden.rs +++ b/crates/ui-patterns/tests/it/docking/hidden.rs @@ -2,8 +2,8 @@ use craft_behavior::Axis; use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx}; -use craft_ui::docking::{DockConfig, DockPanels, HidePanels, PanelSpec}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, HidePanels, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::env::{BodyMode, ShellCx, ShellEntry, WindowKey}; use craft_ui::testing::{Fixture, trial}; @@ -11,6 +11,7 @@ use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::RefCell; use std::collections::BTreeSet; use std::rc::Rc; +use std::sync::Arc; const CANVAS: usize = 1; /// Docked, and named by the host's `HidePanels::Except`. @@ -25,7 +26,11 @@ struct Panels { shown: Rc>>, } -impl DockPanels for Panels { +/// Panels named by number; the canvas is protected. +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { fn spec(&self, panel: &usize) -> PanelSpec { PanelSpec::new(format!("Panel {panel}")) } @@ -33,7 +38,9 @@ impl DockPanels for Panels { fn permissions(&self, panel: &usize) -> Permissions { if *panel == CANVAS { Permissions::PROTECTED } else { Permissions::ALL } } +} +impl DockPanels for Panels { fn body(&mut self, panel: &usize, _: &mut Ui, _: &mut BodyCx<'_>) { self.shown.borrow_mut().insert(*panel); } @@ -44,7 +51,8 @@ fn layout() -> Layout { let start = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![TOOLBAR], 0)])]); let end = Node::dock(DockEdge::End, vec![Column::new(vec![Group::new(vec![LAYERS], 0)])]); let root = Node::split(Axis::X, SplitSize::Ratio(0.2), start, Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![CANVAS], 0), end)); - let window = |panel: usize, x: f32| Floating::single(vec![panel], 0, Rect::from_min_size(Pos2::new(x, 60.0), Vec2::new(120.0, 120.0))); + let window = + |panel: usize, x: f32| Floating::single(panel as u64, vec![panel], 0, Rect::from_min_size(Pos2::new(x, 60.0), Vec2::new(120.0, 120.0))); Layout::new(Some(root), vec![window(PALETTE, 90.0), window(NAVIGATOR, 220.0)]) } @@ -54,10 +62,11 @@ fn shown_under(shell: ShellCx, keeps: bool) -> BTreeSet { let seen = Rc::clone(&shown); let mut fixture = Fixture::new(move |ui| { seen.borrow_mut().clear(); - let mut workspace = Workspace::new(layout()); + let mut workspace = Arc::new(Workspace::new(layout())); let mut panels = Panels { shown: Rc::clone(&seen) }; + let specs = Tracked::new(Specs); let keep = |panel: &usize| *panel == TOOLBAR || *panel == PALETTE; - let mut area = DockArea::new("Hidden dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()); + let mut area = DockArea::new("Hidden dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()); if keeps { area = area.hide(HidePanels::Except(&keep)); } diff --git a/crates/ui-patterns/tests/it/docking/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index cbdcbb917..3808733d0 100644 --- a/crates/ui-patterns/tests/it/docking/mod.rs +++ b/crates/ui-patterns/tests/it/docking/mod.rs @@ -37,3 +37,13 @@ fn sizes(gap: f32, least_pane: f32, strip: f32) -> DockSizes { sizes }) } + +/// Panel specs that name each panel by its number ("Panel 3"), with every permission. +#[derive(craft_ui::contract::PlainData)] +struct Numbered; + +impl craft_ui::docking::PanelSpecs

for Numbered { + fn spec(&self, panel: &P) -> craft_ui::docking::PanelSpec { + craft_ui::docking::PanelSpec::new(format!("Panel {panel}")) + } +} diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 5e25fb2f1..ea59f8728 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -4,9 +4,9 @@ use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; -use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _, SizeLimits}; +use craft_ui::contract::{Bind, BodyCx, DropMark, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked}; use craft_ui::display::Text; -use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec}; +use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; @@ -24,18 +24,41 @@ const ROOT_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(300.0, const PALETTE_AT: Rect = Rect { min: Pos2::new(200.0, 150.0), max: Pos2::new(600.0, 450.0) }; const PALETTE_TITLE: &str = "Tools"; -/// Palette panels with the given rights. -struct Palettes(Permissions); +/// The palettes' specs: palettes named `PALETTE_TITLE` with `rights`. `least` keeps them no smaller than +/// `PALETTE_LEAST`; `stepped` lays panel 1's content in a grid, as a toolbar's that never collapses, beside a canvas. +#[derive(Clone, Copy, PlainData)] +struct Specs { + rights: Permissions, + least: bool, + stepped: bool, +} -impl DockPanels for Palettes { - fn spec(&self, _: &u32) -> PanelSpec { - PanelSpec::new(PALETTE_TITLE) +impl Specs { + /// Palettes with `rights`. + fn with(rights: Permissions) -> Tracked { + Tracked::new(Specs { rights, least: false, stepped: false }) + } +} + +impl PanelSpecs for Specs { + fn spec(&self, panel: &u32) -> PanelSpec { + match (self.stepped, *panel) { + (true, 1) => PanelSpec::new(PALETTE_TITLE).grid(tools_grid()), + (true, _) => PanelSpec::new("Canvas"), + _ if self.least => PanelSpec::new(PALETTE_TITLE).limits(SizeLimits::at_least(PALETTE_LEAST)), + _ => PanelSpec::new(PALETTE_TITLE), + } } fn permissions(&self, _: &u32) -> Permissions { - self.0 + if self.stepped { Permissions::ALL.collapses(false) } else { self.rights } } +} +/// Palette panels with empty bodies. +struct Palettes; + +impl DockPanels for Palettes { fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} } @@ -44,14 +67,6 @@ impl DockPanels for Palettes { struct MoveProbe(Vec); impl DockPanels for MoveProbe { - fn spec(&self, _: &u32) -> PanelSpec { - PanelSpec::new(PALETTE_TITLE) - } - - fn permissions(&self, _: &u32) -> Permissions { - Permissions::ALL - } - fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { let ctx = ui.ctx(); self.0.push(craft_ui::testing::windows::moved_by_app(ctx, ctx.viewport_id())); @@ -69,11 +84,11 @@ fn a_native_dock_window_is_moved_by_the_app_from_its_first_pass() { let mut saved = Placement::new(PALETTE_AT.size().into(), 1.0); saved.position_px = Some([PALETTE_AT.min.x as i32, PALETTE_AT.min.y as i32]); window.native = Some(saved); - let mut workspace = Workspace::new(Layout::new(None, vec![window])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![window]))); let mut probe = MoveProbe(Vec::new()); windows.frame(vec![], vec![], |ui| { let config = DockConfig::default().native_windows(true); - let _ = DockArea::new("Native dock", Bind::bound(&mut workspace), &mut probe, config).show(ui); + let _ = DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut probe, config).show(ui); }); assert!(!probe.0.is_empty(), "the window's first frame runs the panel's body"); assert!(probe.0.iter().all(|known| *known), "every pass of the window knows the app moves it: {:?}", probe.0); @@ -84,16 +99,16 @@ fn a_native_dock_window_is_moved_by_the_app_from_its_first_pass() { fn the_dock_records_where_the_os_put_its_native_window() { let windows = Windows::new(); windows.root_info(info(true, ROOT_AT)); - let mut window = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))); + let mut window = Floating::single(100, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))); let mut saved = Placement::new(PALETTE_AT.size().into(), 1.0); saved.position_px = Some([200, 150]); window.native = Some(saved); - let mut workspace = Workspace::new(Layout::new(None, vec![window])); - let run = |workspace: &mut Workspace| { + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![window]))); + let run = |workspace: &mut Arc>| { let mut actions = Vec::new(); windows.frame(vec![], vec![], |ui| { let config = DockConfig::default().native_windows(true); - let shown = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), config).show(ui); + let shown = DockArea::new("Native dock", Bind::bound(workspace), &Specs::with(Permissions::ALL), &mut Palettes, config).show(ui); actions.extend(shown.actions); }); actions @@ -119,12 +134,13 @@ fn a_float_opens_an_os_window_where_the_host_reports_window_positions() { let opened = |windows: Windows| { windows.root_info(info(true, ROOT_AT)); windows.child_info(info(true, PALETTE_AT)); - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let (mut child, mut recorded) = (false, false); for _ in 0..3 { let out = windows.frame(vec![], vec![], |ui| { let shown = - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Palettes, DockConfig::default()) + .show(ui); recorded |= shown.actions.iter().any(|action| matches!(action, Action::SetNative { .. })); }); child |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT); @@ -144,9 +160,9 @@ fn a_native_dock_window_shows_no_os_title_bar() { let windows = Windows::with(InstallSpec::new(ShellInfo::default().os(os).caps(Caps::native(os)), Arc::new(FakeSystem::new()))); windows.root_info(info(true, ROOT_AT)); windows.child_info(info(true, PALETTE_AT)); - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let out = windows.frame(vec![], vec![], |ui| { - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Palettes, DockConfig::default()).show(ui); }); out.builders.into_iter().find(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, builder)| builder).expect("an OS window opens") }; @@ -162,11 +178,11 @@ fn a_native_dock_window_shows_no_os_title_bar() { fn a_native_float_opens_at_its_own_size() { let windows = Windows::new(); windows.root_info(info(true, ROOT_AT)); - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let mut sizes = Vec::new(); for _ in 0..3 { let out = windows.frame(vec![], vec![], |ui| { - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Palettes, DockConfig::default()).show(ui); }); sizes.extend(out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, builder)| builder.inner_size)); } @@ -182,11 +198,13 @@ fn the_os_close_of_a_native_float_closes_it_when_its_panels_may_close() { let windows = Windows::new(); windows.root_info(info(true, ROOT_AT)); windows.child_info(info(true, PALETTE_AT)); - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); - let run = |workspace: &mut Workspace| { + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); + let run = |workspace: &mut Arc>| { let mut actions = Vec::new(); windows.frame(vec![], vec![], |ui| { - actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(rights), DockConfig::default()).show(ui).actions); + actions.extend( + DockArea::new("Native dock", Bind::bound(workspace), &Specs::with(rights), &mut Palettes, DockConfig::default()).show(ui).actions, + ); }); actions.iter().any(|action| matches!(action, Action::CloseWindow { .. })) }; @@ -222,14 +240,6 @@ fn tools_grid() -> DockGrid { struct SteppedPalette; impl DockPanels for SteppedPalette { - fn spec(&self, panel: &u32) -> PanelSpec { - if *panel == 1 { PanelSpec::new(PALETTE_TITLE).grid(tools_grid()) } else { PanelSpec::new("Canvas") } - } - - fn permissions(&self, _: &u32) -> Permissions { - Permissions::ALL.collapses(false) - } - fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { if *panel == 1 { Text::new("One").show(ui); @@ -241,8 +251,9 @@ impl DockPanels for SteppedPalette { /// A dock of one docked group and one native palette. struct NativeDock { windows: Windows, - workspace: Workspace, + workspace: Arc>, stepped: bool, + specs: Tracked, /// The palette window's builder as the integration keeps it: each frame's builder patched onto it, which sends the /// window only the limits a builder carries. builder: Option, @@ -250,14 +261,14 @@ struct NativeDock { impl NativeDock { fn on(os: Os, system: Arc) -> Self { - let palette = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + let palette = Floating::single(101, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); Self::with(os, system, palette, false) } /// The dock with a stepped palette of one step ([`SteppedPalette`]). fn stepped(os: Os, system: Arc) -> Self { let column = Column::new(vec![Group::new(vec![1], 0)]).with_steps(1); - Self::with(os, system, Floating::new(column, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())), true) + Self::with(os, system, Floating::new(102, column, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())), true) } fn with(os: Os, system: Arc, palette: Floating, stepped: bool) -> Self { @@ -265,8 +276,9 @@ impl NativeDock { let windows = Windows::with(InstallSpec::new(shell, system)); windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); - let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])); - let mut dock = NativeDock { windows, workspace, stepped, builder: None }; + let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette]))); + let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped }); + let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -282,10 +294,11 @@ impl NativeDock { fn frame_with(&mut self, root: Vec, child: Vec) -> (Vec>, Vec) { let mut actions = Vec::new(); let workspace = &mut self.workspace; - let (mut palettes, mut stepped) = (Palettes(Permissions::ALL), SteppedPalette); + let (mut palettes, mut stepped) = (Palettes, SteppedPalette); let panels: &mut dyn DockPanels = if self.stepped { &mut stepped } else { &mut palettes }; + let specs = &self.specs; let out = self.windows.frame(root, child, |ui| { - actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui).actions); + actions.extend(DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui).actions); }); for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) { match self.builder.as_mut() { @@ -479,7 +492,7 @@ fn a_palette_drag_resolves_the_main_windows_drops_at_the_system_pointer_not_wher /// The steps of the stepped palette's column. fn palette_steps(dock: &NativeDock) -> Option { - dock.workspace.layout.floating[0].column.steps + dock.workspace.layout().floating[0].column.steps } /// One frame of `dock` with `child` events, after which the palette's window is where the app sent it, as the OS @@ -515,12 +528,12 @@ fn a_native_stepped_palette_resizes_in_whole_steps_that_the_app_runs() { // The right grip straddles the window's right edge. let grip = Pos2::new(at.width() - 1.0, at.height() / 2.0); - for events in [vec![moved(grip)], vec![press(grip)], vec![moved(grip + Vec2::new(1.6 * grid.step, 0.0))], vec![]] { + for events in [vec![moved(grip)], vec![press(grip)], vec![moved(grip + Vec2::new(1.6 * (grid.width(2) - grid.width(1)), 0.0))], vec![]] { sent.extend(placed_frame(&mut dock, events, &mut at)); } assert_eq!(palette_steps(&dock), Some(2), "{os:?}: a drag of 1.6 steps sets the whole step it reached"); assert_eq!(at.width(), grid.width(2), "{os:?}: the window takes the width of its steps while the drag runs"); - let end = grip + Vec2::new(1.6 * grid.step, 0.0); + let end = grip + Vec2::new(1.6 * (grid.width(2) - grid.width(1)), 0.0); for events in [vec![release(end)], vec![], vec![]] { sent.extend(placed_frame(&mut dock, events, &mut at)); } @@ -528,7 +541,7 @@ fn a_native_stepped_palette_resizes_in_whole_steps_that_the_app_runs() { let right = at.right(); let grip = Pos2::new(1.0, at.height() / 2.0); - let end = grip - Vec2::new(1.6 * grid.step, 0.0); + let end = grip - Vec2::new(1.6 * (grid.width(2) - grid.width(1)), 0.0); for events in [vec![moved(grip)], vec![press(grip)], vec![moved(end)], vec![], vec![release(end)], vec![], vec![]] { sent.extend(placed_frame(&mut dock, events, &mut at)); } @@ -566,7 +579,7 @@ fn a_native_float_the_os_resizes_or_moves_gets_no_place_back() { sent.extend(dock.frame(vec![]).1); } assert!(placing(&sent).is_empty(), "the OS's places come back: {:?}", placing(&sent)); - let recorded = dock.workspace.layout.floating[0].native.clone().expect("the model records the window"); + let recorded = dock.workspace.layout().floating[0].native.clone().expect("the model records the window"); assert_eq!(Vec2::from(recorded.normal.size), at.size(), "the model holds the OS's last size"); } @@ -577,7 +590,7 @@ fn an_app_change_of_a_native_floats_place_moves_its_window_once() { let to = Rect::from_min_size(Pos2::new(1100.0, 200.0), Vec2::new(320.0, 260.0)); let mut placement = Placement::new(to.size().into(), 1.0); placement.position_px = Some([to.min.x as i32, to.min.y as i32]); - dock.workspace.apply(Action::set_native(1, Some(placement)), false, |_| Permissions::ALL).expect("the model takes the place"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_native(1, Some(placement)), false, |_| Permissions::ALL).expect("the model takes the place"); let mut sent = Vec::new(); for _ in 0..3 { sent.extend(dock.frame(vec![]).1); @@ -627,11 +640,11 @@ fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { sent }; let mut at = FLOAT_AT; - dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); follow(&mut dock, &mut at, 3); let strip = at; assert!(strip.width() < expanded.x, "the OS window shows the strip: {strip:?}"); - let recorded = |dock: &NativeDock| dock.workspace.layout.floating[0].native.clone().expect("the model records the window"); + let recorded = |dock: &NativeDock| dock.workspace.layout().floating[0].native.clone().expect("the model records the window"); assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "collapsed, the model keeps the expanded size"); // The OS moves the strip over the start half of the main window. @@ -641,10 +654,10 @@ fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { let sent = follow(&mut dock, &mut at, 4); assert!(placing(&sent).is_empty(), "the strip stays where it was dropped: {:?}", placing(&sent)); assert_eq!(at, dropped); - assert_eq!(dock.workspace.layout.floating[0].edge, Some(DockEdge::Start), "it keeps to the edge nearer the strip"); + assert_eq!(dock.workspace.layout().floating[0].edge, Some(DockEdge::Start), "it keeps to the edge nearer the strip"); assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "moved, the model keeps the expanded size"); - dock.workspace.apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands"); let sent = follow(&mut dock, &mut at, 3); assert!(sent.contains(&ViewportCommand::InnerSize(expanded)), "the window takes its expanded size back: {:?}", placing(&sent)); assert_eq!(at.min, dropped.min, "it opens from the strip's place, against the start edge"); @@ -669,11 +682,11 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { actions }; frame(&mut dock, &mut at, vec![]); - dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); for _ in 0..3 { frame(&mut dock, &mut at, vec![]); } - assert!(dock.workspace.layout.floating[0].column.iconic, "the column is collapsed"); + assert!(dock.workspace.layout().floating[0].column.iconic, "the column is collapsed"); assert!(at.width() < FLOAT_AT.width(), "the OS window shows the strip: {at:?}"); // The double arrow is the title row's square at the end the strip keeps to: a point just inside its outer corner. @@ -683,7 +696,7 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { for events in [vec![moved(arrow)], vec![press(arrow)], vec![release(arrow)], vec![], vec![]] { actions.extend(frame(&mut dock, &mut at, events)); } - assert!(!dock.workspace.layout.floating[0].column.iconic, "the click expands the column: {actions:?}"); + assert!(!dock.workspace.layout().floating[0].column.iconic, "the click expands the column: {actions:?}"); assert_eq!(at.size(), FLOAT_AT.size(), "the OS window takes its expanded size"); } @@ -693,10 +706,6 @@ struct Least; const PALETTE_LEAST: Vec2 = Vec2::new(240.0, 160.0); impl DockPanels for Least { - fn spec(&self, _: &u32) -> PanelSpec { - PanelSpec::new(PALETTE_TITLE).limits(SizeLimits::at_least(PALETTE_LEAST)) - } - fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} } @@ -707,14 +716,21 @@ fn a_native_palette_is_never_sized_below_its_limits() { let windows = Windows::new(); windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); - let mut window = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + let mut window = Floating::single(103, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); let mut saved = Placement::new(FLOAT_AT.size().into(), 1.0); saved.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]); window.native = Some(saved); - let mut workspace = Workspace::new(Layout::new(None, vec![window])); - let run = |workspace: &mut Workspace| { + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![window]))); + let run = |workspace: &mut Arc>| { let out = windows.frame(vec![], vec![], |ui| { - let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Least, DockConfig::default().native_windows(true)).show(ui); + let _ = DockArea::new( + "Native dock", + Bind::bound(workspace), + &Tracked::new(Specs { rights: Permissions::ALL, least: true, stepped: false }), + &mut Least, + DockConfig::default().native_windows(true), + ) + .show(ui); }); out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect::>() }; @@ -723,7 +739,7 @@ fn a_native_palette_is_never_sized_below_its_limits() { } let mut small = Placement::new([80.0, 60.0], 1.0); small.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]); - workspace.apply(Action::set_native(1, Some(small)), false, |_| Permissions::ALL).expect("the model takes the place"); + Arc::make_mut(&mut workspace).apply(Action::set_native(1, Some(small)), false, |_| Permissions::ALL).expect("the model takes the place"); let mut sent = Vec::new(); for _ in 0..3 { sent.extend(run(&mut workspace)); @@ -742,11 +758,12 @@ fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_scree windows.root_info(ViewportInfo { fullscreen: Some(true), ..info(true, MAIN_AT) }); windows.child_info(info(true, FLOAT_AT)); let start = float().rect; - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let mut child = false; - let mut run = |workspace: &mut Workspace, events: Vec| { + let mut run = |workspace: &mut Arc>, events: Vec| { let out = windows.frame(events, vec![], |ui| { - let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + let _ = + DockArea::new("Native dock", Bind::bound(workspace), &Specs::with(Permissions::ALL), &mut Palettes, DockConfig::default()).show(ui); }); child |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT); }; @@ -765,7 +782,7 @@ fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_scree run(&mut workspace, vec![]); } assert!(!child, "no OS window opens over the full-screen window"); - let moved_to = workspace.layout.floating[0].rect.min; + let moved_to = workspace.layout().floating[0].rect.min; assert!( (moved_to - (start.min + by)).length() <= by.length() / 2.0, "the drag moved the float with the pointer: {moved_to:?} from {:?}", @@ -777,10 +794,6 @@ fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_scree struct Veiled; impl DockPanels for Veiled { - fn spec(&self, _: &u32) -> PanelSpec { - PanelSpec::new(PALETTE_TITLE) - } - fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { let _ = DropVeil::new("Drop").show(ui, |_, _| {}); } @@ -794,15 +807,15 @@ fn a_file_dropped_on_a_native_float_reaches_window_files_once() { let windows = Windows::new(); windows.root_info(info(true, ROOT_AT)); windows.child_info(info(true, PALETTE_AT)); - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let mut frame = |hovered: Vec, dropped: Vec| { let mut files = 0; windows.frame_with_files(vec![], vec![], hovered, dropped, |ui| { let config = DockConfig::default(); let shown = if veiled { - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Veiled, config).show(ui) + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Veiled, config).show(ui) } else { - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), config).show(ui) + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Palettes, config).show(ui) }; files += shown.window_files.len(); }); @@ -824,7 +837,7 @@ fn a_file_dropped_on_a_native_float_reaches_window_files_once() { /// A palette float made in the app window. fn float() -> Floating { - Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))) + Floating::single(104, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))) } fn info(focused: bool, rect: Rect) -> ViewportInfo { diff --git a/crates/ui-patterns/tests/it/docking/panel_menu.rs b/crates/ui-patterns/tests/it/docking/panel_menu.rs index db3227c09..0a0ad89e7 100644 --- a/crates/ui-patterns/tests/it/docking/panel_menu.rs +++ b/crates/ui-patterns/tests/it/docking/panel_menu.rs @@ -4,22 +4,29 @@ use craft_behavior::Axis; use craft_behavior::PartKey; use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx, Role, ShowContainer as _}; -use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, WindowMenuRows}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Role, ShowContainer as _, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs, WindowMenuRows}; use craft_ui::menu::{Menu, PanelRow}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; + +/// Panels named by number. +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } +} struct Panels; impl DockPanels for Panels { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} /// A host row, so each group shows its panel menu button. @@ -32,11 +39,11 @@ impl DockPanels for Panels { #[trial] fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0, 1], 0), Node::tabs(vec![2, 3], 0)); - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); - let held = Rc::clone(&workspace); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Specs)); let mut fixture = Fixture::new(move |ui| { let mut shown = held.borrow().clone(); - DockArea::new("Dock", Bind::bound(&mut shown), &mut Panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut shown), &specs, &mut Panels, DockConfig::default()).show(ui); *held.borrow_mut() = shown; }); fixture.room(Vec2::new(1200.0, 600.0)).settle(); @@ -48,7 +55,8 @@ fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { fixture.click(&buttons[1]).idle(2); let float = fixture.by_label("Float").expect("the menu's Float row"); fixture.click(&float).idle(2); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); let floated: Vec = layout.floating.iter().flat_map(|window| window.panels().copied().collect::>()).collect(); assert_eq!(floated, vec![2], "Float reaches the group whose menu ran it"); } @@ -57,9 +65,10 @@ fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { /// then the panel menu button. #[trial] fn tab_reaches_the_tabs_then_the_drag_band_then_the_panel_menu_button() { - let mut workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new())); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new()))); + let specs = Tracked::new(Specs); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut Panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(800.0, 600.0)).settle(); let tab = fixture.by_label("Panel 0").expect("the group's tab"); @@ -87,7 +96,7 @@ fn the_window_menu_opens_and_closes_the_flyout_of_a_panel_in_a_collapsed_column( let shown = *open.borrow(); let mut menu_open = true; Menu::new("Window").open(Bind::bound(&mut menu_open)).show(ui, |ui, _| { - let out = WindowMenuRows::new(&layout, &Panels, &[1, 2]).flyout(shown.as_ref()).show(ui); + let out = WindowMenuRows::new(&layout, &Tracked::new(Specs), &[1, 2]).flyout(shown.as_ref()).show(ui); if let Some(next) = out.flyout { *open.borrow_mut() = next; } diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 60f7a82f0..51ae39283 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -6,25 +6,33 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, SplitSize, Workspace}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, BodyCx, MemoProps, MemoView, Role, Show as _}; -use craft_ui::docking::{DockConfig, DockPanels, PanelDrag, PanelSpec}; +use craft_ui::contract::{Bind, BodyCx, MemoProps, MemoView, PlainData, Role, Show as _, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelDrag, PanelSpec, PanelSpecs}; use craft_ui::menu::PanelRow; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; use craft_ui::testing::in_audit_run; use craft_ui::testing::pointer::{moved, press}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_runs, last_pass_runs, trial}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; + +/// Panels named by their number, which count the specs the dock reads. +#[derive(PlainData)] +struct Named; + +impl PanelSpecs for Named { + fn spec(&self, panel: &usize) -> PanelSpec { + SPEC_READS.with(|reads| reads.set(reads.get() + 1)); + PanelSpec::new(format!("Panel {panel}")) + } +} struct Panels; impl DockPanels for Panels { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} /// A host row, so each group shows its panel menu button and its menu. @@ -37,9 +45,10 @@ impl DockPanels for Panels { fn settled_runs(groups: usize, tabs: usize) -> Vec<(&'static str, u32)> { let group = |at: usize| Node::tabs((tabs * at..tabs * (at + 1)).collect(), 0); let root = (1..groups).fold(group(0), |left, at| Node::split(Axis::X, SplitSize::Ratio(0.5), left, group(at))); - let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let specs = Tracked::new(Named); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut Panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); last_pass_runs(fixture.ctx()) @@ -82,6 +91,13 @@ fn a_settled_dock_group_runs_the_same_whatever_its_tab_count() { thread_local! { /// The panels whose memoized bodies ran on this trial's thread, in order. static BODY_RUNS: RefCell> = const { RefCell::new(Vec::new()) }; + /// The panel specs the docks read on this trial's thread. + static SPEC_READS: Cell = const { Cell::new(0) }; +} + +/// Takes the count of specs the docks read since the last call. +fn spec_reads() -> u32 { + SPEC_READS.with(|reads| reads.replace(0)) } /// Takes the panels whose bodies ran since the last call. @@ -103,19 +119,25 @@ fn panel_body(props: &mut BodyProps, ui: &mut Ui) { Button::new(format!("Body {}", props.panel)).show(ui); } -/// Panels whose bodies are memoized views, named by `labels`; `plain` is a panel whose body is not, which counts its -/// runs in `plain_runs`. +/// The panels' names, by panel; the specs count their reads. +#[derive(PlainData)] +struct Labels(Vec); + +impl PanelSpecs for Labels { + fn spec(&self, panel: &usize) -> PanelSpec { + SPEC_READS.with(|reads| reads.set(reads.get() + 1)); + PanelSpec::new(self.0[*panel].clone()) + } +} + +/// Panels whose bodies are memoized views; `plain` is a panel whose body is not, which counts its runs in +/// `plain_runs`. struct Memo { - labels: Rc>>, plain: Option, plain_runs: Rc>, } impl DockPanels for Memo { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(self.labels.borrow()[*panel].clone()) - } - fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { if self.plain == Some(*panel) { self.plain_runs.set(self.plain_runs.get() + 1); @@ -133,27 +155,29 @@ impl DockPanels for Memo { /// A settled dock whose panels are [`Memo`]. struct MemoDock { fixture: Fixture, - labels: Rc>>, + labels: Rc>>, plain_runs: Rc>, - workspace: Rc>>, + workspace: Rc>>>, /// The panel each pass of the dock reported picked. picked: Rc>>, } /// A settled dock over `layout` whose panels are [`Memo`], with `plain` a body that is not memoized. fn memo_dock(layout: Layout, plain: Option) -> MemoDock { - let labels = Rc::new(RefCell::new((0..32).map(|panel| format!("Panel {panel}")).collect::>())); + let labels = Rc::new(RefCell::new(Tracked::new(Labels((0..32).map(|panel| format!("Panel {panel}")).collect())))); let plain_runs = Rc::new(Cell::new(0)); - let workspace = Rc::new(RefCell::new(Workspace::new(layout))); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout)))); let picked = Rc::new(RefCell::new(Vec::new())); - let mut panels = Memo { labels: Rc::clone(&labels), plain, plain_runs: Rc::clone(&plain_runs) }; - let (shown, seen) = (Rc::clone(&workspace), Rc::clone(&picked)); + let mut panels = Memo { plain, plain_runs: Rc::clone(&plain_runs) }; + let (shown, seen, named) = (Rc::clone(&workspace), Rc::clone(&picked), Rc::clone(&labels)); let mut fixture = Fixture::new(move |ui| { - let output = DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &mut panels, DockConfig::default()).show(ui); + let specs = named.borrow(); + let output = DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &*specs, &mut panels, DockConfig::default()).show(ui); seen.borrow_mut().extend(output.picked); }); fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); body_runs(); + spec_reads(); picked.borrow_mut().clear(); MemoDock { fixture, labels, plain_runs, workspace, picked } } @@ -176,7 +200,7 @@ fn full(groups: usize) -> Layout { let columns = vec![Column::new(vec![Group::new(vec![20], 0)]).with_width(240.0), iconic]; let root = side_by_side(groups).root.expect("the groups"); let root = Node::split(Axis::X, SplitSize::Ratio(0.7), root, Node::dock(DockEdge::End, columns)); - let window = Floating::single(vec![22], 0, Rect::from_min_size(Pos2::new(200.0, 300.0), Vec2::new(300.0, 200.0))); + let window = Floating::single(100, vec![22], 0, Rect::from_min_size(Pos2::new(200.0, 300.0), Vec2::new(300.0, 200.0))); Layout::new(Some(root), vec![window]) } @@ -275,7 +299,7 @@ fn the_pointer_over_a_body_runs_only_that_body() { #[trial] fn a_tab_switch_runs_only_its_group() { let MemoDock { mut fixture, workspace, .. } = memo_dock(side_by_side(3), None); - workspace.borrow_mut().apply(Action::activate(3), false, |_| Permissions::ALL).expect("panel 3 is shown"); + Arc::make_mut(&mut workspace.borrow_mut()).apply(Action::activate(3), false, |_| Permissions::ALL).expect("panel 3 is shown"); fixture.frame(Vec::new()); let rows_ran = frame_ran_ids(&fixture, "TabRow"); // The changed row runs in the real run; the discard pass its new size asks for measures it once (no measure of the @@ -304,7 +328,7 @@ fn a_label_change_runs_only_its_groups_chrome() { const RENAMED: &str = "A renamed panel whose title is far too long to share its group's tab row with the other panel"; let MemoDock { mut fixture, labels, .. } = memo_dock(side_by_side(3), None); assert!(fixture.by_label("More tabs").is_none(), "every group's tabs fit before the change"); - labels.borrow_mut()[4] = RENAMED.to_owned(); + labels.borrow_mut().edit(|labels| labels.0[4] = RENAMED.to_owned()); fixture.frame(Vec::new()); let rows_ran = frame_ran_ids(&fixture, "TabRow"); assert_eq!( @@ -352,7 +376,8 @@ fn a_click_on_a_replayed_tab_row_is_picked_once() { assert_eq!(*picked.borrow(), vec![1], "the click picked panel 1 once"); fixture.frame(vec![egui::Event::PointerGone]).idle(SETTLE); assert_eq!(*picked.borrow(), vec![1], "no frame after the click picks again"); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); assert!(matches!(layout.root.as_ref(), Some(Node::Split { first, .. }) if matches!(&**first, Node::Tabs { active: 1, .. })), "panel 1 is shown"); } @@ -367,7 +392,8 @@ fn a_double_click_on_a_replayed_column_bar_collapses_its_column() { assert_eq!(memo_of(&fixture, "BarProps"), (0, 1), "the bar replays before the click"); let band = fixture.by_label("Move panel column").expect("the column's band").center(); fixture.click_at(band).click_at(band).settle(); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); let Some(Node::Split { second, .. }) = layout.root.as_ref() else { panic!("the split") }; assert!(matches!(&**second, Node::Dock { columns, .. } if columns[0].iconic), "the column collapsed to icons: {layout:?}"); } @@ -383,7 +409,8 @@ fn a_tab_dropped_on_a_settled_group_lands_there() { fixture.frame(vec![moved(to)]); assert!(drag::mark(fixture.ctx()).is_some(), "the settled group's strip takes the drop in the frame the pointer arrives"); fixture.release_at(to).idle(1); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); let group = layout.place(&4).and_then(|place| layout.node_of(&place)); assert!(matches!(group, Some(Node::Tabs { panels, .. }) if panels.contains(&0)), "the tab joined the third group: {group:?}"); } @@ -400,7 +427,7 @@ fn close_in_a_settled_groups_panel_menu_closes_the_panel() { let close = fixture.by_label("Close").expect("the menu's Close row"); fixture.click(&close); fixture.frame(vec![egui::Event::PointerGone]); - assert!(workspace.borrow().layout.place(&2).is_none(), "Close closed the second group's panel"); + assert!(workspace.borrow().layout().place(&2).is_none(), "Close closed the second group's panel"); } /// Panels without versions whose bodies note the id of the `Ui` they run in. @@ -409,10 +436,6 @@ struct Noted { } impl DockPanels for Noted { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { self.ids.borrow_mut().push((*panel, ui.scope_id())); } @@ -423,16 +446,53 @@ impl DockPanels for Noted { #[trial] fn a_tab_moved_to_the_front_keeps_the_shown_bodys_ids() { let ids: Rc>> = Rc::default(); - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new())))); - let (shown, mut panels) = (Rc::clone(&workspace), Noted { ids: Rc::clone(&ids) }); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new()))))); + let (shown, mut panels, specs) = (Rc::clone(&workspace), Noted { ids: Rc::clone(&ids) }, Tracked::new(Named)); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &mut panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &specs, &mut panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(800.0, 600.0)).settle(); let body_id = |ids: &RefCell>| ids.borrow().iter().rev().find(|(panel, _)| *panel == 0).map(|(_, id)| *id); let before = body_id(&ids).expect("panel 0's body ran"); - workspace.borrow_mut().layout.root = Some(Node::tabs(vec![1, 0], 1)); + *workspace.borrow_mut() = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![1, 0], 1)), Vec::new()))); ids.borrow_mut().clear(); fixture.frame(Vec::new()); assert_eq!(body_id(&ids), Some(before), "the shown body keeps its id when another tab moves to the front"); } + +/// An idle dock reads no panel spec and builds nothing it derives: its specs, permissions and keys are kept while the +/// workspace, the spec model and the lock are unchanged. That holds for a read-only dock too. +#[trial] +fn an_idle_dock_reads_no_spec_and_builds_nothing() { + let MemoDock { mut fixture, .. } = memo_dock(side_by_side(4), None); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an idle pass of a dock of 8 panels builds nothing"); + } + assert_eq!(spec_reads(), 0, "and reads no spec"); + + let shown = Arc::new(Workspace::new(side_by_side(4))); + let specs = Tracked::new(Named); + let mut fixture = Fixture::new(move |ui| { + DockArea::read_only("Shown", &shown, &specs, &mut Panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); + spec_reads(); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an idle pass of a read-only dock builds nothing"); + } + assert_eq!(spec_reads(), 0, "and reads no spec"); +} + +/// One workspace edit reads the specs once, in the frame of the edit, and none after. +#[trial] +fn one_workspace_edit_reads_the_specs_once() { + let MemoDock { mut fixture, workspace, .. } = memo_dock(side_by_side(4), None); + Arc::make_mut(&mut workspace.borrow_mut()).apply(Action::activate(3), false, |_| Permissions::ALL).expect("panel 3 is shown"); + fixture.frame(Vec::new()); + assert_eq!(spec_reads(), 8, "the edit reads each of the 8 panels' specs once: one build"); + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "the next pass builds nothing"); + assert_eq!(spec_reads(), 0, "and reads no spec"); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index ae8016407..387d32446 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -12,7 +12,7 @@ An app with dockable panels shows a `DockArea`. The parts are for patterns that ## Model -A `Workspace` is a saved arrangement: its `layout` and the `hidden` panels with the place each one goes back to. A `Layout` is a docked tree (`root: Option>`) plus floating windows (`floating: Vec>`). `P` is the app's panel key. Every panel occurs once. +A `Workspace` is a saved arrangement: its `layout()` and the `hidden()` panels with the place each one goes back to. Its fields are private; it changes only through its methods. A `Layout` is a docked tree (`root: Option>`) plus floating windows (`floating: Vec>`). `P` is the app's panel key. Every panel occurs once. `Node` has four forms: @@ -39,7 +39,7 @@ To load a saved workspace: ```rust let mut panels = Panels { document: &mut state.document }; -let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default()); +let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default()); if let Some(panel) = state.maximized { area = area.maximized(panel); } @@ -50,18 +50,27 @@ for event in area.show(ui).events { } ``` -The host implements `DockPanels

`: +The host holds the workspace as an `Arc>` (`state.workspace`): a pass shares it instead of cloning it, and an edit writes a new one (`Arc::make_mut`). + +The host keeps its panels' specs in a plain-data model that implements `PanelSpecs

`, held in a `Tracked` (`state.specs`): | Method | Does | | --- | --- | -| `spec` | The panel's `PanelSpec`, read every pass: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`. | +| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`. | | `permissions` | The panel's `Permissions` (default `ALL`). | + +The area reads them only when the model's revision, the workspace's revision or the lock changes (`runtime::derived`), and keeps what it read otherwise, so an idle pass reads no spec. A host changes a label or a limit by editing the model. A spec reads no style: a tool rail's grid is `DockGrid::rail(cells)`, which the dock sizes from its own tokens. + +The host implements `DockPanels

` for the views: + +| Method | Does | +| --- | --- | | `body` | Shows the panel's body in the group's body, which the group insets by the panel padding (`Pad::Regular`). The group is the body's panel, so the body adds no `Panel` or padding of its own. A document panel's body (`WindowKind::Document`) is shown edge to edge. | | `group_view` | Takes a whole group in place of its tab strip and body, in a `Ui` held to the group's rect; a canvas group draws its document here. Default `None`. | | `group_header` | The host's controls in a group header, before the tab strip. | | `panel_rows` | The host's rows of a panel's menu, before the dock's own. | -The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a layout locked. +The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision. A panel body, or code a body calls, changes the workspace during the pass with `docking::request_actions(ctx, actions)`, never by writing the workspace the area shows. The running area takes them unapplied and returns them in `DockAreaOutput::requested`, in order, for the host to apply after `actions` in the same frame. With no area over that panel type running, `request_actions` hands the actions back for the caller to apply. @@ -103,9 +112,10 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A column collapsed to icons takes drops as an expanded column does: its edges (a new column beside it, docked only), the seams between its icon groups, the top of the first group and the bottom of the last (a new group above or below), and each icon group's cells (join its tabs). The column's state wins: a panel dropped into a collapsed column shows as an icon, one dropped into an expanded column shows expanded. - Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides. - A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to its edge of the float area: `Floating::edge`, else the one nearer its rect. A move keeps the edge it began with. A collapsed window's move ends at the edge nearer its strip where it was dropped, with the rect that shows the strip there (`WindowColumn::dropped`), and the area records that edge (`Action::MoveFloating`'s `edge`); a unit dragged out of a collapsed column (`start_icon_drag`) floats collapsed the same way, its strip under the pointer (`Target::Float`'s `edge`). Collapsing a floating column and moving an expanded window clear the edge. A column that neither collapses nor has steps shows no double arrow and offers no collapse in its menu (`ColumnArrow::Fixed`). -- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. +- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns; `DockGrid::rail` for a tool rail, sized by the dock). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. -- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. +- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives. +- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`): it only grows while the layout lives, and `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, so an OS window never passes to another window. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. - Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s. From d1386328c25f0382b5ff0bed4cdc29e6fb594321 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 12:55:02 +0000 Subject: [PATCH 06/89] Dock on Derived: one rail-grid conversion, window ids never reused, docs - A panel's grid is read only through DockSizes::stepped, in the dock's own sizes, so DockGrid::rail is converted in one place; ToolRail counts its columns in its scope's style (DockSizes::of_scope), and ToolRail::dock_grid is gone. - A layout's window counter starts above every id it is built or loaded with; a dock area raises a workspace an undo brings back above every id it has shown (Workspace::raise_window_floor). A saved u64::MAX id loads without overflow. - Floating::id and DockArea::new docs say how ids are given and why to keep one Arc. Part of #2336. --- crates/behavior/src/dock/layout.rs | 50 +++++++++++++++---- crates/behavior/src/dock/node.rs | 46 ++++++++++------- crates/behavior/src/dock/workspace.rs | 8 +++ crates/behavior/tests/dock_apply.rs | 30 +++++++++++ crates/ui-panels/src/docking/dock_column.rs | 6 +-- .../src/docking/dock_column/sizing.rs | 15 +++--- crates/ui-panels/src/docking/mod.rs | 2 +- crates/ui-panels/src/docking/placed.rs | 4 +- crates/ui-panels/src/docking/targets.rs | 16 ++++-- crates/ui-panels/src/rails/tool.rs | 23 ++++----- crates/ui-panels/src/rails/tool/stories.rs | 3 +- crates/ui-panels/src/rails/tool/trials.rs | 43 ++++++++++++++-- crates/ui-patterns/src/patterns/dock/area.rs | 35 +++++++------ .../ui-patterns/tests/it/docking/columns.rs | 17 +++++++ .../tests/it/docking/panel_menu.rs | 32 ++++++++++++ docs/ui-docking.md | 4 +- 16 files changed, 254 insertions(+), 80 deletions(-) diff --git a/crates/behavior/src/dock/layout.rs b/crates/behavior/src/dock/layout.rs index f5b13eef7..045d04b98 100644 --- a/crates/behavior/src/dock/layout.rs +++ b/crates/behavior/src/dock/layout.rs @@ -22,19 +22,34 @@ use super::{ /// /// Equality compares the tree and the windows, not the window id counter. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(from = "Saved

", bound(deserialize = "P: serde::Deserialize<'de>"))] #[non_exhaustive] pub struct Layout

{ /// The docked layout; `None` when nothing is docked. pub root: Option>, /// Floating windows, with unique ids. - #[serde(deserialize_with = "super::node::floating_serde::unique_ids")] pub floating: Vec>, - /// The least id [`Self::fresh_window_id`] may draw: above every id this layout has drawn, and above every id - /// the layouts it replaced held. Not saved. + /// The least id [`Self::fresh_window_id`] may draw: above every id the layout held when it was built or loaded, + /// every id it has drawn since, and every id the layouts it replaced held. Not saved. #[serde(skip)] pub(super) next_window: u64, } +/// A layout as saved: the tree and the windows, which load with unique ids. +#[derive(serde::Deserialize)] +#[serde(bound(deserialize = "P: serde::Deserialize<'de>"))] +struct Saved

{ + root: Option>, + #[serde(deserialize_with = "super::node::floating_serde::unique_ids")] + floating: Vec>, +} + +impl

From> for Layout

{ + fn from(saved: Saved

) -> Self { + Layout::new(saved.root, saved.floating) + } +} + impl PartialEq for Layout

{ fn eq(&self, other: &Self) -> bool { self.root == other.root && self.floating == other.floating @@ -48,24 +63,37 @@ impl

Default for Layout

{ } impl

Layout

{ - /// A layout with the docked tree `root` and the floating windows `floating`. + /// A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id + /// in `floating`. pub fn new(root: Option>, floating: Vec>) -> Self { - Self { root, floating, next_window: 0 } + let mut layout = Self { root, floating, next_window: 0 }; + layout.next_window = layout.window_floor(); + layout } - /// An id for a new floating window: above every window id the layout holds or has drawn, so an id, and the OS - /// window it names, is never given to another window while the layout lives. + /// An id for a new floating window: above every window id the layout held when it was built or loaded and every + /// id it has drawn since, so an id, and the OS window it names, is never given to another window while the layout + /// lives. Should those ids run out (a window holds `u64::MAX`), the least id no window holds. pub fn fresh_window_id(&mut self) -> u64 { - let id = self.window_floor(); - self.next_window = id.saturating_add(1); + let floor = self.window_floor(); + let held = |id: u64| self.floating.iter().any(|window| window.id == id); + let id = if held(floor) { (0..=u64::MAX).find(|id| !held(*id)).unwrap_or(floor) } else { floor }; + self.next_window = self.next_window.max(id.saturating_add(1)); id } - /// The least id no window of the layout holds or has held. - fn window_floor(&self) -> u64 { + /// The least id above every id the layout holds or has held. + pub fn window_floor(&self) -> u64 { self.floating.iter().map(|window| window.id.saturating_add(1)).fold(self.next_window, u64::max) } + /// Keeps new window ids at or above `floor`. Returns whether the counter moved. + pub(super) fn raise_window_floor(&mut self, floor: u64) -> bool { + let raised = floor > self.next_window; + self.next_window = self.next_window.max(floor); + raised + } + /// Takes the windows of `incoming`, which replaces this layout, onto ids this layout never gave out: a window /// whose id is below this layout's floor gets a fresh one, and the counter keeps growing from both. pub(super) fn hand_ids_to(&self, incoming: &mut Layout

) { diff --git a/crates/behavior/src/dock/node.rs b/crates/behavior/src/dock/node.rs index 1d0a0bfd8..d44d1dc45 100644 --- a/crates/behavior/src/dock/node.rs +++ b/crates/behavior/src/dock/node.rs @@ -68,16 +68,17 @@ pub struct StackEntry

{ /// /// Serde reads every saved shape (see `floating_serde`); a window that is one expanded column with one plain group /// and no native rect writes the v1 shape `{panels, active, rect}`, so older builds can read files that use no -/// newer feature. Every window writes its `id`; a window read without one gets a fresh one. +/// newer feature. Every window writes its `id`; a window read without one, or with one an earlier window took, gets an +/// id above every saved one. /// /// Equality ignores `id`: two windows with the same contents and place are the same layout. #[derive(Clone, Debug)] #[non_exhaustive] pub struct Floating

{ /// Names the window across panel moves, and its OS window. - /// Unique within a layout: [`Self::new`] draws a fresh id, [`Self::with_id`] sets one, - /// loading keeps the saved id (or draws one when it is missing or taken), and merging - /// windows keeps the receiving window's. + /// Unique within a layout: [`Self::new`] and [`Self::with_id`] take one from the caller (a window a layout adds + /// takes [`Layout::fresh_window_id`](super::Layout::fresh_window_id)), loading keeps the saved id (or gives one + /// above every saved id when it is missing or taken), and merging windows keeps the receiving window's. pub id: u64, /// The window's groups, top to bottom, and its collapsed state. Its `width` is unused: the window's width is /// `rect`'s. @@ -405,24 +406,35 @@ pub(super) mod floating_serde { } /// Floating windows as saved, each read into the windows it becomes. A window keeps its saved id unless an - /// earlier window took it; one without an id, or with a taken one, gets the next id above every saved one. + /// earlier window took it; one without an id, or with a taken one, gets the next id above every saved one, or, + /// should those run out (a saved `u64::MAX`), the least id no saved or given window holds. pub(in crate::dock) fn unique_ids<'de, D: Deserializer<'de>, P: Deserialize<'de>>(deserializer: D) -> Result>, D::Error> { let mut windows = Vec::new(); for saved in Vec::>::deserialize(deserializer)? { windows.extend(saved.into_windows::()?); } - let mut next = windows.iter().filter_map(|(id, _)| *id).max().map_or(0, |id| id.saturating_add(1)); - let mut seen = std::collections::HashSet::new(); - Ok(windows - .into_iter() - .map(|(id, window)| { - let id = id.filter(|id| seen.insert(*id)).unwrap_or_else(|| { - next += 1; - next - 1 - }); - Floating { id, ..window } - }) - .collect()) + let saved: std::collections::HashSet = windows.iter().filter_map(|(id, _)| *id).collect(); + let mut next = saved.iter().max().map_or(Some(0), |id| id.checked_add(1)); + let mut given = std::collections::HashSet::new(); + let mut out = Vec::with_capacity(windows.len()); + for (id, window) in windows { + let id = match id.filter(|id| given.insert(*id)) { + Some(id) => id, + None => { + let id = match next { + Some(id) => { + next = id.checked_add(1); + id + } + None => (0..=u64::MAX).find(|id| !saved.contains(id) && !given.contains(id)).unwrap_or(0), + }; + given.insert(id); + id + } + }; + out.push(Floating { id, ..window }); + } + Ok(out) } } diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index ddaed82c0..5aba1f0b5 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -127,6 +127,14 @@ impl

Workspace

{ self } + /// Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + /// workspace an undo brings back to it, so no id, and no OS window, goes to a second window. + pub fn raise_window_floor(&mut self, floor: u64) { + if self.layout.raise_window_floor(floor) { + self.touch(); + } + } + /// Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool) { let before = self.hidden.len(); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index af2d0eae2..c4461067d 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -457,6 +457,7 @@ fn every_workspace_mutator_moves_the_revision() { moves("apply_all", &|workspace| drop(workspace.apply_all([Action::close(5), Action::close(4)], false, allow).unwrap())); moves("set_visible", &|workspace| workspace.set_visible(5, false, None, false, allow).unwrap()); moves("reconcile", &|workspace| workspace.reconcile(|panel| *panel != 5, allow, &Workspace::new(docked()))); + moves("raise_window_floor", &|workspace| workspace.raise_window_floor(1000)); moves("forget_hidden", &|workspace| { workspace.apply(Action::close(5), false, allow).unwrap(); let revision = workspace.revision(); @@ -506,4 +507,33 @@ fn window_ids_stay_unique_within_each_layout_and_are_never_reused() { let saved = r#"{"layout":{"root":null,"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":7,"panels":[2],"active":0,"rect":[0,0,100,100]},{"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#; let loaded: Workspace = serde_json::from_str(saved).unwrap(); assert_eq!(window_ids(&loaded), [7, 8, 9], "a load keeps the first of a duplicate id and numbers the rest above every saved id"); + + // A loaded layout draws above the ids it loaded with, not only the ones it drew: a closed window's id stays used. + let saved = r#"{"layout":{"root":{"Tabs":{"panels":[4,5],"active":0}},"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":9,"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#; + let mut loaded: Workspace = serde_json::from_str(saved).unwrap(); + loaded.apply(Action::close(3), false, allow).unwrap(); + loaded.apply(Action::float(4, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert_eq!(window_ids(&loaded), [7, 10], "the new window does not take the closed window's id 9"); + + // An undo brings back an older workspace whose counter is lower: raised to the floor the dock has shown, it draws + // no id a later window had. + let older = Workspace::new(docked()); + let mut later = older.clone(); + later.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + let drawn: Vec = window_ids(&later).into_iter().filter(|id| !window_ids(&older).contains(id)).collect(); + let mut undone = older.clone(); + undone.raise_window_floor(later.layout().window_floor()); + undone.apply(Action::float(5, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(window_ids(&undone).iter().all(|id| !drawn.contains(id)), "the undone workspace draws past {drawn:?}: {:?}", window_ids(&undone)); + + // A saved id at the top of the range loads without overflow, and the windows still get unique ids. + let saved = format!( + r#"{{"layout":{{"root":null,"floating":[{{"id":{},"panels":[1],"active":0,"rect":[0,0,100,100]}},{{"panels":[2],"active":0,"rect":[0,0,100,100]}}]}}}}"#, + u64::MAX + ); + let loaded: Workspace = serde_json::from_str(&saved).unwrap(); + assert_eq!(window_ids(&loaded), [u64::MAX, 0], "a window without an id takes the least free one once the range above is used"); + let mut layout = loaded.layout().clone(); + let fresh = layout.fresh_window_id(); + assert!(!window_ids(&loaded).contains(&fresh), "a draw past the top of the range takes a free id: {fresh}"); } diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 8cabf2989..c3fbd8fe4 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -32,7 +32,7 @@ use bar::panel_names; pub(super) use bar::{BarRecord, CHEVRON, ColumnGrip, bar_band, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar}; use sizing::group_sizes; -pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; +pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, width_bounds}; const DIVIDER: PartKey = PartKey::new("divider"); const EDGE: PartKey = PartKey::new("edge"); @@ -78,11 +78,11 @@ pub enum ColumnArrow { impl ColumnArrow { /// The arrow of `column`: an expanded column whose panels do not collapse (`collapses` false) switches steps /// when it is stepped and has none otherwise; any other column collapses or expands. - pub fn of

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, collapses: bool) -> Self { + pub fn of

(column: &Column

, sizes: &DockSizes, spec: &dyn Fn(&P) -> PanelSpec, collapses: bool) -> Self { if collapses || column.iconic { return ColumnArrow::Collapse; } - stepped(column, spec).map_or(ColumnArrow::Fixed, |(_, steps)| ColumnArrow::Steps(steps)) + sizes.stepped(column, spec).map_or(ColumnArrow::Fixed, |(_, steps)| ColumnArrow::Steps(steps)) } /// The steps a click gives a stepped column: two from one, else one. `None` for any other arrow. diff --git a/crates/ui-panels/src/docking/dock_column/sizing.rs b/crates/ui-panels/src/docking/dock_column/sizing.rs index 31bdba43a..2b2bf4829 100644 --- a/crates/ui-panels/src/docking/dock_column/sizing.rs +++ b/crates/ui-panels/src/docking/dock_column/sizing.rs @@ -55,12 +55,15 @@ pub fn column_cells

( .collect() } -/// The grid and steps of a stepped column: its [`Column::steps`] and the [`DockGrid`] of its first panel that -/// declares a valid one. `None` for a column without steps or whose panels declare none, which sizes as any other. -pub fn stepped

(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> { - let steps = column.steps?; - let grid = column.panels().find_map(|panel| spec(panel).grid.filter(|grid| grid.valid()))?; - Some((grid, grid.clamp(steps))) +impl DockSizes { + /// The grid and steps of a stepped column: its [`Column::steps`] and the [`DockGrid`] of its first panel that + /// declares a valid one, in these sizes (a [`DockGrid::rail`] takes their rail widths). `None` for a column without + /// steps or whose panels declare none, which sizes as any other. Every dock reads a panel's grid through here. + pub fn stepped

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> { + let steps = column.steps?; + let grid = column.panels().find_map(|panel| spec(panel).grid.map(|grid| grid.resolved(self)).filter(|grid| grid.valid()))?; + Some((grid, grid.clamp(steps))) + } } /// Column widths that add up to `total` as far as their bounds allow. Each entry is `(width, (lo, hi))`. The diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 1ce3cab72..bf4e19204 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -59,7 +59,7 @@ mod iconic; pub use dock_column::{ ColumnArrow, ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, column_cells, fit_widths, group_heights, - group_rects, scale_widths, stacked, stepped, width_bounds, + group_rects, scale_widths, stacked, width_bounds, }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes}; diff --git a/crates/ui-panels/src/docking/placed.rs b/crates/ui-panels/src/docking/placed.rs index c276de59b..316758548 100644 --- a/crates/ui-panels/src/docking/placed.rs +++ b/crates/ui-panels/src/docking/placed.rs @@ -3,7 +3,7 @@ use super::frame::maximize; use super::tree::{self, FrameRules}; -use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects, stepped}; +use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects}; use craft_behavior::Flow; use craft_behavior::dock::{Column, Layout, Node}; use egui::Rect; @@ -109,7 +109,7 @@ fn column_rects( if !column.panels().any(moves) { return Some(()); } - if column.iconic || stepped(column, placing.spec).is_some() { + if column.iconic || placing.sizes.stepped(column, placing.spec).is_some() { return None; } if column.panels().all(moves) { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 20f26a4a2..6ddfd9bf2 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -4,7 +4,7 @@ //! previous pass's registry, because a drop is decided against what was on screen when the pointer moved. Every //! zone is a rect. A spot names a group by an anchor panel, as the dock model does. -use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds}; +use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; use crate::style::StyleCx; @@ -80,6 +80,12 @@ impl DockSizes { StyleCx::with_root(ctx, DockSizes::style) } + /// The sizes in the style of the scope `ui` is in: what a dock shown in `ui` sizes with. + pub fn of_scope(ui: &egui::Ui) -> Self { + let env = crate::runtime::env::Env::of(ui); + Self::style(&StyleCx::of_env(ui.ctx(), &env)) + } + /// The sizes of the style context `cx`. pub fn style(cx: &StyleCx<'_>) -> Self { let size = &cx.tokens.size; @@ -119,7 +125,7 @@ impl DockSizes { /// floated iconic column use it): the stored width kept within the panels' limits, or a stepped column's width /// at its steps ([`stepped`]). pub fn expanded_width

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> f32 { - if let Some((grid, steps)) = stepped(column, spec) { + if let Some((grid, steps)) = self.stepped(column, spec) { return grid.width(steps); } let (lo, hi) = self.width_bounds(column, spec); @@ -133,7 +139,7 @@ impl DockSizes { if column.iconic { // Widening an iconic column stops at the width it expands to. (self.iconic_least, self.expanded_width(column, spec).max(self.iconic_least)) - } else if let Some((grid, _)) = stepped(column, spec) { + } else if let Some((grid, _)) = self.stepped(column, spec) { (grid.width(1), grid.width(grid.most)) } else { self.width_bounds(column, spec) @@ -167,7 +173,7 @@ impl DockSizes { Some(Node::Dock { columns, .. }) => columns, _ => return Vec::new(), }; - let fixed = |column: &Column

| !column.iconic && stepped(column, spec).is_some(); + let fixed = |column: &Column

| !column.iconic && self.stepped(column, spec).is_some(); let current: Vec<(f32, (f32, f32))> = columns .iter() .map(|column| { @@ -193,7 +199,7 @@ impl DockSizes { columns .iter() .map(|column| { - let keeps = column.iconic || stepped(column, spec).is_some(); + let keeps = column.iconic || self.stepped(column, spec).is_some(); (self.width(column, spec), (!keeps).then(|| self.width_bounds(column, spec).0.max(1.0))) }) .collect() diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 4d7491a80..e1b74bd1d 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -9,7 +9,7 @@ use crate::contract::{ ShowContainer as _, Sizing, WordSetCx as _, }; use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox}; -use crate::docking::DockGrid; +use crate::docking::{DockGrid, DockSizes}; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; use crate::runtime::access::Name; @@ -92,7 +92,7 @@ type FooterFn<'a> = Box; /// The rail of tool slots, laid out in a grid of columns: one `FlyoutButton` per visible slot showing the slot's shown /// tool, the slot with the current tool toggled on. A click selects the shown tool, a row of the flyout selects that /// tool. The rail takes as many columns as the width it gets holds, the most whole columns that fit -/// ([`dock_grid`](ToolRail::dock_grid)): it is a button and the control padding wide at one column and a button and the tight gap wider for each further column, +/// ([`DockGrid::rail`] in the scope's style): it is a button and the control padding wide at one column and a button and the tight gap wider for each further column, /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button /// follows the last slot; the host's footer stays in view under the slots, which scroll when the room is short under @@ -156,13 +156,6 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { .label(label) } - /// The grid of a rail of `cells` cells (its visible slots and the Edit Toolbar button) in the root style: - /// [`DockGrid::rail`] resolved there. A panel's spec gives the unresolved [`DockGrid::rail`], which its dock - /// resolves in its own style. - pub fn dock_grid(ctx: &egui::Context, cells: usize) -> DockGrid { - DockGrid::rail(cells).resolved(&crate::docking::DockSizes::of(ctx)) - } - /// The cells the rail lays out: its visible slots and the Edit Toolbar button. fn cells(&self) -> usize { visible_slots(self.slots, self.hidden).len() + usize::from(self.edit_toolbar.is_some()) @@ -170,8 +163,10 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { /// Sets up the pass for a rail `width` wide: its columns, its roving grid and its footer. Returns what the body /// draws from. - fn prepare(&mut self, ctx: &egui::Context, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> Draw<'a, T> { - self.columns = usize::from(Self::dock_grid(ctx, self.cells()).steps_within(width)); + fn prepare(&mut self, ui: &Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> Draw<'a, T> { + // The grid in the scope's style, as the dock column around the rail sizes it. + let grid = DockGrid::rail(self.cells()).resolved(&DockSizes::of_scope(ui)); + self.columns = usize::from(grid.steps_within(width)); self.props = std::mem::take(&mut self.props).roving(Roving::new(NavShape::wrapped_grid(self.columns))); self.footer = Some(Box::new(footer)); Draw { @@ -307,13 +302,13 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { /// Shows the rail one column wide, for a host that lays it at the start of a row (the full-window workspaces' /// tool strips): the width `ui` has left belongs to what follows it in the row. pub fn show_column(self, ui: &mut Ui, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput { - let one = Self::dock_grid(ui.ctx(), 1).width(1); + let one = DockGrid::rail(1).resolved(&DockSizes::of_scope(ui)).width(1); self.show_within(ui, one, footer) } /// Shows the rail laid out `width` wide. fn show_within(mut self, ui: &mut Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput { - let draw = self.prepare(ui.ctx(), width, footer); + let draw = self.prepare(ui, width, footer); let last = remembered(draw.slots, draw.current, draw.last_used); let (mut events, mut edit_toolbar) = (Vec::new(), None); let shown = self.show(ui, |ui, _| edit_toolbar = draw.run(ui, &mut events)); @@ -340,7 +335,7 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { /// The size of the rail laid out `width` wide, with `footer` under its rows: as many columns as `width` holds, /// as tall as its rows and footer (at most the room along the axis it scrolls on). pub fn measure_rail(mut self, ui: &Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> Vec2 { - let draw = self.prepare(ui.ctx(), width, footer); + let draw = self.prepare(ui, width, footer); self.measure_in(ui, Proposal::Width(width), |ui, _| { draw.run(ui, &mut Vec::new()); }) diff --git a/crates/ui-panels/src/rails/tool/stories.rs b/crates/ui-panels/src/rails/tool/stories.rs index ef3fd0455..ea76a7500 100644 --- a/crates/ui-panels/src/rails/tool/stories.rs +++ b/crates/ui-panels/src/rails/tool/stories.rs @@ -1,6 +1,7 @@ //! Stories of `ToolRail`, and the commands its stories and the flyout's use as tools. use super::{LastUsed, RailTool, ToolRail, ToolSlot}; +use crate::docking::{DockGrid, DockSizes}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -52,7 +53,7 @@ fn tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { data.choice("hidden", Vec::::new(), &[("None", Vec::new()), ("Pencil", vec![2]), ("Stamp", vec![4]), ("Eraser", vec![3])]).clone(); let slots = slots(); let last = LastUsed::default(); - let width = ToolRail::::dock_grid(ui.ctx(), slots.len() + 1).width(u16::from(columns)); + let width = DockGrid::rail(slots.len() + 1).resolved(&DockSizes::of_scope(ui)).width(u16::from(columns)); // design: allow[contract/memory](the story gives the rail the width of its chosen columns, as a dock column does) let out = ui .scope(|ui| { diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index fb884b5ee..0e6a0468b 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -6,6 +6,10 @@ use super::{LastUsed, ToolRail, ToolSlot}; use crate::buttons::Button; use crate::contract::Props as _; use crate::contract::Show as _; +use crate::contract::ShowContainer as _; +use crate::docking::{DockGrid, DockSizes}; +use crate::layout_components::Stack; +use crate::runtime::env::ThemeScope; use crate::testing::pointer::{moved, wheel}; use crate::testing::relations::{above, grows_with}; use crate::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; @@ -61,7 +65,7 @@ fn rail_in(width: f32, height: f32) -> (Fixture, Rc>) { /// of them one fewer, and a wider one no more columns than the rail has cells. #[trial] fn a_tool_rail_lays_out_the_most_whole_columns_its_width_holds() { - let grid = ToolRail::::dock_grid(Fixture::new(|_| {}).ctx(), LABELS.len()); + let grid = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(Fixture::new(|_| {}).ctx())); for steps in 1..=3_u16 { let (fixture, _) = rail_in(grid.width(steps), 800.0); assert_eq!(columns_of(&fixture), usize::from(steps), "a width of {steps} steps shows {steps} columns"); @@ -80,7 +84,7 @@ fn a_tool_rail_lays_out_the_most_whole_columns_its_width_holds() { /// and fewer columns need more rows. #[trial] fn a_tool_rail_measures_its_rows_plus_its_footer_at_a_width() { - let grid = ToolRail::::dock_grid(Fixture::new(|_| {}).ctx(), LABELS.len()); + let grid = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(Fixture::new(|_| {}).ctx())); let mut heights = Vec::new(); for steps in [1_u16, 2] { let (fixture, measured) = rail_in(grid.width(steps), 800.0); @@ -99,7 +103,7 @@ fn a_tool_rail_measures_its_rows_plus_its_footer_at_a_width() { /// above it, down to a room smaller than one scroll region's usual least height. #[trial] fn in_a_short_room_the_rows_scroll_above_the_footer_that_stays_in_view() { - let grid = ToolRail::::dock_grid(Fixture::new(|_| {}).ctx(), LABELS.len()); + let grid = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(Fixture::new(|_| {}).ctx())); for height in [160.0, 100.0] { let (mut fixture, measured) = rail_in(grid.width(1), height); let foot = rect(&fixture, "Foot"); @@ -227,3 +231,36 @@ fn a_click_on_a_slot_selects_its_tool_once() { fn near(a: f32, b: f32) -> bool { (a - b).abs() < 1.0 } + +/// A rail in a scope whose density differs from the root's counts its columns in that scope's style, the style its dock +/// column is stepped in: under a comfortable root, a compact scope two rail steps wide shows two columns, where the +/// root's rail would fit one. +#[trial] +fn a_rail_in_another_density_counts_its_columns_in_that_density() { + let scoped: Rc>> = Rc::default(); + let seen = Rc::clone(&scoped); + let compact = || ThemeScope::new().density(craft_theme::Size::Compact); + let mut probe = Fixture::new(move |ui| { + Stack::new().theme(compact()).show(ui, |ui, _| { + seen.set(Some(DockGrid::rail(LABELS.len()).resolved(&DockSizes::of_scope(ui)))); + }); + }); + probe.density(craft_theme::Size::Comfortable).settle(); + let grid = scoped.get().expect("the scope ran"); + let root = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(probe.ctx())); + let width = grid.width(2); + assert_eq!(root.steps_within(width), 1, "the root's rail fits one column in two compact steps: {grid:?}, root {root:?}"); + + let mut fixture = Fixture::new(move |ui| { + Stack::new().theme(compact()).show(ui, |ui, _| { + let slots = slots(); + let last = LastUsed::default(); + ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| { + Button::new("Foot").show(ui); + }); + }); + }); + let tall = 800.0; + fixture.density(craft_theme::Size::Comfortable).room(Vec2::new(width, tall)).settle(); + assert_eq!(columns_of(&fixture), 2, "two rail steps of the scope's style show two columns"); +} diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 156944aa4..cfcc8e97c 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -13,7 +13,7 @@ use crate::docking::{ ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, WindowColumn, actions, - column_cells, dock_states, frame, move_actions, stepped, with_area_rules, + column_cells, dock_states, frame, move_actions, with_area_rules, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within}; @@ -145,7 +145,8 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { /// A dock area named `label` over `workspace`, with its panels' specs from `specs`, their views from `panels` and /// its behaviour from `config`. The root's id comes from the label under the parent's id, and inside an `AppShell` - /// from the window too, so two windows' docks never share state. + /// from the window too, so two windows' docks never share state. Keep one `Arc` across frames and clone the `Arc`, + /// not the workspace: a new workspace value each frame is a new revision, which reads every spec each frame. pub fn new + 'a>( label: impl Into

{ open: Option

, /// The running move or resize of a floating window. moving: Option>, + /// The least window id above every id the workspaces this area showed held: an undo that brings back an older + /// workspace keeps its new windows above it ([`Workspace::raise_window_floor`]). + window_floor: u64, } /// A floating window's move or resize as one workspace edit: its gesture and the workspace when it began. @@ -198,7 +202,7 @@ struct Moving

{ impl

Default for AreaMemory

{ fn default() -> Self { - AreaMemory { open: None, moving: None } + AreaMemory { open: None, moving: None, window_floor: 0 } } } @@ -223,7 +227,7 @@ impl Drops<'_, P> { let shell = cx.env.get::().0; let bounds = shell.as_ref().map_or(cx.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, self.config, self.specs); - let spec = |panel: &P| spec_in(self.specs, &sizes, panel); + let spec = |panel: &P| spec_in(self.specs, panel); let protected = |panel: &P| (self.permissions)(panel).is_protected(); let (hide, _) = hide::resolved(self.hide, shell.as_ref()); let mut target = DockDropTarget::new(&ctx, self.dock, self.layout, self.permissions); @@ -267,11 +271,9 @@ struct Scene<'s, P> { floated: &'s [(P, Location

)], } -/// The spec of `panel` in `specs`, or an unnamed one, with its grid in the dock's `sizes`. -fn spec_in(specs: &HashMap, sizes: &DockSizes, panel: &P) -> PanelSpec { - let mut spec = specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())); - spec.grid = spec.grid.map(|grid| grid.resolved(sizes)); - spec +/// The spec of `panel` in `specs`, or an unnamed one. +fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec { + specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) } /// What an area derives from its workspace, its panels' specs and its lock, kept while none of them changes: whether @@ -306,7 +308,7 @@ impl DockModel

{ impl Scene<'_, P> { fn spec(&self, panel: &P) -> PanelSpec { - spec_in(self.specs, &self.sizes, panel) + spec_in(self.specs, panel) } fn permissions(&self, panel: &P) -> Permissions { @@ -437,6 +439,8 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { open_requests::

(&ctx); let shown = root.show(ui, |ui, body| { let Some(sizes) = body.style::>>().map(|style| *style.sizes()) else { return }; + let memory = body.memory::>(); + memory.window_floor = memory.window_floor.max(current.layout().window_floor()); let input = Input { id, ctx: &ctx, @@ -506,7 +510,7 @@ struct Applied

{ /// Applies `proposed` in order to the workspace the binding holds, with the panels' permissions from `specs` (narrowed /// when `locked`; an action may open a panel the layout does not hold). A refused action changes nothing and is left /// out of the result. The accepted ones are written as one edit, which a given workspace does not take. `current` is -/// the workspace as the pass started. +/// the workspace as the pass started. New windows take ids above every id the area has shown (`AreaMemory::window_floor`). fn apply_actions( body: &mut BodyCx<'_>, mut workspace: BindMut<'_, Arc>>, @@ -522,6 +526,7 @@ fn apply_actions( }; let permissions = |panel: &P| specs.permissions(panel); let mut next = Workspace::clone(&before); + next.raise_window_floor(body.memory::>().window_floor); let mut actions = Vec::new(); for action in proposed { if next.apply(action.clone(), locked, permissions).is_ok() { @@ -1070,7 +1075,7 @@ impl Pass<'_, P> { ) -> Option { let scene = self.scene; let spec_of = |panel: &P| scene.spec(panel); - let (grid, steps) = stepped(column, &spec_of)?; + let (grid, steps) = scene.sizes.stepped(column, &spec_of)?; let by_height = match change.kind { PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), _ => (change.rect.width() - fitted.x).abs() <= 0.5, @@ -1101,7 +1106,7 @@ impl Pass<'_, P> { fn stepped_height(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, width: f32, in_window: bool) -> Option { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); - if column.iconic || stepped(column, &spec).is_none() { + if column.iconic || scene.sizes.stepped(column, &spec).is_none() { return None; } let mut height = 0.0; @@ -1116,7 +1121,7 @@ impl Pass<'_, P> { fn arrow_of(&self, column: &Column

) -> ColumnArrow { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); - ColumnArrow::of(column, &spec, column.panels().all(|panel| scene.permissions(panel).collapses)) + ColumnArrow::of(column, &scene.sizes, &spec, column.panels().all(|panel| scene.permissions(panel).collapses)) } /// What a click on the double arrow of `column`, whose first panel is `first`, asks for when it reports @@ -1186,7 +1191,7 @@ impl Pass<'_, P> { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); if let Some(width) = work.width { - match stepped(column, &spec) { + match scene.sizes.stepped(column, &spec) { // The edge of a stepped column moves in whole steps: the most that fit where it is dragged. Some((grid, steps)) if !column.iconic => { let to = grid.steps_within(width); diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index d5c0f4809..458d2df43 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -144,6 +144,23 @@ fn a_stepped_column_keeps_its_width_while_the_others_scale() { assert_eq!(grid.steps_within(f32::MAX), grid.most, "no more steps than the grid has columns"); } +/// A tool rail's grid is sized by the dock's own style: a column of two rail steps is a rail button and its padding +/// plus one more button and gap wide, and the side's width leaves it alone. +#[trial] +fn a_rail_column_steps_in_the_docks_rail_cells() { + let sizes = super::sizes(4.0, 100.0, STRIP); + let with_rail = |panel: &u32| if *panel == TOOLS { PanelSpec::new("Tools").grid(DockGrid::rail(6)) } else { spec(panel) }; + let spec: &dyn Fn(&u32) -> PanelSpec = &with_rail; + let columns = vec![Column::new(vec![Group::new(vec![2], 0)]).with_width(250.0), Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(2)]; + let root = Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, columns)); + let live = Workspace::new(Layout::new(Some(root), Vec::new())); + let rail = end_columns(live.layout())[1].clone(); + assert_eq!(sizes.width(&rail, spec), sizes.rail_first + sizes.rail_step, "two rail steps in the dock's sizes"); + let actions = sizes.resize_side(live.layout(), DockEdge::End, spec, sum(&[250.0, sizes.rail_first + sizes.rail_step]) + 80.0); + let touches_tools = |action: &Action| matches!(action, Action::ResizeColumn { panel: TOOLS, .. } | Action::SetColumnSteps { .. }); + assert!(!actions.is_empty() && !actions.iter().any(touches_tools), "the side's width leaves the rail column alone: {actions:?}"); +} + /// A toolbar: a panel whose two lines of content lay out in a grid and never collapse. #[derive(PlainData)] struct Tools; diff --git a/crates/ui-patterns/tests/it/docking/panel_menu.rs b/crates/ui-patterns/tests/it/docking/panel_menu.rs index 0a0ad89e7..b3b76895e 100644 --- a/crates/ui-patterns/tests/it/docking/panel_menu.rs +++ b/crates/ui-patterns/tests/it/docking/panel_menu.rs @@ -115,3 +115,35 @@ fn the_window_menu_opens_and_closes_the_flyout_of_a_panel_in_a_collapsed_column( assert_eq!(*actions.borrow(), vec![Action::close(1)], "the row of a showing panel closes it"); assert_eq!(*flyout.borrow(), None, "and leaves the flyout alone"); } + +/// Floats panel 2 through the panel menu of the second group. +fn float_second_group(fixture: &mut Fixture) { + let buttons: Vec<_> = + fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Panel Menu")).collect(); + fixture.click(&buttons[1]).idle(2); + let float = fixture.by_label("Float").expect("the menu's Float row"); + fixture.click(&float).idle(2); +} + +/// An undo that brings back the workspace from before a float keeps the area's next window off the id the undone +/// window had: the area remembers the ids it has shown. +#[trial] +fn a_window_floated_after_an_undo_takes_a_new_id() { + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0, 1], 0), Node::tabs(vec![2, 3], 0)); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Specs)); + let mut fixture = Fixture::new(move |ui| { + DockArea::new("Dock", Bind::bound(&mut *held.borrow_mut()), &specs, &mut Panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + let older = Arc::clone(&workspace.borrow()); + float_second_group(&mut fixture); + let undone: Vec = workspace.borrow().layout().floating.iter().map(|window| window.id).collect(); + assert_eq!(undone.len(), 1, "Float made a window"); + *workspace.borrow_mut() = older; + fixture.settle(); + float_second_group(&mut fixture); + let ids: Vec = workspace.borrow().layout().floating.iter().map(|window| window.id).collect(); + assert_eq!(ids.len(), 1, "Float made a window again"); + assert_ne!(ids, undone, "the window after the undo does not take the undone window's id"); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 387d32446..f7f3553f6 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -50,7 +50,7 @@ for event in area.show(ui).events { } ``` -The host holds the workspace as an `Arc>` (`state.workspace`): a pass shares it instead of cloning it, and an edit writes a new one (`Arc::make_mut`). +The host holds the workspace as an `Arc>` (`state.workspace`): a pass shares it instead of cloning it, and an edit writes a new one (`Arc::make_mut`). Keep that one `Arc` across frames and clone the `Arc`, not the workspace: a new workspace value is a new revision, so a host that wraps a fresh copy each frame makes the area read every spec each frame. The host keeps its panels' specs in a plain-data model that implements `PanelSpecs

`, held in a `Tracked` (`state.specs`): @@ -115,7 +115,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns; `DockGrid::rail` for a tool rail, sized by the dock). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. - A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives. -- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`): it only grows while the layout lives, and `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, so an OS window never passes to another window. +- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. - Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s. From b729d8b4224440859498902f1d9d602636da6c16 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 12:51:41 +0000 Subject: [PATCH 07/89] Derived: a replayed view keeps the values it derived A replay asks for no derived value, so the memo rule dropped the values of a view that replayed for a few frames and the view's next run built them again. The record notes the slots a run asked for, as it does for layout memory, and a replay keeps them. last_frame_derived_builds counts the builds of every pass of a frame. IconId is plain data. --- crates/behavior/src/cursor.rs | 2 +- crates/ui-contract/src/runtime/derived.rs | 18 +++++++++++ crates/ui-contract/src/runtime/measure.rs | 28 ++++++++++++++--- crates/ui-contract/src/runtime/replay.rs | 13 ++++++++ crates/ui-contract/src/testing/mod.rs | 8 ++--- .../ui-contract/tests/it/runtime/derived.rs | 31 ++++++++++++++++++- 6 files changed, 89 insertions(+), 11 deletions(-) diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index e3ffa2745..af14c260b 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -46,7 +46,7 @@ pub enum CursorIcon { } /// An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui_macros::PlainData)] pub struct IconId(Cow<'static, str>); impl IconId { diff --git a/crates/ui-contract/src/runtime/derived.rs b/crates/ui-contract/src/runtime/derived.rs index 3334103ef..92d3569a3 100644 --- a/crates/ui-contract/src/runtime/derived.rs +++ b/crates/ui-contract/src/runtime/derived.rs @@ -54,6 +54,7 @@ pub fn derived(ctx: &Context, id: Id, ke crate::runtime::measure::count_memo_key_bytes(ctx, memo.bytes()); let key = memo.finish(); let slot = id.with(TypeId::of::()); + crate::runtime::replay::note_derived_keep(ctx, slot); let viewport = pass::current_viewport(ctx); let frame = pass::frame_nr(ctx, viewport); let kept = PerViewport::::with(ctx, viewport, |store| { @@ -73,3 +74,20 @@ pub fn derived(ctx: &Context, id: Id, ke PerViewport::::with(ctx, viewport, |store| store.entries.insert(slot, entry)); value } + +/// Keeps the values under `slots` through this frame, for a replayed run that asked for them: the replay asks for +/// nothing, and an entry no pass asked for in a frame is dropped by the memo rule. +pub(crate) fn keep(ctx: &Context, slots: &[Id]) { + if slots.is_empty() { + return; + } + let viewport = pass::current_viewport(ctx); + let frame = pass::frame_nr(ctx, viewport); + PerViewport::::with(ctx, viewport, |store| { + for slot in slots { + if let Some(entry) = store.entries.get_mut(slot) { + entry.touched = frame; + } + } + }); +} diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 8fd0fc014..cc9010ece 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -58,6 +58,9 @@ struct BodyRuns { pub(crate) struct DerivedBuilds { pass: u64, builds: Vec<(Id, u32)>, + /// The frame `frame_builds` counts, and the builds of every pass of it. + frame: u64, + frame_builds: Vec<(Id, u32)>, } /// How many contributions the measuring runs of a pass made that stand, with the pass that counted them. @@ -555,17 +558,32 @@ pub(crate) fn count_derived(ctx: &Context, id: Id) { return; } let pass = ctx.cumulative_pass_nr(); + let frame = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)); pass_state::with::(ctx, |log| { - if log.pass != pass { - *log = DerivedBuilds { pass, builds: Vec::new() }; + if log.frame != frame { + log.frame = frame; + log.frame_builds.clear(); } - match log.builds.iter_mut().find(|(of, _)| *of == id) { - Some((_, count)) => *count += 1, - None => log.builds.push((id, 1)), + if log.pass != pass { + log.pass = pass; + log.builds.clear(); + } + for builds in [&mut log.builds, &mut log.frame_builds] { + match builds.iter_mut().find(|(of, _)| *of == id) { + Some((_, count)) => *count += 1, + None => builds.push((id, 1)), + } } }); } +/// The components that built a derived value in any pass of the last frame, and how many builds each. +#[cfg(feature = "testing")] +pub fn last_frame_derived_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)).saturating_sub(1); + pass_state::with::(ctx, |log| if log.frame == last { log.frame_builds.clone() } else { Vec::new() }) +} + /// The components that built a derived value in the last pass, and how many builds each; empty when that pass built /// none. #[cfg(feature = "testing")] diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index b22730d9a..bde005d12 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -157,6 +157,8 @@ pub(crate) struct Facts { pub(crate) owners: Vec, /// The layout memory entries the run kept (`note_layout_keep`): a replay keeps them (`layout_memory::keep`). pub(crate) layout_keeps: Vec, + /// The derived values the run asked for (`note_derived_keep`): a replay keeps them, since it asks for none. + pub(crate) derived_keeps: Vec, /// The framework inputs the run read outside its props (`runtime::inputs`). pub(crate) inputs: Inputs, /// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one @@ -234,6 +236,7 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.discards |= open.facts.discards; outer.facts.owners.extend(open.facts.owners.iter().copied()); outer.facts.layout_keeps.extend(open.facts.layout_keeps.iter().copied()); + outer.facts.derived_keeps.extend(open.facts.derived_keeps.iter().copied()); outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake); let kept = outer.kept; outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..)))); @@ -249,6 +252,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { // Every measure of an entry keeps it again: the record keeps each one once. facts.layout_keeps.sort_unstable_by_key(|id| id.value()); facts.layout_keeps.dedup(); + facts.derived_keeps.sort_unstable_by_key(|id| id.value()); + facts.derived_keeps.dedup(); // A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees: // its run is never replayed. facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback(); @@ -361,11 +366,13 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { pass_state::with::(ctx, |recorder| recorder.replaying = false); } crate::runtime::layout_memory::keep(ctx, &record.facts.layout_keeps); + crate::runtime::derived::keep(ctx, &record.facts.derived_keeps); if let Some(at) = record.facts.wake { crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); } with_open(ctx, |facts| { facts.layout_keeps.extend(record.facts.layout_keeps.iter().copied()); + facts.derived_keeps.extend(record.facts.derived_keeps.iter().copied()); facts.reads.extend(record.facts.reads.iter().copied()); facts.inputs.extend(record.facts.inputs); facts.wake = min_wake(facts.wake, record.facts.wake); @@ -481,6 +488,12 @@ pub(crate) fn note_layout_keep(ctx: &Context, id: egui::Id) { with_open(ctx, |facts| facts.layout_keeps.push(id)); } +/// Notes that the running code asked for the derived value kept under `slot`: a replay of the records open around it +/// keeps it too, as the replay asks for nothing and an entry no pass asked for in a frame is dropped. +pub(crate) fn note_derived_keep(ctx: &Context, slot: egui::Id) { + with_open(ctx, |facts| facts.derived_keeps.push(slot)); +} + /// Notes that the memory owner `owner` registered in the running code. pub(crate) fn note_owner(ctx: &Context, owner: egui::Id) { with_open(ctx, |facts| facts.owners.push(owner)); diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 32977778f..73b597b60 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -45,10 +45,10 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ - MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs, - last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, - last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, - widest_runs, + MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds, + last_frame_memo_runs, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, + last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, + run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-contract/tests/it/runtime/derived.rs b/crates/ui-contract/tests/it/runtime/derived.rs index dbb8343de..b981ee7a3 100644 --- a/crates/ui-contract/tests/it/runtime/derived.rs +++ b/crates/ui-contract/tests/it/runtime/derived.rs @@ -1,7 +1,7 @@ //! Derived values: built once per key, kept while the key is unchanged, and dropped by the memo rule once absent. use craft_ui::runtime::derived::derived; -use craft_ui::testing::{Fixture, last_pass_derived_builds, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, trial}; use egui::Id; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -60,3 +60,32 @@ fn an_absent_derived_value_is_dropped_by_the_memo_rule() { fixture.frame(Vec::new()); assert_eq!(builds(&fixture), 1, "with none shown, every absent value was dropped"); } + +/// A memoized view that replays asks for no derived value, and its values stay kept: when the pointer then runs the +/// view, it finds them. +#[trial] +fn a_replayed_view_keeps_the_values_it_derived() { + use craft_ui::contract::MemoView; + use craft_ui::testing::pointer; + let at: Rc> = Rc::default(); + let shown = Rc::clone(&at); + let mut fixture = Fixture::new(move |ui| { + let out = MemoView::new("deriving", 1u32, |key: &mut u32, ui: &mut egui::Ui| { + let value = derived(ui.ctx(), Id::NULL.with("derived"), key, || key.to_string()); + ui.label(value.as_str()).rect.center() + }) + .show(ui); + if let Some(out) = out { + shown.set(out); + } + }); + fixture.room(egui::Vec2::new(200.0, 100.0)); + fixture.settle().idle(3); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "an idle frame builds nothing"); + } + fixture.frame(vec![pointer::moved(at.get())]); + assert_eq!(last_frame_memo_runs(fixture.ctx()).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count(), 1, "the pointer runs the view"); + assert_eq!(builds(&fixture), 0, "the view runs for the pointer and finds its value kept"); +} From 866ddeaaf7bde39ab8f6ea40447c1d526a464ec3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 12:51:41 +0000 Subject: [PATCH 08/89] craft-layers: the Layers panel reads a Tracked tree and derives its display order LayersPanel::new takes &Tracked; LayerTree is plain data and its Id feeds memo keys. The display order, its row keys and the filtered flag are one Derived value keyed by the tracked revision, the filter and the opens of a reveal, so a pass that runs for another reason walks nothing. LayerTree::revision is removed; the list's order revision follows the key. FakeLayers loses its revision field and call counters. --- crates/layers/src/ui/filter/mod.rs | 17 +-- crates/layers/src/ui/mock.rs | 28 +---- crates/layers/src/ui/panel/body.rs | 8 +- crates/layers/src/ui/panel/body/rows.rs | 87 ++++++++++---- crates/layers/src/ui/panel/mod.rs | 18 +-- crates/layers/src/ui/panel/stories.rs | 21 ++-- crates/layers/src/ui/tree.rs | 51 ++++---- crates/layers/tests/it/main.rs | 1 + crates/layers/tests/it/panel_drag_menu.rs | 4 +- crates/layers/tests/it/panel_filter.rs | 10 +- crates/layers/tests/it/panel_input.rs | 23 ++-- crates/layers/tests/it/panel_memo.rs | 134 ++++++++++++++++++++++ crates/layers/tests/it/panel_order.rs | 32 ++---- crates/layers/tests/it/panel_reveal.rs | 5 +- crates/layers/tests/it/panel_rows.rs | 18 +-- 15 files changed, 294 insertions(+), 163 deletions(-) create mode 100644 crates/layers/tests/it/panel_memo.rs diff --git a/crates/layers/src/ui/filter/mod.rs b/crates/layers/src/ui/filter/mod.rs index 09566dff0..d37261ae1 100644 --- a/crates/layers/src/ui/filter/mod.rs +++ b/crates/layers/src/ui/filter/mod.rs @@ -11,7 +11,7 @@ mod stories; use craft_behavior::{EditEvent, IconId, Mixed, SelectionChange}; use craft_theme::{ControlSize, LabelColor}; use craft_ui::buttons::ToggleButton; -use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, Entry, MemoProps, NoValue, Outcome, PlainData, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::layout_components::Row; use craft_ui::list::{ListWords, label_color_label}; use craft_ui::pickers::Select; @@ -26,7 +26,7 @@ use super::tree::{LayerInfo, LayerKind, LayerPart, LayerTree}; /// What the Layers panel filters by: the filter bar's type select, Photoshop's types in its order /// (Selected waits for the feature that needs it). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum FilterBy { @@ -73,7 +73,7 @@ impl FilterBy { } /// A layer kind the Kind filter toggles. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum FilterKind { @@ -125,7 +125,7 @@ impl LayerKind { /// A layer effect kind, as the Effect filter picks it and [`LayerInfo::effect_kinds`] reports it, /// in Photoshop's order. `Overlay` stands for Color, Gradient and Pattern Overlay. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, PlainData, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum EffectKind { @@ -177,7 +177,7 @@ impl EffectKind { /// A layer attribute the Attribute filter picks, or its opposite: Photoshop's nine attributes, /// then their opposites. Each opposite lists the layers (and groups) its attribute doesn't. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum LayerAttribute { @@ -303,7 +303,7 @@ impl LayerAttribute { } /// Where a smart object's contents come from, as [`LayerInfo::smart`] reports it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum SmartSource { /// A file outside the document. @@ -313,7 +313,7 @@ pub enum SmartSource { } /// A kind of smart object the Smart Object filter toggles. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SmartKind { @@ -335,7 +335,7 @@ impl SmartKind { /// document) and passes it to [`LayersPanel::filter`](super::panel::LayersPanel::filter); every /// field has a serde default. Each type reads its own field; the others keep their values while /// another type is picked. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(default)] #[non_exhaustive] pub struct LayerFilter { @@ -354,6 +354,7 @@ pub struct LayerFilter { /// Color: the label colour; `None` (no label) at first. Serialized by name (`"none"`, `"red"`, /// … `"gray"`). #[serde(with = "label_name")] + #[memo_props(hash = "a plain enum with a derived Hash")] pub color: Option, /// Smart Object: the kinds toggled on, in the order they were toggled. pub smart: Vec, diff --git a/crates/layers/src/ui/mock.rs b/crates/layers/src/ui/mock.rs index f064b7f5e..2747a003d 100644 --- a/crates/layers/src/ui/mock.rs +++ b/crates/layers/src/ui/mock.rs @@ -1,9 +1,7 @@ //! `FakeLayers`: a `LayerTree` for stories and tests. -use std::cell::Cell; - use craft_theme::LabelColor; -use craft_ui::contract::Entry; +use craft_ui::contract::{Entry, PlainData}; use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut as S, blend_entries}; use craft_ui::runtime::env::Label; @@ -15,7 +13,7 @@ use super::tree::{ }; /// One layer of a [`FakeLayers`] tree. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PlainData)] #[non_exhaustive] pub struct FakeLayer { /// The layer's id. @@ -36,7 +34,7 @@ pub struct FakeLayer { /// A fake document's layers, kept in plain vectors: the tests' and stories' `LayerTree`. Ids are /// `u32`; the app's state (open groups, selection, effects open) is a field the test sets. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PlainData)] #[non_exhaustive] pub struct FakeLayers { /// Every layer, each group before its children, topmost first among siblings. @@ -45,15 +43,11 @@ pub struct FakeLayers { pub selection: LayerSelection, /// The layer under the pointer on the canvas. pub hovered: Option, - /// The revision the tree reports; `None` walks every pass. - pub revision: Option, /// The layers with no visible pixels, which only the app knows: the Attribute filter's Empty. pub empty: Vec, /// The linked smart objects whose file is not there, which only the app knows: the Smart Object /// filter's Missing. pub missing: Vec, - info_calls: Cell, - sub_rows_calls: Cell, } impl FakeLayers { @@ -301,16 +295,6 @@ impl FakeLayers { tree.selection.sub_row = Some(LayerRowKey::Filters(smart, Some(0))); tree } - - /// How many times `info` was called since the last [`take_info_calls`](Self::take_info_calls). - pub fn take_info_calls(&self) -> usize { - self.info_calls.replace(0) - } - - /// How many times `sub_rows` was called since the last [`take_sub_rows_calls`](Self::take_sub_rows_calls). - pub fn take_sub_rows_calls(&self) -> usize { - self.sub_rows_calls.replace(0) - } } impl FakeLayers { @@ -380,7 +364,6 @@ impl LayerTree for FakeLayers { } fn info(&self, id: &u32) -> LayerInfo { - self.info_calls.set(self.info_calls.get() + 1); self.layer(id).map(|layer| layer.info.clone()).unwrap_or_else(|| LayerInfo::new(String::new(), LayerKind::Pixel)) } @@ -400,7 +383,6 @@ impl LayerTree for FakeLayers { } fn sub_rows(&self, id: &u32, group: SubRowGroup) -> Option { - self.sub_rows_calls.set(self.sub_rows_calls.get() + 1); let layer = self.layer(id)?; match group { SubRowGroup::Effects => layer.effects.clone(), @@ -468,10 +450,6 @@ impl LayerTree for FakeLayers { self.hovered } - fn revision(&self) -> Option { - self.revision - } - fn footer(&self) -> LayersFooterState { let active = self.selection.active.is_some(); LayersFooterState { diff --git a/crates/layers/src/ui/panel/body.rs b/crates/layers/src/ui/panel/body.rs index 3e101044a..155359e35 100644 --- a/crates/layers/src/ui/panel/body.rs +++ b/crates/layers/src/ui/panel/body.rs @@ -77,7 +77,7 @@ pub(super) fn show_body( .selection(Bind::bound(&mut selection)) .can_rename(|key| matches!(key, LayerRowKey::Layer(id) if tree.info(id).renamable)) .accepts(|drag: &ListDrag>, _over, insert| { - accepts_drop(tree, drag, &order, insert, craft_ui::runtime::pointer::frame(&ctx).mods) + accepts_drop(tree, drag, order, insert, craft_ui::runtime::pointer::frame(&ctx).mods) }) .drag_payload({ let document = cx.document; @@ -98,7 +98,7 @@ pub(super) fn show_body( hovered = Some(id.clone()); } let row = build_row(cx, key).cells(item.cells()).state(item.row.clone()); - match rows.rows.get(item.at) { + match rows.rows().get(item.at) { Some(shown) if shown.has_children => row.depth(shown.paint_depth).group(shown.open), Some(shown) => row.depth(shown.paint_depth), None => row, @@ -107,7 +107,7 @@ pub(super) fn show_body( let mut events: Vec> = reveal.opens.iter().cloned().map(LayersEvent::Open).collect(); let drop_preview = match &out.pending_drop { - Some(PendingDrop::Reorder(mv)) if cx.options.preview_on_canvas_when_reordering => match layer_drop(mv, &order, &parent_of, filtered) { + Some(PendingDrop::Reorder(mv)) if cx.options.preview_on_canvas_when_reordering => match layer_drop(mv, order, &parent_of, filtered) { Some(LayerDrop::Layers(layers)) => Some(layers), _ => None, }, @@ -115,7 +115,7 @@ pub(super) fn show_body( }; let selection_changed = out.events.iter().any(|event| matches!(event, CollectionEvent::Selection(_))); let list_events = out.events; - map_events(cx, &order, &parent_of, filtered, lock_name, session, list_events, &mut events); + map_events(cx, order, &parent_of, filtered, lock_name, session, list_events, &mut events); if selection_changed { let mut layers: Vec = Vec::new(); for key in &selection.items { diff --git a/crates/layers/src/ui/panel/body/rows.rs b/crates/layers/src/ui/panel/body/rows.rs index c682c9f64..74e144b32 100644 --- a/crates/layers/src/ui/panel/body/rows.rs +++ b/crates/layers/src/ui/panel/body/rows.rs @@ -2,9 +2,10 @@ use craft_behavior::{ColumnKey, DisplayOrder, ItemSource, Selection}; use craft_keymap::Mods; -use craft_ui::contract::{OpenChange, SweepApply}; +use craft_ui::contract::{BodyCx, MemoKey, MemoProps, OpenChange, Revision, SweepApply, Tracked}; use craft_ui::list::{ThumbTarget, tree_steps}; use std::borrow::Cow; +use std::sync::Arc; use super::super::context::PanelContext; use super::super::events::LayerColumn; @@ -27,55 +28,91 @@ pub(in crate::ui::panel) struct DisplayRow { pub(super) open: bool, } -/// The rows of the tree as the list shows them: layers, and under each layer whose effects are open -/// the Smart Filter and effect rows. -pub(in crate::ui::panel) struct LayerRows<'t, T: LayerTree> { - tree: &'t T, - pub(in crate::ui::panel) rows: Vec>, - /// The filter left a layer out: rows list at their shown depth, so a drop finds its place by its neighbours. - pub(in crate::ui::panel) filtered: bool, - revision: Option, +/// What the display order derives from: the tree's tracked revision, the filter and the groups a reveal opens. A +/// change of any of them builds the rows again; nothing else does. +#[derive(MemoProps)] +pub(in crate::ui::panel) struct RowsKey<'a, Id: MemoProps> { + pub(in crate::ui::panel) tree: Revision, + pub(in crate::ui::panel) filter: &'a LayerFilter, + pub(in crate::ui::panel) opened: &'a [Id], } -impl<'t, T: LayerTree> LayerRows<'t, T> { - /// The rows for `filter`, with the groups in `opened` shown open besides the tree's own. - pub(in crate::ui::panel) fn new(tree: &'t T, filter: &LayerFilter, opened: &[T::Id]) -> Self { +/// The display order of the tree, derived from a [`RowsKey`] and kept across passes. +pub(in crate::ui::panel) struct RowsModel { + pub(in crate::ui::panel) rows: Vec>, + /// The row keys in display order. + keys: Vec>, + /// The filter left a layer out: rows list at their shown depth, so a drop finds its place by its neighbours. + pub(in crate::ui::panel) filtered: bool, + /// The number the list keeps its display order by: it follows the key. + revision: u64, +} + +impl RowsModel { + /// The rows of `tree` for `filter`, with the groups in `opened` shown open besides the tree's own. + fn walk>(tree: &T, filter: &LayerFilter, opened: &[Id], revision: u64) -> Self { let active = filter.active(); let mut walk = Walk { tree, filter, active, open_all: active && filter.lists_closed_contents(), opened, left_out: false }; let mut rows = Vec::new(); push_level(&mut walk, tree.children(None), Level { shown: 0, true_depth: 0 }, &mut rows); - let revision = tree.revision().filter(|_| !active && opened.is_empty()); - LayerRows { tree, rows, filtered: walk.left_out, revision } + let keys = rows.iter().map(|row| row.key.clone()).collect(); + RowsModel { rows, keys, filtered: walk.left_out, revision } + } +} + +/// The rows of the tree as the list shows them: layers, and under each layer whose effects are open +/// the Smart Filter and effect rows. +pub(in crate::ui::panel) struct LayerRows<'t, T: LayerTree> { + tree: &'t T, + model: Arc>, +} + +impl<'t, T: LayerTree> LayerRows<'t, T> { + /// The rows for `filter` and `opened`, derived by the body `cx` from the tracked `tree`. + pub(in crate::ui::panel) fn new(cx: &BodyCx<'_>, tree: &'t Tracked, filter: &LayerFilter, opened: &[T::Id]) -> Self { + let key = RowsKey { tree: tree.revision(), filter, opened }; + // The low half of the key's hash tells the list when the order changed. + let revision = MemoKey::of(&key) as u64; + let model = cx.derived(&key, || RowsModel::walk(&**tree, filter, opened, revision)); + LayerRows { tree: &**tree, model } } - pub(in crate::ui::panel) fn keys(&self) -> Vec> { - self.rows.iter().map(|row| row.key.clone()).collect() + pub(in crate::ui::panel) fn rows(&self) -> &[DisplayRow] { + &self.model.rows + } + + pub(in crate::ui::panel) fn filtered(&self) -> bool { + self.model.filtered + } + + pub(in crate::ui::panel) fn keys(&self) -> &[LayerRowKey] { + &self.model.keys } } impl DisplayOrder> for LayerRows<'_, T> { fn len(&self) -> usize { - self.rows.len() + self.model.rows.len() } fn key(&self, at: usize) -> LayerRowKey { - self.rows[at].key.clone() + self.model.rows[at].key.clone() } fn depth(&self, at: usize) -> usize { - self.rows[at].depth + self.model.rows[at].depth } fn has_children(&self, at: usize) -> bool { - self.rows[at].has_children + self.model.rows[at].has_children } fn open(&self, at: usize) -> bool { - self.rows[at].open + self.model.rows[at].open } fn text(&self, at: usize) -> Option> { - match &self.rows[at].key { + match &self.model.rows[at].key { LayerRowKey::Layer(id) | LayerRowKey::Mask(id, _) => Some(Cow::Owned(self.tree.info(id).name)), LayerRowKey::Effects(id, index) => sub_label(self.tree, id, SubRowGroup::Effects, *index), LayerRowKey::Filters(id, index) => sub_label(self.tree, id, SubRowGroup::SmartFilters, *index), @@ -83,13 +120,13 @@ impl DisplayOrder> for LayerRows<'_, T> { } fn revision(&self) -> Option { - self.revision + Some(self.model.revision) } } impl ItemSource> for LayerRows<'_, T> { fn toggled(&self, at: usize, column: &ColumnKey) -> bool { - match &self.rows[at].key { + match &self.model.rows[at].key { LayerRowKey::Layer(id) if *column == EYE => self.tree.info(id).visible, LayerRowKey::Layer(id) if *column == LOCK => self.tree.info(id).locks.any(), LayerRowKey::Effects(id, index) if *column == EYE => sub_on(self.tree, id, SubRowGroup::Effects, *index), @@ -99,7 +136,7 @@ impl ItemSource> for LayerRows<'_, T> { } fn sub_row(&self, at: usize) -> Option { - self.rows[at].sub_steps + self.model.rows[at].sub_steps } } diff --git a/crates/layers/src/ui/panel/mod.rs b/crates/layers/src/ui/panel/mod.rs index 1402b2661..c05b59c83 100644 --- a/crates/layers/src/ui/panel/mod.rs +++ b/crates/layers/src/ui/panel/mod.rs @@ -26,7 +26,7 @@ pub(crate) use row::FX_BADGE; use std::cell::RefCell; -use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _}; +use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _, Tracked}; use craft_ui::layout_components::Stack; use craft_ui::list::ListWords; use craft_ui::primitives::textures::{ThumbSource, Thumbnails}; @@ -160,7 +160,7 @@ impl Default for Session { #[derive(craft_ui::contract::Pattern)] #[pattern(probe(LayersPanel<'static, crate::ui::mock::FakeLayers>))] pub struct LayersPanel<'a, T: LayerTree> { - tree: &'a T, + tree: &'a Tracked, settings: Option<&'a LayersSettings>, thumbnails: Option>, filter: Option>, @@ -213,8 +213,9 @@ impl Outcome for LayersOutput { } impl<'a, T: LayerTree> LayersPanel<'a, T> { - /// The panel showing `tree`. - pub fn new(tree: &'a T) -> Self { + /// The panel showing `tree`. The panel derives the display order from the tracked revision, so an edit of the tree + /// through the `Tracked` is what makes it walk the tree again. + pub fn new(tree: &'a Tracked) -> Self { Self { tree, settings: None, @@ -339,7 +340,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { /// rows, the footer. Events are reported in that order. pub fn show(self, ui: &mut Ui) -> LayersOutput { let LayersPanel { - tree, + tree: tracked, settings, thumbnails, mut filter, @@ -355,6 +356,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { rename, document, } = self; + let tree: &T = tracked; let env = Env::of(ui); let words = env.words::(); let list_words = env.words::(); @@ -440,13 +442,13 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { }) .show(ui, |ui, stack| { let filter = current.borrow().clone(); - let session = stack.memory::>(); let plan = reveal_plan(tree, reveal.clone()); - let rows = LayerRows::new(tree, &filter, &plan.opened()); + let rows = LayerRows::new(stack, tracked, &filter, &plan.opened()); + let session = stack.memory::>(); if let Some(layer) = rename.clone() { start_rename(ui, list, layer); } - let body = show_body(ui, &cx, &rows, session, &plan, rows.filtered, &unlock_label); + let body = show_body(ui, &cx, &rows, session, &plan, rows.filtered(), &unlock_label); let menus = show_row_menus(ui, &cx, &body.response, row_menu.as_deref(), session); let mut reported = body.events; reported.extend(menus); diff --git a/crates/layers/src/ui/panel/stories.rs b/crates/layers/src/ui/panel/stories.rs index bbc228244..f107c14a5 100644 --- a/crates/layers/src/ui/panel/stories.rs +++ b/crates/layers/src/ui/panel/stories.rs @@ -2,6 +2,7 @@ //! tree; extra columns; effects and Smart Filters open; filtered by Artboard and by Group, which keep each group open or //! closed. +use craft_ui::contract::Tracked; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -35,14 +36,14 @@ fn layers_panel_tree(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); // PhotoCraft's Hide Layers key, which the app hands the panel. let hide_layers = craft_keymap::Chord::new(craft_keymap::Mods::CMD, craft_keymap::Key::Comma); - let shown = LayersPanel::new(&tree).visibility_key(hide_layers).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).visibility_key(hide_layers).show(ui); with_readout(data, shown) } #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::sample(); - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -50,7 +51,7 @@ fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Name, name: String::from("o"), ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } @@ -59,14 +60,14 @@ fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_target_cell(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); let target = |_: &u32, info: &LayerInfo| Icon::new(IconSpec::svg(IconId::new(if info.visible { "target" } else { "circle" }))); - let shown = LayersPanel::new(&tree).trailing(target, |_, _| {}).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).trailing(target, |_, _| {}).show(ui); with_readout(data, shown) } #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); - let shown = LayersPanel::new(&tree).lock_column(true).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).lock_column(true).show(ui); with_readout(data, shown) } @@ -75,7 +76,7 @@ fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_row_kinds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::row_kinds(); - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -84,7 +85,7 @@ fn layers_panel_row_kinds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_frame_selected(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut tree = FakeLayers::row_kinds(); tree.selection = LayerSelection::new(vec![2], Some(2), LayerPart::Pixels); - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -96,7 +97,7 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { for layer in &mut tree.layers { layer.effects_open = layer.effects.is_some() || layer.smart_filters.is_some(); } - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -105,7 +106,7 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::boards(); let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } @@ -114,6 +115,6 @@ fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_by_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::fifty(); let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index 3c13a7f1c..164295075 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -11,17 +11,20 @@ use std::hash::Hash; use craft_behavior::IconId; use craft_keymap::Mods; use craft_theme::LabelColor; -use craft_ui::contract::{Entry, ReorderMove}; +use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove}; use craft_ui::list::ThumbTarget; use super::filter::{EffectKind, LayerFilter, SmartSource}; use super::panel::MenuTarget; -/// The app's view of its layers, built per pass over its document (no copies of the layers). +/// The app's model of its layers, held in a [`Tracked`](craft_ui::contract::Tracked) the panel reads +/// (`LayersPanel::new(&Tracked)`). It is plain data, so every edit moves the tracked revision, which keys what +/// the panel derives from the tree. /// /// ```ignore -/// struct PhotoLayers<'a> { doc: &'a Document, ui: &'a UiState } -/// impl LayerTree for PhotoLayers<'_> { +/// #[derive(PlainData)] +/// struct PhotoLayers { layers: LayerIndex, open: HashSet } +/// impl LayerTree for PhotoLayers { /// type Id = LayerId; /// fn children(&self, parent: Option<&LayerId>) -> Vec { /* top of the stack first */ } /// /* … */ @@ -30,11 +33,12 @@ use super::panel::MenuTarget; /// /// The panel calls [`info`](Self::info) only for the rows it draws (the rows in view and one /// above and below), so a tree of 10,000 layers costs what its visible rows cost. -/// [`children`](Self::children) and [`is_open`](Self::is_open) are walked once per pass to build -/// the display order, unless [`revision`](Self::revision) says nothing changed. -pub trait LayerTree { - /// The app's layer id: the key of a row, of its thumbnails and of every event. - type Id: Clone + Eq + Hash + Debug + Send + Sync + 'static; +/// [`children`](Self::children) and [`is_open`](Self::is_open) are walked to build the display order, and only when the +/// tracked revision, the filter or a reveal's opens changed. +pub trait LayerTree: PlainData { + /// The app's layer id: the key of a row, of its thumbnails and of every event. It feeds the memo key of the + /// display order when a reveal opens groups. + type Id: Clone + Eq + Hash + Debug + Send + Sync + MemoProps + 'static; /// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the /// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text. @@ -107,18 +111,10 @@ pub trait LayerTree { fn hovered(&self) -> Option { None } - - /// A number that changes whenever rows are added, removed, moved, opened or closed, or an - /// effects or Smart Filters row is added or removed; with it - /// the panel keeps its display order between passes instead of walking the tree each pass. - /// `None` (the default) walks every pass. - fn revision(&self) -> Option { - None - } } /// What one layer row shows. Build it with [`LayerInfo::new`] and set the fields that differ. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, PlainData)] #[non_exhaustive] pub struct LayerInfo { /// The layer's name, shown on one line with an ellipsis. @@ -131,6 +127,7 @@ pub struct LayerInfo { /// Whether the row draws faint: hidden itself or inside a hidden group (the app decides). pub dimmed: bool, /// The label colour that fills the eye cell; `None` for none. + #[plain_data(assume = "a plain Copy enum of colours")] pub label: Option, /// The layer's locks: any of them shows the lock indicator. pub locks: LayerLocks, @@ -240,7 +237,7 @@ impl LayerInfo { /// The mark in a layer thumbnail's corner ([`LayerInfo::thumb_badge`]), in the badge box the mask /// badges use. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum ThumbBadge { /// A smart object: a window glyph. @@ -250,7 +247,7 @@ pub enum ThumbBadge { } /// What a layer is. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum LayerKind { /// Pixels (PhotoCraft's raster layer). @@ -284,7 +281,7 @@ pub enum LayerKind { } /// The part of a layer edits go to, and the thumbnail that stands for it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum LayerPart { /// The layer's own pixels; a frame as a whole, its shape and content together. @@ -303,7 +300,7 @@ pub enum LayerPart { } /// One mask of a layer. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub struct MaskInfo { /// [`LayerPart::LayerMask`] or [`LayerPart::VectorMask`]. @@ -316,7 +313,7 @@ pub struct MaskInfo { } /// A layer's locks. Start from `LayerLocks::default()` (nothing locked) and set the fields that are on. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub struct LayerLocks { /// Lock transparent pixels. @@ -378,7 +375,7 @@ impl LockKind { } /// The selection as the app keeps it. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, PlainData)] #[non_exhaustive] pub struct LayerSelection { /// The selected layers, in the order they were selected. @@ -406,7 +403,7 @@ impl Default for LayerSelection { } /// The key of one row of the panel, and of what a drag carries. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum LayerRowKey { /// A layer's row. @@ -446,7 +443,7 @@ pub enum SubRowGroup { } /// The effects or Smart Filter rows of a layer: a header row, then the items, top first. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, PlainData)] #[non_exhaustive] pub struct SubRows { /// The "Effects" or "Smart Filters" row; its eye shows or hides them all. @@ -463,7 +460,7 @@ impl SubRows { } /// One effects or Smart Filter row. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, PlainData)] #[non_exhaustive] pub struct SubRow { /// The row's text: "Effects", "Drop Shadow", "Gaussian Blur". diff --git a/crates/layers/tests/it/main.rs b/crates/layers/tests/it/main.rs index 0fb972e0e..8bcd971ef 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -5,6 +5,7 @@ mod comps; mod panel_drag_menu; mod panel_filter; mod panel_input; +mod panel_memo; mod panel_order; mod panel_reveal; mod panel_rows; diff --git a/crates/layers/tests/it/panel_drag_menu.rs b/crates/layers/tests/it/panel_drag_menu.rs index 7e006571f..3eddc6a26 100644 --- a/crates/layers/tests/it/panel_drag_menu.rs +++ b/crates/layers/tests/it/panel_drag_menu.rs @@ -9,7 +9,7 @@ use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayerDrop, LayerSelect, LayersDrag, LayersEvent, LayersPanel, MaskMove}; use craft_layers::ui::tree::{LayerPart, LayerRowKey, LayerTree as _}; use craft_theme::LabelColor; -use craft_ui::contract::Entry; +use craft_ui::contract::{Entry, Tracked}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Modifiers, Pos2, Vec2}; use std::cell::RefCell; @@ -27,7 +27,7 @@ const PANEL: Vec2 = Vec2::new(420.0, 560.0); fn rig() -> (Fixture, Seen, Asked) { let (seen, asked): (Seen, Asked) = (Rc::default(), Rc::default()); let (sink, menus) = (Rc::clone(&seen), Rc::clone(&asked)); - let tree = FakeLayers::sample(); + let tree = Tracked::new(FakeLayers::sample()); let mut fixture = Fixture::new(move |ui| { let out = LayersPanel::new(&tree) .row_menu(|target| { diff --git a/crates/layers/tests/it/panel_filter.rs b/crates/layers/tests/it/panel_filter.rs index 18a7177bb..7a6436f60 100644 --- a/crates/layers/tests/it/panel_filter.rs +++ b/crates/layers/tests/it/panel_filter.rs @@ -6,7 +6,7 @@ use craft_layers::ui::filter::{EffectKind, FilterBy, FilterKind, LayerAttribute, use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayersEvent, LayersPanel}; use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Tracked}; use craft_ui::testing::{Fixture, trial}; use egui::Vec2; use std::cell::{Cell, RefCell}; @@ -23,14 +23,14 @@ type Shared = Rc>; /// A panel over the artboard tree and a filter the trial sets; Find Layers runs in the pass after `find` is set. struct Rig { fixture: Fixture, - tree: Shared, + tree: Shared>, filter: Shared, find: Rc>, } /// The rig, its filter set by `start`. fn rig(start: impl FnOnce(&mut LayerFilter)) -> Rig { - let tree = Rc::new(RefCell::new(FakeLayers::boards())); + let tree = Rc::new(RefCell::new(Tracked::new(FakeLayers::boards()))); let mut filter = LayerFilter::default(); start(&mut filter); let filter = Rc::new(RefCell::new(filter)); @@ -196,7 +196,7 @@ fn find_layers_puts_the_caret_in_the_name_field_with_its_text_selected() { /// Kind, reported as a filter event so the app stores it. #[trial] fn the_type_select_lists_only_the_offered_types() { - let tree = Rc::new(RefCell::new(FakeLayers::boards())); + let tree = Rc::new(RefCell::new(Tracked::new(FakeLayers::boards()))); let mut start = LayerFilter::default(); start.by = FilterBy::Artboard; let filter = Rc::new(RefCell::new(start)); @@ -226,7 +226,7 @@ fn the_type_select_lists_only_the_offered_types() { fn a_filter_the_bar_applies_deselects_what_it_hides() { let mut tree = FakeLayers::sample(); tree.selection = LayerSelection::new(vec![3, 2, 4], Some(3), LayerPart::Pixels); - let tree = Rc::new(RefCell::new(tree)); + let tree = Rc::new(RefCell::new(Tracked::new(tree))); let filter = Rc::new(RefCell::new(LayerFilter::default())); let find = Rc::new(Cell::new(false)); let seen: Shared>> = Rc::default(); diff --git a/crates/layers/tests/it/panel_input.rs b/crates/layers/tests/it/panel_input.rs index ef21ce072..129293663 100644 --- a/crates/layers/tests/it/panel_input.rs +++ b/crates/layers/tests/it/panel_input.rs @@ -5,7 +5,7 @@ use craft_behavior::{EditEvent, EditHistory, Mixed, SelectionChange}; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayerColumn, LayerDrop, LayerPosition, LayerToggle, LayersEvent, LayersPanel}; use craft_layers::ui::tree::{LayerKind, LayerPart, LayerSelection}; -use craft_ui::contract::{MemoProps, MemoView, Outbox, PlainData, Tracked}; +use craft_ui::contract::{MemoProps, MemoView, Outbox, Tracked}; use craft_ui::testing::access::focused_key; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, Target, pointer, trial}; @@ -15,7 +15,7 @@ use std::rc::Rc; /// The app around the panel: the tree it shows and what it reported. struct App { - tree: FakeLayers, + tree: Tracked, events: Vec>, } @@ -68,7 +68,7 @@ fn apply(tree: &mut FakeLayers, event: &LayersEvent) { fn show(ui: &mut Ui, app: &mut App) { let App { tree, events } = app; - let out = LayersPanel::new(&*tree).show(ui); + let out = LayersPanel::new(tree).show(ui); for event in &out.events { apply(tree, event); } @@ -77,7 +77,7 @@ fn show(ui: &mut Ui, app: &mut App) { /// The panel over `tree`, in a room tall enough for every row. fn rig(tree: FakeLayers) -> (Fixture, Shared) { - let app = Rc::new(RefCell::new(App { tree, events: Vec::new() })); + let app = Rc::new(RefCell::new(App { tree: Tracked::new(tree), events: Vec::new() })); let shared = Rc::clone(&app); let mut fixture = Fixture::new(move |ui| show(ui, &mut shared.borrow_mut())); fixture.room(PANEL); @@ -246,24 +246,17 @@ fn shift_right_and_left_open_and_close_the_active_layers_effects() { assert_eq!(fx(take(&app)), [(7, false)], "Shift+Left closes them"); } -/// The tree a memoized view of the panel shows, as the app's model. -#[derive(PlainData)] -struct Model { - #[plain_data(assume = "a mock tree: its only interior mutability is call counters, which no view shows")] - tree: FakeLayers, -} - /// A memoized view of the panel over the app's model; it applies what the panel reports to the model and sends it on. #[derive(MemoProps)] struct PanelView<'a> { - model: &'a mut Tracked, + model: &'a mut Tracked, events: Outbox<'a, LayersEvent>, } fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) { - let out = LayersPanel::new(&props.model.tree).show(ui); + let out = LayersPanel::new(props.model).show(ui); for event in out.events { - props.model.edit(|model| apply(&mut model.tree, &event)); + apply(props.model, &event); props.events.send(event); } } @@ -274,7 +267,7 @@ fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) { #[trial] fn a_rows_access_focus_action_leads_the_focused_rows_to_it() { let settled = || { - let mut model = Tracked::new(Model { tree: FakeLayers::sample() }); + let mut model = Tracked::new(FakeLayers::sample()); let mut events = Vec::new(); let mut fixture = Fixture::new(move |ui| { MemoView::new("layers", PanelView { model: &mut model, events: Outbox::new(&mut events) }, panel_view).show(ui); diff --git a/crates/layers/tests/it/panel_memo.rs b/crates/layers/tests/it/panel_memo.rs new file mode 100644 index 000000000..5f72626bf --- /dev/null +++ b/crates/layers/tests/it/panel_memo.rs @@ -0,0 +1,134 @@ +//! `LayersPanel` in a host's memoized view: what the panel derives from its tracked tree, and when. + +use craft_layers::ui::filter::{FilterBy, LayerFilter}; +use craft_layers::ui::mock::FakeLayers; +use craft_layers::ui::panel::{LayersEvent, LayersPanel}; +use craft_ui::contract::{Bind, MemoProps, MemoView, Outbox, Tracked}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, pointer, trial}; +use egui::{Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; + +/// The panel's room: wide enough for a row's parts, tall enough for the sample tree and the footer. +const PANEL: Vec2 = Vec2::new(420.0, 560.0); + +type Shared = Rc>; + +/// What a host's view of the panel reads: the tracked tree, the filter the app stores, and an outbox for the events. +#[derive(MemoProps)] +struct Host<'a> { + tree: &'a Tracked, + filter: Bind<'a, LayerFilter>, + events: Outbox<'a, LayersEvent>, +} + +fn host(props: &mut Host<'_>, ui: &mut Ui) { + let out = LayersPanel::new(props.tree).filter(props.filter.reborrowed()).show(ui); + for event in out.events { + props.events.send(event); + } +} + +/// A fixture showing the panel over `tree` in a host view, with the shared tree, filter and delivered events. +struct Rig { + fixture: Fixture, + tree: Shared>, + filter: Shared, + seen: Shared>>, +} + +fn rig(tree: FakeLayers) -> Rig { + let tree = Rc::new(RefCell::new(Tracked::new(tree))); + let filter: Shared = Rc::default(); + let seen: Shared>> = Rc::default(); + let (shown, by, sink) = (Rc::clone(&tree), Rc::clone(&filter), Rc::clone(&seen)); + let mut fixture = Fixture::new(move |ui| { + let tree = shown.borrow(); + let mut filter = by.borrow_mut(); + let mut events = sink.borrow_mut(); + MemoView::new("layers", Host { tree: &tree, filter: Bind::bound(&mut filter), events: Outbox::new(&mut events) }, host).show(ui); + }); + fixture.room(PANEL); + fixture.settle().idle(2); + Rig { fixture, tree, filter, seen } +} + +impl Rig { + /// The builds of every pass of the last frame. + fn builds(&self) -> u32 { + last_frame_derived_builds(self.fixture.ctx()).iter().map(|(_, builds)| builds).sum() + } + + /// The host view's runs and replays in the last frame. + fn host_runs(&self) -> (u32, u32) { + let runs = last_frame_memo_runs(self.fixture.ctx()); + let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count() as u32; + (count(MemoRun::Ran), count(MemoRun::Replayed)) + } + + /// One frame with no input, after the edit of the trial. + fn frame(&mut self) -> &mut Self { + self.fixture.frame(Vec::new()); + self + } +} + +/// An idle panel of 50 layers builds nothing and replays; so do the frames after it. +#[trial] +fn an_idle_panel_builds_nothing_and_replays() { + let mut rig = rig(FakeLayers::fifty()); + for _ in 0..3 { + rig.frame(); + assert_eq!(rig.builds(), 0, "an idle frame builds no display order"); + assert_eq!(rig.host_runs(), (0, 1), "the host view replays"); + } +} + +/// One layer edit through the `Tracked` builds the display order once and runs the view once, then it replays. +#[trial] +fn one_layer_edit_builds_once() { + let mut rig = rig(FakeLayers::fifty()); + rig.tree.borrow_mut().layers[3].info.name = String::from("Renamed"); + rig.frame(); + assert_eq!(rig.builds(), 1, "the edit builds the display order once"); + assert_eq!(rig.host_runs().0, 1, "and runs the view once"); + rig.frame(); + assert_eq!(rig.builds(), 0, "the next pass builds nothing"); + assert_eq!(rig.host_runs(), (0, 1), "and replays"); +} + +/// A filter change builds the display order once. +#[trial] +fn a_filter_change_builds_once() { + let mut rig = rig(FakeLayers::fifty()); + { + let mut filter = rig.filter.borrow_mut(); + filter.by = FilterBy::Name; + filter.name = String::from("mark"); + } + rig.frame(); + assert_eq!(rig.builds(), 1, "the filter builds the display order once"); + rig.frame(); + assert_eq!(rig.builds(), 0, "the next pass builds nothing"); + assert_eq!(rig.host_runs(), (0, 1), "and the view replays"); +} + +/// A pass that runs the view for another reason, the pointer over it, keeps the display order. +#[trial] +fn a_pass_that_runs_the_view_for_the_pointer_builds_nothing() { + let mut rig = rig(FakeLayers::fifty()); + rig.fixture.frame(vec![pointer::moved(egui::Pos2::new(100.0, 200.0))]); + assert_eq!(rig.host_runs().0, 1, "the pointer over the panel runs the view"); + assert_eq!(rig.builds(), 0, "and the display order is kept"); +} + +/// An event from a click reaches the host once, in the run that produced it, and not again while the view replays. +#[trial] +fn a_clicks_event_is_delivered_once_across_the_run_and_the_replays() { + let mut rig = rig(FakeLayers::sample()); + let row = rig.fixture.by_label("Title").expect("the Title row shows"); + rig.seen.borrow_mut().clear(); + rig.fixture.click(&row).idle(4); + let selects = rig.seen.borrow().iter().filter(|event| matches!(event, LayersEvent::Select(_))).count(); + assert_eq!(selects, 1, "{:?}", rig.seen.borrow()); +} diff --git a/crates/layers/tests/it/panel_order.rs b/crates/layers/tests/it/panel_order.rs index 1dda63bdb..51664da0d 100644 --- a/crates/layers/tests/it/panel_order.rs +++ b/crates/layers/tests/it/panel_order.rs @@ -1,11 +1,11 @@ //! `LayersPanel`: the order of the rows, a filter over them and where a Smart Filter drop lands. use craft_behavior::EditEvent; -use craft_layers::ui::filter::{FilterKind, LayerFilter}; +use craft_layers::ui::filter::LayerFilter; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayerDrop, LayerPosition, LayersEvent, LayersPanel}; -use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerRowKey, LayerTree, SubRowGroup}; -use craft_ui::contract::Bind; +use craft_layers::ui::tree::{LayerRowKey, LayerTree, SubRowGroup}; +use craft_ui::contract::{Bind, PlainData, Tracked}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Pos2, Vec2}; use std::cell::RefCell; @@ -22,17 +22,16 @@ const ONE_PANEL: Vec2 = by(400.0, 560.0); type Seen = Rc>>>; type Shared = Rc>; -/// What a rig holds: the fixture, the events its panel reported, the tree and the filter it shows. -struct Rig { +/// What a rig holds: the fixture, the events its panel reported, and the tracked tree it shows. +struct Rig { fixture: Fixture, seen: Seen, - tree: Shared, - filter: Shared, + tree: Shared>, } fn rig_of + 'static>(tree: T) -> Rig { let seen: Seen = Rc::default(); - let tree = Rc::new(RefCell::new(tree)); + let tree = Rc::new(RefCell::new(Tracked::new(tree))); let filter: Shared = Rc::default(); let (sink, shown, by) = (Rc::clone(&seen), Rc::clone(&tree), Rc::clone(&filter)); let mut fixture = Fixture::new(move |ui| { @@ -43,14 +42,14 @@ fn rig_of + 'static>(tree: T) -> Rig { }); fixture.room(ONE_PANEL); fixture.settle(); - Rig { fixture, seen, tree, filter } + Rig { fixture, seen, tree } } fn rig() -> Rig { rig_of(FakeLayers::sample()) } -impl Rig { +impl Rig { fn row(&self, label: &str) -> Target { self.fixture.by_label(label).unwrap_or_else(|| panic!("no row named {label}")) } @@ -140,19 +139,6 @@ fn rows_are_listed_top_first_and_closed_groups_hide_their_layers() { assert_eq!(rig.order(&all), all); } -/// A filter reads fields the tree revision does not cover, so it applies even while the revision stands. -#[trial] -fn a_filter_applies_even_while_the_tree_revision_stands() { - let mut rig = rig(); - rig.tree.borrow_mut().revision = Some(1); - rig.filter.borrow_mut().kinds = vec![FilterKind::Pixel]; - rig.fixture.idle(3); - assert!(rig.fixture.by_label("Clipped").is_some()); - rig.tree.borrow_mut().layers[1].info = LayerInfo::new("Clipped", LayerKind::Text); - rig.fixture.idle(3); - assert!(rig.fixture.by_label("Clipped").is_none(), "a kind change shows at the same revision"); -} - /// A Smart Filter moves within its own object, with the slot counted after taking it out; effects keep their order. #[trial] fn smart_filters_reorder_within_their_object_and_effects_keep_their_order() { diff --git a/crates/layers/tests/it/panel_reveal.rs b/crates/layers/tests/it/panel_reveal.rs index 59d691d35..f611cc7a2 100644 --- a/crates/layers/tests/it/panel_reveal.rs +++ b/crates/layers/tests/it/panel_reveal.rs @@ -4,6 +4,7 @@ use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{Groups, LayersEvent, LayersPanel}; use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection}; +use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Vec2}; use std::cell::{Cell, RefCell}; @@ -49,7 +50,7 @@ fn short() -> FakeLayers { struct Rig { fixture: Fixture, - docs: Vec>, + docs: Vec>>, /// The document shown, by its position in `docs`. shown: Rc>, reveal: Rc>>, @@ -59,7 +60,7 @@ struct Rig { /// The panel over the documents `docs`, each keyed by its position when there are several. The host applies the /// panel's opens in the pass that reports them, as an app does. fn rig(docs: Vec) -> Rig { - let docs: Vec> = docs.into_iter().map(|tree| Rc::new(RefCell::new(tree))).collect(); + let docs: Vec>> = docs.into_iter().map(|tree| Rc::new(RefCell::new(Tracked::new(tree)))).collect(); let keyed = docs.len() > 1; let shown: Rc> = Rc::default(); let reveal: Rc>> = Rc::default(); diff --git a/crates/layers/tests/it/panel_rows.rs b/crates/layers/tests/it/panel_rows.rs index f5acee6e2..95bdc7818 100644 --- a/crates/layers/tests/it/panel_rows.rs +++ b/crates/layers/tests/it/panel_rows.rs @@ -6,6 +6,7 @@ use craft_layers::testing; use craft_layers::ui::mock::{FakeLayers, sub_row}; use craft_layers::ui::panel::{ActivateOn, LayerDrop, LayersEvent, LayersPanel, MaskMove}; use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerRowKey, LayerSelection, MaskInfo, SubRow, SubRowGroup, SubRows}; +use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; @@ -19,7 +20,7 @@ const SMART: u32 = 2; /// The app around the panel: the tree it shows, what it reported and the layer it last called hovered. struct App { - tree: FakeLayers, + tree: Tracked, events: Vec>, hovered: Option, } @@ -58,12 +59,12 @@ fn apply(tree: &mut FakeLayers, event: &LayersEvent) { } fn rig(tree: FakeLayers) -> (Fixture, Shared) { - let app = Rc::new(RefCell::new(App { tree, events: Vec::new(), hovered: None })); + let app = Rc::new(RefCell::new(App { tree: Tracked::new(tree), events: Vec::new(), hovered: None })); let shared = Rc::clone(&app); let mut fixture = Fixture::new(move |ui| { let mut app = shared.borrow_mut(); let App { tree, events, hovered } = &mut *app; - let out = LayersPanel::new(&*tree).show(ui); + let out = LayersPanel::new(tree).show(ui); for event in &out.events { apply(tree, event); } @@ -400,12 +401,11 @@ fn long(count: usize) -> (FakeLayers, u32) { layer.effects_open = true; layer.smart_filters = Some(SubRows::new(SubRow::new("Smart Filters"), vec![sub_row("Gaussian Blur"), sub_row("Sharpen")])); tree.selection = LayerSelection::new(vec![1], Some(1), LayerPart::Pixels); - tree.revision = Some(1); (tree, id) } -/// FW15: a long layer list asks the app only for the rows in view: a settled frame makes as many `info` and -/// `sub_rows` calls for 2,000 layers as for 200, and an off-screen group or Smart Filter row lays out nothing. +/// FW15: a long layer list builds only the rows in view: a settled frame builds as many rows for 2,000 layers as +/// for 200, and an off-screen group or Smart Filter row lays out nothing. /// Scrolled into view they show; a filter selected there stays selected after it scrolls away again. #[trial] fn a_long_layer_list_asks_only_for_the_rows_in_view() { @@ -413,9 +413,8 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() { for count in [200, 2_000] { let (tree, smart) = long(count); let (mut fixture, app) = rig(tree); - let _ = (app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls()); fixture.frame(vec![]); - calls.push((app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls())); + calls.push(craft_ui::testing::row_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum::()); for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] { assert!(fixture.by_label(name).is_none(), "{count} layers: the off-screen row {name:?} lays out nothing"); } @@ -444,5 +443,6 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() { assert!(take(&app).iter().all(|event| !matches!(event, LayersEvent::Select(_))), "{count} layers: scrolling selects nothing"); assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter stays selected"); } - assert_eq!(calls[0], calls[1], "a settled frame asks for as many rows for 2,000 layers as for 200 (info, sub_rows)"); + assert!(calls[0] > 0, "the rows in view are built"); + assert_eq!(calls[0], calls[1], "a settled frame builds as many rows for 2,000 layers as for 200"); } From ef60cb99a5ed100aa620100af0f4c9e7aa962701 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 12:56:51 +0000 Subject: [PATCH 09/89] craft-theme: LabelColor is plain data and memo props craft-layers no longer marks its LabelColor fields: the type derives PlainData in craft-theme (a tier-0 crate, as craft-behavior is), and the contract crate keys it as it keys the other theme types. --- Cargo.lock | 2 ++ crates/layers/src/ui/filter/mod.rs | 1 - crates/layers/src/ui/tree.rs | 1 - crates/theme/Cargo.toml | 2 ++ crates/theme/src/parts.rs | 2 +- crates/ui-contract/src/contract/memo.rs | 7 +++++++ 6 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2fe181826..881c49f6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4152,6 +4152,8 @@ name = "craft-theme" version = "0.1.0" dependencies = [ "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", "ecolor", "log", "proptest", diff --git a/crates/layers/src/ui/filter/mod.rs b/crates/layers/src/ui/filter/mod.rs index d37261ae1..083aba700 100644 --- a/crates/layers/src/ui/filter/mod.rs +++ b/crates/layers/src/ui/filter/mod.rs @@ -354,7 +354,6 @@ pub struct LayerFilter { /// Color: the label colour; `None` (no label) at first. Serialized by name (`"none"`, `"red"`, /// … `"gray"`). #[serde(with = "label_name")] - #[memo_props(hash = "a plain enum with a derived Hash")] pub color: Option, /// Smart Object: the kinds toggled on, in the order they were toggled. pub smart: Vec, diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index 164295075..d8f10d5cd 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -127,7 +127,6 @@ pub struct LayerInfo { /// Whether the row draws faint: hidden itself or inside a hidden group (the app decides). pub dimmed: bool, /// The label colour that fills the eye cell; `None` for none. - #[plain_data(assume = "a plain Copy enum of colours")] pub label: Option, /// The layer's locks: any of them shows the lock indicator. pub locks: LayerLocks, diff --git a/crates/theme/Cargo.toml b/crates/theme/Cargo.toml index 4102c7127..6417fe894 100644 --- a/crates/theme/Cargo.toml +++ b/crates/theme/Cargo.toml @@ -10,6 +10,8 @@ repository.workspace = true [dependencies] bitflags = { workspace = true } +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } ecolor = { workspace = true } serde = { workspace = true } smallvec = { workspace = true } diff --git a/crates/theme/src/parts.rs b/crates/theme/src/parts.rs index ad9512ab5..c08e1e7c2 100644 --- a/crates/theme/src/parts.rs +++ b/crates/theme/src/parts.rs @@ -330,7 +330,7 @@ pub struct BorderColors { } /// PhotoCraft's layer label colours (`LabelColor`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)] pub enum LabelColor { #[allow(missing_docs)] Red, diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index a6f800f5d..791e1a7f7 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -958,6 +958,13 @@ impl MemoProps for craft_theme::variant::Tone { } } +/// Derived `Hash` over a unit enum. +impl MemoProps for craft_theme::LabelColor { + 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. From 47379d792c4609db3112944f746e87136bb24f3c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 13:09:00 +0000 Subject: [PATCH 10/89] Chords, command refs and colours are plain data; the keymap generation is public --- Cargo.lock | 2 ++ crates/keymap/Cargo.toml | 3 +++ crates/keymap/src/chord.rs | 6 +++--- crates/keymap/src/command.rs | 3 ++- crates/theme/src/color.rs | 2 +- crates/ui-contract/src/runtime/commands/board.rs | 11 +++++++++-- crates/ui-contract/src/runtime/commands/mod.rs | 4 ++-- crates/ui-contract/src/runtime/inputs.rs | 2 +- 8 files changed, 23 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 881c49f6c..cb611a042 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3110,6 +3110,8 @@ dependencies = [ "craft-host", "craft-i18n", "craft-settings", + "craft-tracked", + "craft-ui-macros", "craft-xml", "egui", "serde", diff --git a/crates/keymap/Cargo.toml b/crates/keymap/Cargo.toml index 6a693d2b0..61beb609a 100644 --- a/crates/keymap/Cargo.toml +++ b/crates/keymap/Cargo.toml @@ -19,6 +19,9 @@ craft-xml = { workspace = true } egui = { workspace = true, optional = true } craft-i18n = { workspace = true } craft-host = { workspace = true } +# Chords and command refs are held in `Tracked` models. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } [dev-dependencies] # `serde` for setting `RawInput` fields only the suite's egui fork has. diff --git a/crates/keymap/src/chord.rs b/crates/keymap/src/chord.rs index 86c410798..6a069d7db 100644 --- a/crates/keymap/src/chord.rs +++ b/crates/keymap/src/chord.rs @@ -23,7 +23,7 @@ macro_rules! keys { /// A key on the keyboard, independent of any UI toolkit. /// /// Digits are the main row; numeric keypad keys map to the same keys. - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)] #[non_exhaustive] pub enum Key { $(#[allow(missing_docs)] $variant),* @@ -388,7 +388,7 @@ impl<'de> Deserialize<'de> for Key { } /// Modifier keys held with a chord's key. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Mods { /// The command modifier: ⌘ on macOS, Ctrl on Windows and Linux. pub cmd: bool, @@ -453,7 +453,7 @@ impl Mods { } /// A key with modifiers. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)] pub struct Chord { /// The modifiers held with the key. pub mods: Mods, diff --git a/crates/keymap/src/command.rs b/crates/keymap/src/command.rs index ae0095f7e..8ee338d32 100644 --- a/crates/keymap/src/command.rs +++ b/crates/keymap/src/command.rs @@ -10,13 +10,14 @@ use serde_json::Value; pub const MAX_KEY: usize = 256; /// A command id with the parameters a binding runs it with. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct CommandRef { /// The command's id. pub id: String, /// `Null` for no parameters. #[serde(default)] + #[plain_data(assume = "a JSON value owns its data and has no interior mutability")] pub params: Value, } diff --git a/crates/theme/src/color.rs b/crates/theme/src/color.rs index d0a5eff24..272e7019e 100644 --- a/crates/theme/src/color.rs +++ b/crates/theme/src/color.rs @@ -226,7 +226,7 @@ impl From for Oklch { /// An encoded sRGB colour with float channels in 0..=1 and straight alpha: the value a colour /// picker edits. Eight bits lose the precision that HSB and OKLCH edits need. -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui_macros::PlainData)] pub struct Srgba { /// Red, encoded. pub r: f32, diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index e80cfddde..97cb94bbc 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -1113,11 +1113,18 @@ pub(crate) fn edit_chords(ctx: &Context) -> Arc<[(EditCommand, Chord)]> { with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.edit_chords)).unwrap_or_default()) } -/// The generation of the window's keymap: it moves each time a new keymap is built. -pub(crate) fn keymap_generation(ctx: &Context) -> u64 { +/// The generation of the window's keymap without noting a read: it moves each time a new keymap is built. +pub(crate) fn keymap_built(ctx: &Context) -> u64 { with(ctx, |board| board.keymaps) } +/// The generation of the window's keymap, for a key that holds what is derived from its chords: it moves each time a +/// new keymap is built. The caller's view reads the keymap, so a change of it runs the view. +pub fn keymap_generation(ctx: &Context) -> u64 { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); + keymap_built(ctx) +} + /// Whether the queue holds a command for one of `instances`: only a run of the view they registered in takes it. pub(crate) fn queued_for(ctx: &Context, instances: &[Id]) -> bool { !instances.is_empty() && with(ctx, |board| board.queue.iter().any(|fired| fired.target.is_some_and(|target| instances.contains(&target)))) diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index c53e067da..a41db0e7e 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -29,12 +29,12 @@ pub(crate) use board::{ begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts, }; #[doc(hidden)] -pub use board::{bound_around, take_around}; +pub use board::{bound_around, keymap_generation, take_around}; #[cfg(feature = "testing")] #[doc(hidden)] pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; -pub(crate) use board::{keymap_generation, queued_for}; +pub(crate) use board::{keymap_built, queued_for}; use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked}; use craft_behavior::CommandFlags; diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 8b4e3eb3d..4c3d8d51c 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -124,7 +124,7 @@ pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)), Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), - Input::Keymap => return crate::runtime::commands::keymap_generation(ctx), + Input::Keymap => return crate::runtime::commands::keymap_built(ctx), Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} } with(ctx, |generations| generations.gens[input as usize]) From 49758ecee88f37ed06169c836de2de5c868db6ab Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 13:09:00 +0000 Subject: [PATCH 11/89] craft-menu: the menu model is plain data, from_items groups rows in one pass, tidy works in place --- crates/menu/src/layout.rs | 6 +- crates/menu/src/model.rs | 130 ++++++++++++++++++++------------------ crates/menu/src/theme.rs | 6 +- 3 files changed, 76 insertions(+), 66 deletions(-) diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index 8c5053f27..fd1627385 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -389,7 +389,9 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar { Node::Standard { .. } if !appkit => None, other => Some(other.clone()), }); - tidy(shown.collect()) + let mut kept: Vec = shown.collect(); + tidy(&mut kept); + kept } let on = target.platforms(); let menus = bar.menus.iter().map(|m| Menu { children: keep(&m.children, on, target == Target::Mac), ..m.clone() }).collect(); @@ -428,7 +430,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str, /// Tidy every menu and drop the ones the moves emptied, unless `keep_empty`. fn finish(bar: &mut MenuBar, keep_empty: impl Fn(&Menu) -> bool) { for m in &mut bar.menus { - m.children = tidy(std::mem::take(&mut m.children)); + tidy(&mut m.children); } bar.menus.retain(|m| !m.children.is_empty() || keep_empty(m)); } diff --git a/crates/menu/src/model.rs b/crates/menu/src/model.rs index 164db097d..867b86bb7 100644 --- a/crates/menu/src/model.rs +++ b/crates/menu/src/model.rs @@ -1,6 +1,7 @@ //! The menu tree, the flat rows it can be built from, and the keys that tell a backend what //! changed. +use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use std::ops::BitOr; @@ -8,7 +9,7 @@ use craft_keymap::{Chord, CommandRef, Mods}; use craft_theme::Srgba; /// The app's menus, in order, and its open documents. -#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct MenuBar { /// The top-level menus, left to right. @@ -18,7 +19,7 @@ pub struct MenuBar { } /// An open document, listed in the Window menu. -#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct Document { /// What choosing it runs (bring the document to the front). @@ -51,7 +52,7 @@ impl Document { } /// A top-level menu. -#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct Menu { /// The title in the bar. @@ -64,7 +65,7 @@ pub struct Menu { /// What a top-level menu is for, set by the app. macOS treats the app, Window and Help menus /// specially; File is where the system Close Window item goes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum MenuRole { /// Any menu without a fixed place. @@ -85,7 +86,7 @@ pub enum MenuRole { } /// The platforms an item or submenu is shown on. All of them by default. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] pub struct Platforms(u8); impl Platforms { @@ -132,7 +133,7 @@ impl BitOr for Platforms { } /// One entry of a menu. -#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum Node { /// An item the user can choose. @@ -162,7 +163,7 @@ pub enum Node { } /// One menu item: a command with its label, shortcut and state. -#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct Item { /// What the item runs: the app's command (`file.open`), with its parameters @@ -198,7 +199,7 @@ pub struct Item { /// The command a row runs while `mods` are held as it is chosen (Alt on Merge Visible runs Stamp /// Visible). -#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct Alternate { /// The modifiers that select the alternate. @@ -222,7 +223,7 @@ impl Alternate { } /// A plain item, or one with a checked state. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum ItemKind { /// An ordinary item. @@ -247,7 +248,7 @@ impl ItemKind { /// Items the layouts put in fixed places. The app tags its own About, Settings, Quit, Appearance /// and Language items; the Mac layout adds Hide and Minimize. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum ItemRole { /// The About item. @@ -268,7 +269,7 @@ pub enum ItemRole { } /// The items AppKit provides. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum Standard { #[allow(missing_docs)] @@ -307,7 +308,7 @@ pub(crate) fn label_or_system(label: &str, english: &str, system: impl FnOnce(&s /// The commands of the items the crate adds itself. The crate runs them; an app sees them only /// in a layout's result. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum Builtin { /// Hide the app: a custom item, because AppKit's own always takes ⌘H, which apps often bind. @@ -653,73 +654,78 @@ impl Row { /// The menus as a tree, from flat rows, in the order an in-window bar draws them: one menu per /// entry of `tops`, and at each depth leaves and separators in order, with a submenu where its -/// first row is. The result is [`tidy`]. +/// first row is. The result is [`tidy`]. Each row is visited once per depth of its path. pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar { + /// One entry of a level in order: a row of the level itself, or the group of rows under a submenu name. + enum Slot<'r> { + Leaf(&'r Row), + Group(&'r str, Vec<&'r Row>), + } fn level(rows: &[&Row], depth: usize) -> Vec { - let mut out = Vec::new(); - let mut shown: Vec<&str> = Vec::new(); + let mut slots: Vec> = Vec::new(); + let mut groups: HashMap<&str, usize> = HashMap::new(); for it in rows { if it.path.len() == depth { - if it.label == "---" { - out.push(Node::Separator); - } else { - out.push(Node::Item(Item { - shortcut: it.shortcut, - enabled: it.enabled, - kind: it.kind, - tint: it.tint, - tooltip: it.tooltip.clone(), - alternate: it.alternate.clone(), - ..Item::new(it.command.clone(), it.label.clone()) - })); - } + slots.push(Slot::Leaf(it)); } else if let Some(name) = it.path.get(depth) { - let name = name.as_str(); - if shown.contains(&name) { - continue; + let at = *groups.entry(name.as_str()).or_insert_with(|| { + slots.push(Slot::Group(name.as_str(), Vec::new())); + slots.len() - 1 + }); + if let Slot::Group(_, members) = &mut slots[at] { + members.push(it); } - shown.push(name); - let child: Vec<&Row> = rows.iter().copied().filter(|c| c.path.get(depth).map(String::as_str) == Some(name)).collect(); - out.push(Node::submenu(name, level(&child, depth + 1))); } } - tidy(out) + let mut out = Vec::with_capacity(slots.len()); + for slot in slots { + match slot { + Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator), + Slot::Leaf(it) => out.push(Node::Item(Item { + shortcut: it.shortcut, + enabled: it.enabled, + kind: it.kind, + tint: it.tint, + tooltip: it.tooltip.clone(), + alternate: it.alternate.clone(), + ..Item::new(it.command.clone(), it.label.clone()) + })), + Slot::Group(name, members) => out.push(Node::submenu(name, level(&members, depth + 1))), + } + } + tidy(&mut out); + out } - let menus = tops - .iter() - .map(|top| { - let rows: Vec<&Row> = rows.iter().filter(|r| r.path.first().map(String::as_str) == Some(*top)).collect(); - Menu::new(*top, level(&rows, 1)) - }) - .collect(); + let mut by_top: HashMap<&str, Vec<&Row>> = HashMap::new(); + for row in rows { + if let Some(top) = row.path.first() { + by_top.entry(top.as_str()).or_default().push(row); + } + } + let menus = tops.iter().map(|top| Menu::new(*top, level(by_top.get(top).map_or(&[][..], Vec::as_slice), 1))).collect(); MenuBar { menus, documents: Vec::new() } } /// Drop separators at the start or end of a level and collapse runs of them, and drop empty -/// submenus, at every depth. A submenu holding only a disabled placeholder (`No Recent Files`) +/// submenus, at every depth, in place. A submenu holding only a disabled placeholder (`No Recent Files`) /// stays. -pub fn tidy(nodes: Vec) -> Vec { - let mut out: Vec = Vec::with_capacity(nodes.len()); - for n in nodes { - let n = match n { - Node::Submenu { label, children, role, platforms } => { - let children = tidy(children); - if children.is_empty() { - continue; - } - Node::Submenu { label, children, role, platforms } +pub fn tidy(nodes: &mut Vec) { + let mut previous_separator = true; + nodes.retain_mut(|node| { + if let Node::Submenu { children, .. } = node { + tidy(children); + if children.is_empty() { + return false; } - other => other, - }; - if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) { - continue; } - out.push(n); + let separator = matches!(node, Node::Separator); + let keep = !(separator && previous_separator); + previous_separator = separator; + keep + }); + while matches!(nodes.last(), Some(Node::Separator)) { + nodes.pop(); } - while matches!(out.last(), Some(Node::Separator)) { - out.pop(); - } - out } /// A hash of everything a native menu can only change by rebuilding: menus, roles, item diff --git a/crates/menu/src/theme.rs b/crates/menu/src/theme.rs index cdc380930..8d53cf586 100644 --- a/crates/menu/src/theme.rs +++ b/crates/menu/src/theme.rs @@ -131,7 +131,8 @@ impl ThemeMenu { nodes.extend(self.mode_groups(|_| true)); nodes.push(Node::Separator); nodes.push(Node::Item(Item::new(ThemeChoice::NextMode.command(), labels.toggle.as_str()))); - tidy(nodes) + tidy(&mut nodes); + nodes } /// The rows for a quick menu: the Appearance Settings row running `settings`, then the @@ -139,7 +140,8 @@ impl ThemeMenu { pub fn favorite_items(&self, labels: &ThemeLabels, settings: CommandRef) -> Vec { let mut nodes = vec![Node::Item(Item::new(settings, labels.settings.as_str())), Node::Separator]; nodes.extend(self.mode_groups(|r| self.favorites.contains(&r.id))); - tidy(nodes) + tidy(&mut nodes); + nodes } /// The "Appearance" submenu, tagged [`crate::ItemRole::Appearance`]. From d395d4f831a68be047f3a087a9e1957b90d54d69 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 17:04:18 +0000 Subject: [PATCH 12/89] Component sets: the app's set of component looks as a root env value craft-theme gets `ComponentSet { Creative, Office }`: the app states its set in `AppDefaults::set`, the user's own choice for the app (`AppChoice::set`) overrides it, and `Selection::set` carries the result. The suite's choice never carries a set. ui-contract makes the set a style-affecting env value: `RootEnv::set` puts it in the root app values, a container overrides it for its subtree through `Overrides::values`, and windows, layers and popups take the scope's value. A component reads it in `style` with `StyleCx::set`. `Fixture::set` sets it in tests. The gallery gets a Set choice in the More popover and a Set axis in the Variants view. --- crates/theme-store/src/lib.rs | 5 +-- crates/theme-store/src/tests.rs | 3 +- crates/theme-store/src/watch/tests.rs | 3 +- crates/theme/src/lib.rs | 4 +-- crates/theme/src/selection.rs | 37 +++++++++++++++++--- crates/theme/tests/main.rs | 1 + crates/theme/tests/selection.rs | 25 +++++++++++++ crates/ui-contract/src/runtime/env/root.rs | 13 ++++++- crates/ui-contract/src/runtime/env/values.rs | 23 +++++++++++- crates/ui-contract/src/style/cx.rs | 5 +++ crates/ui-contract/src/testing/fixture.rs | 5 +++ crates/ui-gallery/src/chrome/card.rs | 5 +++ crates/ui-gallery/src/chrome/options.rs | 11 ++++-- crates/ui-gallery/src/chrome/variants.rs | 12 +++++-- crates/ui-gallery/src/viewer/appearance.rs | 9 +++-- crates/ui-gallery/src/viewer/mod.rs | 2 +- crates/ui-gallery/src/viewer/settings.rs | 6 +++- 17 files changed, 149 insertions(+), 20 deletions(-) create mode 100644 crates/theme/tests/selection.rs diff --git a/crates/theme-store/src/lib.rs b/crates/theme-store/src/lib.rs index ce039617d..9ff9fff52 100644 --- a/crates/theme-store/src/lib.rs +++ b/crates/theme-store/src/lib.rs @@ -15,7 +15,7 @@ //! `craft-theme`. //! //! ``` -//! use craft_theme::{ThemeId, AppDefaults, ModeChoice, Size, ThemePair}; +//! use craft_theme::{ThemeId, AppDefaults, ComponentSet, ModeChoice, Size, ThemePair}; //! use craft_theme_store::{SelectionChange, Store, StoreOptions, SuiteDir}; //! //! let mut store = Store::open(&SuiteDir::memory(), StoreOptions::new("doc 1.0")); @@ -30,7 +30,8 @@ //! assert_eq!((accepted.suite.theme_dark.as_ref(), accepted.suite.mode, accepted.revision), (Some(&graphite.id), None, 1)); //! //! let artcraft = ThemeId::parse("craft.artcraft").unwrap(); -//! let defaults = AppDefaults { theme: ThemePair::same(artcraft), mode: ModeChoice::Dark, size: Size::Compact, sizes: Default::default() }; +//! let defaults = +//! AppDefaults { theme: ThemePair::same(artcraft), mode: ModeChoice::Dark, size: Size::Compact, sizes: Default::default(), set: ComponentSet::Office }; //! let selection = accepted.suite.with_defaults(&defaults); //! assert_eq!((selection.theme.light, selection.mode), (graphite.id, ModeChoice::Dark)); //! ``` diff --git a/crates/theme-store/src/tests.rs b/crates/theme-store/src/tests.rs index 62a41a71a..51345c712 100644 --- a/crates/theme-store/src/tests.rs +++ b/crates/theme-store/src/tests.rs @@ -3,7 +3,7 @@ use craft_ui::testing::trial; use std::{fs, path::Path, time::Duration}; -use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Selection, Size, TextSize, ThemeId, ThemePair}; +use craft_theme::{ComponentSet, ContrastChoice, ModeChoice, MotionChoice, Selection, Size, TextSize, ThemeId, ThemePair}; use crate::{ Accepted, FileStamp, Problem, SelectionChange, SelectionError, Store, StoreError, StoreOptions, SuiteDir, @@ -31,6 +31,7 @@ fn sel(theme: &str, mode: ModeChoice) -> Selection { motion: MotionChoice::System, size: Size::Compact, text_size: TextSize::Small, + set: ComponentSet::Creative, } } diff --git a/crates/theme-store/src/watch/tests.rs b/crates/theme-store/src/watch/tests.rs index 094c505ae..2ebfd5d9f 100644 --- a/crates/theme-store/src/watch/tests.rs +++ b/crates/theme-store/src/watch/tests.rs @@ -11,7 +11,7 @@ use std::{ time::{Duration, Instant}, }; -use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Selection, Size, TextSize, ThemeId, ThemePair}; +use craft_theme::{ComponentSet, ContrastChoice, ModeChoice, MotionChoice, Selection, Size, TextSize, ThemeId, ThemePair}; use super::SuiteWatch; use crate::{Accepted, SelectionChange, Store, StoreOptions, SuiteDir}; @@ -33,6 +33,7 @@ fn sel(theme: &str, mode: ModeChoice) -> Selection { motion: MotionChoice::System, size: Size::Compact, text_size: TextSize::Small, + set: ComponentSet::Creative, } } diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index 3bed2c09f..1064277b1 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -86,8 +86,8 @@ pub use ramp::{Mode, Ramp, RampKind}; pub use resolve::{Resolved, resolve, resolve_sized}; pub use scale::{Duration, Easing, Elevation, Opacity, Radius, Space, Stroke}; pub use selection::{ - AppChoice, AppDefaults, ContrastChoice, Fallback, ModeChoice, MotionChoice, Selection, Shown, SuiteChoice, SystemAppearance, ThemePair, - resolve_selection, + AppChoice, AppDefaults, ComponentSet, ContrastChoice, Fallback, ModeChoice, MotionChoice, Selection, Shown, SuiteChoice, SystemAppearance, + ThemePair, resolve_selection, }; pub use stateful::{FlagMask, Flags, Mix, Resolve, StateMix, Stateful}; pub use theme::{ diff --git a/crates/theme/src/selection.rs b/crates/theme/src/selection.rs index 970a4f7c1..b4e77a9d5 100644 --- a/crates/theme/src/selection.rs +++ b/crates/theme/src/selection.rs @@ -1,4 +1,4 @@ -//! What the user picked (theme per mode, mode, contrast, motion, size, text size), how the suite's +//! What the user picked (theme per mode, mode, contrast, motion, size, text size, component set), how the suite's //! choice, an app's own choice and the app's defaults combine, and resolution of the result //! against what the OS reports. @@ -112,6 +112,19 @@ impl ThemePair { } } +/// The set of component looks an app shows: each component that has variants maps the set to one of them (a ruler's +/// face, for one), and every other component looks the same in each set. A component stays functionally identical +/// across sets. The app states its set ([`AppDefaults::set`]); the suite's choice never carries one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ComponentSet { + /// The look the creative apps' users expect. + #[default] + Creative, + /// The look the office apps' users expect. + Office, +} + /// What the user picked, every field concrete (after defaults are filled in). #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Selection { @@ -127,6 +140,9 @@ pub struct Selection { pub size: Size, /// The text size. pub text_size: TextSize, + /// The component set: the app's own, never the suite's. + #[serde(default)] + pub set: ComponentSet, } /// The suite's choice as `selection.json` holds it. Each field is set once a user picks it in @@ -167,6 +183,7 @@ impl SuiteChoice { motion: self.motion.unwrap_or_default(), size: self.size.unwrap_or(defaults.size), text_size: self.text_size.unwrap_or_default(), + set: defaults.set, } } @@ -210,6 +227,8 @@ pub struct AppDefaults { /// The app's own sizes: base overrides and component pins, applied to whichever size set is /// chosen. pub sizes: AppSizes, + /// The component set the app shows when the user hasn't chosen one for it. + pub set: ComponentSet, } /// An app's own choice, kept in the app's preferences: "Use a different theme / mode / size in @@ -226,12 +245,15 @@ pub struct AppChoice { pub mode: Option, /// The app's own size set. pub size: Option, + /// The app's own component set. No user-visible choice sets it yet. + #[serde(default)] + pub set: Option, } impl AppChoice { - /// A choice with all three fields given. + /// A choice of theme, mode and size; the component set follows the app's default. pub const fn new(theme: Option, mode: Option, size: Option) -> Self { - Self { theme, mode, size } + Self { theme, mode, size, set: None } } /// This choice with the app's own mode. @@ -246,12 +268,19 @@ impl AppChoice { self } - /// `suite` with this app's theme, mode and size where set. + /// This choice with the app's own component set. + pub fn with_set(mut self, set: ComponentSet) -> Self { + self.set = Some(set); + self + } + + /// `suite` with this app's theme, mode, size and component set where set. pub fn apply(&self, suite: &Selection) -> Selection { Selection { theme: self.theme.clone().unwrap_or_else(|| suite.theme.clone()), mode: self.mode.unwrap_or(suite.mode), size: self.size.unwrap_or(suite.size), + set: self.set.unwrap_or(suite.set), ..suite.clone() } } diff --git a/crates/theme/tests/main.rs b/crates/theme/tests/main.rs index 6eea01a7d..93a7bd1fa 100644 --- a/crates/theme/tests/main.rs +++ b/crates/theme/tests/main.rs @@ -1,3 +1,4 @@ //! Integration tests, built into the library's own test executable. mod dumps; +mod selection; diff --git a/crates/theme/tests/selection.rs b/crates/theme/tests/selection.rs new file mode 100644 index 000000000..6dacfc927 --- /dev/null +++ b/crates/theme/tests/selection.rs @@ -0,0 +1,25 @@ +//! The component set: the app states it, the user's own choice for the app overrides it, and the suite's choice never +//! carries it. + +use craft_theme::{AppChoice, AppDefaults, ComponentSet, ModeChoice, Size, SuiteChoice, ThemeId, ThemePair}; + +#[test] +fn the_component_set_is_the_apps_unless_the_user_chose_one_for_it_and_never_the_suites() { + let defaults = AppDefaults { + theme: ThemePair::same(ThemeId::suite_default()), + mode: ModeChoice::Light, + size: Size::Comfortable, + sizes: Default::default(), + set: ComponentSet::Office, + }; + let suite = SuiteChoice::default().with_defaults(&defaults); + assert_eq!(suite.set, ComponentSet::Office, "a fresh install shows the app's set"); + let follows = AppChoice::new(None, None, None).apply(&suite); + assert_eq!(follows.set, ComponentSet::Office, "an app choice without a set keeps the app's"); + let own = AppChoice::new(None, None, None).with_set(ComponentSet::Creative).apply(&suite); + assert_eq!(own.set, ComponentSet::Creative, "the user's set for the app wins"); + let stored: AppChoice = serde_json::from_str(r#"{"theme":null,"mode":null,"size":null}"#).expect("a stored choice without a set reads"); + assert_eq!(stored.apply(&suite).set, ComponentSet::Office); + let shared = SuiteChoice::from(own); + assert_eq!(shared.with_defaults(&defaults).set, ComponentSet::Office, "the suite's choice carries no set to other apps"); +} diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index d2433b696..23fc27c0b 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -8,7 +8,7 @@ use craft_behavior::MotionMode; use craft_i18n::CalendarDate; use craft_i18n::Direction; use craft_theme::{ - AppSizes, Appearance, Contrast, ContrastChoice, Mode, ModeChoice, MotionChoice, Size, SystemAppearance, TextSize, ThemeDef, ThemeId, + AppSizes, Appearance, ComponentSet, Contrast, ContrastChoice, Mode, ModeChoice, MotionChoice, Size, SystemAppearance, TextSize, ThemeDef, ThemeId, }; use egui::Context; use std::sync::Arc; @@ -198,6 +198,17 @@ impl RootEnv { self } + /// Sets the component set (`Selection::set`): a root app value, so a container can set another for its subtree. + pub fn set(mut self, set: ComponentSet) -> Self { + self.values.set(set); + self + } + + /// The component set the root's values carry. + pub fn component_set(&self) -> ComponentSet { + self.values.get::() + } + /// Sets today's date, as the host's clock and time zone give it. pub fn today(mut self, date: CalendarDate) -> Self { self.today = Some(date); diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 2a461ae2b..52591cf9a 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -1,4 +1,4 @@ -//! The library values the env carries: scale, motion policy and arena id. +//! The library values the env carries: scale, motion policy, arena id and the component set. use super::EnvValue; use craft_behavior::{ColumnKey, MotionMode}; @@ -140,6 +140,27 @@ impl EnvValue for InBar { } } +/// The component set: an app sets it on its root (`RootEnv::set`) and a container may set another for its subtree +/// (`Overrides::values`); every window, layer and popup opened inside takes the scope's. A component with variants +/// reads it in `style` (`StyleCx::set`) and maps it to one of them. It is in the style key, so a change restyles as a +/// theme or density change does. +impl EnvValue for craft_theme::ComponentSet { + const AFFECTS_STYLE: bool = true; + + fn root() -> Self { + craft_theme::ComponentSet::default() + } + + fn style_hash(&self) -> Option { + use std::hash::Hasher as _; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + self.hash(&mut hasher); + Some(hasher.finish()) + } +} + +impl super::StyleValue for craft_theme::ComponentSet {} + /// Where a shell pane sits. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index db46b47fc..d82c9f33b 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -136,6 +136,11 @@ impl<'a> StyleCx<'a> { self.tokens.density() } + /// The component set of the scope, for a component that maps it to one of its named variants. + pub fn set(&self) -> craft_theme::ComponentSet { + self.env::() + } + /// A style context for the scope the pipeline or an app colour hook runs in. #[expect(clippy::too_many_arguments, reason = "one argument per input the style cache key covers")] #[doc(hidden)] diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index b2165c890..52ef2f8ac 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -343,6 +343,11 @@ impl Fixture { self.set_root(|root| root.density = density) } + /// The component set. + pub fn set(&mut self, set: craft_theme::ComponentSet) -> &mut Self { + self.root_value(set) + } + /// The interface scale. pub fn scale(&mut self, scale: Scale) -> &mut Self { self.set_root(|root| root.scale = scale) diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index ced8c50c8..a4e6917af 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -53,6 +53,8 @@ pub struct Look { pub direction: Option, /// The control size. pub size: Option, + /// The component set. + pub set: Option, } /// One story a card shows. @@ -434,6 +436,9 @@ impl Host<'_> { env.direction = look.direction; env.size = look.size; env.wheel = gated.then_some(craft_ui::runtime::env::WheelScope::Gated); + if let Some(set) = look.set { + env.values.set(set); + } }, |ui| match region { Some(key) => inspect::record(ui, key, |ui| show(ui, data)), diff --git a/crates/ui-gallery/src/chrome/options.rs b/crates/ui-gallery/src/chrome/options.rs index 5006b1a5a..1c75cfce6 100644 --- a/crates/ui-gallery/src/chrome/options.rs +++ b/crates/ui-gallery/src/chrome/options.rs @@ -2,7 +2,8 @@ //! layout and the workspace switch at the end. use crate::viewer::{ - CONTRASTS, DENSITIES, DIRECTIONS, GalleryCommands, MODES, MOTIONS, Preview, SCALES, TEXT_SIZES, VariantAxis, Viewer, Workspace, theme_entries, + CONTRASTS, DENSITIES, DIRECTIONS, GalleryCommands, MODES, MOTIONS, Preview, SCALES, SETS, TEXT_SIZES, VariantAxis, Viewer, Workspace, + theme_entries, }; use craft_behavior::{IconId, Value}; use craft_ui::bars::{Bar, BarKind}; @@ -40,15 +41,21 @@ fn line(ui: &mut Ui, mut add: impl FnMut(&mut Ui)) { fn more_form(ui: &mut Ui, viewer: &mut Viewer) { let env = &mut viewer.env; let (contrasts, densities, motions) = (CONTRASTS.entries(), DENSITIES.entries(), MOTIONS.entries()); - let (directions, text_sizes, scales) = (DIRECTIONS.entries(), TEXT_SIZES.entries(), SCALES.entries()); + let (directions, text_sizes, scales, sets) = (DIRECTIONS.entries(), TEXT_SIZES.entries(), SCALES.entries(), SETS.entries()); + // The set is a root app value, not a field of the root. + let mut set = env.component_set(); Stack::new().show(ui, |ui, _| { line(ui, |ui| choose(ui, "Contrast", &mut env.contrast, &contrasts)); line(ui, |ui| choose(ui, "Size", &mut env.density, &densities)); + line(ui, |ui| choose(ui, "Set", &mut set, &sets)); line(ui, |ui| choose(ui, "Reduced motion", &mut env.motion, &motions)); line(ui, |ui| choose(ui, "Direction", &mut env.direction, &directions)); line(ui, |ui| choose(ui, "Text", &mut env.text_size, &text_sizes)); line(ui, |ui| pick(ui, "Scale", &mut env.scale, &scales)); }); + if set != env.component_set() { + env.values.set(set); + } } /// The Variants toggle and its menu of axes: the toggle shows whether a Variants view is open, and a press opens the diff --git a/crates/ui-gallery/src/chrome/variants.rs b/crates/ui-gallery/src/chrome/variants.rs index a4eded1ca..d6d7b67ce 100644 --- a/crates/ui-gallery/src/chrome/variants.rs +++ b/crates/ui-gallery/src/chrome/variants.rs @@ -4,7 +4,7 @@ use super::card::Look; use super::overview::{Spec, SpecStory, apply, grid, on_background, selected_type, target_story}; use super::panels::Panels; -use crate::viewer::{DIRECTIONS, MODES, PanelId, VariantAxis, entry_of}; +use crate::viewer::{DIRECTIONS, MODES, PanelId, SETS, VariantAxis, entry_of}; use craft_i18n::Direction; use craft_theme::variant::Tone; use craft_theme::{ControlSize, Mode, ModeChoice}; @@ -29,6 +29,7 @@ fn noun(axis: VariantAxis) -> &'static str { VariantAxis::Mode => "mode", VariantAxis::Contrast => "contrast", VariantAxis::Size => "size", + VariantAxis::Set => "set", VariantAxis::Direction => "direction", VariantAxis::ControlSize => "control size", VariantAxis::DirectionAndControlSize => "direction and control size", @@ -65,6 +66,9 @@ fn values(axis: VariantAxis) -> Option> { .map(|choice| Value { label: choice.label, look: Look { direction: direction(choice.value), ..Look::default() } }) .collect(), ), + VariantAxis::Set => { + Some(SETS.0.iter().map(|choice| Value { label: choice.label, look: Look { set: Some(choice.value), ..Look::default() } }).collect()) + } VariantAxis::ControlSize => { Some(sizes.iter().map(|(size, label)| Value { label, look: Look { size: Some(*size), ..Look::default() } }).collect()) } @@ -122,10 +126,11 @@ pub(super) fn show(ui: &mut Ui, p: &mut Panels<'_>, tab: PanelId) -> bool { let cards: Vec = match (target, values(axis)) { (Some((type_name, index)), Some(values)) => { let Some(entry) = entry_of(type_name) else { return false }; - let (mode, direction) = (p.env.appearance(ui.ctx()).mode, p.env.direction); + let (mode, direction, set) = (p.env.appearance(ui.ctx()).mode, p.env.direction, p.env.component_set()); let shown = |look: &Look| match axis { VariantAxis::Mode => look.mode == Some(mode), VariantAxis::Direction => look.direction == Some(direction), + VariantAxis::Set => look.set == Some(set), _ => false, }; values @@ -180,6 +185,9 @@ pub(super) fn show(ui: &mut Ui, p: &mut Panels<'_>, tab: PanelId) -> bool { if let Some(direction) = card.look.direction { p.env.direction = direction; } + if let Some(set) = card.look.set { + p.env.values.set(set); + } closed = true; } if closed { diff --git a/crates/ui-gallery/src/viewer/appearance.rs b/crates/ui-gallery/src/viewer/appearance.rs index 18469bec1..6b433e7df 100644 --- a/crates/ui-gallery/src/viewer/appearance.rs +++ b/crates/ui-gallery/src/viewer/appearance.rs @@ -1,7 +1,7 @@ //! The choices of the options bar: the named options of each root value, the theme list and the Variants axes. use craft_i18n::Direction; -use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, ThemeDef, ThemeId, builtins}; +use craft_theme::{ComponentSet, ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, ThemeDef, ThemeId, builtins}; use craft_ui::contract::Entry; use craft_ui::runtime::env::Scale; @@ -66,6 +66,7 @@ choices!(TEXT_SIZES: TextSize = [ (TextSize::Large, "large", "Large"), ]); choices!(DENSITIES: Size = [(Size::Compact, "compact", "Compact"), (Size::Comfortable, "comfortable", "Comfortable")]); +choices!(SETS: ComponentSet = [(ComponentSet::Creative, "creative", "Creative"), (ComponentSet::Office, "office", "Office")]); choices!(MOTIONS: MotionChoice = [ (MotionChoice::Full, "full", "Off"), (MotionChoice::Reduced, "reduced", "On"), @@ -91,6 +92,8 @@ pub enum VariantAxis { Contrast, /// Compact and comfortable density. Size, + /// The creative and the office component set. + Set, /// Left to right and right to left. Direction, /// Small and medium controls. @@ -101,11 +104,12 @@ pub enum VariantAxis { impl VariantAxis { /// Every axis, in menu order. - pub const ALL: [VariantAxis; 7] = [ + pub const ALL: [VariantAxis; 8] = [ VariantAxis::Theme, VariantAxis::Mode, VariantAxis::Contrast, VariantAxis::Size, + VariantAxis::Set, VariantAxis::Direction, VariantAxis::ControlSize, VariantAxis::DirectionAndControlSize, @@ -118,6 +122,7 @@ impl VariantAxis { VariantAxis::Mode => "Every mode (light, dark)", VariantAxis::Contrast => "Every contrast (standard, high)", VariantAxis::Size => "Every size (compact, comfortable)", + VariantAxis::Set => "Every set (creative, office)", VariantAxis::Direction => "Every direction (LTR, RTL)", VariantAxis::ControlSize => "Every control size (Sm, Md)", VariantAxis::DirectionAndControlSize => "Every direction and control size", diff --git a/crates/ui-gallery/src/viewer/mod.rs b/crates/ui-gallery/src/viewer/mod.rs index 642bf13a7..160bde8ed 100644 --- a/crates/ui-gallery/src/viewer/mod.rs +++ b/crates/ui-gallery/src/viewer/mod.rs @@ -10,7 +10,7 @@ mod state; mod tree; pub use appearance::{ - CONTRASTS, Choice, Choices, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, TEXT_SIZES, VariantAxis, theme_entries, theme_named, theme_of, + CONTRASTS, Choice, Choices, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, SETS, TEXT_SIZES, VariantAxis, theme_entries, theme_named, theme_of, }; pub use catalog::{Catalog, ComponentInfo, Declared, Entry, StoryGroup, display_name}; pub use commands::GalleryCommands; diff --git a/crates/ui-gallery/src/viewer/settings.rs b/crates/ui-gallery/src/viewer/settings.rs index b213a437b..a23d264d4 100644 --- a/crates/ui-gallery/src/viewer/settings.rs +++ b/crates/ui-gallery/src/viewer/settings.rs @@ -1,6 +1,6 @@ //! What the viewer keeps between runs, in the gallery's own `config.toml`. -use super::appearance::{CONTRASTS, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, TEXT_SIZES, theme_named}; +use super::appearance::{CONTRASTS, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, SETS, TEXT_SIZES, theme_named}; use super::catalog::Catalog; use super::layout; use super::state::{Preview, Viewer, Workspace}; @@ -25,6 +25,8 @@ pub struct GallerySettings { pub text_size: String, /// The density preset. pub density: String, + /// The component set. + pub set: String, /// The motion mode. pub motion: String, /// The interface scale in percent. @@ -68,6 +70,7 @@ impl GallerySettings { contrast: CONTRASTS.name(env.contrast).to_owned(), text_size: TEXT_SIZES.name(env.text_size).to_owned(), density: DENSITIES.name(env.density).to_owned(), + set: SETS.name(env.component_set()).to_owned(), motion: MOTIONS.name(env.motion).to_owned(), scale: SCALES.name(env.scale).to_owned(), direction: DIRECTIONS.name(env.direction).to_owned(), @@ -91,6 +94,7 @@ impl GallerySettings { env.contrast = CONTRASTS.parse(&self.contrast).unwrap_or(default.contrast); env.text_size = TEXT_SIZES.parse(&self.text_size).unwrap_or(default.text_size); env.density = DENSITIES.parse(&self.density).unwrap_or(default.density); + env.values.set(SETS.parse(&self.set).unwrap_or(default.component_set())); env.motion = MOTIONS.parse(&self.motion).unwrap_or(default.motion); env.scale = SCALES.parse(&self.scale).unwrap_or(default.scale); env.direction = DIRECTIONS.parse(&self.direction).unwrap_or(default.direction); From 73e5bc474ec9dadde4aea0b35fc2377883d3a90e Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 13:15:21 +0000 Subject: [PATCH 13/89] craft-menu: the bar's labels are one derived value keyed by the model revision, language and keymap --- crates/menu/src/bar.rs | 54 ++++++++-- crates/menu/src/bar/stories.rs | 17 +++- crates/menu/src/context.rs | 66 ++++++++++-- crates/menu/src/keymap.rs | 74 +++++++++----- crates/menu/tests/it/from_items.rs | 116 ++++++++++++++++++++++ crates/menu/tests/it/main.rs | 1 + crates/menu/tests/it/memo.rs | 72 +++++++++++++- crates/menu/tests/it/mnemonic.rs | 11 +- crates/ui-contract/src/contract/memo.rs | 7 ++ crates/ui-contract/src/testing/fixture.rs | 8 ++ 10 files changed, 370 insertions(+), 56 deletions(-) create mode 100644 crates/menu/tests/it/from_items.rs diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 20effdb29..8d978dd18 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -11,8 +11,10 @@ #[cfg(feature = "screen-testing")] mod stories; +use craft_host::target::Os; +use craft_i18n::Words; use craft_keymap::{CommandRef, Platform}; -use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless}; +use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked}; use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle}; use craft_ui::runtime::env::{Env, Label}; use egui::{Rect, Ui}; @@ -87,7 +89,7 @@ pub type EnglishFn = fn(Labeled<'_>) -> Option; #[derive(craft_ui::contract::Pattern)] #[pattern(probe(MenuBarUi<'static, EnglishFn>))] pub struct MenuBarUi<'a, E = EnglishFn> { - bar: &'a MenuBar, + bar: &'a Tracked, /// The platform set with [`target`](Self::target); the shell's when none is. target: Option, english: Option>, @@ -99,7 +101,7 @@ pub struct MenuBarUi<'a, E = EnglishFn> { /// Every input of the bar's view. #[derive(MemoProps)] struct BarProps<'a, #[memo_props(stateless)] E> { - bar: &'a MenuBar, + bar: &'a Tracked, target: Target, english: Option>, preferred: &'a [(&'a str, char)], @@ -110,7 +112,7 @@ struct BarProps<'a, #[memo_props(stateless)] E> { impl<'a> MenuBarUi<'a> { /// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]). - pub fn new(bar: &'a MenuBar) -> MenuBarUi<'a> { + pub fn new(bar: &'a Tracked) -> MenuBarUi<'a> { MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false } } } @@ -184,13 +186,32 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B }); let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>); let rows = Rows::new(props.target).english(english).preferred(props.preferred); - let labels = - rows.labels(&props.bar.menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| rows.english_of(Labeled::Title(&menu.title))); - let shared = &rows; - let titles: Vec> = - props.bar.menus.iter().zip(labels).map(|(menu, label)| MenuTitle::new(label, move |ui| shared.show(ui, &menu.children))).collect(); + let env = Env::of(ui); + let os = env.view().shell().os; + // The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it. + let key = LabelKey { + bar: props.bar, + target: props.target, + os, + preferred: props.preferred, + english: props.english, + words: &env.words, + keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()), + }; + let labels = craft_ui::runtime::derived::derived(ui.ctx(), ui.scope_id().with("menu-labels"), &key, || { + rows.bar_labels(&props.bar.menus, keymap_platform(props.target, os)) + }); + let (shared, labels) = (&rows, &*labels); + let titles: Vec> = props + .bar + .menus + .iter() + .zip(&labels.titles) + .zip(&labels.menus) + .map(|((menu, title), level)| MenuTitle::new(title.clone(), move |ui| shared.show(ui, &menu.children, level))) + .collect(); // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. - let bar_model = props.bar; + let bar_model: &MenuBar = props.bar; let entries = move || entries_of(bar_model, english); let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard); if let Some(menu) = props.help { @@ -198,3 +219,16 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B } MenuBarOutput { titles: bar.show(ui).titles } } + +/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English +/// hooks, the language and the keymap. +#[derive(MemoProps)] +struct LabelKey<'a, #[memo_props(stateless)] E> { + bar: &'a Tracked, + target: Target, + os: Os, + preferred: &'a [(&'a str, char)], + english: Option>, + words: &'a Words, + keymap: u64, +} diff --git a/crates/menu/src/bar/stories.rs b/crates/menu/src/bar/stories.rs index a48970a67..b21cde03a 100644 --- a/crates/menu/src/bar/stories.rs +++ b/crates/menu/src/bar/stories.rs @@ -1,11 +1,14 @@ //! Stories of the in-window bar over a small model. +use std::sync::Arc; + +use craft_ui::contract::Tracked; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; use crate::{Document, Item, LayoutOptions, Menu, MenuBar, MenuBarUi, MenuRole, Node, Target, layout}; -fn model() -> MenuBar { +fn build() -> MenuBar { let item = |id: &str, label: &str| Item::new(id, label); let bar = MenuBar { menus: vec![ @@ -37,9 +40,15 @@ fn model() -> MenuBar { layout(&bar, Target::Linux, &LayoutOptions::new("Sample")).bar } +/// The story's model, kept in the story's memory: a model made again each pass is a new source, and the bar would run each time. +fn model(ui: &Ui) -> Arc> { + let id = ui.scope_id().with("model"); + ui.data_mut(|data| data.get_temp_mut_or_insert_with(id, || Arc::new(Tracked::new(build()))).clone()) +} + #[story(MenuBarUi<'static>, covers = [Default], drive = Drive::Never)] fn menu_bar_ui(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model()).target(Target::Linux).show(ui); + MenuBarUi::new(&model(ui)).target(Target::Linux).show(ui); StoryOutput::default() } @@ -51,12 +60,12 @@ fn open_window(fixture: &mut Fixture) { #[story(MenuBarUi<'static>, covers = [Open], drive = Drive::Custom(open_window))] fn menu_bar_ui_with_documents(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model()).target(Target::Linux).show(ui); + MenuBarUi::new(&model(ui)).target(Target::Linux).show(ui); StoryOutput::default() } #[story(MenuBarUi<'static>, covers = [], drive = Drive::Never)] fn menu_bar_ui_with_help_search(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model()).target(Target::Linux).help_search(true).show(ui); + MenuBarUi::new(&model(ui)).target(Target::Linux).help_search(true).show(ui); StoryOutput::default() } diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index 7e1dfd667..6f6f3ac28 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -26,7 +26,32 @@ use crate::model::{Builtin, Item, ItemKind, Node}; /// AppKit's own items ([`Node::Standard`]) are left out. The chord of a row without a binding is the item's own /// shortcut, written for the shell's operating system. pub fn rows(ui: &mut Ui, nodes: &[Node]) { - Rows::new(Target::of_shell(Env::of(ui).view().shell())).show(ui, nodes); + let rows = Rows::new(Target::of_shell(Env::of(ui).view().shell())); + let labels = rows.level_labels(nodes, rows.platform(ui)); + rows.show(ui, nodes, &labels); +} + +/// The text a menu level shows for its nodes, parallel to them: what [`LevelLabels::build`] works out once for a +/// model, so a pass that shows the menu again writes none of it. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct LevelLabels { + rows: Vec, +} + +/// One node's text: its label as the menu shows it (markers escaped, mnemonic marked), the item's shortcut text, and the +/// text of a submenu's own level. Separators and AppKit's items hold empty text. +#[derive(Debug, Default, PartialEq)] +struct RowLabels { + label: String, + shortcut: Option, + children: LevelLabels, +} + +/// The text of a bar: its titles as the bar shows them and the text of each menu's rows. +#[derive(Debug, PartialEq)] +pub(crate) struct BarLabels { + pub(crate) titles: Vec, + pub(crate) menus: Vec, } /// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its @@ -120,12 +145,35 @@ impl<'a> Rows<'a> { .collect() } - /// Shows `nodes` as the rows of the menu body `ui` is in. - pub(crate) fn show(&self, ui: &mut Ui, nodes: &[Node]) { + /// The text of `nodes` and of every submenu below them, with shortcuts written for `platform`. + pub(crate) fn level_labels(&self, nodes: &[Node], platform: Platform) -> LevelLabels { let labels = self.node_labels(nodes); - for (node, label) in nodes.iter().zip(labels) { + let rows = nodes + .iter() + .zip(labels) + .map(|(node, label)| match node { + Node::Item(item) => { + RowLabels { label, shortcut: item.shortcut.as_ref().map(|chord| chord.display(platform)), children: LevelLabels::default() } + } + Node::Submenu { children, .. } => RowLabels { label, shortcut: None, children: self.level_labels(children, platform) }, + Node::Separator | Node::Standard { .. } => RowLabels::default(), + }) + .collect(); + LevelLabels { rows } + } + + /// The text of a whole bar: the titles and each menu's rows. + pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels { + let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title))); + BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() } + } + + /// Shows `nodes` as the rows of the menu body `ui` is in, with their `labels`. + pub(crate) fn show(&self, ui: &mut Ui, nodes: &[Node], labels: &LevelLabels) { + for (node, text) in nodes.iter().zip(&labels.rows) { + let label = text.label.clone(); match node { - Node::Item(item) => self.item(ui, item, label), + Node::Item(item) => self.item(ui, item, label, text.shortcut.clone()), Node::Separator => { Divider::horizontal().show(ui); } @@ -133,7 +181,7 @@ impl<'a> Rows<'a> { if is_dead(children) { MenuItem::submenu(label).enabled(false).show(ui); } else { - Menu::submenu_row(ui, label, |ui, _| self.show(ui, children)); + Menu::submenu_row(ui, label, |ui, _| self.show(ui, children, &text.children)); } } Node::Standard { .. } => {} @@ -141,9 +189,7 @@ impl<'a> Rows<'a> { } } - fn item(&self, ui: &mut Ui, item: &Item, label: String) { - let platform = self.platform(ui); - let shortcut = item.shortcut.as_ref().map(|chord| chord.display(platform)); + fn item(&self, ui: &mut Ui, item: &Item, label: String, shortcut: Option) { match Builtin::of(&item.command) { Some(Builtin::Quit) => { if local(ui, item, label, shortcut).ran { @@ -162,7 +208,7 @@ impl<'a> Rows<'a> { } /// The platform whose key names the shortcut column shows. - fn platform(&self, ui: &Ui) -> Platform { + pub(crate) fn platform(&self, ui: &Ui) -> Platform { keymap_platform(self.target, Env::of(ui).view().shell().os) } } diff --git a/crates/menu/src/keymap.rs b/crates/menu/src/keymap.rs index fd6816bfb..896c2d3ee 100644 --- a/crates/menu/src/keymap.rs +++ b/crates/menu/src/keymap.rs @@ -2,8 +2,9 @@ //! enabled and checked update. use craft_keymap::{CommandKind, CommandRef, Keymap}; +use craft_ui::contract::Tracked; -use crate::model::{Builtin, ItemKind, MenuBar}; +use crate::model::{Builtin, Item, ItemKind, MenuBar}; /// Give each item the shortcut its command has in `keymap`, the user's overrides included, and /// make the items of toggle commands (kind [`CommandKind::Toggle`]) check items. @@ -12,14 +13,23 @@ use crate::model::{Builtin, ItemKind, MenuBar}; /// one in its home scope first, so a chord another command wins is not shown. A command with no /// such binding loses its shortcut, and an item whose command the keymap doesn't know keeps its /// own. A toggle's check item keeps its checked state; radio items stay radio items. Call it on -/// the app's bar, before the layout. -pub fn apply_keymap(bar: &mut MenuBar, keymap: &Keymap) { - bar.for_each_item_mut(|it| { - let Some(bindable) = keymap.bindable(&it.command) else { return }; - it.shortcut = keymap.shown_chord(&it.command); - if bindable.kind == CommandKind::Toggle && it.kind == ItemKind::Plain { - it.kind = ItemKind::Check(false); - } +/// the app's bar, before the layout. The bar is written, and its revision moves, only when an item changes. +pub fn apply_keymap(bar: &mut Tracked, keymap: &Keymap) { + let wanted = |it: &Item| { + let bindable = keymap.bindable(&it.command)?; + let kind = if bindable.kind == CommandKind::Toggle && it.kind == ItemKind::Plain { ItemKind::Check(false) } else { it.kind }; + Some((keymap.shown_chord(&it.command), kind)) + }; + if !bar.items().into_iter().any(|it| wanted(it).is_some_and(|(shortcut, kind)| shortcut != it.shortcut || kind != it.kind)) { + return; + } + bar.edit(|bar| { + bar.for_each_item_mut(|it| { + if let Some((shortcut, kind)) = wanted(it) { + it.shortcut = shortcut; + it.kind = kind; + } + }); }); } @@ -56,20 +66,38 @@ impl Default for ItemState { /// Set every item's enabled and checked state from `state`, called once per item of the app's /// commands. `checked: Some(..)` makes a plain item a check item and sets a radio item's -/// selection. The built-in items and the open documents are left alone. -pub fn apply_state(bar: &mut MenuBar, mut state: impl FnMut(&CommandRef) -> ItemState) { - let documents: Vec = bar.documents.iter().map(|d| d.command.clone()).collect(); - bar.for_each_item_mut(|it| { - if Builtin::of(&it.command).is_some() || documents.contains(&it.command) { - return; - } - let s = state(&it.command); - it.enabled = s.enabled; - if let Some(on) = s.checked { - it.kind = match it.kind { - ItemKind::Radio(_) => ItemKind::Radio(on), - ItemKind::Plain | ItemKind::Check(_) => ItemKind::Check(on), +/// selection. The built-in items and the open documents are left alone. The bar is written, and +/// its revision moves, only when an item changes. +pub fn apply_state(bar: &mut Tracked, mut state: impl FnMut(&CommandRef) -> ItemState) { + let skipped = |it: &Item| Builtin::of(&it.command).is_some() || bar.is_document(&it.command); + // One entry per item, depth first, as `for_each_item_mut` walks them. + let wanted: Vec> = bar + .items() + .into_iter() + .map(|it| { + if skipped(it) { + return None; + } + let s = state(&it.command); + let kind = match (s.checked, it.kind) { + (None, kind) => kind, + (Some(on), ItemKind::Radio(_)) => ItemKind::Radio(on), + (Some(on), ItemKind::Plain | ItemKind::Check(_)) => ItemKind::Check(on), }; - } + Some((s.enabled, kind)) + }) + .collect(); + let differs = bar.items().into_iter().zip(&wanted).any(|(it, want)| want.is_some_and(|(enabled, kind)| enabled != it.enabled || kind != it.kind)); + if !differs { + return; + } + bar.edit(|bar| { + let mut wanted = wanted.into_iter(); + bar.for_each_item_mut(|it| { + if let Some((enabled, kind)) = wanted.next().flatten() { + it.enabled = enabled; + it.kind = kind; + } + }); }); } diff --git a/crates/menu/tests/it/from_items.rs b/crates/menu/tests/it/from_items.rs new file mode 100644 index 000000000..7d1783ae5 --- /dev/null +++ b/crates/menu/tests/it/from_items.rs @@ -0,0 +1,116 @@ +//! `from_items` groups flat rows by menu path in one pass; the tree is the one the row-by-row walk made: submenus where their +//! first row is, separators tidied at every depth. + +use craft_menu::{CommandRef, MenuBar, Node, Row, from_items, tidy}; +use craft_ui::testing::trial; + +/// The row-by-row walk `from_items` replaced: every submenu filters all rows of its level again. +fn reference(tops: &[&str], rows: &[Row]) -> MenuBar { + fn level(rows: &[&Row], depth: usize) -> Vec { + let mut out = Vec::new(); + let mut shown: Vec<&str> = Vec::new(); + for it in rows { + if it.path.len() == depth { + out.push(if it.label == "---" { Node::Separator } else { Node::Item(craft_menu::Item::new(it.command.clone(), it.label.clone())) }); + } else if let Some(name) = it.path.get(depth) { + let name = name.as_str(); + if shown.contains(&name) { + continue; + } + shown.push(name); + let child: Vec<&Row> = rows.iter().copied().filter(|c| c.path.get(depth).map(String::as_str) == Some(name)).collect(); + out.push(Node::submenu(name, level(&child, depth + 1))); + } + } + old_tidy(out) + } + let menus = tops + .iter() + .map(|top| { + let rows: Vec<&Row> = rows.iter().filter(|r| r.path.first().map(String::as_str) == Some(*top)).collect(); + craft_menu::Menu::new(*top, level(&rows, 1)) + }) + .collect(); + MenuBar::new(menus) +} + +/// The tidy `from_items` used before it worked in place. +fn old_tidy(nodes: Vec) -> Vec { + let mut out: Vec = Vec::with_capacity(nodes.len()); + for mut n in nodes { + if let Node::Submenu { children, .. } = &mut n { + *children = old_tidy(std::mem::take(children)); + if children.is_empty() { + continue; + } + } + if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) { + continue; + } + out.push(n); + } + while matches!(out.last(), Some(Node::Separator)) { + out.pop(); + } + out +} + +fn row(path: &[&str], id: &str) -> Row { + Row::new(path, CommandRef::new(id), id) +} + +#[trial] +fn from_items_builds_the_tree_the_row_by_row_walk_built() { + let rows = [ + Row::separator(&["File"]), + row(&["File"], "file.new"), + row(&["File", "Recent"], "file.a"), + Row::separator(&["File"]), + Row::separator(&["File"]), + row(&["File", "Recent", "More"], "file.deep"), + row(&["File", "Recent"], "file.b"), + row(&["File"], "file.save"), + Row::separator(&["File", "Recent"]), + row(&["File", "Export"], "file.png"), + Row::separator(&["File"]), + row(&["Edit"], "edit.undo"), + row(&["Stray"], "stray"), + row(&["Edit", "Find", "In Files"], "edit.find"), + Row::separator(&["Edit"]), + Row::separator(&["Edit", "Empty"]), + ]; + let tops = ["File", "Edit", "View"]; + assert_eq!(from_items(&tops, &rows), reference(&tops, &rows)); + let bar = from_items(&tops, &rows); + assert_eq!(bar.menus.len(), 3, "a top with no rows stays an empty menu"); + assert!(bar.menus[2].children.is_empty()); + let Node::Submenu { label, .. } = &bar.menus[0].children[1] else { panic!("the submenu sits where its first row is") }; + assert_eq!(label, "Recent"); +} + +#[trial] +fn tidy_drops_edge_and_repeated_separators_and_empty_submenus_in_place() { + let mut nodes = vec![ + Node::Separator, + Node::Separator, + Node::Item(craft_menu::Item::new("a", "A")), + Node::submenu("Empty", vec![Node::Separator]), + Node::Separator, + Node::Separator, + Node::submenu("Kept", vec![Node::Separator, Node::Item(craft_menu::Item::new("b", "B")), Node::Separator]), + Node::Separator, + ]; + tidy(&mut nodes); + let labels: Vec<&str> = nodes + .iter() + .map(|n| match n { + Node::Item(it) => it.label.as_str(), + Node::Submenu { label, children, .. } => { + assert_eq!(children.len(), 1, "the submenu's own separators are tidied"); + label.as_str() + } + _ => "-", + }) + .collect(); + assert_eq!(labels, ["A", "-", "Kept"]); +} diff --git a/crates/menu/tests/it/main.rs b/crates/menu/tests/it/main.rs index 0a5fd90c0..97451028e 100644 --- a/crates/menu/tests/it/main.rs +++ b/crates/menu/tests/it/main.rs @@ -2,6 +2,7 @@ #[cfg(target_os = "macos")] mod appkit; +mod from_items; mod keytips; mod layout; mod memo; diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index a07bc1b90..04ee82549 100644 --- a/crates/menu/tests/it/memo.rs +++ b/crates/menu/tests/it/memo.rs @@ -3,17 +3,23 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; use craft_host::target::Os; +use craft_keymap::Overrides; use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items}; -use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_memo_runs, trial}; +use craft_ui::contract::Tracked; +use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_derived_builds, last_frame_memo_runs, trial}; use egui::{Event, Key, Modifiers}; -fn model(title: &str) -> MenuBar { - from_items(&[title, "Edit"], &[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")]) +fn model(title: &str) -> Tracked { + Tracked::new(from_items( + &[title, "Edit"], + &[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")], + )) } -fn fixture(bar: &Rc>) -> Fixture { +fn fixture(bar: &Rc>>) -> Fixture { let bar = Rc::clone(bar); let mut fixture = Fixture::new(move |ui| { MenuBarUi::new(&bar.borrow()).target(Target::Linux).show(ui); @@ -40,7 +46,7 @@ fn an_idle_menu_bar_replays_and_a_title_rename_runs_it_once() { } assert!(fixture.by_label("File").is_some(), "a replayed bar keeps its titles' nodes"); - *bar.borrow_mut() = model("Document"); + bar.borrow_mut().edit(|bar| *bar = model("Document").into_inner()); fixture.frame(vec![]); assert_eq!(counted(&fixture).0, 1, "a model change runs the bar once in that frame"); assert!(fixture.by_label("Document").is_some(), "and it shows the new title"); @@ -81,3 +87,59 @@ fn an_open_menu_runs_the_bar_and_closing_it_replays_it() { fixture.frame(vec![]); assert_eq!(counted(&fixture), (0, 1), "after the menu closes and the keyboard leaves, the bar replays"); } + +/// The label builds of the last frame. +fn label_builds(fixture: &Fixture) -> u32 { + last_frame_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum() +} + +#[trial] +fn an_idle_bar_and_an_open_menu_build_no_labels() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + for _ in 0..3 { + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "an idle bar builds no labels"); + } + fixture.key(Key::F, Modifiers::ALT); + fixture.settle(); + assert!(fixture.by_label("New").is_some(), "Alt+F opened File"); + for _ in 0..3 { + fixture.frame(vec![]); + assert!(counted(&fixture).0 > 0, "the bar runs each pass while a menu is open"); + assert_eq!(label_builds(&fixture), 0, "and builds no labels"); + } +} + +#[trial] +fn a_model_edit_builds_the_labels_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + bar.borrow_mut().edit(|bar| *bar = model("Document").into_inner()); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 1, "one edit builds the labels once"); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "and the next frame none"); +} + +#[trial] +fn a_locale_change_builds_the_labels_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + fixture.host(crate::mnemonic::turkish()); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 1, "a language change builds the labels once"); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "and the next frame none"); +} + +#[trial] +fn a_keymap_change_builds_the_labels_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + fixture.overrides(Arc::new(Overrides::default())); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 1, "a new keymap builds the labels once"); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "and the next frame none"); +} diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index d8ecfd115..8a43bc0c7 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -6,12 +6,13 @@ use std::sync::Arc; use craft_host::target::Os; use craft_host::{AppInfo, Host}; use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items}; +use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers}; #[trial] fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { - let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")]); + let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")])); let english = |labeled: Labeled<'_>| match labeled { Labeled::Title("文件") => Some("File".to_owned()), Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()), @@ -30,7 +31,7 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { } /// A host whose interface language is Turkish, with an empty catalog. -fn turkish() -> Arc { +pub(crate) fn turkish() -> Arc { let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]); let tr = i18n.from_code("tr").unwrap_or_else(|| panic!("tr is offered")); Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).lang(tr).build()) @@ -39,8 +40,10 @@ fn turkish() -> Arc { /// The rows shown after Alt with `key` on a Linux bar titled `ix` and `ı` under a Turkish host: `One` is `ix`'s, `Two` /// is `ı`'s. fn opened_by(key: Key) -> (bool, bool) { - let bar = - from_items(&["ix", "ı"], &[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")]); + let bar = Tracked::new(from_items( + &["ix", "ı"], + &[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")], + )); let mut fixture = Fixture::new(move |ui| { MenuBarUi::new(&bar).show(ui); }); diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 791e1a7f7..53ff63d0f 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -1020,6 +1020,13 @@ impl MemoProps for craft_behavior::fit::FitKeep { } } +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_host::target::Os { + 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) { diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index b2165c890..468f22afc 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -298,6 +298,14 @@ impl Fixture { self } + /// Sets the user's binding overrides for every following pass, as an app's `FrameInput.commands` does: the keymap is + /// rebuilt when the `Arc` is another one. + pub fn overrides(&mut self, overrides: std::sync::Arc) -> &mut Self { + self.commands = self.commands.clone().overrides(overrides); + self.frames.commands(self.commands.clone()); + self + } + /// The room the story is shown in. pub fn room(&mut self, room: Vec2) -> &mut Self { self.room = room; From 1d40128fadaa14dcca58f41f54140875fd269cbb Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 13:15:22 +0000 Subject: [PATCH 14/89] craft-menu: NativeMenu::sync_with is keyed by a checked key; sync and had_input are removed --- crates/menu/README.md | 19 ++++++------ crates/menu/src/driver.rs | 54 ++++++++-------------------------- crates/menu/src/lib.rs | 6 ++-- crates/menu/tests/it/appkit.rs | 6 ++-- crates/menu/tests/it/native.rs | 10 +++---- 5 files changed, 33 insertions(+), 62 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index fdda51669..a654dbcaf 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -96,7 +96,8 @@ items. Each frame, `apply_state(&mut bar, |command| ItemState { enabled, checked })` sets enabled and checked from the app's state. `checked: Some(..)` makes a plain item a check item and selects or clears a radio item; `None` leaves the kind as it is. The built-in items and the open documents -are left alone. Both run on the app's bar, before the layout. +are left alone. Both run on the app's bar, before the layout. The bar is held in a `Tracked`; both write it only when an item changes, so +its revision (the key of the in-window bar's kept labels and of `sync_with`) moves only then. ## Keyboard Shortcuts dialog @@ -240,7 +241,7 @@ Each frame, in this order: 2. `set_gate`, with the app's state for this frame. 3. `take_clicks`, and run the commands it returns: the clicks since the last frame that the gate allows now. Minimize and Quit are already handled. -4. `sync_with`, which lays the menus out again only when the app's state changed or a menu event +4. `sync_with`, which lays the menus out again only when its key changed or a menu event arrived, and re-syncs them in place when the gate changed. ```rust @@ -256,14 +257,13 @@ if let Some(menu) = &mut self.native_menu { for command in menu.take_clicks(ctx) { self.run_command(ctx, &command); } - let state = self.menu_state_hash(craft_menu::had_input(ctx).then_some(ctx.cumulative_frame_nr())); - for c in menu.sync_with(state, || craft_menu::mac_layout(&self.menu_bar(), &LayoutOptions::new("PhotoCraft"))) { + for c in menu.sync_with(&(&self.menu_bar, &self.workspace), || craft_menu::mac_layout(&self.menu_bar(), &LayoutOptions::new("PhotoCraft"))) { log::info!("menu: {} is {} on macOS and {} in the app; {}", c.shortcut, c.system, c.command, c.resolution); } } ``` -`sync_with` builds the layout only when `state` changed or a menu event arrived, because +`sync_with` builds the layout only when its key changed or a menu event arrived, because building the rows usually walks every command's enabled state. The backend then updates labels, enabled and checked in place and rebuilds only when `structure_key` (or, for the open documents, `window_key`) changes. Adding or removing an item in a dynamic list (recent files, @@ -271,11 +271,10 @@ workspaces, plugins) changes `structure_key`; relabelling one doesn't. An item t item once stays one, unchecked, when the app's state stops giving it a checked state, so that doesn't rebuild the menus. -`state` must cover everything the menus show. A change that comes without input, such as a load -or save finishing on a worker or a timer, leaves the menus stale until the next input or menu -event unless it is in the hash. An app that can't keep the hash complete calls -`menu.sync(layout)` instead, with the layout built every frame: it is compared with the last -one and synced only when it differs. +The key is a `MemoProps` value: the menu model held in a `Tracked` (`apply_state` and +`apply_keymap` write it only when an item changes, so its revision moves only then) and whatever +else the layout reads, each as a checked input, so a change that comes without input (a load +finishing on a worker) reaches the menus the frame it lands. An app that needs a click while egui is idle (to wake its own loop, or hand the command to a worker) sets `menu.on_command(Box::new(|command| ..))`. The hook runs from the menu event diff --git a/crates/menu/src/driver.rs b/crates/menu/src/driver.rs index 3c79dc831..2ee60003f 100644 --- a/crates/menu/src/driver.rs +++ b/crates/menu/src/driver.rs @@ -5,7 +5,7 @@ use std::collections::HashSet; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use craft_keymap::{Chord, CommandRef, Key, Mods}; -use craft_ui::contract::MemoProps; +use craft_ui::contract::{MemoKey, MemoProps}; use craft_ui::runtime::windows::{KeyEquivalent, WindowAction, WindowHost}; use crate::layout::{Clash, Layout}; @@ -203,8 +203,8 @@ pub trait Backend { /// The native menu bar, while the app uses one (its in-window menus are hidden then). pub struct NativeMenu { backend: Box, - /// The state the menus were last built from. - state: Option, + /// The key the menus were last built from. + state: Option, clicks: Vec, /// An event arrived (AppKit may have toggled a check item itself): re-sync. dirty: bool, @@ -388,23 +388,18 @@ impl NativeMenu { out } - /// Bring the native menu up to date. `state` is a hash of what the menus show (see - /// [`had_input`]); `build` lays them out ([`crate::mac_layout`]) and runs only when `state` - /// changed or a menu event arrived since the last sync, since building the rows usually walks - /// every command's enabled state. A menu event re-syncs because AppKit flips a check or radio - /// item's state itself when it is chosen: the sync sets it back to the app's state. A gate - /// change ([`NativeMenu::set_gate`]) re-syncs the menus last laid out, greyed or not, without - /// calling `build`. - /// - /// `state` must cover everything the menus show. A change that comes without input, such as - /// a load or save finishing on a worker or a timer, leaves the menus stale until the next - /// input or menu event unless it is in the hash. An app that can't keep the hash complete - /// uses [`NativeMenu::sync`] instead. + /// Bring the native menu up to date. `key` is everything the layout reads, as a [`MemoProps`] value (the + /// app's `Tracked` menu model, the language's `Words`, the keymap generation): `build` lays the menus out + /// ([`crate::mac_layout`]) and runs only when the key changed or a menu event arrived since the last sync, since + /// building the rows usually walks every command's enabled state. A menu event re-syncs because AppKit flips a + /// check or radio item's state itself when it is chosen: the sync sets it back to the app's state. A gate change + /// ([`NativeMenu::set_gate`]) re-syncs the menus last laid out, greyed or not, without calling `build`. /// /// Returns the layout's clashes when they differ from the last ones returned, for the app to /// log; otherwise nothing. - pub fn sync_with(&mut self, state: u64, build: impl FnOnce() -> Layout) -> Vec { - let relayout = self.state != Some(state) || self.dirty; + pub fn sync_with(&mut self, key: &K, build: impl FnOnce() -> Layout) -> Vec { + let key = MemoKey::of(key); + let relayout = self.state != Some(key) || self.dirty; if !relayout && self.synced_gate == Some(self.gate) { return Vec::new(); } @@ -413,27 +408,12 @@ impl NativeMenu { let mut layout = build(); self.keep_kinds(&mut layout.bar); clashes = self.keep(layout); - self.state = Some(state); + self.state = Some(key); } self.push(); clashes } - /// [`NativeMenu::sync_with`] without a state hash: the app lays the menus out every frame - /// and they are synced when the layout differs from the last one (or a menu event or gate - /// change calls for it), so they never go stale. It costs a layout per frame. - pub fn sync(&mut self, mut layout: Layout) -> Vec { - self.keep_kinds(&mut layout.bar); - if !self.dirty && self.bar.as_ref() == Some(&layout.bar) && self.clashes == layout.clashes && self.synced_gate == Some(self.gate) { - return Vec::new(); - } - let clashes = self.keep(layout); - // A later `sync_with` lays the menus out again. - self.state = None; - self.push(); - clashes - } - /// An item that was a check item once stays one, unchecked: switching its kind would change /// [`crate::structure_key`] and rebuild the menus. fn keep_kinds(&mut self, bar: &mut MenuBar) { @@ -514,11 +494,3 @@ fn text_editing_key(c: &Chord) -> bool { pub(crate) fn native_ok(c: &Chord) -> bool { c.has_command() } - -/// A key press, typed text or click this frame. It may have changed state an app's menu hash -/// doesn't list, so apps fold it into the `state` passed to [`NativeMenu::sync_with`], for -/// example as `had_input(ctx).then_some(ctx.cumulative_frame_nr())`. Keys come from the key -/// stage (`keys::keyed`), which also counts the presses a focused component took from egui. -pub fn had_input(ctx: &egui::Context) -> bool { - craft_ui::runtime::keys::keyed(ctx) || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))) -} diff --git a/crates/menu/src/lib.rs b/crates/menu/src/lib.rs index 3c569058a..2f475d5c5 100644 --- a/crates/menu/src/lib.rs +++ b/crates/menu/src/lib.rs @@ -88,8 +88,8 @@ //! [`NativeMenu::on_command`] sees each allowed click as it arrives, also while egui is idle. //! //! Per frame: [`NativeMenu::poll`], then [`NativeMenu::set_gate`], [`NativeMenu::take_clicks`] and run the commands, then -//! [`NativeMenu::sync_with`], which lays the menus out again only when the app's state changed -//! (or [`NativeMenu::sync`], which compares a layout built every frame). +//! [`NativeMenu::sync_with`], which lays the menus out again only when its key changed (the menu model's +//! `Tracked` revision and the other inputs of the layout). //! The input filter also keeps a click or Escape that closes an open native menu away //! from egui. #![warn(missing_docs)] @@ -118,7 +118,7 @@ pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi}; pub use craft_keymap::{Chord, CommandRef}; pub use customize::Customization; pub use documents::DOCUMENT_COMMAND_PREFIX; -pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, had_input}; +pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu}; pub use help::{HelpCommand, HelpLabels, HelpLink, HelpMenu}; pub use keymap::{ItemState, apply_keymap, apply_state}; pub use keytips::{KeytipControl, Keytips, KeytipsOutput}; diff --git a/crates/menu/tests/it/appkit.rs b/crates/menu/tests/it/appkit.rs index 59f887363..d80bbee31 100644 --- a/crates/menu/tests/it/appkit.rs +++ b/crates/menu/tests/it/appkit.rs @@ -133,11 +133,11 @@ pub(super) fn run() { }; assert!(new_enabled(&main), "no dialog: New is enabled"); menu.set_gate(Gate::default().modal(true)); - menu.sync_with(1, || layout(1)); + menu.sync_with(&1_u64, || layout(1)); assert!(Retained::as_ptr(&main) == Retained::as_ptr(&main_menu()), "the gate updated the menu, not rebuilt it"); assert!(!new_enabled(&main_menu()), "a dialog greys New"); menu.set_gate(Gate::default()); - menu.sync_with(1, || layout(1)); + menu.sync_with(&1_u64, || layout(1)); assert!(new_enabled(&main_menu()), "New is enabled again"); // A key equivalent: ⌘R reaches egui as the key press ⌘R, once, and is no click. @@ -179,7 +179,7 @@ pub(super) fn run() { // Window ends with the open documents. Opening one rebuilds only the Window menu, which AppKit still knows as // its Window menu; choosing a row brings that document forward. - menu.sync_with(2, || layout(2)); + menu.sync_with(&2_u64, || layout(2)); assert!(Retained::as_ptr(&main) == Retained::as_ptr(&main_menu()), "a new document rebuilt only the Window menu"); let window = submenu(&main_menu(), "Window"); assert!(nsapp.windowsMenu().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)), "AppKit knows the new Window menu"); diff --git a/crates/menu/tests/it/native.rs b/crates/menu/tests/it/native.rs index 564f66667..968520630 100644 --- a/crates/menu/tests/it/native.rs +++ b/crates/menu/tests/it/native.rs @@ -146,14 +146,14 @@ fn a_modal_gate_greys_the_apps_items() { builds.set(builds.get() + 1); mac_layout(&sample(false, true), &opts) }; - menu.sync_with(1, build); + menu.sync_with(&1_u64, build); menu.set_gate(modal()); - menu.sync_with(1, build); - menu.sync_with(1, build); + menu.sync_with(&1_u64, build); + menu.sync_with(&1_u64, build); menu.set_gate(Gate::default()); - menu.sync_with(1, build); + menu.sync_with(&1_u64, build); menu.set_gate(typing(true)); - menu.sync_with(1, build); + menu.sync_with(&1_u64, build); assert_eq!((builds.get(), synced.borrow().len()), (1, 4), "one layout; synced open, greyed, open, typing"); let synced = synced.borrow(); From e40ff16dfc690936d2fcd7feec08dac634829b67 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 13:16:39 +0000 Subject: [PATCH 15/89] craft-ui-panels: trial that an open flyout builds no derived values --- crates/ui-panels/src/rails/tool/trials.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index 0e6a0468b..5ba506230 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -1,6 +1,7 @@ //! Trials of `ToolRail`: its columns for a width, its measure, a short room and its glyph role. #![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] +use super::super::FlyoutButton; use super::stories::tools; use super::{LastUsed, ToolRail, ToolSlot}; use crate::buttons::Button; @@ -10,9 +11,10 @@ use crate::contract::ShowContainer as _; use crate::docking::{DockGrid, DockSizes}; use crate::layout_components::Stack; use crate::runtime::env::ThemeScope; +use crate::testing::pointer::secondary; use crate::testing::pointer::{moved, wheel}; use crate::testing::relations::{above, grows_with}; -use crate::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; +use crate::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, trial}; use egui::{Rect, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -264,3 +266,22 @@ fn a_rail_in_another_density_counts_its_columns_in_that_density() { fixture.density(craft_theme::Size::Comfortable).room(Vec2::new(width, tall)).settle(); assert_eq!(columns_of(&fixture), 2, "two rail steps of the scope's style show two columns"); } + +/// A flyout resolves its rows through the command board, so an open flyout builds no derived value in any frame. +#[trial] +fn an_open_flyout_builds_no_derived_values() { + let tools = tools(&[1, 2]); + let shown = 1_u8; + let mut fixture = Fixture::new(move |ui| { + FlyoutButton::new(&tools, &shown).show(ui); + }); + fixture.room(Vec2::new(200.0, 200.0)).settle(); + let button = rect(&fixture, "Brush").center(); + fixture.frame(vec![secondary(button, true), secondary(button, false)]); + fixture.settle(); + assert!(fixture.by_label("Pencil").is_some(), "the right click opened the flyout"); + for _ in 0..3 { + fixture.frame(vec![]); + assert!(last_frame_derived_builds(fixture.ctx()).iter().all(|(_, builds)| *builds == 0), "no derived value is built per pass"); + } +} From 0ab21b8b6fb9e5eb3214926e094c9ad64e1f7146 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 13:23:25 +0000 Subject: [PATCH 16/89] craft-menu: trials that sync_with lays out only when its key moves and apply_state keeps the revision when nothing changes --- crates/menu/tests/it/native.rs | 47 +++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/menu/tests/it/native.rs b/crates/menu/tests/it/native.rs index 968520630..6f9ace31c 100644 --- a/crates/menu/tests/it/native.rs +++ b/crates/menu/tests/it/native.rs @@ -8,10 +8,10 @@ use std::sync::{Arc, Mutex}; use craft_keymap::Mods; use craft_menu::{ - Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, LayoutOptions, MenuBar, NativeMenu, mac_layout, - structure_key, + Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu, apply_state, + mac_layout, structure_key, }; -use craft_ui::contract::{Props as _, Show as _}; +use craft_ui::contract::{Props as _, Show as _, Tracked}; use craft_ui::testing::focus::key_release; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::click; @@ -309,3 +309,44 @@ fn an_option_click_runs_the_rows_alternate() { let key = dispatch.chosen(&merge, Some(&shortcut), false, true, held([true, false, true, true]), Some(&alternate)); assert_eq!(key, Event::Key(chord("Cmd+Alt+Shift+E")), "a key equivalent is never swapped"); } + +/// The menus are laid out again only when the key moved or a menu event arrived: a model edit moves the `Tracked` key once. +#[trial] +fn sync_with_lays_the_menus_out_only_when_the_key_moves() { + let (mut menu, _, events, _) = driver(); + let opts = LayoutOptions::new("Sample"); + let mut model = Tracked::new(sample(false, true)); + let builds = Cell::new(0); + let build = |model: &Tracked| { + builds.set(builds.get() + 1); + mac_layout(model, &opts) + }; + for _ in 0..3 { + menu.sync_with(&model, || build(&model)); + } + assert_eq!(builds.get(), 1, "a key that did not move lays the menus out once"); + model.edit(|bar| bar.tag_menu("File", craft_menu::MenuRole::Other)); + menu.sync_with(&model, || build(&model)); + menu.sync_with(&model, || build(&model)); + assert_eq!(builds.get(), 2, "an edit moves the key once"); + events.borrow_mut().push(Event::Handled(cmd("file.new"))); + menu.poll(&egui::Context::default()); + menu.sync_with(&model, || build(&model)); + assert_eq!(builds.get(), 3, "a menu event lays them out again"); +} + +/// `apply_state` writes the model only when an item's state differs, so a frame that changes nothing keeps its revision. +#[trial] +fn apply_state_with_no_change_keeps_the_revision() { + let mut model = Tracked::new(sample(false, true)); + let state = |_: &CommandRef| ItemState::default(); + apply_state(&mut model, state); + let kept = model.revision(); + apply_state(&mut model, state); + assert_eq!(model.revision(), kept, "the same state writes nothing"); + apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new"))); + assert_ne!(model.revision(), kept, "a changed state moves the revision"); + let moved = model.revision(); + apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new"))); + assert_eq!(model.revision(), moved, "and the same changed state again does not"); +} From 95d7fc34b45c626c5e8e18c82e60fd9630128eea Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 14:32:35 +0000 Subject: [PATCH 17/89] Trials: idle key bytes of a tool rail, a dock and a menu bar do not grow with their models --- crates/menu/tests/it/memo.rs | 18 +++++++++++++++- crates/ui-panels/src/rails/tool/trials.rs | 24 ++++++++++++++++++++- crates/ui-patterns/tests/it/docking/runs.rs | 16 +++++++++++++- 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index 04ee82549..614a6d891 100644 --- a/crates/menu/tests/it/memo.rs +++ b/crates/menu/tests/it/memo.rs @@ -9,7 +9,7 @@ use craft_host::target::Os; use craft_keymap::Overrides; use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items}; use craft_ui::contract::Tracked; -use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_derived_builds, last_frame_memo_runs, trial}; +use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes, trial}; use egui::{Event, Key, Modifiers}; fn model(title: &str) -> Tracked { @@ -143,3 +143,19 @@ fn a_keymap_change_builds_the_labels_once() { fixture.frame(vec![]); assert_eq!(label_builds(&fixture), 0, "and the next frame none"); } + +/// The key bytes of an idle pass of a bar whose File menu has `rows` rows. +fn idle_key_bytes(rows: usize) -> usize { + let items: Vec = (0..rows).map(|row| Row::new(&["File"], CommandRef::new(format!("file.row{row}")), format!("Row {row}"))).collect(); + let bar = Rc::new(RefCell::new(Tracked::new(from_items(&["File"], &items)))); + let mut fixture = fixture(&bar); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "an idle bar builds no labels"); + last_pass_memo_key_bytes(fixture.ctx()) +} + +/// An idle bar feeds the same key bytes whatever its model's size. +#[trial] +fn a_menu_bars_idle_key_bytes_do_not_grow_with_its_rows() { + assert_eq!(idle_key_bytes(20), idle_key_bytes(2_000), "the key follows the model's revision, not its rows"); +} diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index 5ba506230..7065a5f70 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -14,7 +14,7 @@ use crate::runtime::env::ThemeScope; use crate::testing::pointer::secondary; use crate::testing::pointer::{moved, wheel}; use crate::testing::relations::{above, grows_with}; -use crate::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, trial}; +use crate::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes, trial}; use egui::{Rect, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -285,3 +285,25 @@ fn an_open_flyout_builds_no_derived_values() { assert!(last_frame_derived_builds(fixture.ctx()).iter().all(|(_, builds)| *builds == 0), "no derived value is built per pass"); } } + +/// The key bytes of an idle pass of a rail of `count` slots, a quarter of whose tools are hidden and half remembered. +fn idle_key_bytes(count: u8) -> usize { + let slots: Vec> = (0..count).map(|id| ToolSlot::new(u32::from(id), tools(&[id]))).collect(); + let hidden: Vec = (0..count / 4).collect(); + let mut last = LastUsed::default(); + for id in 0..count / 2 { + last.set(u32::from(id), id); + } + let mut fixture = Fixture::new(move |ui| { + ToolRail::new("Tools", &slots, &0, &last).hidden(&hidden).show_rail(ui, |_, _| {}); + }); + fixture.room(Vec2::new(120.0, 400.0)).settle().idle(1); + assert_eq!(last_frame_derived_builds(fixture.ctx()), Vec::new(), "an idle rail builds no derived value"); + last_pass_memo_key_bytes(fixture.ctx()) +} + +/// An idle rail feeds the same key bytes whatever its number of slots, with hidden and remembered tools in proportion. +#[trial] +fn a_tool_rails_idle_key_bytes_do_not_grow_with_its_slots() { + assert_eq!(idle_key_bytes(10), idle_key_bytes(100), "the key follows revisions, not the slots, the hidden or the remembered tools"); +} diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 51ae39283..398357f73 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -13,7 +13,7 @@ use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; use craft_ui::testing::in_audit_run; use craft_ui::testing::pointer::{moved, press}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_runs, last_pass_runs, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, trial}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -496,3 +496,17 @@ fn one_workspace_edit_reads_the_specs_once() { assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "the next pass builds nothing"); assert_eq!(spec_reads(), 0, "and reads no spec"); } + +/// The key bytes of an idle pass of a dock whose single group holds `tabs` panels. +fn idle_key_bytes(tabs: usize) -> usize { + let MemoDock { mut fixture, .. } = memo_dock(Layout::new(Some(Node::tabs((0..tabs).collect(), 0)), Vec::new()), None); + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an idle pass builds no derived value"); + last_pass_memo_key_bytes(fixture.ctx()) +} + +/// An idle dock feeds the same key bytes whatever the number of its panels. +#[trial] +fn a_docks_idle_key_bytes_do_not_grow_with_its_panels() { + assert_eq!(idle_key_bytes(4), idle_key_bytes(32), "the tab row's key follows the dock's revisions, not its titles"); +} From 75f2d453b034be3c605fd077e354ce3dfbc16f7d Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 14:58:19 +0000 Subject: [PATCH 18/89] craft-ui-panels: the tool rail's slots, last-used tools and hidden tools are Tracked values, so its key does not walk them --- crates/color-ui/src/ui/pair/stories.rs | 4 +- crates/imaging/src/ui/fill/mod.rs | 19 +++--- crates/imaging/src/ui/fill/tool.rs | 2 +- crates/imaging/src/ui/liquify/mod.rs | 28 ++++++--- crates/imaging/src/ui/liquify/tools.rs | 2 +- crates/imaging/src/ui/select_mask/mod.rs | 17 ++--- crates/imaging/src/ui/select_mask/tools.rs | 2 +- .../src/ui/vanishing_point/commands.rs | 2 +- crates/imaging/src/ui/vanishing_point/mod.rs | 20 +++--- crates/imaging/src/ui/wide_angle/mod.rs | 39 ++++++++---- crates/ui-gallery/src/mock/editor.rs | 2 +- crates/ui-gallery/src/mock/model.rs | 9 ++- crates/ui-gallery/src/mock/panels.rs | 15 ++--- crates/ui-panels/src/rails/drawer/stories.rs | 5 +- crates/ui-panels/src/rails/tool.rs | 62 ++++++++++++------- crates/ui-panels/src/rails/tool/data.rs | 6 +- crates/ui-panels/src/rails/tool/stories.rs | 6 +- crates/ui-panels/src/rails/tool/trials.rs | 19 +++--- crates/ui-panels/tests/it/rails/drawer.rs | 11 ++-- 19 files changed, 164 insertions(+), 106 deletions(-) diff --git a/crates/color-ui/src/ui/pair/stories.rs b/crates/color-ui/src/ui/pair/stories.rs index 3941bdef6..c4c0279f7 100644 --- a/crates/color-ui/src/ui/pair/stories.rs +++ b/crates/color-ui/src/ui/pair/stories.rs @@ -3,7 +3,7 @@ use super::{PairWell, SwatchPair, Well}; use craft_behavior::Mixed; use craft_theme::Srgba; -use craft_ui::contract::{Show as _, Validity}; +use craft_ui::contract::{Show as _, Tracked, Validity}; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -101,7 +101,7 @@ fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (active, active_at) = data.value_at("active", Well::Primary); - let (slots, last): (Vec>, LastUsed) = (Vec::new(), LastUsed::default()); + let (slots, last): (Tracked>>, Tracked>) = (Tracked::default(), Tracked::default()); let wells = [PairWell::new("Foreground colour", Srgba::rgb(0.0, 0.0, 0.0)), PairWell::new("Background colour", Srgba::rgb(1.0, 1.0, 1.0))]; let mut shown = None; ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| { diff --git a/crates/imaging/src/ui/fill/mod.rs b/crates/imaging/src/ui/fill/mod.rs index 7653eea8d..0847dce26 100644 --- a/crates/imaging/src/ui/fill/mod.rs +++ b/crates/imaging/src/ui/fill/mod.rs @@ -62,7 +62,7 @@ use craft_ui::buttons::IconButton; use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff}; use craft_ui::canvas_controls::{Marquee, MarqueeLook}; -use craft_ui::contract::{Bind, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, Tracked, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; use craft_ui::dialog::{ DialogResult, DialogWords, FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, @@ -238,7 +238,8 @@ pub struct ContentAwareFillWorkspace { preview_view: FullWindowView, framing: PreviewFraming, tool: FillTool, - last_used: LastUsed, + last_used: Tracked>, + slots: Tracked>>, options: FillToolOptions, canvas: FillCanvas, hand: HandTool, @@ -294,7 +295,8 @@ impl ContentAwareFillWorkspace { preview_view: FullWindowView::new(), framing: PreviewFraming::default(), tool: FillTool::SamplingBrush, - last_used: LastUsed::default(), + last_used: Tracked::new(LastUsed::default()), + slots: Tracked::new(FillTool::slots()), canvas: FillCanvas::new(), hand: HandTool::new(navigation), zoom: ZoomTool::new(navigation), @@ -388,7 +390,6 @@ impl ContentAwareFillWorkspace { let params = env.words::(); let title = FullWindowTitle::new(env.words::().name.clone()).subject(self.subject.clone()).zoom(self.view.zoom_percent()).label(&env); - let slots = FillTool::slots(); let mut reset_all = false; let this = RefCell::new(&mut *self); @@ -410,7 +411,7 @@ impl ContentAwareFillWorkspace { }) .show(ui, |ui, cx| { let mut guard = this.borrow_mut(); - guard.show_body(ui, cx, &env, &slots, source); + guard.show_body(ui, cx, &env, source); }); let work = this.into_inner(); @@ -604,7 +605,7 @@ impl ContentAwareFillWorkspace { } /// The body: the steps and keys, the options bar, the tool strip and the canvas; then the preview job. - fn show_body(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, env: &Env, slots: &[ToolSlot], source: &dyn FillSource) { + fn show_body(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, env: &Env, source: &dyn FillSource) { let ctx = ui.ctx().clone(); let words = env.words::(); while let Some((command, _)) = cx.take_command::() { @@ -623,7 +624,7 @@ impl ContentAwareFillWorkspace { if fired.phase == FirePhase::Release { continue; } - let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool)); + let slot = self.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool)); let tools: Vec<&RailTool> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect(); let picked = slot.and_then(|slot| { tool_pick(&tools, slot.id, &self.tool, &self.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id)) @@ -652,9 +653,9 @@ impl ContentAwareFillWorkspace { } Row::new().fill().show(ui, |ui, _| { - let rail = ToolRail::new(words.tools.clone(), slots, &self.tool, &self.last_used).show_column(ui, |_, _| {}); + let rail = ToolRail::new(words.tools.clone(), &self.slots, &self.tool, &self.last_used).show_column(ui, |_, _| {}); if let Some(next) = rail.last_used { - self.last_used = next; + *self.last_used = next; } if let Some(tool) = rail.select { self.pick(Some(&ctx), tool); diff --git a/crates/imaging/src/ui/fill/tool.rs b/crates/imaging/src/ui/fill/tool.rs index cdf9d350f..83ecfb942 100644 --- a/crates/imaging/src/ui/fill/tool.rs +++ b/crates/imaging/src/ui/fill/tool.rs @@ -18,7 +18,7 @@ use super::session::{FillLimit, FillLimits, FillSession, FillStrokeEvent, Sampli use crate::ui::select_mask::EditMode; /// The tools of Content-Aware Fill's strip: Sampling Brush (B), Lasso (L), Hand (H), Zoom (Z). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum FillTool { /// The Sampling Brush. diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index b0346aebf..4f7709952 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -72,14 +72,14 @@ use craft_behavior::{CancelReason, Cursor, EditEvent, EditHistory, Mixed}; use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, tool_pick}; use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff}; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Tracked, Pattern, Props as _, Show as _, ShowContainer as _}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, }; use craft_ui::layout_components::Row; use craft_ui::primitives::Checker; -use craft_ui::rails::{LastUsed, ToolRail}; +use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase}; use craft_ui::runtime::env::Env; use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; @@ -223,15 +223,28 @@ pub struct LiquifyDone { /// What the workspace keeps between passes besides the session: the view, the strip's memory and the tool in progress. None of it is /// the app's, and none of it is in the history. -#[derive(Clone, Default)] +#[derive(Clone)] struct LiquifyView { view: FullWindowView, - last_used: LastUsed, + last_used: Tracked>, + slots: Tracked>>, canvas: LiquifyCanvas, /// The canvas the tools run under, to cancel their gestures outside a pass. canvas_id: Option, } +impl Default for LiquifyView { + fn default() -> Self { + LiquifyView { + view: FullWindowView::default(), + last_used: Tracked::default(), + slots: Tracked::new(LiquifyTool::slots()), + canvas: LiquifyCanvas::default(), + canvas_id: None, + } + } +} + /// The Liquify workspace: the session and its history and the settings, as one value the app keeps while Liquify /// is open, with the view, the strip's memory and the stroke in progress. /// @@ -441,7 +454,6 @@ impl LiquifyWorkspace { self.edit.events.push(LiquifyEvent::BackdropWanted(of)); self.asked = Some(of); } - let slots = LiquifyTool::slots(); let preview_label = words.preview.clone(); let this = RefCell::new(&mut *self); @@ -499,7 +511,7 @@ impl LiquifyWorkspace { if fired.phase == FirePhase::Release { continue; } - let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool)); + let slot = work.view.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool)); let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect(); let picked = slot.and_then(|slot| { tool_pick(&tools, slot.id, &work.edit.settings.tool, &work.view.last_used, PickStep::of(&fired), |_| true) @@ -544,9 +556,9 @@ impl LiquifyWorkspace { .fill() .show(ui, |ui, _| { let rail = - ToolRail::new(words.tools.clone(), &slots, &work.edit.settings.tool, &state.last_used).show_column(ui, |_, _| {}); + ToolRail::new(words.tools.clone(), &state.slots, &work.edit.settings.tool, &state.last_used).show_column(ui, |_, _| {}); if let Some(next) = rail.last_used { - state.last_used = next; + *state.last_used = next; } if let Some(tool) = rail.select { work.edit.pick(Some(&ctx), state, tool); diff --git a/crates/imaging/src/ui/liquify/tools.rs b/crates/imaging/src/ui/liquify/tools.rs index d30b5c973..276efd901 100644 --- a/crates/imaging/src/ui/liquify/tools.rs +++ b/crates/imaging/src/ui/liquify/tools.rs @@ -11,7 +11,7 @@ use super::session::{LiquifyStroke, StrokeEvent}; /// The tools of Liquify's strip, in strip order, with Photoshop's letters. Serialised with the /// engine's names (`forwardWarp`, `twirlCw`, `lassoMask`, …) so a [`LiquifyStroke`] passes to /// PhotoCraft's engine unchanged. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum LiquifyTool { diff --git a/crates/imaging/src/ui/select_mask/mod.rs b/crates/imaging/src/ui/select_mask/mod.rs index 4982a9b00..dbeb70393 100644 --- a/crates/imaging/src/ui/select_mask/mod.rs +++ b/crates/imaging/src/ui/select_mask/mod.rs @@ -68,14 +68,14 @@ use craft_theme::Srgba; use craft_ui::buttons::IconButton; use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff}; -use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, Tracked, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, }; use craft_ui::layout_components::{Row, Stack}; use craft_ui::primitives::Checker; -use craft_ui::rails::{LastUsed, ToolRail}; +use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase}; use craft_ui::runtime::edit::next_gesture_id; use craft_ui::runtime::env::Env; @@ -295,7 +295,8 @@ pub struct SelectMaskWorkspace { view: FullWindowView, mask_view: MaskViewState, tool: SelectMaskTool, - last_used: LastUsed, + last_used: Tracked>, + slots: Tracked>>, options: SelectMaskToolOptions, canvas: SelectMaskCanvas, zoom_tool: ZoomTool, @@ -351,7 +352,8 @@ impl SelectMaskWorkspace { checkerboard: open.checkerboard, view: FullWindowView::new(), tool: SelectMaskTool::Quick, - last_used: LastUsed::default(), + last_used: Tracked::new(LastUsed::default()), + slots: Tracked::new(SelectMaskTool::slots()), options: SelectMaskToolOptions::default(), canvas, zoom_tool: ZoomTool::new(open.navigation), @@ -486,7 +488,6 @@ impl SelectMaskWorkspace { let words = env.words::(); let common = env.words::(); let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env); - let slots = SelectMaskTool::slots(); self.start_pass(ui.ctx()); let request = self.request_now(); let key = format!("{request:?}"); @@ -552,7 +553,7 @@ impl SelectMaskWorkspace { if fired.phase == FirePhase::Release { continue; } - let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool)); + let slot = work.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool)); let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect(); let picked = slot.and_then(|slot| { tool_pick(&tools, slot.id, &work.tool, &work.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id)) @@ -590,9 +591,9 @@ impl SelectMaskWorkspace { let preview = falloff.as_ref().and_then(|falloff| work.canvas.resize().preview(falloff)); let shown = Row::new().fill().show(ui, |ui, _| { - let rail = ToolRail::new(words.tools.clone(), &slots, &work.tool, &work.last_used).show_column(ui, |_, _| {}); + let rail = ToolRail::new(words.tools.clone(), &work.slots, &work.tool, &work.last_used).show_column(ui, |_, _| {}); if let Some(next) = rail.last_used { - work.last_used = next; + *work.last_used = next; } if let Some(tool) = rail.select { work.pick(Some(&ctx), tool); diff --git a/crates/imaging/src/ui/select_mask/tools.rs b/crates/imaging/src/ui/select_mask/tools.rs index 51e40d898..f84d70e59 100644 --- a/crates/imaging/src/ui/select_mask/tools.rs +++ b/crates/imaging/src/ui/select_mask/tools.rs @@ -84,7 +84,7 @@ impl EditPhase { /// The tools of Select and Mask's strip, with Photoshop's letters. Quick Selection and Object /// Selection share the W slot, Lasso and Polygonal Lasso the L slot. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum SelectMaskTool { /// W. diff --git a/crates/imaging/src/ui/vanishing_point/commands.rs b/crates/imaging/src/ui/vanishing_point/commands.rs index 208a7c5a3..c4ffe21f0 100644 --- a/crates/imaging/src/ui/vanishing_point/commands.rs +++ b/crates/imaging/src/ui/vanishing_point/commands.rs @@ -47,7 +47,7 @@ pub enum VanishingPointStripTool { } /// A slot of the strip. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] pub(super) enum Pick { EditPlane, CreatePlane, diff --git a/crates/imaging/src/ui/vanishing_point/mod.rs b/crates/imaging/src/ui/vanishing_point/mod.rs index 507b004ba..cdd1f6cdc 100644 --- a/crates/imaging/src/ui/vanishing_point/mod.rs +++ b/crates/imaging/src/ui/vanishing_point/mod.rs @@ -52,7 +52,7 @@ use craft_behavior::edit_history::Step; use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed}; use craft_ui::bars::StatusMessage; use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; -use craft_ui::contract::{Bind, Job, Pending, Remember as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Job, Tracked, Pending, Remember as _, Show as _, ShowContainer as _}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, @@ -187,14 +187,21 @@ pub enum VanishingPointEvent { } /// What the dialog's body keeps between passes: the view, the strip's memory and the canvas the tools run under. -#[derive(Clone, Default)] +#[derive(Clone)] struct VanishingView { view: FullWindowView, - last_used: LastUsed, + last_used: Tracked>, + slots: Tracked>>, /// The canvas the tools run under, to cancel their gestures outside a pass. canvas: Option, } +impl Default for VanishingView { + fn default() -> Self { + VanishingView { view: FullWindowView::default(), last_used: Tracked::default(), slots: Tracked::new(slots()), canvas: None } + } +} + /// The New Plane form's state. #[derive(Clone, Default)] struct NewPlaneState { @@ -368,7 +375,6 @@ impl FullWindowWorkspace for VanishingPointWorkspace { let words = env.words::(); let common = env.words::(); let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env); - let slots = slots(); let status: RefCell>> = RefCell::new(None); let events = RefCell::new(Vec::::new()); let shown_canvas = std::cell::Cell::new(None); @@ -416,7 +422,7 @@ impl FullWindowWorkspace for VanishingPointWorkspace { } // A tool key's release picks nothing. let Some(pick) = command.pick().filter(|_| fired.phase != FirePhase::Release) else { continue }; - let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == pick)); + let slot = state.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == pick)); let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect(); let current = Pick::of(work.strip, work.editor.tool()); let picked = slot.and_then(|slot| { @@ -464,9 +470,9 @@ impl FullWindowWorkspace for VanishingPointWorkspace { let shown = Row::new() .fill() .show(ui, |ui, _| { - let rail = ToolRail::new(words.tools.clone(), &slots, ¤t, &state.last_used).show_column(ui, |_, _| {}); + let rail = ToolRail::new(words.tools.clone(), &state.slots, ¤t, &state.last_used).show_column(ui, |_, _| {}); if let Some(next) = rail.last_used { - state.last_used = next; + *state.last_used = next; } chosen = rail.select.filter(|pick| *pick != current); let mut canvas = FullWindowCanvas::new(Bind::bound(&mut state.view), image) diff --git a/crates/imaging/src/ui/wide_angle/mod.rs b/crates/imaging/src/ui/wide_angle/mod.rs index 99593ec61..1ea5215fa 100644 --- a/crates/imaging/src/ui/wide_angle/mod.rs +++ b/crates/imaging/src/ui/wide_angle/mod.rs @@ -37,7 +37,7 @@ use std::time::Duration; use craft_behavior::edit_history::Step; use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed}; use craft_ui::canvas::{CanvasTool, HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; -use craft_ui::contract::{Bind, Pattern, Remember as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Tracked, Pattern, Remember as _, Show as _, ShowContainer as _}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, @@ -58,7 +58,7 @@ use serde_json::Value; use crate::ui::live_preview::settings_hash; /// The tools of the strip. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum WideAngleTool { /// A. @@ -146,11 +146,12 @@ pub enum WideAngleEvent { } /// The state the dialog body keeps between passes: what the app does not read. -#[derive(Clone, Default)] +#[derive(Clone)] struct Body { view: Option, tool: WideAngleTool, - last_used: LastUsed, + last_used: Tracked>, + slots: Tracked>>, constraint: ConstraintTool, hand: Option, zoom: Option, @@ -162,6 +163,24 @@ struct Body { adding: bool, } +impl Default for Body { + fn default() -> Self { + let slots = TOOL_SLOT.iter().zip(0..).map(|(&(tool, command), slot)| ToolSlot::new(slot, vec![RailTool::new(tool, command)])).collect(); + Body { + view: None, + tool: WideAngleTool::default(), + last_used: Tracked::default(), + slots: Tracked::new(slots), + constraint: ConstraintTool::default(), + hand: None, + zoom: None, + canvas: None, + menu: None, + adding: false, + } + } +} + /// A change the passes ask of the session, applied after the dialog has been shown. enum Action { /// The panel's correction edit. @@ -349,11 +368,9 @@ impl FullWindowWorkspace for WideAngleWorkspace { end_gesture(&ctx, &mut body, CancelReason::UndoDuringGesture); } - let slots: Vec> = - TOOL_SLOT.iter().zip(0..).map(|(&(tool, command), slot)| ToolSlot::new(slot, vec![RailTool::new(tool, command)])).collect(); let mut next = None; while let Some((command, fired)) = cx.take_command::() { - next = pick(&slots, command, &fired, &body).or(next); + next = pick(command, &fired, &body).or(next); } let image = source.source(); @@ -369,10 +386,10 @@ impl FullWindowWorkspace for WideAngleWorkspace { } Row::new().fill().show(ui, |ui, _| { - let rail = ToolRail::new(words.tools.clone(), &slots, &body.tool, &body.last_used).show_column(ui, |_, _| {}); + let rail = ToolRail::new(words.tools.clone(), &body.slots, &body.tool, &body.last_used).show_column(ui, |_, _| {}); next = rail.select.or(next); if let Some(last_used) = rail.last_used { - body.last_used = last_used; + *body.last_used = last_used; } if let Some(tool) = next.take().filter(|tool| *tool != body.tool) { end_gesture(&ctx, &mut body, CancelReason::Removed); @@ -566,12 +583,12 @@ fn edit_name<'a>(words: &'a WideAngleWords, edit: &WideAngleConstraintEdit) -> & } /// The tool a fired tool command picks, through its slot's pick rule; a tool key's release picks nothing. -fn pick(slots: &[ToolSlot], command: WideAngleCommands, fired: &Fired, body: &Body) -> Option { +fn pick(command: WideAngleCommands, fired: &Fired, body: &Body) -> Option { if fired.phase == FirePhase::Release { return None; } let tool = TOOL_SLOT.iter().find(|(_, c)| *c == command)?.0; - let slot = slots.iter().find(|slot| slot.tools.iter().any(|t| t.id == tool))?; + let slot = body.slots.iter().find(|slot| slot.tools.iter().any(|t| t.id == tool))?; let visible: Vec<&RailTool> = slot.tools.iter().collect(); tool_pick(&visible, slot.id, &body.tool, &body.last_used, PickStep::of(fired), |_| true).map(|t| t.id) } diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index b381a6057..ec79b3dc0 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -96,7 +96,7 @@ impl<'a> EditorMock<'a> { fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { let mut tools = cx.keep::().clone(); let (events, picked) = { - let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, last_used: &mut state.last_used, picked: None }; + let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, slots: &state.slots, last_used: &mut state.last_used, picked: None }; // The mock app is a preview inside the gallery's page: its floats stay in it. let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default().native_windows(false)) diff --git a/crates/ui-gallery/src/mock/model.rs b/crates/ui-gallery/src/mock/model.rs index 691d3a8f1..b953bd304 100644 --- a/crates/ui-gallery/src/mock/model.rs +++ b/crates/ui-gallery/src/mock/model.rs @@ -33,7 +33,7 @@ const TOOLS_DOCK_WIDTH: f32 = 120.0; /// The tools of the rail. Each is a command of the `tools` group; a tool alone in its slot carries its letter, and the /// letter of a slot with several is the pick command of [`ToolKey`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[command(prefix = "mockTool")] #[non_exhaustive] pub enum Tool { @@ -414,7 +414,9 @@ pub struct MockState { /// The current tool. pub tool: Tool, /// The tool each rail slot showed last. - pub last_used: LastUsed, + pub last_used: Tracked>, + /// The rail's slots. + pub slots: Tracked>>, /// The status bar's item. pub status_item: StatusItem, /// The status bar's message: the newest thing the mock had to say. @@ -442,7 +444,8 @@ impl Default for MockState { specs: Tracked::new(MockSpecs), document: Document::default(), tool: Tool::Move, - last_used: LastUsed::default(), + last_used: Tracked::new(LastUsed::default()), + slots: Tracked::new(Tool::slots()), status_item: StatusItem::DocumentDimensions, status: None, colors: ColorPair::default(), diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index 1a8d3434f..e83065144 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -13,7 +13,7 @@ use craft_ui::canvas::{ tool_pass, }; use craft_ui::canvas_controls::{Guides, Marquee}; -use craft_ui::contract::SizeLimits; +use craft_ui::contract::{SizeLimits, Tracked}; use craft_ui::contract::{ Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, MemoProps, MemoView, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SweepApply, SweepStep, ToggleColumn, WordSetCx as _, @@ -22,7 +22,7 @@ use craft_ui::docking::{DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs}; use craft_ui::list::{ListRow, ToggleCell}; use craft_ui::patterns::canvas::NavigatorPanel; use craft_ui::primitives::textures::Revision; -use craft_ui::rails::{LastUsed, ToolRail}; +use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::env::UnitKind; use craft_ui::shell::CanvasPanel; use craft_ui::table::Table; @@ -45,7 +45,9 @@ pub(super) struct Panels<'a> { pub(super) tool: Tool, pub(super) tools: &'a mut Tools, /// The tool each toolbar slot showed last; the toolbar writes it. - pub(super) last_used: &'a mut LastUsed, + pub(super) last_used: &'a mut Tracked>, + /// The toolbar's slots. + pub(super) slots: &'a Tracked>>, /// The tool the toolbar picked in this pass. pub(super) picked: Option, } @@ -58,9 +60,8 @@ impl Panels<'_> { /// The toolbar's rail in the rect the dock gives it, or its height at a width: as many tool columns as the width /// holds. The rail's own padding surrounds the buttons, so no group padding applies. fn toolbar(&mut self, ui: &mut Ui, at: GroupAt) -> f32 { - let slots = Tool::slots(); - let (current, last_used) = (self.tool, self.last_used.clone()); - let rail = ToolRail::new("Tools", &slots, ¤t, &last_used); + let current = self.tool; + let rail = ToolRail::new("Tools", self.slots, ¤t, self.last_used); match at { GroupAt::Measure(width) => rail.measure_rail(ui, width, |_, _| {}).y, GroupAt::Show(rect) => { @@ -69,7 +70,7 @@ impl Panels<'_> { self.picked = output.select; } if let Some(next) = output.last_used { - *self.last_used = next; + **self.last_used = next; } rect.height() } diff --git a/crates/ui-panels/src/rails/drawer/stories.rs b/crates/ui-panels/src/rails/drawer/stories.rs index eb22e6385..1218fe7c8 100644 --- a/crates/ui-panels/src/rails/drawer/stories.rs +++ b/crates/ui-panels/src/rails/drawer/stories.rs @@ -1,6 +1,7 @@ //! Stories of `ToolbarDrawer`. use super::{DrawerGroup, ToolbarDrawer}; +use crate::contract::Tracked; use crate::rails::tool::stories::{BRUSH, tools}; use crate::rails::tool::{LastUsed, ToolRail, ToolSlot}; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -11,8 +12,8 @@ use egui::Ui; #[story(ToolbarDrawer<'static, u8>, covers = [], drive = Drive::Never)] fn toolbar_drawer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let groups = [DrawerGroup::new("Drawing", tools(&[0, 1, 2])), DrawerGroup::new("Retouching", tools(&[3, 4]))]; - let slots = [ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))]; - let last = LastUsed::default(); + let slots = Tracked::new(vec![ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))]); + let last = Tracked::new(LastUsed::default()); let rail = ToolRail::new("Tools", &slots, &BRUSH, &last).edit_toolbar("Edit Toolbar").show_rail(ui, |_, _| {}); let open = data.value("open", false); let Some(opener) = rail.edit_toolbar.as_ref() else { return rail.into() }; diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index e1b74bd1d..8f68463fe 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -8,7 +8,7 @@ use crate::contract::{ Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, NoValue, Outcome, Pad, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, WordSetCx as _, }; -use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox}; +use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox, PlainData, Tracked}; use crate::docking::{DockGrid, DockSizes}; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; @@ -102,14 +102,14 @@ type FooterFn<'a> = Box; /// grid. While the toolbar is edited the buttons are dragged and take drops, and report the drop in the output. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, probe(ToolRail<'static, u8>))] -pub struct ToolRail<'a, T: Value + MemoProps + 'static> { +pub struct ToolRail<'a, T: Value + MemoProps + PlainData + 'static> { #[common] common: Common, #[container] props: ContainerProps, - slots: &'a [ToolSlot], + slots: &'a Tracked>>, current: &'a T, - last_used: &'a LastUsed, + last_used: &'a Tracked>, /// The side of the rail its flyouts and drawer open on: the side of the canvas. #[prop] opens: Side, @@ -120,17 +120,16 @@ pub struct ToolRail<'a, T: Value + MemoProps + 'static> { #[prop(flag)] editing: bool, /// The tools the user's toolbar settings hide. - #[prop] - hidden: &'a [T], + hidden: Option<&'a Tracked>>, footer: Option>, /// The columns the rail lays out in this pass. columns: usize, } -impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { +impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { /// A one-column rail named `label` over `slots`, with `current` the host's tool and `last_used` what the slots /// showed last. - pub fn new(label: impl Into

{ /// Which panels the host hides. Protected panels always stay. While the shell hides the panels and keeps the tools /// (Shift+Tab), the panels `Except` names stay and every other panel hides; while it hides the dock (Tab), every panel /// hides. +/// +/// The set is a `Tracked` value, so a dock keys what it shows by the set's revision and keeps the pruned layout until +/// the set, the workspace or the shell's visibility changes. +#[derive(Clone, Copy)] #[non_exhaustive] -pub enum HidePanels<'a, P> { +pub enum HidePanels<'a> { /// Hides none. None, /// Hides every panel. All, - /// Every panel except those for which the function returns true. - Except(&'a dyn Fn(&P) -> bool), + /// Every panel except those whose [`PanelKey`] the set holds. + Except(&'a Tracked>), } -impl

Clone for HidePanels<'_, P> { - fn clone(&self) -> Self { - *self +impl MemoProps for HidePanels<'_> { + fn key(&self, key: &mut MemoKey) { + match self { + HidePanels::None => key.write_u32(0), + HidePanels::All => key.write_u32(1), + HidePanels::Except(keep) => { + key.write_u32(2); + keep.key(key); + } + } } } -impl

Copy for HidePanels<'_, P> {} - /// Where a docking command floats a panel, group or column when it gives no rect. A dock records one each pass; /// the host reads it to turn a command into placements. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/ui-panels/src/docking/frame.rs b/crates/ui-panels/src/docking/frame.rs index e57718e4c..3c95ae5d4 100644 --- a/crates/ui-panels/src/docking/frame.rs +++ b/crates/ui-panels/src/docking/frame.rs @@ -1,6 +1,7 @@ //! What the tree adds around the groups: Maximize Frame, the hidden-panel prune and the outer edge bands. use super::config::DockConfig; +use super::PanelKey; use super::event::HidePanels; use super::targets::{DockSizes, DockSpot, DockTargets}; use super::tree; @@ -27,6 +28,11 @@ pub struct FrameView<'a, P: Clone> { } impl FrameView<'_, P> { + /// The view with its layout owned, to keep it past the layout it was made from. + pub fn into_owned(self) -> FrameView<'static, P> { + FrameView { layout: Cow::Owned(self.layout.into_owned()), maximized: self.maximized, hidden: self.hidden, paths: self.paths } + } + /// Writes the split sizes of `edited`, an edit of the view's layout, into `layout`, the layout the view was made /// from. Panels the view left out keep their place; only the docked tree's split sizes change: floating windows /// have no splits. @@ -64,13 +70,13 @@ fn split_sizes

(node: &Node

, paths: &HashMap, Vec>) -> Vec< pub fn maximize<'a, P: Clone + Eq + Hash>( layout: &'a Layout

, maximized: Option<&P>, - hide: HidePanels<'_, P>, + hide: HidePanels<'_>, protected: &dyn Fn(&P) -> bool, ) -> FrameView<'a, P> { let hidden = |panel: &P| match hide { HidePanels::None => false, HidePanels::All => !protected(panel), - HidePanels::Except(keep) => !protected(panel) && !keep(panel), + HidePanels::Except(keep) => !protected(panel) && !keep.contains(&PanelKey::of(panel)), }; // Only a docked panel maximizes its frame. let frame = maximized.and_then(|panel| match layout.place(panel)? { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index ea0f215f2..16c7f8438 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -5,7 +5,7 @@ use super::commands::DockCommands; use super::drop::{self, DragUnit, start_group_drag}; use super::targets::{DockSizes, DockSpot, DockTargets, ZoneRule}; use super::words::DockWords; -use super::{PanelDrag, PanelKey, PanelTitle}; +use super::{PanelDrag, PanelKey, PanelTitle, Titles}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; use crate::contract::{ @@ -245,7 +245,7 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { #[container] props: ContainerProps, anchor: P, - panels: &'a [PanelTitle], + panels: Titles, active: PanelKey, /// Only the header shows; the body and its drop spots are left out. #[prop(flag)] @@ -292,10 +292,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup<'a, P> { /// The group named by `anchor` (one of its panels) with its `panels`, `active` showing. The group is named by the /// active panel's title. - pub fn new(anchor: P, panels: &'a [PanelTitle], active: PanelKey) -> Self { + pub fn new(anchor: P, panels: Titles, active: PanelKey) -> Self { let props = ContainerProps::new().sizing(Sizing::Fill).header(HeaderRegion::new().fill(SurfaceKind::Background)).command_scope(DockCommands::SCOPE); - let title = panels.iter().find(|panel| panel.key == active).map(|panel| panel.title.clone()).unwrap_or_default(); + let title = panels.as_slice().iter().find(|panel| panel.key == active).map(|panel| panel.title.clone()).unwrap_or_default(); DockGroup { common: Common::new(), props, @@ -445,7 +445,7 @@ impl Component for let Some(dock) = self.dock else { return }; let (rect, rtl, header) = (cx.rect, cx.flow.is_rtl(), cx.style.header); let strip = Rect::from_min_size(rect.min, Vec2::new(rect.width(), header)); - DockTargets::

::register(&cx.core.ctx, dock, DockSpot::tab(self.anchor.clone(), self.panels.len()), strip); + DockTargets::

::register(&cx.core.ctx, dock, DockSpot::tab(self.anchor.clone(), self.panels.as_slice().len()), strip); if self.minimized { return; } @@ -518,7 +518,7 @@ impl Container for } let row = TabRow { anchor: self.anchor.clone(), - panels: self.panels, + panels: self.panels.clone(), active: self.active, closable: self.closable, wheel_selects: self.wheel_selects_tabs, @@ -585,7 +585,7 @@ struct TabRow<'a, P> { /// The group's anchor panel, which names its drop spots. #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] anchor: P, - panels: &'a [PanelTitle], + panels: Titles, active: PanelKey, closable: bool, wheel_selects: bool, @@ -598,7 +598,7 @@ fn tab_row(row: &mu let env = crate::runtime::env::Env::of(ui); let name = Label::from(env.words::().panels.as_str().to_owned()); let rtl = env.direction.is_rtl(); - let (panels, active, closable) = (row.panels, row.active, row.closable); + let (panels, active, closable) = (row.panels.as_slice(), row.active, row.closable); let from = PanelKey::of(&row.anchor); let drags = crate::runtime::drag::started(ui.ctx()); let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str())); diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index bf4e19204..45552a3f7 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -78,13 +78,14 @@ use craft_behavior::{Axis, EditEvents, Flow, Metrics, PartKey, Sense}; use divider::{Divider, Drag}; use egui::{Rect, Response, Vec2}; use std::fmt::Debug; +use std::sync::Arc; use std::hash::{DefaultHasher, Hash, Hasher}; use tree::{FrameRules, SplitHandle}; const HANDLE: PartKey = PartKey::new("handle"); /// The stable key of a panel. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, crate::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, crate::contract::MemoProps, crate::contract::PlainData)] #[non_exhaustive] pub struct PanelKey(pub u64); @@ -114,6 +115,38 @@ pub struct PanelTitle { pub closable: bool, } +/// The tab titles of one group, with the key that stands for them in a memoized view's key. A host that keeps its +/// titles derived from revisions gives [`Titles::new`] the key it derived them under, so the key does not walk the +/// titles; [`Titles::from_content`] keys by the titles themselves. +#[derive(Clone, Debug)] +pub struct Titles { + list: Arc>, + key: u128, +} + +impl Titles { + /// The titles `list`, made from the inputs `key` follows: equal keys must mean equal titles. + pub fn new(key: &K, list: Arc>) -> Self { + Titles { list, key: crate::contract::MemoKey::of(key) } + } + + /// The titles `list`, keyed by their content: the key walks them. + pub fn from_content(list: Vec) -> Self { + Titles { key: crate::contract::MemoKey::of(&list), list: Arc::new(list) } + } + + /// The titles in tab order. + pub fn as_slice(&self) -> &[PanelTitle] { + &self.list + } +} + +impl crate::contract::MemoProps for Titles { + fn key(&self, key: &mut crate::contract::MemoKey) { + self.key.key(key); + } +} + impl PanelTitle { /// A panel `key` titled `title`, not closable from its tab. pub fn new(key: PanelKey, title: impl Into

, @@ -214,7 +215,7 @@ struct Drops<'a, P> { permissions: &'a dyn Fn(&P) -> Permissions, config: &'a DockConfig, specs: &'a HashMap, - hide: HidePanels<'a, P>, + hide: HidePanels<'a>, maximized: Option<&'a P>, rtl: bool, } @@ -254,9 +255,19 @@ struct Report

{ files: Vec, } +/// The inputs of the workspace's derived values: the workspace, the panels' specs and the lock. +#[derive(Clone, Copy, crate::contract::MemoProps)] +pub(super) struct ModelKey { + workspace: Revision, + specs: Revision, + locked: bool, +} + /// What every part of one pass reads. struct Scene<'s, P> { dock: Id, + /// The key the pruned layout was derived under: what every group's derived values follow. + view: u128, sizes: DockSizes, config: &'s DockConfig, layout: &'s Layout

, @@ -348,7 +359,7 @@ struct Look { /// What a group's header shows besides its panels' bodies: the tab titles, the panel menu's rows and whether the host /// gave any, and the panel commands' states. struct GroupParts { - titles: Vec, + titles: Titles, hosted: bool, states: Vec<(DockCommands, CommandState)>, } @@ -409,7 +420,8 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { Some(Mixed::Same(held)) => held, _ => Arc::default(), }; - let model = derived(&ctx, id, &(held.revision(), specs.revision(), locked), || DockModel::of(&held, specs, locked)); + let key = ModelKey { workspace: held.revision(), specs: specs.revision(), locked }; + let model = derived(&ctx, id, &key, || DockModel::of(&held, specs, locked)); let error = model.error.clone(); let current = if error.is_none() { held } else { Arc::default() }; let rights = &model.rights; @@ -449,6 +461,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { specs: &model.specs, keys: &model.keys, hide, + model: key, maximized: maximized.as_ref(), auto_collapse, sizes, @@ -549,7 +562,8 @@ struct Input<'i, P> { config: &'i DockConfig, specs: &'i HashMap, keys: &'i HashMap, - hide: HidePanels<'i, P>, + hide: HidePanels<'i>, + model: ModelKey, maximized: Option<&'i P>, auto_collapse: bool, sizes: DockSizes, @@ -578,16 +592,19 @@ fn show_area( panels: &mut dyn DockPanels

, mut flyout: Option<&mut Bind<'_, Option

>>, ) -> Passed

{ - let Input { id, ctx, current, config, specs, keys, hide, maximized, auto_collapse, sizes, rtl } = *input; + let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, sizes, rtl } = *input; let shell = body.shell(); let mut memory = body.memory::>().clone(); let protected = |panel: &P| rights.get(panel).is_some_and(|rights| rights.is_protected()); - let Shown { view, floating } = hide::shown(current.layout(), maximized, hide, shell.as_ref(), &protected); + let (hide, floating) = hide::resolved(hide, shell.as_ref()); + let prune = PruneKey { model, hide, floating, maximized: maximized.map(PanelKey::of) }; + let view = derived(ctx, id.with("pruned"), &prune, || frame::maximize(current.layout(), maximized, hide, &protected).into_owned()); let layout: &Layout

= &view.layout; let bounds = shell.as_ref().map_or(body.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, config, specs); let scene = Scene { dock: id, + view: MemoKey::of(&prune), sizes, config, layout, @@ -904,6 +921,7 @@ impl Pass<'_, P> { } let shown = &members[active]; let words = body.words::(); + let ctx = ui.ctx().clone(); let panels = RefCell::new(&mut *self.panels); // The tab titles, the menu rows and the panel commands' states, built when the group runs. // The tab titles, whether the host gives menu rows and the panel commands' states, built once per pass; the @@ -911,10 +929,14 @@ impl Pass<'_, P> { let parts: OnceCell = OnceCell::new(); let parts_of = || { parts.get_or_init(|| { - let titles = members - .iter() - .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) - .collect(); + let key = (scene.view, PanelKey::of(anchor)); + let list = derived(&ctx, scene.dock.with(("titles", key.1)), &key, || { + members + .iter() + .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) + .collect::>() + }); + let titles = Titles::new(&key, list); let hosted = !panels.borrow_mut().panel_rows(shown).is_empty(); let permissions = |panel: &P| scene.permissions(panel); let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &permissions).floated(scene.floated), shown); @@ -926,7 +948,7 @@ impl Pass<'_, P> { let panels = &panels; let words = &words; let GroupParts { titles, hosted, states } = parts_of(); - let mut group = DockGroup::new(anchor.clone(), titles, PanelKey::of(&members[at])) + let mut group = DockGroup::new(anchor.clone(), titles.clone(), PanelKey::of(&members[at])) .extra(move |ui, body| panels.borrow_mut().group_header(members, at, ui, body)) .dock(self.dock) .zones(scene.config.zone_rule()) diff --git a/crates/ui-patterns/src/patterns/dock/hide.rs b/crates/ui-patterns/src/patterns/dock/hide.rs index 7ea931261..944613d3b 100644 --- a/crates/ui-patterns/src/patterns/dock/hide.rs +++ b/crates/ui-patterns/src/patterns/dock/hide.rs @@ -1,39 +1,27 @@ //! The hidden-panel prune of a dock area: what the host hides, the shell's panel visibility and Maximize Frame -//! decide which panels the area shows. +//! decide which panels the area shows. The area derives the pruned layout under a [`PruneKey`] and keeps it while the +//! key holds. -use crate::docking::HidePanels; -use crate::docking::frame::{FrameView, maximize}; +use super::area::ModelKey; +use crate::docking::{HidePanels, PanelKey}; use crate::runtime::env::ShellCx; -use craft_behavior::dock::Layout; -use std::hash::Hash; -/// The layout as the area shows it, and whether its floating windows show. -pub(super) struct Shown<'a, P: Clone> { - /// The pruned layout with its write-back map. - pub(super) view: FrameView<'a, P>, - /// Floating windows show: the shell shows them, or it hides the panels and the view keeps what the host names. +/// What the pruned layout is a function of: the workspace, the specs and the lock (the protected panels), what is +/// hidden after the shell's visibility, whether floating windows show and the maximized panel. +#[derive(crate::contract::MemoProps)] +pub(super) struct PruneKey<'h> { + pub(super) model: ModelKey, + pub(super) hide: HidePanels<'h>, pub(super) floating: bool, -} - -/// `layout` with the host's `hide`, the shell's panel visibility and the frame of `maximized` applied. Protected -/// panels always stay, so a canvas shows while the dock is hidden. While the shell hides the panels and keeps the -/// tools (Shift+Tab), the panels the host's `HidePanels::Except` names stay, docked or floating, and every other panel -/// hides; while the shell hides the dock (Tab, body-only mode), every panel hides. Size edits made on the view go back -/// through `FrameView::write_back`. -pub(super) fn shown<'a, P: Clone + Eq + Hash>( - layout: &'a Layout

, - maximized: Option<&P>, - hide: HidePanels<'_, P>, - shell: Option<&ShellCx>, - protected: &dyn Fn(&P) -> bool, -) -> Shown<'a, P> { - let (hide, floating) = resolved(hide, shell); - Shown { view: maximize(layout, maximized, hide, protected), floating } + pub(super) maximized: Option, } /// The panels the area hides, the host's `hide` with the shell's panel visibility applied, and whether floating windows -/// show (see [`shown`]). -pub(super) fn resolved<'h, P>(hide: HidePanels<'h, P>, shell: Option<&ShellCx>) -> (HidePanels<'h, P>, bool) { +/// show. Protected panels always stay, so a canvas shows while the dock is hidden. While the shell hides the panels and +/// keeps the tools (Shift+Tab), the panels the host's `HidePanels::Except` names stay, docked or floating, and every +/// other panel hides; while the shell hides the dock (Tab, body-only mode), every panel hides. Size edits made on the +/// pruned view go back through `FrameView::write_back`. +pub(super) fn resolved<'h>(hide: HidePanels<'h>, shell: Option<&ShellCx>) -> (HidePanels<'h>, bool) { match shell { None => (hide, true), Some(shell) if shell.panels_hidden() => (if let HidePanels::Except(keep) = hide { HidePanels::Except(keep) } else { HidePanels::All }, true), diff --git a/crates/ui-patterns/tests/it/docking/drop_session.rs b/crates/ui-patterns/tests/it/docking/drop_session.rs index 21677b6d8..80c1a314a 100644 --- a/crates/ui-patterns/tests/it/docking/drop_session.rs +++ b/crates/ui-patterns/tests/it/docking/drop_session.rs @@ -6,7 +6,7 @@ use craft_behavior::dock::{Layout, Node, Permissions, SplitSize}; use craft_ui::contract::SizeLimits; use craft_ui::contract::{Bind, Common, Component, Cx, MeasureCx, Pointer as _, Role, Show as _, ShowContainer as _}; use craft_ui::docking::tree::{self, FrameRules}; -use craft_ui::docking::{DockDropTarget, DockDropped, DockGroup, DockSizes, GroupDrag, PanelDrag, PanelKey, PanelTitle, SplitArea}; +use craft_ui::docking::{DockDropTarget, DockDropped, DockGroup, DockSizes, GroupDrag, PanelDrag, PanelKey, PanelTitle, SplitArea, Titles}; use craft_ui::runtime::drag; use craft_ui::style::{ComponentStyle, StyleCx}; use craft_ui::testing::pointer::{moved, press, release}; @@ -130,7 +130,7 @@ fn bed(layout: Layout) -> Bed { for (anchor, panels, rect) in &placed { let titles: Vec = panels.iter().map(|panel| PanelTitle::new(PanelKey::of(panel), panel.clone())).collect(); let active = titles.first().map_or(PanelKey::new(0), |title| title.key); - DockGroup::new(anchor.clone(), &titles, active).dock(dock_id()).show_at(ui, *rect, |_, _| ()); + DockGroup::new(anchor.clone(), Titles::from_content(titles.clone()), active).dock(dock_id()).show_at(ui, *rect, |_, _| ()); } }); for dropped in shared_taken.borrow_mut().drain(..) { diff --git a/crates/ui-patterns/tests/it/docking/hidden.rs b/crates/ui-patterns/tests/it/docking/hidden.rs index 64cfec75e..263178cd0 100644 --- a/crates/ui-patterns/tests/it/docking/hidden.rs +++ b/crates/ui-patterns/tests/it/docking/hidden.rs @@ -3,7 +3,7 @@ use craft_behavior::Axis; use craft_behavior::dock::{Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; -use craft_ui::docking::{DockConfig, DockPanels, HidePanels, PanelSpec, PanelSpecs}; +use craft_ui::docking::{DockConfig, DockPanels, HidePanels, PanelKey, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::env::{BodyMode, ShellCx, ShellEntry, WindowKey}; use craft_ui::testing::{Fixture, trial}; @@ -65,7 +65,7 @@ fn shown_under(shell: ShellCx, keeps: bool) -> BTreeSet { let mut workspace = Arc::new(Workspace::new(layout())); let mut panels = Panels { shown: Rc::clone(&seen) }; let specs = Tracked::new(Specs); - let keep = |panel: &usize| *panel == TOOLBAR || *panel == PALETTE; + let keep = Tracked::new(BTreeSet::from([PanelKey::of(&TOOLBAR), PanelKey::of(&PALETTE)])); let mut area = DockArea::new("Hidden dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()); if keeps { area = area.hide(HidePanels::Except(&keep)); diff --git a/crates/ui-patterns/tests/it/docking/split.rs b/crates/ui-patterns/tests/it/docking/split.rs index 89df28103..47825ed49 100644 --- a/crates/ui-patterns/tests/it/docking/split.rs +++ b/crates/ui-patterns/tests/it/docking/split.rs @@ -2,14 +2,15 @@ use craft_behavior::Axis; use craft_behavior::dock::{Column, Group, Layout, Node, SplitSize}; -use craft_ui::contract::Role; +use craft_ui::contract::{Role, Tracked}; use craft_ui::docking::frame::maximize; use craft_ui::docking::tree; -use craft_ui::docking::{DockColumn, HidePanels, PanelSpec}; +use craft_ui::docking::{DockColumn, HidePanels, PanelKey, PanelSpec}; use craft_ui::testing::memory::global; use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, trial}; use egui::{Pos2, Rect}; +use std::collections::BTreeSet; use std::cell::RefCell; use std::rc::Rc; @@ -64,7 +65,7 @@ fn a_column_divider_dragged_past_a_minimum_and_back_stays_under_the_pointer() { fn a_resize_under_a_pruned_view_keeps_the_hidden_panels() { let rest = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![1], 0), Node::tabs(vec![2], 0)); let mut layout = Layout::new(Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), rest)), Vec::new()); - let keep = |panel: &usize| *panel != 2; + let keep = Tracked::new(BTreeSet::from([PanelKey::of(&0_usize), PanelKey::of(&1_usize)])); let none_protected = |_: &usize| false; let original = layout.clone(); let view = maximize(&original, None, HidePanels::Except(&keep), &none_protected); From 8b7fb7143d9aad719e2c454e0601780ec5682099 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 15:01:43 +0000 Subject: [PATCH 20/89] craft-ui-patterns: a group's tab titles are derived once and keyed by their content, so a tab row replays unless its own titles changed --- crates/imaging/src/ui/fill/mod.rs | 2 +- crates/imaging/src/ui/liquify/mod.rs | 6 +++--- crates/imaging/src/ui/select_mask/mod.rs | 2 +- crates/imaging/src/ui/vanishing_point/mod.rs | 2 +- crates/imaging/src/ui/wide_angle/mod.rs | 2 +- crates/ui-gallery/src/mock/editor.rs | 9 ++++++++- crates/ui-gallery/src/mock/panels.rs | 2 +- crates/ui-panels/src/docking/event.rs | 2 +- crates/ui-panels/src/docking/frame.rs | 2 +- crates/ui-panels/src/docking/mod.rs | 15 +++++---------- crates/ui-panels/src/docking/stories.rs | 4 +++- crates/ui-panels/src/rails/tool/stories.rs | 2 +- crates/ui-panels/src/rails/tool/trials.rs | 2 +- crates/ui-panels/tests/it/rails/drawer.rs | 2 +- crates/ui-patterns/src/patterns/dock/area.rs | 19 +++++++++++-------- crates/ui-patterns/tests/it/docking/runs.rs | 4 +++- crates/ui-patterns/tests/it/docking/split.rs | 2 +- 17 files changed, 44 insertions(+), 35 deletions(-) diff --git a/crates/imaging/src/ui/fill/mod.rs b/crates/imaging/src/ui/fill/mod.rs index 0847dce26..626ff09b4 100644 --- a/crates/imaging/src/ui/fill/mod.rs +++ b/crates/imaging/src/ui/fill/mod.rs @@ -62,7 +62,7 @@ use craft_ui::buttons::IconButton; use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff}; use craft_ui::canvas_controls::{Marquee, MarqueeLook}; -use craft_ui::contract::{Bind, Tracked, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, Tracked, clicked}; use craft_ui::dialog::{ DialogResult, DialogWords, FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index 4f7709952..235b828fb 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -72,7 +72,7 @@ use craft_behavior::{CancelReason, Cursor, EditEvent, EditHistory, Mixed}; use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, tool_pick}; use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff}; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, Tracked, Pattern, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _, Tracked}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, @@ -555,8 +555,8 @@ impl LiquifyWorkspace { let shown = Row::new() .fill() .show(ui, |ui, _| { - let rail = - ToolRail::new(words.tools.clone(), &state.slots, &work.edit.settings.tool, &state.last_used).show_column(ui, |_, _| {}); + let rail = ToolRail::new(words.tools.clone(), &state.slots, &work.edit.settings.tool, &state.last_used) + .show_column(ui, |_, _| {}); if let Some(next) = rail.last_used { *state.last_used = next; } diff --git a/crates/imaging/src/ui/select_mask/mod.rs b/crates/imaging/src/ui/select_mask/mod.rs index dbeb70393..00dd8cb9a 100644 --- a/crates/imaging/src/ui/select_mask/mod.rs +++ b/crates/imaging/src/ui/select_mask/mod.rs @@ -68,7 +68,7 @@ use craft_theme::Srgba; use craft_ui::buttons::IconButton; use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff}; -use craft_ui::contract::{Bind, Tracked, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, Tracked, clicked}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, diff --git a/crates/imaging/src/ui/vanishing_point/mod.rs b/crates/imaging/src/ui/vanishing_point/mod.rs index cdd1f6cdc..7c77829c0 100644 --- a/crates/imaging/src/ui/vanishing_point/mod.rs +++ b/crates/imaging/src/ui/vanishing_point/mod.rs @@ -52,7 +52,7 @@ use craft_behavior::edit_history::Step; use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed}; use craft_ui::bars::StatusMessage; use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; -use craft_ui::contract::{Bind, Job, Tracked, Pending, Remember as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Job, Pending, Remember as _, Show as _, ShowContainer as _, Tracked}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, diff --git a/crates/imaging/src/ui/wide_angle/mod.rs b/crates/imaging/src/ui/wide_angle/mod.rs index 1ea5215fa..3da72dbfc 100644 --- a/crates/imaging/src/ui/wide_angle/mod.rs +++ b/crates/imaging/src/ui/wide_angle/mod.rs @@ -37,7 +37,7 @@ use std::time::Duration; use craft_behavior::edit_history::Step; use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed}; use craft_ui::canvas::{CanvasTool, HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick}; -use craft_ui::contract::{Bind, Tracked, Pattern, Remember as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Pattern, Remember as _, Show as _, ShowContainer as _, Tracked}; use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index ec79b3dc0..cb265feb5 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -96,7 +96,14 @@ impl<'a> EditorMock<'a> { fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { let mut tools = cx.keep::().clone(); let (events, picked) = { - let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, slots: &state.slots, last_used: &mut state.last_used, picked: None }; + let mut panels = Panels { + document: &mut state.document, + tool: state.tool, + tools: &mut tools, + slots: &state.slots, + last_used: &mut state.last_used, + picked: None, + }; // The mock app is a preview inside the gallery's page: its floats stay in it. let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default().native_windows(false)) diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index e83065144..dde2721b2 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -13,11 +13,11 @@ use craft_ui::canvas::{ tool_pass, }; use craft_ui::canvas_controls::{Guides, Marquee}; -use craft_ui::contract::{SizeLimits, Tracked}; use craft_ui::contract::{ Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, MemoProps, MemoView, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SweepApply, SweepStep, ToggleColumn, WordSetCx as _, }; +use craft_ui::contract::{SizeLimits, Tracked}; use craft_ui::docking::{DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs}; use craft_ui::list::{ListRow, ToggleCell}; use craft_ui::patterns::canvas::NavigatorPanel; diff --git a/crates/ui-panels/src/docking/event.rs b/crates/ui-panels/src/docking/event.rs index 34ff1f38f..02e7fe009 100644 --- a/crates/ui-panels/src/docking/event.rs +++ b/crates/ui-panels/src/docking/event.rs @@ -2,8 +2,8 @@ use super::{DockCommands, DockSizes, DragUnit, PanelKey}; use crate::contract::{MemoKey, MemoProps, Tracked}; -use std::collections::BTreeSet; use egui::{Rect, Vec2}; +use std::collections::BTreeSet; /// A request for host state outside the layout, or a report of where something ended up. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/ui-panels/src/docking/frame.rs b/crates/ui-panels/src/docking/frame.rs index 3c95ae5d4..8201517d8 100644 --- a/crates/ui-panels/src/docking/frame.rs +++ b/crates/ui-panels/src/docking/frame.rs @@ -1,7 +1,7 @@ //! What the tree adds around the groups: Maximize Frame, the hidden-panel prune and the outer edge bands. -use super::config::DockConfig; use super::PanelKey; +use super::config::DockConfig; use super::event::HidePanels; use super::targets::{DockSizes, DockSpot, DockTargets}; use super::tree; diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 45552a3f7..0fc63b564 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -78,8 +78,8 @@ use craft_behavior::{Axis, EditEvents, Flow, Metrics, PartKey, Sense}; use divider::{Divider, Drag}; use egui::{Rect, Response, Vec2}; use std::fmt::Debug; -use std::sync::Arc; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; use tree::{FrameRules, SplitHandle}; const HANDLE: PartKey = PartKey::new("handle"); @@ -115,9 +115,9 @@ pub struct PanelTitle { pub closable: bool, } -/// The tab titles of one group, with the key that stands for them in a memoized view's key. A host that keeps its -/// titles derived from revisions gives [`Titles::new`] the key it derived them under, so the key does not walk the -/// titles; [`Titles::from_content`] keys by the titles themselves. +/// The tab titles of one group with their content key, taken once when they are made: a memoized view that holds them +/// feeds that key, not the titles. A host keeps a group's titles in a derived value so the key is taken only when they +/// are rebuilt. #[derive(Clone, Debug)] pub struct Titles { list: Arc>, @@ -125,12 +125,7 @@ pub struct Titles { } impl Titles { - /// The titles `list`, made from the inputs `key` follows: equal keys must mean equal titles. - pub fn new(key: &K, list: Arc>) -> Self { - Titles { list, key: crate::contract::MemoKey::of(key) } - } - - /// The titles `list`, keyed by their content: the key walks them. + /// The titles `list`, keyed by their content: this call walks them. pub fn from_content(list: Vec) -> Self { Titles { key: crate::contract::MemoKey::of(&list), list: Arc::new(list) } } diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index dd7344a34..3149f9795 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -4,7 +4,9 @@ use super::SplitFramesCx as _; use super::group::MENU; use super::stack::{StackSection, StackSections}; use super::tree::FrameRules; -use super::{DockCommands, DockGroup, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelSpecs, PanelTitle, SplitArea, Splitter, Titles, WindowMenuRows}; +use super::{ + DockCommands, DockGroup, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelSpecs, PanelTitle, SplitArea, Splitter, Titles, WindowMenuRows, +}; use crate::contract::SizeLimits; use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Tracked, Validity}; use crate::menu::{Menu, PanelRow}; diff --git a/crates/ui-panels/src/rails/tool/stories.rs b/crates/ui-panels/src/rails/tool/stories.rs index e69348626..2206c0d3d 100644 --- a/crates/ui-panels/src/rails/tool/stories.rs +++ b/crates/ui-panels/src/rails/tool/stories.rs @@ -1,7 +1,7 @@ //! Stories of `ToolRail`, and the commands its stories and the flyout's use as tools. -use crate::contract::Tracked; use super::{LastUsed, RailTool, ToolRail, ToolSlot}; +use crate::contract::Tracked; use crate::docking::{DockGrid, DockSizes}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index 87a0247f5..4faa6f1c8 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -6,9 +6,9 @@ use super::stories::tools; use super::{LastUsed, ToolRail, ToolSlot}; use crate::buttons::Button; use crate::contract::Props as _; -use crate::contract::Tracked; use crate::contract::Show as _; use crate::contract::ShowContainer as _; +use crate::contract::Tracked; use crate::docking::{DockGrid, DockSizes}; use crate::layout_components::Stack; use crate::runtime::env::ThemeScope; diff --git a/crates/ui-panels/tests/it/rails/drawer.rs b/crates/ui-panels/tests/it/rails/drawer.rs index 931ac6516..e508026fe 100644 --- a/crates/ui-panels/tests/it/rails/drawer.rs +++ b/crates/ui-panels/tests/it/rails/drawer.rs @@ -1,8 +1,8 @@ //! The drawer's own logic: how an edit changes the toolbar and what a drop on the rail asks for, and which of its tools //! drag, where the rail leaves group gaps and which side the drawer opens on. -use craft_ui::rails::{DropAt, RailTool, ToolSlot, ToolbarEdit, apply_toolbar_edit}; use craft_ui::contract::Tracked; +use craft_ui::rails::{DropAt, RailTool, ToolSlot, ToolbarEdit, apply_toolbar_edit}; use craft_ui::runtime::commands::EditCommands; use craft_ui::runtime::drag; use craft_ui::testing::{Fixture, stories, trial}; diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 04b32a332..7f1f5ffe8 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -2,18 +2,18 @@ //! the parts of `docking`, takes the drops of tab and group drags, and applies their actions to the workspace. use super::hide::{self, PruneKey}; +use crate::contract::Revision; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ Bind, BindMut, BodyCx, Cx, Entry, MemoKey, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, Tracked, WordSetCx as _, }; -use crate::contract::Revision; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, - IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, Titles, SplitArea, WindowColumn, actions, + IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, Titles, WindowColumn, actions, column_cells, dock_states, frame, move_actions, with_area_rules, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; @@ -930,13 +930,16 @@ impl Pass<'_, P> { let parts_of = || { parts.get_or_init(|| { let key = (scene.view, PanelKey::of(anchor)); - let list = derived(&ctx, scene.dock.with(("titles", key.1)), &key, || { - members - .iter() - .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) - .collect::>() + // Keyed by their content once built, so a group's tab row replays unless its own titles changed. + let titles = derived(&ctx, scene.dock.with(("titles", key.1)), &key, || { + Titles::from_content( + members + .iter() + .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) + .collect(), + ) }); - let titles = Titles::new(&key, list); + let titles = Titles::clone(&titles); let hosted = !panels.borrow_mut().panel_rows(shown).is_empty(); let permissions = |panel: &P| scene.permissions(panel); let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &permissions).floated(scene.floated), shown); diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 398357f73..ec73100e1 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -13,7 +13,9 @@ use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; use craft_ui::testing::in_audit_run; use craft_ui::testing::pointer::{moved, press}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, trial}; +use craft_ui::testing::{ + Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, trial, +}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; diff --git a/crates/ui-patterns/tests/it/docking/split.rs b/crates/ui-patterns/tests/it/docking/split.rs index 47825ed49..2d89727a4 100644 --- a/crates/ui-patterns/tests/it/docking/split.rs +++ b/crates/ui-patterns/tests/it/docking/split.rs @@ -10,8 +10,8 @@ use craft_ui::testing::memory::global; use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, trial}; use egui::{Pos2, Rect}; -use std::collections::BTreeSet; use std::cell::RefCell; +use std::collections::BTreeSet; use std::rc::Rc; fn spec(panel: &u8) -> PanelSpec { From b2508904136d3432421226512bd595cb8b9cd46c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 15:08:32 +0000 Subject: [PATCH 21/89] craft-ui-panels: HidePanels derives MemoProps, Titles keys through its content key, ToolRail::hidden is a derived prop --- crates/ui-panels/src/docking/event.rs | 17 ++--------------- crates/ui-panels/src/docking/group.rs | 1 + crates/ui-panels/src/docking/mod.rs | 7 ++++--- crates/ui-panels/src/rails/tool.rs | 13 ++----------- crates/ui-panels/src/rails/tool/trials.rs | 5 ++++- 5 files changed, 13 insertions(+), 30 deletions(-) diff --git a/crates/ui-panels/src/docking/event.rs b/crates/ui-panels/src/docking/event.rs index 02e7fe009..29042c15a 100644 --- a/crates/ui-panels/src/docking/event.rs +++ b/crates/ui-panels/src/docking/event.rs @@ -1,7 +1,7 @@ //! `DockEvent`, `FloatSpace` and `HidePanels`: what a dock reports to the host and the host tells a dock. use super::{DockCommands, DockSizes, DragUnit, PanelKey}; -use crate::contract::{MemoKey, MemoProps, Tracked}; +use crate::contract::{MemoProps, Tracked}; use egui::{Rect, Vec2}; use std::collections::BTreeSet; @@ -47,7 +47,7 @@ pub enum DockEvent

{ /// /// The set is a `Tracked` value, so a dock keys what it shows by the set's revision and keeps the pruned layout until /// the set, the workspace or the shell's visibility changes. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, MemoProps)] #[non_exhaustive] pub enum HidePanels<'a> { /// Hides none. @@ -58,19 +58,6 @@ pub enum HidePanels<'a> { Except(&'a Tracked>), } -impl MemoProps for HidePanels<'_> { - fn key(&self, key: &mut MemoKey) { - match self { - HidePanels::None => key.write_u32(0), - HidePanels::All => key.write_u32(1), - HidePanels::Except(keep) => { - key.write_u32(2); - keep.key(key); - } - } - } -} - /// Where a docking command floats a panel, group or column when it gives no rect. A dock records one each pass; /// the host reads it to turn a command into placements. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 16c7f8438..237c1014a 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -585,6 +585,7 @@ struct TabRow<'a, P> { /// The group's anchor panel, which names its drop spots. #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] anchor: P, + #[memo_props(hash = "its Hash is the content key taken when the titles were made")] panels: Titles, active: PanelKey, closable: bool, diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 0fc63b564..f6fdc7168 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -136,9 +136,10 @@ impl Titles { } } -impl crate::contract::MemoProps for Titles { - fn key(&self, key: &mut crate::contract::MemoKey) { - self.key.key(key); +/// Feeds the content key taken when the titles were made, not the titles. +impl Hash for Titles { + fn hash(&self, state: &mut H) { + self.key.hash(state); } } diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 8f68463fe..0e76f6049 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -120,6 +120,7 @@ pub struct ToolRail<'a, T: Value + MemoProps + PlainData + 'static> { #[prop(flag)] editing: bool, /// The tools the user's toolbar settings hide. + #[prop(into)] hidden: Option<&'a Tracked>>, footer: Option>, /// The columns the rail lays out in this pass. @@ -155,13 +156,6 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { .label(label) } - /// The tools the user's toolbar settings hide. - #[must_use] - pub fn hidden(mut self, hidden: &'a Tracked>) -> Self { - self.hidden = Some(hidden); - self - } - /// The cells the rail lays out: its visible slots and the Edit Toolbar button. fn cells(&self) -> usize { visible_slots(self.slots, hidden_in(self.hidden)).len() + usize::from(self.edit_toolbar.is_some()) @@ -189,10 +183,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { } /// The tools a rail hides: the host's, or none. -fn hidden_in<'a, T>(hidden: Option<&'a Tracked>>) -> &'a [T] -where - T: PlainData, -{ +fn hidden_in(hidden: Option<&Tracked>>) -> &[T] { hidden.map_or(&[], |hidden| hidden.as_slice()) } diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index 4faa6f1c8..f9b9c2404 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -284,6 +284,9 @@ fn an_open_flyout_builds_no_derived_values() { } } +/// The room of the key-byte trial. +const KEY_BYTES_ROOM: Vec2 = Vec2::new(120.0, 400.0); + /// The key bytes of an idle pass of a rail of `count` slots, a quarter of whose tools are hidden and half remembered. fn idle_key_bytes(count: u8) -> usize { let slots = Tracked::new((0..count).map(|id| ToolSlot::new(u32::from(id), tools(&[id]))).collect::>()); @@ -296,7 +299,7 @@ fn idle_key_bytes(count: u8) -> usize { let mut fixture = Fixture::new(move |ui| { ToolRail::new("Tools", &slots, &0, &last).hidden(&hidden).show_rail(ui, |_, _| {}); }); - fixture.room(Vec2::new(120.0, 400.0)).settle().idle(1); + fixture.room(KEY_BYTES_ROOM).settle().idle(1); assert_eq!(last_frame_derived_builds(fixture.ctx()), Vec::new(), "an idle rail builds no derived value"); last_pass_memo_key_bytes(fixture.ctx()) } From 6769a5ca210d292bb81a7633f6b2e165b7737b6d Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 15:10:15 +0000 Subject: [PATCH 22/89] craft-ui-panels: the tool rail derives its remembered tools under the slots', last-used and hidden revisions --- crates/ui-panels/src/rails/tool.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 0e76f6049..0fc0f1c46 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -314,7 +314,11 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { /// Shows the rail laid out `width` wide. fn show_within(mut self, ui: &mut Ui, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput { let draw = self.prepare(ui, width, footer); - let last = remembered(draw.slots, draw.current, draw.last_used); + // The last-used tools after this pass: derived while the slots, the remembered and hidden tools and the current tool are as they were. + let key = (draw.slots.revision(), draw.last_used.revision(), draw.hidden.map(Tracked::revision), draw.current); + let last = + crate::runtime::derived::derived(ui.ctx(), ui.id().with("remembered"), &key, || remembered(draw.slots, draw.current, draw.last_used)); + let last = last.as_ref().clone(); let (mut events, mut edit_toolbar) = (Vec::new(), None); let shown = self.show(ui, |ui, _| edit_toolbar = draw.run(ui, &mut events)); let (mut select, mut double_clicked, mut flyout, mut dropped) = (None, None, None, None); From e80eacc2abcdb44b983773cca46a5775fcc4285a Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 14:34:17 +0000 Subject: [PATCH 23/89] ui-bench: menu-80-rows, inspector-1000-fields and --only; trial of component runs per menu row --- crates/ui-bench/src/bin/foundation/main.rs | 31 +++++++++----- crates/ui-bench/src/harness.rs | 5 ++- crates/ui-bench/src/scenario.rs | 2 + crates/ui-widgets/tests/it/menu/mod.rs | 2 + .../ui-widgets/tests/it/menu/runs_per_row.rs | 40 +++++++++++++++++++ 5 files changed, 69 insertions(+), 11 deletions(-) create mode 100644 crates/ui-widgets/tests/it/menu/runs_per_row.rs diff --git a/crates/ui-bench/src/bin/foundation/main.rs b/crates/ui-bench/src/bin/foundation/main.rs index c4a5d79ef..5a3e22ca8 100644 --- a/crates/ui-bench/src/bin/foundation/main.rs +++ b/crates/ui-bench/src/bin/foundation/main.rs @@ -66,16 +66,17 @@ impl Library for Foundation { fn build(&self, name: &str) -> SceneBuild { let (scene, equivalent): (Box, &'static str) = match name { - "inspector-500-fields" => ( - Box::new(InspectorScene::new()), + "inspector-500-fields" | "inspector-1000-fields" => ( + Box::new(InspectorScene::new(if name == "inspector-500-fields" { 500 } else { 1000 })), // F8-MERGE: family (Field row): the field's own side label stands in for the `Field` row. - "500 rows alternating NumberField and TextField, each with its side label (no Field row component yet)", + "500 (or 1000) rows alternating NumberField and TextField, each with its side label (no Field row component yet)", ), "virtual-list-10000" => (Box::new(ListScene::new(Selected::None)), "List over 10,000 ListRow rows, one selected row"), "sheet-50x200" => (Box::new(SheetScene), "BenchList of 200 rows, each with 50 cell parts that paint their text"), // F8-MERGE: canvas: the canvas component and its declared controls. "canvas-50-controls" => (Box::new(CanvasScene), "a leaf with 50 control parts painted as knobs"), - "menu-40-rows" => (Box::new(MenuScene), "a Menu open from the first frame over 40 MenuItem rows"), + "menu-40-rows" => (Box::new(MenuScene { rows: 40 }), "a Menu open from the first frame over 40 MenuItem rows"), + "menu-80-rows" => (Box::new(MenuScene { rows: 80 }), "a Menu open from the first frame over 80 MenuItem rows"), "table-1000x5" => (Box::new(TableScene), "a Table of 1,000 rows and 5 columns, text in every cell"), "tile-grid-500" => (Box::new(TileGridScene), "a TileGrid of 500 Tiles"), "text-field-100kb" => (Box::new(TextScene::new()), "TextField::lines(30) bound with Bind::bound over a 100 KB String"), @@ -114,8 +115,8 @@ struct InspectorScene { } impl InspectorScene { - fn new() -> Self { - Self { values: (0..500).map(|i| Some(f64::from(i))).collect(), texts: (0..500).map(|i| format!("Value {i}")).collect() } + fn new(count: i32) -> Self { + Self { values: (0..count).map(|i| Some(f64::from(i))).collect(), texts: (0..count).map(|i| format!("Value {i}")).collect() } } } @@ -195,7 +196,10 @@ impl Scene for CanvasScene { } } -struct MenuScene; +/// A menu open over `rows` items. +struct MenuScene { + rows: usize, +} impl Scene for MenuScene { fn size(&self) -> Vec2 { @@ -205,7 +209,7 @@ impl Scene for MenuScene { fn show(&mut self, ui: &mut Ui, _frame: u64) { let mut open = true; let _ = Menu::new("Items").open(Bind::bound(&mut open)).id_salt("menu").show(ui, |ui, _| { - for key in 0..40 { + for key in 0..self.rows { let _ = MenuItem::new(format!("Item {key}")).id_salt(key).show(ui); } }); @@ -533,8 +537,17 @@ impl Scene for ReadoutScene { } fn main() -> std::process::ExitCode { - let report = run_all(&Foundation { root: RootEnv::default() }); + // `--only ` runs one scenario and prints its row: for profiling, it writes no baseline and runs no gate. + let mut args = std::env::args().skip(1); + let only = match (args.next().as_deref(), args.next()) { + (Some("--only"), Some(name)) => Some(name), + _ => None, + }; + let report = run_all(&Foundation { root: RootEnv::default() }, only.as_deref()); print_table(&report); + if only.is_some() { + return std::process::ExitCode::SUCCESS; + } let baseline = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("baseline"); let outcome = write_json(&report, &baseline.join("foundation.json")).and_then(|()| read_json(&baseline.join("legacy.json"))); let legacy = match outcome { diff --git a/crates/ui-bench/src/harness.rs b/crates/ui-bench/src/harness.rs index defe85f5f..44c37d6e6 100644 --- a/crates/ui-bench/src/harness.rs +++ b/crates/ui-bench/src/harness.rs @@ -114,10 +114,11 @@ fn measure(library: &dyn Library, mut scene: Box) -> Measurement { ) } -/// Measures every scenario of [`SCENARIOS`] on `library`. -pub fn run_all(library: &dyn Library) -> Report { +/// Measures every scenario of [`SCENARIOS`] on `library`, or only the one called `only`. +pub fn run_all(library: &dyn Library, only: Option<&str>) -> Report { let scenarios = SCENARIOS .iter() + .filter(|scenario| only.is_none_or(|name| scenario.name == name)) .map(|scenario| { eprintln!("{}: {}", library.name(), scenario.name); let (equivalent, missing, measurement) = match library.build(scenario.name) { diff --git a/crates/ui-bench/src/scenario.rs b/crates/ui-bench/src/scenario.rs index f2ccbe6b5..235732764 100644 --- a/crates/ui-bench/src/scenario.rs +++ b/crates/ui-bench/src/scenario.rs @@ -15,10 +15,12 @@ pub struct Scenario { /// Every scenario, in report order. pub const SCENARIOS: &[Scenario] = &[ Scenario { name: "inspector-500-fields", description: "an inspector of 500 Field rows", no_discard: false }, + Scenario { name: "inspector-1000-fields", description: "an inspector of 1,000 Field rows", no_discard: false }, Scenario { name: "virtual-list-10000", description: "a 10,000-item virtual list", no_discard: false }, Scenario { name: "sheet-50x200", description: "a sheet of 50 x 200 visible cells as row parts", no_discard: false }, Scenario { name: "canvas-50-controls", description: "a canvas with 50 canvas controls", no_discard: false }, Scenario { name: "menu-40-rows", description: "an open menu with 40 rows", no_discard: false }, + Scenario { name: "menu-80-rows", description: "an open menu with 80 rows", no_discard: false }, Scenario { name: "table-1000x5", description: "a table of 1,000 rows and 5 columns", no_discard: false }, Scenario { name: "tile-grid-500", description: "a tile grid of 500 tiles", no_discard: false }, Scenario { name: "text-field-100kb", description: "a 100 KB multi-line text field, bound", no_discard: false }, diff --git a/crates/ui-widgets/tests/it/menu/mod.rs b/crates/ui-widgets/tests/it/menu/mod.rs index c23c138a0..6e2a75840 100644 --- a/crates/ui-widgets/tests/it/menu/mod.rs +++ b/crates/ui-widgets/tests/it/menu/mod.rs @@ -16,6 +16,8 @@ mod pick_focus; mod rows; +mod runs_per_row; + mod search; mod submenus; diff --git a/crates/ui-widgets/tests/it/menu/runs_per_row.rs b/crates/ui-widgets/tests/it/menu/runs_per_row.rs new file mode 100644 index 000000000..7d50cdb15 --- /dev/null +++ b/crates/ui-widgets/tests/it/menu/runs_per_row.rs @@ -0,0 +1,40 @@ +//! An open menu runs a constant number of components per row: 80 rows run 40 rows' worth more than 40 rows, in the room the +//! `menu-80-rows` scenario of ui-bench gives its menu. + +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::testing::{Fixture, last_pass_runs, trial}; +use egui::vec2; + +/// The room of ui-bench's `MenuScene`. +const ROOM: egui::Vec2 = vec2(800.0, 1400.0); + +/// The components run in the last pass, and how many of the `rows` have a node. +fn runs_and_rows_shown(rows: usize) -> (u32, usize) { + let mut fixture = Fixture::new(move |ui| { + let mut open = true; + let _ = Menu::new("Items").open(Bind::bound(&mut open)).id_salt("menu").show(ui, |ui, _| { + for key in 0..rows { + let _ = MenuItem::new(format!("Item {key}")).id_salt(key).show(ui); + } + }); + }); + fixture.room(ROOM); + fixture.settle().idle(2); + let runs = last_pass_runs(fixture.ctx()).iter().map(|(_, runs)| runs).sum(); + let shown = (0..rows).filter(|key| fixture.by_label(&format!("Item {key}")).is_some()).count(); + (runs, shown) +} + +#[trial] +fn component_runs_grow_by_a_constant_per_menu_row() { + let (few, few_shown) = runs_and_rows_shown(40); + let (many, many_shown) = runs_and_rows_shown(80); + eprintln!("menu runs: 40 rows {few} runs ({few_shown} shown), 80 rows {many} runs ({many_shown} shown)"); + assert_eq!((few_shown, many_shown), (40, 80), "every row has a node in the bench's room, so runs per row means every row"); + let grown = many.checked_sub(few).expect("more rows run no fewer components"); + assert_eq!(grown % 40, 0, "runs grow by a constant per row: {few} runs at 40 rows, {many} at 80"); + let k = grown / 40; + assert!(k >= 1, "each row runs at least one component"); + eprintln!("runs per menu row: {k}"); +} From 3f9adf355dc768fd2466c22775df6ae35068fec3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 17:04:18 +0000 Subject: [PATCH 24/89] Rulers: an edge and a centred face, picked by the component set `RulerFace { Edge, Centred }` sits beside `TickEdge`, and `RulerFace::of(set)` maps the creative set to Edge and the office set to Centred. The shared tick painter takes the face. Centred draws a bar inset in the strip by `space.gap.tight`, centres the marks on it, and puts a number in place of each whole-unit mark. No mark runs under a number (`RulerFace::beside_numbers`), so a whole-unit tick shows only where its number is dropped. TextRuler, VerticalRuler and canvas Rulers take an optional `face` prop in their style key. Unset, the style resolves it from the scope's set. PageRulers passes its face to both of its rulers, and the timeline ruler keeps the edge face. Under Centred: - the strip is on the chrome surface and the bar carries the margin shade and the text column on the well; - numbers show only over the text area and are dropped where a marker stands; - canvas Rulers shade their margin bands as the text ruler does. Edge is the look the rulers had before. Each ruler gets an edge and a centred story. --- crates/design-lint/src/workspace.rs | 1 + crates/pages/src/ui/page_rulers.rs | 98 +++++++++---- crates/pages/src/ui/page_rulers/stories.rs | 46 ++++++- crates/text/src/ui/ruler.rs | 18 ++- crates/text/src/ui/ruler/paint.rs | 69 ++++++---- crates/text/src/ui/ruler/stories.rs | 29 +++- crates/text/tests/it/ruler.rs | 130 ++++++++++++++++++ crates/timeline/src/ui/ruler.rs | 4 +- crates/ui-canvas/src/canvas/rulers/mod.rs | 130 +++++++++++++----- crates/ui-canvas/src/canvas/rulers/stories.rs | 35 ++++- crates/ui-contract/src/primitives/kit.rs | 116 ++++++++++++++-- crates/ui-contract/src/primitives/mod.rs | 4 +- 12 files changed, 567 insertions(+), 113 deletions(-) diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 2475ff7b7..5e6a187c9 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -58,6 +58,7 @@ const CLOSED: &[&str] = &[ "ReorderMove", // built or matched in craft-ui-patterns "RowState", // built or matched in craft-ui-widgets "RuleLook", // built or matched in craft-ui-canvas + "RulerFace", // matched by every ruler (craft-text, craft-pages, craft-ui-canvas): a new face must be drawn by each "ShellRegions", // built or matched in craft-ui-shell "SizeLimits", // built or matched in craft-ui-panels "StoryOutput", // built or matched in craft-ui-widgets diff --git a/crates/pages/src/ui/page_rulers.rs b/crates/pages/src/ui/page_rulers.rs index e19df84a0..ea8be6eb3 100644 --- a/crates/pages/src/ui/page_rulers.rs +++ b/crates/pages/src/ui/page_rulers.rs @@ -17,7 +17,7 @@ use craft_ui::contract::{ Access, Bind, Common, Component, Cx, Focus as _, IdSource, Input, MeasureCx, Name, NoValue, Numeric, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Show as _, Styled as _, WordSetCx as _, }; -use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick, TickEdge, TickRank}; +use craft_ui::primitives::{PaintShape, RulerFace, StrokeWidth, TextRun, Tick, TickEdge, TickRank}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse}; use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole}; @@ -80,6 +80,10 @@ pub struct VerticalRulerStyle { metrics: Metrics, #[style(focus)] focus: FocusLook, + /// The face: the prop's, else the component set's. + face: RulerFace, + /// The strip round the centred face's bar. + strip: StyleColor, /// The text range. fill: StyleColor, /// The margins above and below it. @@ -113,6 +117,9 @@ struct Held(Option<(usize, f32)>); /// shaded as margin and the text range filled, and a drag of a grip is one gesture. /// /// - Ticks and numbers count from the page's top in the unit, through the canvas rulers' tick rule. +/// - The face ([`RulerFace`]) is the prop's, else the component set's: the edge face hangs the ticks from the strip's +/// inner edge with each number below its whole-unit tick; the centred face (Word's) draws a bar inset in the strip +/// with the ticks centred on it and the numbers in place of the whole-unit ticks, over the text range only. /// - A grip drag reports a [`RowDrag`]: Begin, Update per move, Commit on release, Cancel on Escape. It snaps to the /// ruler's step; Alt reports in `mods` that the drag is free of the snap and the position is not snapped. /// - The grips are one Tab stop: Page Down and Page Up pick the next or previous grip, the arrows nudge the focused one @@ -133,13 +140,17 @@ pub struct VerticalRuler<'a> { /// The table row bottoms, points from the page's top, each a grip. #[prop] rows: &'a [f32], + /// The face; unset, the scope's component set picks it ([`RulerFace::of`]). + #[style_key] + #[prop] + face: Option, report: Option, } impl<'a> VerticalRuler<'a> { /// The ruler named `label` along `page`. pub fn new(label: impl Into

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> f32 { if let Some((grid, steps)) = self.stepped(column, spec) { return grid.width(steps); diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 7f1f5ffe8..6f8b6dfc1 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -100,7 +100,7 @@ impl

Outcome for DockAreaOutput

{ /// flyouts; a group is a `DockGroup`; a floating window is a `FloatingGroup` holding one column, shown as a dock's /// column is, whose bar is the window's title row. The host's `DockPanels` supplies the panels. /// - Edits: a divider drag and every [`Action`] of the pass (menu rows, drags, drops) are written to the workspace -/// through its binding, with the panels' [`DockPanels::permissions`] (narrowed when `locked`). The output lists the +/// through its binding, with the panels' [`SpecSource::permissions`](crate::docking::SpecSource::permissions) (narrowed when `locked`). The output lists the /// actions the workspace took, divider sizes and window moves included. A given workspace is not written. /// - Requests: while the pass runs, a body changes the workspace through /// [`request_actions`](crate::docking::request_actions); the output returns those actions unapplied in `requested`. From a36e14750fe0e0d97677c5bf7d5bd3385fb9df49 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 20:01:54 +0000 Subject: [PATCH 28/89] design-lint: the menu bar stories keep their model in a static; GridWidths::Content names the content's measured widths --- crates/menu/src/bar/stories.rs | 16 ++++++++-------- crates/ui-panels/src/docking/spec.rs | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/crates/menu/src/bar/stories.rs b/crates/menu/src/bar/stories.rs index b21cde03a..b59aedca0 100644 --- a/crates/menu/src/bar/stories.rs +++ b/crates/menu/src/bar/stories.rs @@ -1,6 +1,6 @@ //! Stories of the in-window bar over a small model. -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use craft_ui::contract::Tracked; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -40,15 +40,15 @@ fn build() -> MenuBar { layout(&bar, Target::Linux, &LayoutOptions::new("Sample")).bar } -/// The story's model, kept in the story's memory: a model made again each pass is a new source, and the bar would run each time. -fn model(ui: &Ui) -> Arc> { - let id = ui.scope_id().with("model"); - ui.data_mut(|data| data.get_temp_mut_or_insert_with(id, || Arc::new(Tracked::new(build()))).clone()) +/// The stories' model, made once: a model made again each pass is a new source, and the bar would run each time. +fn model() -> Arc> { + static MODEL: LazyLock>> = LazyLock::new(|| Arc::new(Tracked::new(build()))); + MODEL.clone() } #[story(MenuBarUi<'static>, covers = [Default], drive = Drive::Never)] fn menu_bar_ui(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model(ui)).target(Target::Linux).show(ui); + MenuBarUi::new(&model()).target(Target::Linux).show(ui); StoryOutput::default() } @@ -60,12 +60,12 @@ fn open_window(fixture: &mut Fixture) { #[story(MenuBarUi<'static>, covers = [Open], drive = Drive::Custom(open_window))] fn menu_bar_ui_with_documents(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model(ui)).target(Target::Linux).show(ui); + MenuBarUi::new(&model()).target(Target::Linux).show(ui); StoryOutput::default() } #[story(MenuBarUi<'static>, covers = [], drive = Drive::Never)] fn menu_bar_ui_with_help_search(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model(ui)).target(Target::Linux).help_search(true).show(ui); + MenuBarUi::new(&model()).target(Target::Linux).help_search(true).show(ui); StoryOutput::default() } diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index 6af8a0ac2..2758a1cd1 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -69,7 +69,7 @@ pub struct DockGrid { enum GridWidths { /// `first`: the content's width at one column, a cell and the content's own padding on both sides; `step`: the /// width each further column adds, a cell and the gap before it. - Points { first: f32, step: f32 }, + Content { first: f32, step: f32 }, /// A tool rail's cells, sized by the dock's style. Rail, } @@ -77,7 +77,7 @@ enum GridWidths { impl DockGrid { /// A grid `first` wide at one column, `step` wider for each further column, up to `most` columns. pub const fn new(first: f32, step: f32, most: u16) -> Self { - DockGrid { widths: GridWidths::Points { first, step }, most } + DockGrid { widths: GridWidths::Content { first, step }, most } } /// The grid of a tool rail of `cells` cells: a rail button and the control padding on both sides at one column, @@ -89,7 +89,7 @@ impl DockGrid { /// The grid with its widths in points: a [`rail`](Self::rail) grid takes the rail widths of `sizes`. pub fn resolved(self, sizes: &DockSizes) -> Self { match self.widths { - GridWidths::Points { .. } => self, + GridWidths::Content { .. } => self, GridWidths::Rail => DockGrid::new(sizes.rail_first, sizes.rail_step, self.most), } } @@ -98,7 +98,7 @@ impl DockGrid { /// [`resolved`](Self::resolved). fn first_step(self) -> (f32, f32) { match self.widths { - GridWidths::Points { first, step } => (first, step), + GridWidths::Content { first, step } => (first, step), GridWidths::Rail => (0.0, 0.0), } } From 5062108d5b26f520564f4c25b9b73622e44d74aa Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 23:38:59 +0000 Subject: [PATCH 29/89] Format the testing exports --- crates/ui-contract/src/testing/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 22e2c1d0e..65960889b 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -56,8 +56,8 @@ pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds, last_frame_memo_runs, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, - last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, - row_builds, row_measures, run as measuring_run, take_effects, widest_runs, + last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, + run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; From 241990270c0e0d8d86505e7ee7d1b56d49fb0337 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 23:44:01 +0000 Subject: [PATCH 30/89] Docking tests from next: the workspace through its accessor and Arc --- .../tests/it/docking/floating_area.rs | 16 +++++++++------- crates/ui-patterns/tests/it/docking/native.rs | 4 ++-- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 7f02f8934..60704d765 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -252,7 +252,7 @@ fn a_floating_windows_group_starts_under_the_chrome_the_area_sizes_windows_by() fn dragged_from(from: Pos2, by: Vec2) -> Rect { let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0)))); press_and_move(&mut bed.fixture, from, by); - bed.workspace.borrow().layout.floating[0].rect + bed.workspace.borrow().layout().floating[0].rect } /// A floating window's title row is a drag bar, shorter than the panel header of the tab strip under it, as @@ -304,8 +304,8 @@ fn a_click_on_a_floating_windows_bar_neither_moves_nor_docks_it_and_a_drag_moves bed.fixture.frame(vec![press(at)]); bed.fixture.frame(vec![release(at)]); bed.fixture.settle(); - assert_eq!(bed.workspace.borrow().layout.floating.first().map(|window| window.rect), Some(WINDOW_AT), "a click moves nothing"); - assert_eq!(bed.workspace.borrow().layout.floating.len(), 1, "and docks nothing"); + assert_eq!(bed.workspace.borrow().layout().floating.first().map(|window| window.rect), Some(WINDOW_AT), "a click moves nothing"); + assert_eq!(bed.workspace.borrow().layout().floating.len(), 1, "and docks nothing"); let by = Vec2::new(-40.0, 30.0); let rect = dragged_from(at, by); assert!((rect.min - (WINDOW_AT.min + by)).length() <= SLACK, "a drag moves the window: {rect:?}"); @@ -481,7 +481,7 @@ fn strip_band(icon: Rect) -> Pos2 { fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_columns_step() { let mut bed = bed(collapsed_at(WINDOW_AT)); let sizes = IconicSizes::of(bed.fixture.ctx()); - let height = sizes.icons_height(&bed.workspace.borrow().layout.floating[0].column); + let height = sizes.icons_height(&bed.workspace.borrow().layout().floating[0].column); let named = |bed: &Bed| bed.fixture.texts().iter().any(|run| run.text == title(WINDOW)); let height = height + bed.chrome.get(); let strip = strip_window(&bed); @@ -496,7 +496,7 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col bed.fixture.frame(vec![release(side + by)]); bed.fixture.settle(); side += by; - let window = bed.workspace.borrow().layout.floating[0].clone(); + let window = bed.workspace.borrow().layout().floating[0].clone(); let shown = strip_window(&bed); let kept = window.column.iconic_width; assert!(window.column.iconic && kept.is_some_and(|kept| (kept - width).abs() <= SLACK), "{width}: the column keeps the width: {window:?}"); @@ -510,12 +510,14 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col } let resized = strip_window(&bed); for iconic in [false, true] { - bed.workspace.borrow_mut().apply(Action::set_iconic(WINDOW, iconic), false, |_| Permissions::ALL).expect("the column toggles"); + Arc::make_mut(&mut bed.workspace.borrow_mut()) + .apply(Action::set_iconic(WINDOW, iconic), false, |_| Permissions::ALL) + .expect("the column toggles"); bed.fixture.settle(); } let again = strip_window(&bed); assert!((again.width() - resized.width()).abs() <= SLACK, "collapsed again, the strip keeps its width: {resized:?}, then {again:?}"); - assert_eq!(bed.workspace.borrow().layout.floating[0].rect, WINDOW_AT, "the expanded rect is unchanged"); + assert_eq!(bed.workspace.borrow().layout().floating[0].rect, WINDOW_AT, "the expanded rect is unchanged"); } /// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 61469cbad..8e0fd047e 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -680,7 +680,7 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() dock.windows.child_info(info(true, *at)); commands }; - dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); for _ in 0..3 { follow(&mut dock, &mut at, vec![]); } @@ -709,7 +709,7 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() for _ in 0..3 { sent.extend(follow(&mut dock, &mut at, vec![])); } - let palette = &dock.workspace.layout.floating[0]; + let palette = &dock.workspace.layout().floating[0]; assert!(palette.column.iconic_width.is_some_and(|kept| (kept - width).abs() <= 0.5), "the column keeps the width: {:?}", palette.column); let recorded = palette.native.clone().expect("the model records the window"); assert_eq!(Vec2::from(recorded.normal.size), FLOAT_AT.size(), "the model keeps the expanded size"); From c49a12a99d4376cf4319e94de11f55d66bffb641 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 01:24:29 +0100 Subject: [PATCH 31/89] Crop: an edge or corner drag may take a document crop past its bounds The Crop tool bounds the overlay by the canvas while Delete Cropped Pixels is on so that an image-mode turn keeps the frame inside the image (photocraft#10869). The drag rules also cut every edge and corner resize to those bounds, so a crop could not grow the canvas. In the reference application it does. A resize of a document crop now goes past the bounds; turns, moves, drawn frames, nudges and a placed picture's crop (bounded by its source) are unchanged. Fixes storytold/photocraft#16043. Co-Authored-By: Claude Opus 5.5 --- crates/ui-canvas/src/canvas/crop/gesture.rs | 7 +++++- crates/ui-canvas/src/canvas/crop/mod.rs | 4 ++- crates/ui-canvas/tests/it/canvas/crop.rs | 27 +++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-canvas/src/canvas/crop/gesture.rs b/crates/ui-canvas/src/canvas/crop/gesture.rs index b0c322a19..40ca29c96 100644 --- a/crates/ui-canvas/src/canvas/crop/gesture.rs +++ b/crates/ui-canvas/src/canvas/crop/gesture.rs @@ -70,6 +70,9 @@ pub(super) struct Rules { pub image: bool, pub auto_center: bool, pub fills_uncovered: bool, + /// An edge or corner drag may take the frame past `bounds`: the crop grows the canvas there, as in the reference + /// application (a document crop, not one bounded by a placed picture's source). + pub resize_grows: bool, /// The canvas's snapping, with this pass's tolerance. pub snap: Option, pub os: Platform, @@ -89,6 +92,7 @@ impl Rules { /// as it was (a draw not yet sized) or cannot be kept inside. pub fn proposal(&self, drag: &mut Drag, to: Point, mods: Mods, space: bool) -> Option { let at = drag.at_press; + let mut grows = false; let (next, resizing, held) = match &mut drag.kind { Kind::Draw { anchor, cur, last } => { if space { @@ -115,6 +119,7 @@ impl Rules { } else { at.resized(*part, by, hold, mods.alt) }; + grows = self.resize_grows; (next, true, self.ratio.is_some() || mods.shift) } Kind::Turn { grab } => { @@ -137,7 +142,7 @@ impl Rules { if !next.is_finite() { return None; } - match self.bounds { + match self.bounds.filter(|_| !grows) { Some(bounds) => next.within(bounds, resizing, held).or(Some(drag.last)), None => Some(next), } diff --git a/crates/ui-canvas/src/canvas/crop/mod.rs b/crates/ui-canvas/src/canvas/crop/mod.rs index 906c5d810..d3e193be5 100644 --- a/crates/ui-canvas/src/canvas/crop/mod.rs +++ b/crates/ui-canvas/src/canvas/crop/mod.rs @@ -154,7 +154,8 @@ pub struct CropOverlay<'a> { #[prop(flag)] straighten: bool, /// The area the frame may not leave, in document units. An image-mode turn moves or shrinks the frame to keep it - /// inside (Command keeps it as it was at the press). + /// inside (Command keeps it as it was at the press). An edge or corner drag of a document crop may still take it + /// past them: the crop grows the canvas. #[prop] bounds: Option, /// Image mode: the frame stays upright on screen and a move or turn moves or turns the view instead. @@ -232,6 +233,7 @@ impl<'a> CropOverlay<'a> { image: self.image_mode, auto_center: self.auto_center, fills_uncovered: self.fills_uncovered, + resize_grows: matches!(self.scope, CropScope::Document), snap: canvas_snap(env), os: env.shell().os, } diff --git a/crates/ui-canvas/tests/it/canvas/crop.rs b/crates/ui-canvas/tests/it/canvas/crop.rs index 7f85b1012..01f4a6c7b 100644 --- a/crates/ui-canvas/tests/it/canvas/crop.rs +++ b/crates/ui-canvas/tests/it/canvas/crop.rs @@ -803,6 +803,33 @@ fn a_shift_corner_follows_the_diagonal_and_snaps_along_it() { assert!(rig.seen.borrow().snapped.is_empty(), "no snap line reported"); } +#[trial] +fn a_document_crop_grows_past_its_bounds_on_an_edge_or_corner_drag_only() { + // The canvas as the bounds, as the Crop tool sets them with Delete Cropped Pixels on. + let canvas = Rect::new(50.0, 50.0, 350.0, 250.0); + for (what, base) in [("classic", Setup::new()), ("image mode", Setup::image(0.0, false))] { + let mut setup = base; + setup.bounds = Some(canvas); + // An edge dragged past the canvas takes the frame with it: the crop grows the canvas there. + let mut rig = Rig::new(CropBox::upright(RECT), setup.clone()); + rig.drag(rig.at(RECT.x1, 150.0), rig.at(380.0, 150.0), Modifiers::NONE); + let r = rig.rect(); + assert!((r.x1 - 380.0).abs() < 1e-6 && r.x0 == RECT.x0, "{what}: the right edge follows past the canvas: {r:?}"); + // So does a corner. + let mut rig = Rig::new(CropBox::upright(RECT), setup.clone()); + rig.drag(rig.at(RECT.x1, RECT.y1), rig.at(380.0, 280.0), Modifiers::NONE); + let r = rig.rect(); + assert!(r.x1 > canvas.x1 + 1.0 && r.y1 > canvas.y1 + 1.0, "{what}: the corner follows past the canvas: {r:?}"); + } + // A classic move still stops at the canvas. + let mut setup = Setup::new(); + setup.bounds = Some(canvas); + let mut rig = Rig::new(CropBox::upright(RECT), setup); + rig.drag(rig.at(200.0, 150.0), rig.at(300.0, 150.0), Modifiers::NONE); + let r = rig.rect(); + assert!(r.x1 <= canvas.x1 + 1e-6 && (r.width() - RECT.width()).abs() < 1e-6, "a move stays inside: {r:?}"); +} + #[trial] fn an_object_crop_is_bounded_by_its_source_and_a_press_outside_it_reaches_what_lies_beneath() { let source = Rect::new(50.0, 50.0, 350.0, 250.0); From 3eebedfcff23f0595912bdd34028c771a5d69c0b Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 01:19:14 +0000 Subject: [PATCH 32/89] Component sets: the productivity set --- crates/pages/src/ui/page_rulers/stories.rs | 4 +-- .../text/src/ui/character/paragraph_dialog.rs | 2 +- crates/text/src/ui/ruler/stories.rs | 2 +- crates/text/tests/it/ruler.rs | 27 +++++++++++-------- crates/theme-store/src/lib.rs | 2 +- crates/theme/src/selection.rs | 6 ++--- crates/theme/tests/selection.rs | 10 +++---- crates/ui-canvas/src/canvas/rulers/stories.rs | 2 +- crates/ui-contract/src/primitives/kit.rs | 4 +-- crates/ui-gallery/src/viewer/appearance.rs | 6 ++--- docs/contract-api.md | 2 +- 11 files changed, 36 insertions(+), 31 deletions(-) diff --git a/crates/pages/src/ui/page_rulers/stories.rs b/crates/pages/src/ui/page_rulers/stories.rs index 8000f2b77..3e6b2632e 100644 --- a/crates/pages/src/ui/page_rulers/stories.rs +++ b/crates/pages/src/ui/page_rulers/stories.rs @@ -69,7 +69,7 @@ fn vertical_edge_face(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { vertical(ui, &ROWS, Some(Rangef::new(TEXT.0, TEXT.1)), Some(RulerFace::Edge)) } -/// The centred face (the office set's): a bar inset in the strip, ticks centred on it, numbers in place of the +/// The centred face (the productivity set's): a bar inset in the strip, ticks centred on it, numbers in place of the /// whole-unit ticks over the text range only. #[story(VerticalRuler<'static>, covers = [], drive = Drive::Never)] fn vertical_centred_face(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { @@ -121,7 +121,7 @@ fn page_edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { single_page(ui, data, None, Some(RulerFace::Edge)) } -/// Both rulers in the centred face (the office set's). +/// Both rulers in the centred face (the productivity set's). #[story(PageRulers<'static>, covers = [], drive = Drive::Never)] fn page_centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { single_page(ui, data, None, Some(RulerFace::Centred)) diff --git a/crates/text/src/ui/character/paragraph_dialog.rs b/crates/text/src/ui/character/paragraph_dialog.rs index ed0b2a859..db8a654e3 100644 --- a/crates/text/src/ui/character/paragraph_dialog.rs +++ b/crates/text/src/ui/character/paragraph_dialog.rs @@ -2,7 +2,7 @@ //! indentation (before text, and a first-line or hanging indent by an amount), spacing before and after, line //! spacing, with a live sample of the result and a Tabs… button. OK applies everything as one change. //! -//! The Paragraph controls ([`ParagraphControls`](super::ParagraphControls)) are Photoshop's panel; this is the office +//! The Paragraph controls ([`ParagraphControls`](super::ParagraphControls)) are Photoshop's panel; this is the productivity //! apps' dialog over the same paragraph. //! //! ```ignore diff --git a/crates/text/src/ui/ruler/stories.rs b/crates/text/src/ui/ruler/stories.rs index 5f4b3ed7a..46863c602 100644 --- a/crates/text/src/ui/ruler/stories.rs +++ b/crates/text/src/ui/ruler/stories.rs @@ -115,7 +115,7 @@ fn edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { over_a_page(ui, data, Some(RulerFace::Edge)) } -/// The centred face (the office set's): a bar inset in the strip, ticks centred on it, numbers in place of the +/// The centred face (the productivity set's): a bar inset in the strip, ticks centred on it, numbers in place of the /// whole-unit ticks over the column only. #[story(TextRuler<'static>, covers = [], drive = Drive::Never)] fn centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/text/tests/it/ruler.rs b/crates/text/tests/it/ruler.rs index 48972a46b..8bae010b8 100644 --- a/crates/text/tests/it/ruler.rs +++ b/crates/text/tests/it/ruler.rs @@ -337,7 +337,7 @@ fn tick_marks(shapes: &[egui::Shape], strip: egui::Rect) -> Vec { } /// A page-wide ruler in inches, shown with `face` when given, in a fixture whose root takes `set`; `popup` shows it in -/// an open popover inside a scope that sets the office set. +/// an open popover inside a scope that sets the productivity set. fn page_ruler(set: ComponentSet, face: Option, popup: bool) -> (Fixture, Rc>>) { let values = Rc::new(RefCell::new(RulerValues::default())); let strip_at: Rc>> = Rc::new(RefCell::new(None)); @@ -362,7 +362,7 @@ fn page_ruler(set: ComponentSet, face: Option, popup: bool) -> (Fixtu with_env( ui, |env| { - env.values.set(ComponentSet::Office); + env.values.set(ComponentSet::Productivity); }, |ui| { Popover::new("Card", Bind::given(true)).show(ui, |ui, _| ruler(ui)); @@ -400,13 +400,18 @@ fn edge(p: &Painted) -> bool { !p.ticks.is_empty() && p.ticks.iter().all(|tick| (tick.max.y - p.strip.max.y).abs() < 1.0) } -/// With no face given, the component set picks it: the office set's ruler centres its marks on a bar and puts numbers +/// With no face given, the component set picks it: the productivity set's ruler centres its marks on a bar and puts numbers /// in place of the whole-unit ticks, the creative set's hangs them from the strip's bottom edge. #[trial] fn the_component_set_picks_the_ruler_face() { - let (mut fixture, strip) = page_ruler(ComponentSet::Office, None, false); - let office = painted(&mut fixture, &strip); - assert!(centred(&office), "the office set paints the centred face: ticks {:?}, numbers {:?}", office.ticks, office.numbers); + let (mut fixture, strip) = page_ruler(ComponentSet::Productivity, None, false); + let productivity = painted(&mut fixture, &strip); + assert!( + centred(&productivity), + "the productivity set paints the centred face: ticks {:?}, numbers {:?}", + productivity.ticks, + productivity.numbers + ); let (mut fixture, strip) = page_ruler(ComponentSet::Creative, None, false); let creative = painted(&mut fixture, &strip); assert!(edge(&creative), "the creative set paints the edge face: ticks {:?}", creative.ticks); @@ -415,9 +420,9 @@ fn the_component_set_picks_the_ruler_face() { /// A face given on the ruler wins over the component set. #[trial] fn a_given_face_wins_over_the_component_set() { - let (mut fixture, strip) = page_ruler(ComponentSet::Office, Some(RulerFace::Edge), false); + let (mut fixture, strip) = page_ruler(ComponentSet::Productivity, Some(RulerFace::Edge), false); let given_edge = painted(&mut fixture, &strip); - assert!(edge(&given_edge), "the edge face under the office set: ticks {:?}", given_edge.ticks); + assert!(edge(&given_edge), "the edge face under the productivity set: ticks {:?}", given_edge.ticks); let (mut fixture, strip) = page_ruler(ComponentSet::Creative, Some(RulerFace::Centred), false); let given_centred = painted(&mut fixture, &strip); assert!(centred(&given_centred), "the centred face under the creative set: ticks {:?}", given_centred.ticks); @@ -428,7 +433,7 @@ fn a_given_face_wins_over_the_component_set() { fn a_scopes_component_set_reaches_a_popup_opened_inside_it() { let (mut fixture, strip) = page_ruler(ComponentSet::Creative, None, true); let in_popup = painted(&mut fixture, &strip); - assert!(centred(&in_popup), "the popup's ruler takes the scope's office set: ticks {:?}", in_popup.ticks); + assert!(centred(&in_popup), "the popup's ruler takes the scope's productivity set: ticks {:?}", in_popup.ticks); } /// A set change restyles the ruler in the frame it arrives in, in one pass, and the frame after asks for nothing more. @@ -436,9 +441,9 @@ fn a_scopes_component_set_reaches_a_popup_opened_inside_it() { fn a_component_set_change_restyles_the_ruler_in_one_pass_and_then_rests() { let (mut fixture, strip) = page_ruler(ComponentSet::Creative, None, false); assert!(edge(&painted(&mut fixture, &strip))); - fixture.set(ComponentSet::Office); + fixture.set(ComponentSet::Productivity); let changed = painted(&mut fixture, &strip); - assert!(centred(&changed), "the frame of the change paints the office face"); + assert!(centred(&changed), "the frame of the change paints the productivity face"); assert_eq!(fixture.passes(), 1, "the change takes one pass"); fixture.idle(1); assert_eq!(fixture.passes(), 1); diff --git a/crates/theme-store/src/lib.rs b/crates/theme-store/src/lib.rs index 58658d074..8ed3a806a 100644 --- a/crates/theme-store/src/lib.rs +++ b/crates/theme-store/src/lib.rs @@ -31,7 +31,7 @@ //! //! let artcraft = ThemeId::parse("craft.artcraft").unwrap(); //! let defaults = -//! AppDefaults { theme: ThemePair::same(artcraft), mode: ModeChoice::Dark, size: Size::Compact, sizes: Default::default(), set: ComponentSet::Office }; +//! AppDefaults { theme: ThemePair::same(artcraft), mode: ModeChoice::Dark, size: Size::Compact, sizes: Default::default(), set: ComponentSet::Productivity }; //! let selection = accepted.suite.with_defaults(&defaults); //! assert_eq!((selection.theme.light, selection.mode), (graphite.id, ModeChoice::Dark)); //! ``` diff --git a/crates/theme/src/selection.rs b/crates/theme/src/selection.rs index b4e77a9d5..27f927d3e 100644 --- a/crates/theme/src/selection.rs +++ b/crates/theme/src/selection.rs @@ -121,8 +121,8 @@ pub enum ComponentSet { /// The look the creative apps' users expect. #[default] Creative, - /// The look the office apps' users expect. - Office, + /// The look the productivity apps' users expect. + Productivity, } /// What the user picked, every field concrete (after defaults are filled in). @@ -215,7 +215,7 @@ impl From for SuiteChoice { /// What an app shows for every field the suite hasn't chosen. /// /// Each app states its own, normally [`crate::SUITE_DEFAULT`] in both slots with the mode and -/// size that suit it (the creative apps Dark and Compact; office apps may ship Light). +/// size that suit it (the creative apps Dark and Compact; productivity apps may ship Light). #[derive(Clone, Debug, PartialEq)] pub struct AppDefaults { /// The theme for each mode. diff --git a/crates/theme/tests/selection.rs b/crates/theme/tests/selection.rs index 6dacfc927..d496cf684 100644 --- a/crates/theme/tests/selection.rs +++ b/crates/theme/tests/selection.rs @@ -10,16 +10,16 @@ fn the_component_set_is_the_apps_unless_the_user_chose_one_for_it_and_never_the_ mode: ModeChoice::Light, size: Size::Comfortable, sizes: Default::default(), - set: ComponentSet::Office, + set: ComponentSet::Productivity, }; let suite = SuiteChoice::default().with_defaults(&defaults); - assert_eq!(suite.set, ComponentSet::Office, "a fresh install shows the app's set"); + assert_eq!(suite.set, ComponentSet::Productivity, "a fresh install shows the app's set"); let follows = AppChoice::new(None, None, None).apply(&suite); - assert_eq!(follows.set, ComponentSet::Office, "an app choice without a set keeps the app's"); + assert_eq!(follows.set, ComponentSet::Productivity, "an app choice without a set keeps the app's"); let own = AppChoice::new(None, None, None).with_set(ComponentSet::Creative).apply(&suite); assert_eq!(own.set, ComponentSet::Creative, "the user's set for the app wins"); let stored: AppChoice = serde_json::from_str(r#"{"theme":null,"mode":null,"size":null}"#).expect("a stored choice without a set reads"); - assert_eq!(stored.apply(&suite).set, ComponentSet::Office); + assert_eq!(stored.apply(&suite).set, ComponentSet::Productivity); let shared = SuiteChoice::from(own); - assert_eq!(shared.with_defaults(&defaults).set, ComponentSet::Office, "the suite's choice carries no set to other apps"); + assert_eq!(shared.with_defaults(&defaults).set, ComponentSet::Productivity, "the suite's choice carries no set to other apps"); } diff --git a/crates/ui-canvas/src/canvas/rulers/stories.rs b/crates/ui-canvas/src/canvas/rulers/stories.rs index fda918b50..36f4af95d 100644 --- a/crates/ui-canvas/src/canvas/rulers/stories.rs +++ b/crates/ui-canvas/src/canvas/rulers/stories.rs @@ -140,7 +140,7 @@ fn edge_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { in_face(ui, data, RulerFace::Edge) } -/// The centred face (the office set's): a bar inset in each strip, ticks centred on it, labels in place of the major +/// The centred face (the productivity set's): a bar inset in each strip, ticks centred on it, labels in place of the major /// ticks and none over the shaded margins. #[story(Rulers<'static>, covers = [], drive = Drive::Never)] fn centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index 7d9f6b2e6..053c41e4c 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -52,11 +52,11 @@ pub enum RulerFace { } impl RulerFace { - /// The face the component set `set` shows: the creative set the edge face, the office set the centred one. + /// The face the component set `set` shows: the creative set the edge face, the productivity set the centred one. pub const fn of(set: craft_theme::ComponentSet) -> Self { match set { craft_theme::ComponentSet::Creative => RulerFace::Edge, - craft_theme::ComponentSet::Office => RulerFace::Centred, + craft_theme::ComponentSet::Productivity => RulerFace::Centred, } } diff --git a/crates/ui-gallery/src/viewer/appearance.rs b/crates/ui-gallery/src/viewer/appearance.rs index 8542f31b3..6dc56fa8e 100644 --- a/crates/ui-gallery/src/viewer/appearance.rs +++ b/crates/ui-gallery/src/viewer/appearance.rs @@ -66,7 +66,7 @@ choices!(TEXT_SIZES: TextSize = [ (TextSize::Large, "large", "Large"), ]); choices!(DENSITIES: Size = [(Size::Compact, "compact", "Compact"), (Size::Comfortable, "comfortable", "Comfortable")]); -choices!(SETS: ComponentSet = [(ComponentSet::Creative, "creative", "Creative"), (ComponentSet::Office, "office", "Office")]); +choices!(SETS: ComponentSet = [(ComponentSet::Creative, "creative", "Creative"), (ComponentSet::Productivity, "productivity", "Productivity")]); choices!(MOTIONS: MotionChoice = [ (MotionChoice::Full, "full", "Off"), (MotionChoice::Reduced, "reduced", "On"), @@ -92,7 +92,7 @@ pub enum VariantAxis { Contrast, /// Compact and comfortable density. Size, - /// The creative and the office component set. + /// The creative and the productivity component set. Set, /// Left to right and right to left. Direction, @@ -122,7 +122,7 @@ impl VariantAxis { VariantAxis::Mode => "Every mode (light, dark)", VariantAxis::Contrast => "Every contrast (standard, high)", VariantAxis::Size => "Every size (compact, comfortable)", - VariantAxis::Set => "Every set (creative, office)", + VariantAxis::Set => "Every set (creative, productivity)", VariantAxis::Direction => "Every direction (LTR, RTL)", VariantAxis::ControlSize => "Every control size (Sm, Md)", VariantAxis::DirectionAndControlSize => "Every direction and control size", diff --git a/docs/contract-api.md b/docs/contract-api.md index ea219b7d0..f5b3b99ef 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -3034,7 +3034,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub fn edge(look: &RuleLook, rect: Rect, side: RectSide, pixels_per_point: f32) -> Vec`. The line along the `side` edge of `rect`, on the physical pixels just inside it: a row's bottom rule or a - `craft_ui::primitives::RuleKind`: `pub enum RuleKind { Divider, Edge, Grid, DropMark }`. Which rule a look is for. - `craft_ui::primitives::RulerFace`: `pub enum RulerFace { Edge, Centred }`. How a ruler lays out its marks and numbers. A ruler takes a face from its `face` prop, else from the scope's - - `pub const fn of(set: craft_theme::ComponentSet) -> Self`. The face the component set `set` shows: the creative set the edge face, the office set the centred one. + - `pub const fn of(set: craft_theme::ComponentSet) -> Self`. The face the component set `set` shows: the creative set the edge face, the productivity set the centred one. - `pub fn bar(self, strip: Rect, edge: TickEdge) -> Rect`. Where the marks of a strip along `edge` sit: the whole strip for the edge face, the strip inset across its - `pub fn beside_numbers(self, edge: TickEdge, origin: f32, marks: Vec, numbers: &[Rect], pad: f32) -> Vec`. The marks of `marks` this face shows beside the numbers in `numbers` (screen boxes): the edge face shows every - `pub fn centred_number(bar: Rect, edge: TickEdge, at: f32, size: Vec2) -> Rect`. The box a centred number of `size` takes for the mark at `at` (a screen position along `edge`'s axis): centred From 0ea84419cd32e7dfec185431310ec109c4a72153 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 01:34:06 +0000 Subject: [PATCH 33/89] Text ruler: the tab selector shows in the corner its host gives PageRulers handed the text ruler the canvas's top strip, which starts after the canvas corner, and the ruler cut its own corner square out of that strip, so the selector sat one strip depth right of the corner, over the horizontal ruler, and the corner stayed blank. The host now gives the corner (TextRuler::corner): Rulers::strips returns it beside the strips, and PageRulers shows the ruler over the top strip and the corner. The corner follows the host in either direction. The selector's box is the icon size with the theme's small rounding, in the column's colour with the state layer under the pointer; the corner continues the strip round it; the glyph is centred by its own bounds. --- crates/pages/src/ui/page_rulers.rs | 14 +++-- crates/pages/src/ui/view.rs | 2 +- crates/pages/tests/it/rulers.rs | 25 ++++++++- crates/text/src/ui/ruler.rs | 68 +++++++++++++++-------- crates/text/src/ui/ruler/paint.rs | 25 +++++---- crates/text/src/ui/ruler/stories.rs | 13 ++++- crates/text/tests/it/ruler.rs | 8 +-- crates/ui-canvas/src/canvas/rulers/mod.rs | 9 ++- 8 files changed, 111 insertions(+), 53 deletions(-) diff --git a/crates/pages/src/ui/page_rulers.rs b/crates/pages/src/ui/page_rulers.rs index 044bc3500..4c1a45c81 100644 --- a/crates/pages/src/ui/page_rulers.rs +++ b/crates/pages/src/ui/page_rulers.rs @@ -488,7 +488,7 @@ impl<'a> PageRulers<'a> { self } - /// Shows the tab selector in the corner, with the kind a click sets. + /// Shows the tab selector in the canvas's corner, with the kind a click sets. pub fn kind(mut self, kind: Option) -> Self { self.kind = kind; self @@ -554,7 +554,7 @@ impl<'a> PageRulers<'a> { let env = Env::of(ui); (env.words::(), env.view().direction().is_rtl()) }; - let (top_strip, left_strip) = Rulers::strips(ui, canvas_rect); + let (top_strip, left_strip, corner) = Rulers::strips(ui, canvas_rect); let page_size = (f64::from(page.rect.width()) / page.scale, f64::from(page.rect.height()) / page.scale); let shown = edges.reborrow().get().and_then(|edges| edges.same().copied()).unwrap_or_default(); let rules = MarginRules::new(page_size, shown).gutter(gutter).mirrored_even(mirrored_even); @@ -565,8 +565,8 @@ impl<'a> PageRulers<'a> { let scale = (page.scale as f32).max(f32::EPSILON); let rtl = right_to_left.unwrap_or(interface_rtl); - // The ruler counts from the column's start edge and covers the page's width; both are given as screen x, and the - // ruler places its own corner square. + // The ruler counts from the column's start edge and covers the page's width; both are given as screen x. With the + // tab selector it lies along the top strip and the canvas's corner, which holds the selector. let origin = page.rect.min.x + (if rtl { column.1 } else { column.0 }) * scale; let extent = Rangef::new(page.rect.min.x, page.rect.max.x); let mut horizontal = TextRuler::new(label.clone(), ruler, (column.1 - column.0).max(0.0)) @@ -579,13 +579,15 @@ impl<'a> PageRulers<'a> { .scale(scale) .right_to_left(rtl) .id_source(id); + let mut band = top_strip; if let Some(kind) = kind { - horizontal = horizontal.kind(kind); + horizontal = horizontal.kind(kind).corner(corner); + band = top_strip.union(corner); } if let Some(face) = face { horizontal = horizontal.face(face); } - let ruler_out = horizontal.show_at(ui, top_strip); + let ruler_out = horizontal.show_at(ui, band); let vertical_label = Label::from(words.vertical.fill(&[("name", label.as_str())])); let mut vertical = VerticalRuler::new(vertical_label, page).text(Rangef::new(top as f32, bottom as f32)).unit(unit).rows(rows); diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 8e3af84d3..f04171096 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -464,7 +464,7 @@ impl<'a> PageView<'a> { // (`ContainerProps::scroll_owner`), so the app's body runs with the clip opened over the strips again, where // its `PageRulers` show. The canvas's own `with_rulers` would show the general rulers there instead. let (canvas_rect, strips_clip) = if rulers { - let (top, left) = Rulers::strips(ui, rect); + let (top, left, _) = Rulers::strips(ui, rect); let inner = Rect::from_min_max(pos2(left.max.x.min(rect.max.x), top.max.y.min(rect.max.y)), rect.max); (inner, Some(ui.clip_rect().intersect(rect))) } else { diff --git a/crates/pages/tests/it/rulers.rs b/crates/pages/tests/it/rulers.rs index 65512b551..6b893daaf 100644 --- a/crates/pages/tests/it/rulers.rs +++ b/crates/pages/tests/it/rulers.rs @@ -10,7 +10,7 @@ use craft_pages::ui::{PageEdges, PageRulers, RowDrag, VerticalRuler}; use craft_text::ui::DocUnit; use craft_text::ui::ruler::{RulerValues, TabAlign, TabLeader, TabStop, TextRulerWords}; use craft_ui::contract::{Bind, Role, Show as _}; -use craft_ui::runtime::env::UnitKind; +use craft_ui::runtime::env::{Direction, UnitKind}; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Rangef, Rect, pos2, vec2}; use std::cell::{Cell, RefCell}; @@ -228,3 +228,26 @@ fn a_new_salt_during_a_tab_drag_commits_nothing() { fixture.settle(); assert_eq!(commits.get(), 1, "the drag open when the paragraph changed commits nothing"); } + +/// The tab selector shows in the canvas's corner, where the top and left strips meet, in either interface direction: +/// the host places it, so it never lies over the horizontal ruler. +#[trial] +fn the_tab_selector_sits_in_the_canvas_corner_in_both_directions() { + let words = TextRulerWords::default(); + let name = words.tab_selector.fill(&[("kind", words.left_tab.as_str())]); + for direction in [Direction::Ltr, Direction::Rtl] { + let corner = Rc::new(Cell::new(Rect::NOTHING)); + let seen = corner.clone(); + let mut fixture = Fixture::new(move |ui| { + let full = craft_ui::testing::stage(ui); + seen.set(craft_ui::canvas::Rulers::strips(ui, full).2); + let page = demo_placed(1, pos2(full.min.x + PAGE_AT.0, full.min.y + PAGE_AT.1)).remove(0); + let (mut edges, mut values) = (PageEdges::new(Margins::uniform(72.0)), RulerValues::default()); + PageRulers::new("Rulers", &page, Bind::bound(&mut edges), Bind::bound(&mut values)).kind(Some(TabAlign::Left)).show_at(ui, full); + }); + fixture.direction(direction).room(vec2(900.0, 600.0)); + fixture.settle(); + let selector = fixture.by_label(&name).expect("the tab selector shows").rect; + assert!(corner.get().contains_rect(selector), "{direction:?}: the selector {selector:?} lies outside the canvas's corner {:?}", corner.get()); + } +} diff --git a/crates/text/src/ui/ruler.rs b/crates/text/src/ui/ruler.rs index 3eae19469..617c1446c 100644 --- a/crates/text/src/ui/ruler.rs +++ b/crates/text/src/ui/ruler.rs @@ -8,7 +8,7 @@ //! edit of the whole [`RulerValues`], so one drag is one undo step. //! //! ```ignore -//! let out = TextRuler::new("ruler", Bind::given(values.clone()), column_width).unit(unit).kind(tab_kind).show_at(ui, strip); +//! let out = TextRuler::new("ruler", Bind::given(values.clone()), column_width).unit(unit).kind(tab_kind).corner(corner).show_at(ui, band); //! if let Some(EditEvent::Commit { after, .. }) = out.edit.event { doc.set_paragraph_tabs(after); } //! if let Some(kind) = out.kind { tab_kind = kind; } //! if out.open_tabs_dialog { dialogs.open(TabStopsDialog::new(values.stops.clone(), default_tab)); } @@ -16,14 +16,15 @@ use super::length::DocUnit; use craft_behavior::{Axis, GesturePhase, HitLevel, HitPriority, Metrics, NavShape, Roving, Sense}; +use craft_theme::over; use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, Name, Numeric, Outcome, PaintUi, PartsCx, Props as _, Role, WordSetCx as _, }; use craft_ui::primitives::RulerFace; use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse}; -use craft_ui::style::{ComponentStyle, Flags, FocusLook, Stateful, StyleColor, StyleCx, TextLook, TypeRole}; -use egui::{Rect, Response, Vec2}; +use craft_ui::style::{ComponentStyle, Flags, FocusLook, Stateful, States, StyleColor, StyleCx, TextLook, TypeRole, UiTokens}; +use egui::{CornerRadius, Rect, Response, Vec2}; mod geometry; mod items; @@ -302,6 +303,12 @@ pub struct TextRulerStyle { /// The tick numbers. #[style(text)] label: TextLook, + /// The tab selector's box: the column's colour, the state layer over it under the pointer and pressed. + selector: Stateful, + /// The side of the tab selector's box. + selector_side: f32, + /// The rounding of the tab selector's box. + selector_radius: CornerRadius, /// The strip's depth. thickness: f32, /// The gap between a tick and its number. @@ -340,8 +347,8 @@ pub struct TextRulerStyle { /// - A click on the empty column sets a stop of the selector's kind at the snapped position (1/16 in, or the unit's /// minor tick); dragging a stop moves it; dragging it off the ruler ([`dropped_off`]) clears it on release, the stop /// drawn faded meanwhile. Each gesture is one edit of the whole values; Escape restores the start. -/// - The tab selector ([`kind`](Self::kind)) sits in the corner square at the interface's start edge of the rect: -/// click for the next kind, secondary click for the previous one. +/// - The tab selector ([`kind`](Self::kind)) sits in the corner the host gives ([`corner`](Self::corner)), where its +/// rulers meet: click for the next kind, secondary click for the previous one. /// - A table's column borders ([`columns`](Self::columns)): a grip marker on each border of the caret row; dragging /// one reports a [`ColumnDrag`] gesture, snapped like a stop (Alt free). While Alt is held in the drag, each column's /// width shows between its borders. A border is a slider too: the arrows and the screen reader's Increment, @@ -371,7 +378,7 @@ pub struct TextRuler<'a> { #[prop] gaps_draggable: bool, /// The screen x where the ruler's zero sits: a page-wide ruler is measured from the page's text origin. Unset, zero - /// is the strip's start edge. Given against the screen so the corner square, which only the ruler places, does not + /// is the strip's start edge. Given against the screen so the corner, which the rect may hold, does not /// enter the caller's arithmetic. #[prop(quantity = "screen x of the ruler's zero, a position")] origin: Option, @@ -381,9 +388,15 @@ pub struct TextRuler<'a> { /// The unit the markers' values and the ticks show. #[prop] unit: DocUnit, - /// Shows Word's tab selector in the corner, with the kind a click sets. Without it a click sets a left stop. + /// The kind of stop a click sets, which Word's tab selector shows in the [`corner`](Self::corner). Without it a + /// click sets a left stop. #[prop] kind: Option, + /// The square at one end of the rect where the host's rulers meet (the canvas rulers' corner): the tab selector + /// shows there and the strip is the rest of the rect. The host places it, so it sits where the host's corner is in + /// either direction. Without it the whole rect is the strip and no selector shows. + #[prop] + corner: Option, /// Screen points per point (the view's zoom when the ruler sits over a text frame on the canvas); without it the /// column fits into the strip. #[prop(quantity = "scale")] @@ -416,6 +429,7 @@ impl<'a> TextRuler<'a> { extent: None, unit: DocUnit::points(), kind: None, + corner: None, scale: None, right_to_left: None, selected: None, @@ -425,19 +439,18 @@ impl<'a> TextRuler<'a> { .label(label) } - /// The corner square, the strip and the markers' sizes inside `rect`. + /// The part of the host's corner inside `rect`, if any. + fn corner_in(&self, rect: Rect) -> Option { + self.corner.map(|corner| corner.intersect(rect)).filter(|corner| corner.is_positive()) + } + + /// The host's corner, the strip beside it and the markers' sizes inside `rect`. fn layout(&self, rect: Rect, style: &TextRulerStyle, interface_rtl: bool) -> Layout { - let corner_width = if self.kind.is_some() { rect.height().min(rect.width()) } else { 0.0 }; - let (corner, strip) = if interface_rtl { - ( - Rect::from_min_max(egui::pos2(rect.max.x - corner_width, rect.min.y), rect.max), - Rect::from_min_max(rect.min, egui::pos2(rect.max.x - corner_width, rect.max.y)), - ) - } else { - ( - Rect::from_min_max(rect.min, egui::pos2(rect.min.x + corner_width, rect.max.y)), - Rect::from_min_max(egui::pos2(rect.min.x + corner_width, rect.min.y), rect.max), - ) + let corner = self.corner_in(rect); + let strip = match corner { + Some(corner) if corner.center().x < rect.center().x => Rect::from_min_max(egui::pos2(corner.max.x, rect.min.y), rect.max), + Some(corner) => Rect::from_min_max(rect.min, egui::pos2(corner.min.x, rect.max.y)), + None => rect, }; let fit = if self.width > 0.0 { strip.width() / self.width } else { 1.0 }; let scale = self.scale.filter(|scale| scale.is_finite() && *scale > 0.0).unwrap_or(fit).max(f32::EPSILON); @@ -476,11 +489,11 @@ impl<'a> TextRuler<'a> { } } -/// The corner, the strip with its column and the marker sizes. +/// The host's corner, the strip with its column and the marker sizes. pub(super) struct Layout { g: Geometry, shapes: Shapes, - corner: Rect, + corner: Option, } impl Component for TextRuler<'_> { @@ -507,6 +520,13 @@ impl Component for TextRuler<'_> { marker_off: cx.color(colors.text.faint), marker: Stateful::new(cx.color(colors.text.normal)).when(Flags::SELECTED, cx.color(colors.accent.strong)), label: TextLook::new(TypeRole::Caption, Stateful::new(cx.color(colors.text.muted))), + selector: { + let (rest, column) = (cx.color(colors.surface.sunken), colors.surface.sunken); + let (hover, pressed) = (cx.color(over(colors.state.hover, column)), cx.color(over(colors.state.pressed, column))); + Stateful::new(rest).off(States::new(rest, hover, pressed, rest)) + }, + selector_side: tokens.size.icon.sm, + selector_radius: UiTokens::corner(tokens.shape.radius.sm), thickness: tokens.typography.get(TypeRole::Caption).line_height, pad: tokens.space.gap.tight, marker_width: tokens.size.handle.md, @@ -578,8 +598,8 @@ impl Component for TextRuler<'_> { } } cx.roving(Roving::new(NavShape::Flat).page(Some(1)).home_end(false)); - if self.kind.is_some() { - cx.part(SELECTOR, layout.corner) + if let (Some(_), Some(corner)) = (self.kind, layout.corner) { + cx.part(SELECTOR, corner) .sense(Sense::CLICK | Sense::CONTEXT_CLICK) .priority(handle) .pointer_only("the Tabs dialog sets the alignment of a stop"); @@ -615,7 +635,7 @@ impl Component for TextRuler<'_> { node.name = Name::Text(words.table_column.as_str().to_owned()); node.numeric = Some(Numeric::new(at, range.clone()).step(step).text(text.format_value(&numbers, at, 0.0))); } - if let Some(kind) = self.kind { + if let Some(kind) = self.kind.filter(|_| self.corner_in(cx.rect).is_some()) { let name = Self::tab_name(&words, kind); let node = access.node(SELECTOR, Role::BUTTON); node.name = Name::Text(words.tab_selector.fill(&[("kind", name)])); diff --git a/crates/text/src/ui/ruler/paint.rs b/crates/text/src/ui/ruler/paint.rs index 8d51889cf..7c1365b6e 100644 --- a/crates/text/src/ui/ruler/paint.rs +++ b/crates/text/src/ui/ruler/paint.rs @@ -1,7 +1,7 @@ //! The ruler's drawing. use super::geometry::glyph; -use super::items::Item; +use super::items::{Item, SELECTOR}; use super::run::{Held, ruler_text}; use super::{TextRuler, TextRulerStyle}; use craft_ui::canvas::{RulerTick, Rulers, TickRule}; @@ -95,18 +95,23 @@ impl TextRuler<'_> { let end = shapes.right(g.strip, right); triangle(end.left_bottom(), end.right_bottom(), pos2(right, end.min.y), Item::Right); - if let Some(kind) = self.kind { - let corner = layout.corner; - draw.fill(&rect(corner), style.fill); - let side = style.thickness.min(corner.width()).min(corner.height()); - let boxed = Rect::from_center_size(corner.center(), vec2(side, side)); - draw.stroke(&rect(boxed), StrokeWidth::Thin, style.tick); - let (segments, dot) = glyph(&shapes, boxed.center().x, boxed.max.y - (boxed.height() - style.stem) / 2.0, kind, false); + if let (Some(kind), Some(corner)) = (self.kind, layout.corner) { + // The corner continues the strip round it, the box is the column's colour. + let surround = if style.face == RulerFace::Centred { style.strip } else { style.margin }; + draw.fill(&rect(corner), surround); + let side = style.selector_side.min(corner.width()).min(corner.height()); + let boxed = PaintShape::Rect(Rect::from_center_size(corner.center(), vec2(side, side)), style.selector_radius); + draw.fill(&boxed, cx.resolve_part(SELECTOR, &style.selector)); + draw.stroke(&boxed, StrokeWidth::Thin, style.tick); + // The glyph is centred on the box by its own bounds: a left or right stop's foot runs to one side of its stem. + let (segments, dot) = glyph(&shapes, 0.0, 0.0, kind, false); + let bounds = Rect::from_points(&segments.iter().flatten().copied().chain(dot).collect::>()); + let shift = corner.center() - bounds.center(); for [a, b] in segments { - draw.stroke(&path(a, b), StrokeWidth::Thin, cx.resolve(&style.marker)); + draw.stroke(&path(a + shift, b + shift), StrokeWidth::Thin, cx.resolve(&style.marker)); } if let Some(centre) = dot { - draw.fill(&PaintShape::Circle(centre, style.dot), cx.resolve(&style.marker)); + draw.fill(&PaintShape::Circle(centre + shift, style.dot), cx.resolve(&style.marker)); } } } diff --git a/crates/text/src/ui/ruler/stories.rs b/crates/text/src/ui/ruler/stories.rs index 5f4b3ed7a..dd266428b 100644 --- a/crates/text/src/ui/ruler/stories.rs +++ b/crates/text/src/ui/ruler/stories.rs @@ -48,7 +48,16 @@ fn inches() -> DocUnit { fn with_stops_and_indents(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let kind = *data.value("kind", TabAlign::Left); let (values, values_at) = data.value_at("values", word()); - let out = TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).kind(kind).show(ui); + // The selector shows in the corner the host gives, here at the band's start edge in the interface's direction. + let stage = craft_ui::testing::stage(ui); + let (strip, _, corner) = Rulers::strips(ui, stage); + let band = strip.union(corner); + let corner = if craft_ui::runtime::env::Env::of(ui).direction.is_rtl() { + egui::Rect::from_min_max(egui::pos2(band.max.x - corner.width(), band.min.y), band.max) + } else { + corner + }; + let out = TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).kind(kind).corner(corner).show_at(ui, band); if let Some(next) = out.kind { *data.value("kind", TabAlign::Left) = next; } @@ -90,7 +99,7 @@ const THREE_GAPS: [(f32, f32); 3] = [(108.0, 126.0), (225.0, 243.0), (342.0, 360 fn over_a_page(ui: &mut Ui, data: &mut StoryData, face: Option) -> StoryOutput { let (values, values_at) = data.value_at("values", word()); let stage = craft_ui::testing::stage(ui); - let (strip, _) = Rulers::strips(ui, stage); + let (strip, _, _) = Rulers::strips(ui, stage); // The page starts at the strip's start edge: its right edge in a right-to-left interface. let (origin, extent) = if craft_ui::runtime::env::Env::of(ui).direction.is_rtl() { (strip.max.x - PAGE_MARGIN, egui::Rangef::new(strip.max.x - PAGE, strip.max.x)) diff --git a/crates/text/tests/it/ruler.rs b/crates/text/tests/it/ruler.rs index 48972a46b..d2e02492e 100644 --- a/crates/text/tests/it/ruler.rs +++ b/crates/text/tests/it/ruler.rs @@ -159,7 +159,7 @@ fn ruler_numbers_skip_margins_and_markers_thin_out_mirror_for_rtl_and_keep_clear })); let mut fixture = Fixture::new(move |ui| { let stage = craft_ui::testing::stage(ui); - let (strip, _) = Rulers::strips(ui, stage); + let (strip, _, _) = Rulers::strips(ui, stage); let origin = if rtl { strip.max.x - ORIGIN * scale } else { strip.min.x + ORIGIN * scale }; TextRuler::new("Ruler", Bind::bound(&mut *values.borrow_mut()), WIDTH).origin(origin).scale(scale).right_to_left(rtl).show_at(ui, strip); }); @@ -206,7 +206,7 @@ fn a_ruler_cut_to_an_extent_paints_no_tick_past_it() { let seen = strip_at.clone(); let mut fixture = Fixture::new(move |ui| { let stage = craft_ui::testing::stage(ui); - let (strip, _) = Rulers::strips(ui, stage); + let (strip, _, _) = Rulers::strips(ui, stage); *seen.borrow_mut() = Some(strip); TextRuler::new("Ruler", Bind::bound(&mut *values.borrow_mut()), 140.0) .unit(DocUnit::new(UnitKind::Inches, 96.0)) @@ -243,7 +243,7 @@ fn the_ruler_column_is_lighter_than_its_margins() { let seen = strip_at.clone(); let mut fixture = Fixture::new(move |ui| { let stage = craft_ui::testing::stage(ui); - let (strip, _) = Rulers::strips(ui, stage); + let (strip, _, _) = Rulers::strips(ui, stage); *seen.borrow_mut() = Some(strip); TextRuler::new("Ruler", Bind::bound(&mut *values.borrow_mut()), WIDTH) .origin(strip.min.x + ORIGIN) @@ -345,7 +345,7 @@ fn page_ruler(set: ComponentSet, face: Option, popup: bool) -> (Fixtu let mut fixture = Fixture::new(move |ui| { let ruler = |ui: &mut egui::Ui| { let stage = craft_ui::testing::stage(ui); - let (strip, _) = Rulers::strips(ui, stage); + let (strip, _, _) = Rulers::strips(ui, stage); *seen.borrow_mut() = Some(strip); let mut values = values.borrow_mut(); let mut ruler = TextRuler::new("Ruler", Bind::bound(&mut *values), 432.0) diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index 4b7b35bf9..36bfd1070 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -257,13 +257,12 @@ impl<'a> Rulers<'a> { Self::content_rect_of(full, thickness(cx.tokens)) } - /// The top and the left strip inside the canvas's rect `full`, each as thick as the canvas's own rulers, for a ruler - /// of another component (a text ruler, a page ruler) that lies along them. - pub fn strips(ui: &egui::Ui, full: Rect) -> (Rect, Rect) { + /// The top strip, the left strip and the corner where they meet inside the canvas's rect `full`, each as thick as + /// the canvas's own rulers, for a ruler of another component (a text ruler, a page ruler) that lies along them. + pub fn strips(ui: &egui::Ui, full: Rect) -> (Rect, Rect, Rect) { let env = crate::runtime::env::Env::of(ui); let cx = StyleCx::of_env(ui.ctx(), &env); - let (top, left, _) = strips(full, thickness(cx.tokens)); - (top, left) + strips(full, thickness(cx.tokens)) } /// The ticks of one ruler over `values` (ruler units from the zero point): the one tick rule of every ruler, so a From b66a60caf8fb520097c3bf57ac670e2dceb7cbd2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 01:42:09 +0000 Subject: [PATCH 34/89] DocumentWindow: the body takes the window's room and never scrolls --- crates/ui-shell/src/shell/document_window.rs | 4 ++- .../tests/it/shell/document_window.rs | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/ui-shell/src/shell/document_window.rs b/crates/ui-shell/src/shell/document_window.rs index 1bc55a73d..edab6e6fa 100644 --- a/crates/ui-shell/src/shell/document_window.rs +++ b/crates/ui-shell/src/shell/document_window.rs @@ -84,6 +84,8 @@ impl Outcome for DocumentWindowOutput { /// - **Title and focus.** The title is the label given to `new`; it follows the document while the app changes it. /// [`raise`](DocumentWindow::raise) brings the window forward in the pass it is set. With /// [`in_list`](DocumentWindow::in_list) the window makes itself the list's active window when it gains OS focus. +/// - **Body.** The body is laid out in the window's room and never scrolls, in the OS window and on the fallback +/// layer alike; an app that wants scrolling puts a scroll region in the body. /// - **Fallback.** Where OS windows are unavailable the document shows on a movable, resizable layer with a title row. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container)] @@ -138,7 +140,7 @@ impl<'a> DocumentWindow<'a> { /// A window titled `title`, resizable, with the installed decision's frame. pub fn new(title: impl Into

(&self, column: &Column

) -> Option { + column.groups.iter().all(|group| group.minimized).then(|| self.strip * column.groups.len() as f32) + } + /// The width bounds of an expanded column from the limits of its panels. pub fn width_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { let limits = column.groups.iter().flat_map(|group| group.panels.iter()).map(|panel| spec(panel).limits); diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 369cb3c9d..b48af361b 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1191,6 +1191,10 @@ impl Pass<'_, P> { /// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records /// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]). /// + /// A window whose every group is minimized shows its title row and their strips at its rect's place and width + /// ([`WindowColumn::minimized`]): its sides resize its width, and its placement keeps its expanded height, so a + /// restore shows it at that height again. + /// /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps @@ -1251,6 +1255,8 @@ impl Pass<'_, P> { WindowColumn::collapsed(edge, size, scene.sizes.iconic_bounds(&window.column, &spec_of)) } else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) { WindowColumn::fitted(edge, Vec2::new(width, content)) + } else if let Some(strips) = scene.sizes.minimized_height(&window.column) { + WindowColumn::minimized(edge, strips) } else { WindowColumn::expanded(edge) } diff --git a/crates/ui-patterns/src/patterns/dock/area/stories.rs b/crates/ui-patterns/src/patterns/dock/area/stories.rs index 7d798c226..6ccca96f8 100644 --- a/crates/ui-patterns/src/patterns/dock/area/stories.rs +++ b/crates/ui-patterns/src/patterns/dock/area/stories.rs @@ -89,36 +89,43 @@ impl DockPanels for Demo { } /// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the -/// end, with one floating group and one floating window collapsed to icons. -fn workspace() -> Workspace { +/// end, with one floating group, `minimized` or not, and one floating window collapsed to icons. +fn workspace(minimized: bool) -> Workspace { let tools = Column::new(vec![Group::new(vec![TOOLS], 0)]).with_steps(1); let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS], 0), Group::new(vec![PROPERTIES], 0)]).with_width(SIDE); let mut icons = Column::new(vec![Group::new(vec![SWATCHES], 0)]).with_width(SIDE); icons.iconic = true; let centre = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![icons])); let root = Node::split(Axis::X, SplitSize::FixedFirst(SIDE), Node::dock(DockEdge::Start, vec![tools, side]), centre); - let window = Floating::single(vec![HISTORY], 0, WINDOW).with_id(1); + let mut window = Floating::single(vec![HISTORY], 0, WINDOW).with_id(1); + window.column.groups[0].minimized = minimized; let mut collapsed = Floating::single(vec![NAVIGATOR], 0, COLLAPSED_WINDOW).with_id(2); collapsed.column.iconic = true; Workspace::new(Layout::new(Some(root), vec![window, collapsed])) } -fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput { - let (workspace, workspace_at) = data.value_at("workspace", workspace()); +fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo, minimized: bool) -> StoryOutput { + let (workspace, workspace_at) = data.value_at("workspace", workspace(minimized)); DockArea::new("Dock", workspace_at.bind(&mut *workspace), demo, DockConfig::default()).show(ui).into() } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn docked_columns_a_floating_group_and_a_flyout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn a_canvas_group_the_host_draws(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn host_rows_above_the_dock_rows_in_a_panel_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }, false) +} + +/// The floating group minimized: its window shows the title row and the tab strip at its width. +#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] +fn a_minimized_floating_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, true) } diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 7fad2cfbe..94528a104 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -529,6 +529,48 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col assert_eq!(bed.workspace.borrow().layout.floating[0].rect, WINDOW_AT, "the expanded rect is unchanged"); } +/// A floating window whose every group is minimized shows its title row and tab strip at its place and width. Its free +/// side resizes its width and not its height, and its rect keeps the expanded height, which the window shows at again +/// once the group is restored. +#[trial] +fn a_window_whose_groups_are_all_minimized_shows_its_strip_and_comes_back_at_its_height() { + let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let window_layer = |bed: &Bed| { + let layers = layer_rects(bed.fixture.ctx()).into_iter().filter(|rect| rect.contains(window_title())); + layers.min_by(|a, b| a.area().total_cmp(&b.area())).expect("the window's layer holds its title row") + }; + let strip = |bed: &Bed| { + let lists = bed.fixture.by_role(Role::TAB_LIST).into_iter().filter(|list| WINDOW_AT.expand(SLACK).contains_rect(list.rect)); + lists.map(|list| list.rect).next().expect("the window shows its tab strip") + }; + bed.workspace.borrow_mut().apply(Action::set_minimized(WINDOW, true), false, |_| Permissions::ALL).expect("the group minimizes"); + bed.fixture.settle(); + let shown = window_layer(&bed); + assert!((shown.bottom() - strip(&bed).bottom()).abs() <= SLACK, "the window ends at its strip: {shown:?}, {:?}", strip(&bed)); + assert!((shown.min - WINDOW_AT.min).length() <= SLACK && (shown.width() - WINDOW_AT.width()).abs() <= SLACK, "at its place and width: {shown:?}"); + + // The window keeps to the end edge; its start side is free, and a press just inside it holds the side's grip. + let side = Pos2::new(shown.left() + 2.0, shown.center().y); + let by = Vec2::new(-40.0, 10.0); + press_and_move(&mut bed.fixture, side, by); + bed.fixture.frame(vec![release(side + by)]); + bed.fixture.settle(); + let resized = window_layer(&bed); + let rect = bed.workspace.borrow().layout.floating[0].rect; + assert!((resized.width() - (shown.width() - by.x)).abs() <= SLACK, "the side resizes the width: {shown:?}, then {resized:?}"); + assert!((resized.height() - shown.height()).abs() <= SLACK, "the height stays the strip's: {resized:?}"); + assert!( + (rect.width() - resized.width()).abs() <= SLACK && rect.height() == WINDOW_AT.height(), + "the rect takes the width and keeps its height: {rect:?}" + ); + + bed.workspace.borrow_mut().apply(Action::set_minimized(WINDOW, false), false, |_| Permissions::ALL).expect("the group restores"); + bed.fixture.settle(); + let restored = window_layer(&bed); + assert!((restored.height() - WINDOW_AT.height()).abs() <= SLACK, "restored, the window shows at its height: {restored:?}"); + assert!((restored.width() - resized.width()).abs() <= SLACK, "at the width the side gave it: {restored:?}"); +} + /// A floating collapsed column opens its flyouts towards the room of the float area, away from the edge it keeps to. #[trial] fn a_floating_collapsed_columns_flyout_opens_towards_the_room() { diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 681d42e1e..1ed545c30 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -704,6 +704,65 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() assert_eq!(at.width(), width, "the window keeps the width the OS gave it"); } +/// A native palette whose every group is minimized shrinks to its title row and tab strip at its place and width. +/// The OS resizes its width and never its height: AppKit takes the height as fixed, and the app sends no size back +/// for the width the OS gave it. The model keeps the expanded height throughout, and restored, the window takes that +/// height back at the width it was given. +#[trial] +fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_height() { + for os in [Os::Mac, Os::Windows] { + let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new())); + let expanded = FLOAT_AT.size(); + let mut at = FLOAT_AT; + // The OS follows the window commands of each frame, within the limits in force, and the window reports where it is. + let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| { + let mut sent = Vec::new(); + for _ in 0..frames { + let mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + let commands = dock.frame(vec![]).1; + for command in &commands { + match command { + ViewportCommand::MaxInnerSize(limit) => max = Some(*limit), + ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, max.map_or(*size, |max| size.min(max))), + ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), + _ => {} + } + } + dock.windows.child_info(info(true, *at)); + sent.extend(commands); + } + sent + }; + let recorded = + |dock: &NativeDock| Vec2::from(dock.workspace.layout.floating[0].native.clone().expect("the model records the window").normal.size); + dock.workspace.apply(Action::set_minimized(1, true), false, |_| Permissions::ALL).expect("the group minimizes"); + follow(&mut dock, &mut at, 3); + let strips = at; + assert!(strips.height() < expanded.y / 4.0, "{os:?}: the window shrinks to its title row and strip: {strips:?}"); + assert_eq!((strips.min, strips.width()), (FLOAT_AT.min, expanded.x), "{os:?}: at its place and width"); + assert_eq!(recorded(&dock), expanded, "{os:?}: minimized, the model keeps the expanded size"); + let builder = dock.builder.clone().expect("the palette's window opened"); + let (least, most) = (builder.min_inner_size.expect("a least size"), builder.max_inner_size.expect("a most size")); + assert!(least.y == most.y && (least.y - strips.height()).abs() <= 0.5, "{os:?}: the height is fixed: {least:?}..{most:?}, {strips:?}"); + assert!(least.x < most.x, "{os:?}: the width resizes: {least:?}..{most:?}"); + if os == Os::Mac { + assert_eq!(builder.resizable, Some(true), "AppKit resizes the minimized window"); + } + + // The OS widens the window. + let width = expanded.x + 60.0; + at = Rect::from_min_size(at.min, Vec2::new(width, at.height())); + dock.windows.child_info(info(true, at)); + let sent = follow(&mut dock, &mut at, 3); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::InnerSize(_))), "{os:?}: no size goes back: {sent:?}"); + assert_eq!(recorded(&dock), Vec2::new(width, expanded.y), "{os:?}: the model takes the width and keeps the expanded height"); + + dock.workspace.apply(Action::set_minimized(1, false), false, |_| Permissions::ALL).expect("the group restores"); + follow(&mut dock, &mut at, 3); + assert_eq!(at, Rect::from_min_size(FLOAT_AT.min, Vec2::new(width, expanded.y)), "{os:?}: restored, the window takes its height back"); + } +} + /// On a display at 125 % (Windows), a click on the double arrow of a native palette collapsed to icons expands its /// column, and the OS window takes its expanded size. #[trial] diff --git a/docs/ui-docking.md b/docs/ui-docking.md index a6ab3fd4f..782fdccb8 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -104,6 +104,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides. - A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to its edge of the float area: `Floating::edge`, else the one nearer its rect. A move keeps the edge it began with. A collapsed window's move ends at the edge nearer its strip where it was dropped, with the rect that shows the strip there (`WindowColumn::dropped`), and the area records that edge (`Action::MoveFloating`'s `edge`); a unit dragged out of a collapsed column (`start_icon_drag`) floats collapsed the same way, its strip under the pointer (`Target::Float`'s `edge`). Collapsing a floating column and moving an expanded window clear the edge. A column that neither collapses nor has steps shows no double arrow and offers no collapse in its menu (`ColumnArrow::Fixed`). - A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. +- A floating window whose every group is minimized shows its title row and their tab strips, at its rect's place and width (`WindowColumn::minimized`). Its sides resize its width, never its height, and its rect, in the app window and in an OS window's recorded placement, keeps the expanded height, which the window takes back when a group is restored. A window with some groups open keeps its size, and its open groups share the room the strips leave. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. - A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. From 658bbcb6bdc53f48ce13df95373dee8dc2073bf5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 02:37:40 +0000 Subject: [PATCH 43/89] A dragged layer stands under the pointer in the frame of each step The layer host shows a layer whose move band is being dragged at the drag's rect for this pass: the rect the layer had when the band was pressed, moved by the pointer's travel, within its bounds. window_drag runs the drag from the same rect. A caller that places the layer (placed, placed_at, or an anchored layer it places once moved) writes its place once, on the Commit. - The task bar writes its place on the drop only: one edit, no lag. - A floating dock window in the app window reaches the workspace on the drop only; resizes and keyboard moves keep their gesture edits. - A layer root inside an opener's arena steps its press machine early, as its steps 6 to 16 sense in its own arena: the host reads this pass's band press before it places the layer. Trials: a dragged task bar and a dragged floating window stand under the pointer in each frame, in one pass, and are placed once, on the drop. --- .../ui-canvas/src/canvas_controls/task_bar.rs | 15 ++--- .../tests/it/canvas_controls/task_bar.rs | 37 ++++++++++++ crates/ui-contract/src/contract/body/hooks.rs | 6 +- .../src/contract/body/placement.rs | 28 ++++++++- .../ui-contract/src/contract/body/window.rs | 59 ++++++++++++++----- crates/ui-contract/src/contract/mount.rs | 17 ++++-- crates/ui-contract/src/contract/run.rs | 7 ++- crates/ui-patterns/src/patterns/dock/area.rs | 14 +++-- .../tests/it/docking/floating_area.rs | 56 ++++++++++++++---- 9 files changed, 188 insertions(+), 51 deletions(-) diff --git a/crates/ui-canvas/src/canvas_controls/task_bar.rs b/crates/ui-canvas/src/canvas_controls/task_bar.rs index d76711327..1e45fbeb6 100644 --- a/crates/ui-canvas/src/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/src/canvas_controls/task_bar.rs @@ -20,7 +20,7 @@ use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; use craft_behavior::kurbo::Point; use craft_behavior::overlay::{Align, Side}; -use craft_behavior::{EditEvent, IconId, Metrics, Mixed, Sense}; +use craft_behavior::{EditEvent, GesturePhase, IconId, Metrics, Mixed, Sense}; use egui::{Pos2, Rect, Response, Ui}; use std::sync::Arc; @@ -245,8 +245,7 @@ impl<'a> TaskBar<'a> { let rect = shown.output.response.rect; let pick = menu.pick; if shows && kind == TaskBarKind::Task { - let moved = shown.output.moved.filter(|moved| moved.min != rect.min); - let next = settled(held, rect, area, moved, pick); + let next = settled(held, rect, area, shown.output.moved, pick); if next != held { let word = match pick { Some(MenuPick::Reset) => &words.task_bar_reset, @@ -303,8 +302,8 @@ fn layer_overlay(held: &TaskBarPlace, hang: Option, area: Rect, side: Side } } -/// The place after a pass that showed the bar at `shown`. A move (`moved`, a rect other than `shown`) keeps the bar -/// where it was dropped; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A +/// The place after a pass that showed the bar at `shown`. A move that ended (`moved`, where it was dropped) keeps the +/// bar there; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A /// non-finite place is cleared. With no move and no pick, the place stays unchanged; the overlay host keeps the layer /// inside the area. fn settled(held: TaskBarPlace, shown: Rect, area: Rect, moved: Option, pick: Option) -> TaskBarPlace { @@ -333,7 +332,7 @@ pub struct TaskBarLayerStyle { metrics: Metrics, } -/// What the task bar's layer reports: its response, the last move of this pass and why it closed. +/// What the task bar's layer reports: its response, the move that ended in this pass and why it closed. #[derive(Debug)] struct TaskBarLayerOutput { response: Response, @@ -361,6 +360,8 @@ struct TaskBarLayer { props: ContainerProps, /// Open while the bar shows; the caller shows the bar again each pass it wants it. open: Bind<'static, bool>, + /// Where a move by the grip ended in this pass. The layer host shows the bar under the pointer while the move + /// runs, so the place is written once, on the drop. moved: Option, /// Why the layer closed, once it has. closed: Option, @@ -411,7 +412,7 @@ impl Container for TaskBarLayer { } fn placement_changed(&mut self, change: &PlacementChange) { - if change.kind == PlacementKind::Move { + if change.kind == PlacementKind::Move && change.phase == GesturePhase::Commit { self.moved = Some(change.rect); } } diff --git a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs index 0fa97a336..417e2ab86 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs @@ -6,6 +6,7 @@ use craft_ui::buttons::Button; use craft_ui::canvas_controls::{TaskBar, TaskBarDismiss, TaskBarPlace}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::testing::canvas_story::on_canvas; +use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Vec2}; use std::cell::RefCell; @@ -272,3 +273,39 @@ fn the_grip_sits_on_the_members_line() { let dropped = seen(&scene); assert!((dropped.rect.min - (bar.min + by)).length() < 2.0 * SLACK, "a drag on the grip moves the bar: {:?}", dropped.rect); } + +/// A drag of the grip moves the bar under the pointer in the frame of each step, in one pass, and writes its place +/// once, on the drop: one edit for the whole move. +#[trial] +fn a_dragged_task_bar_stands_under_the_pointer_in_each_frame_and_writes_its_place_on_the_drop() { + let scene = Rc::new(RefCell::new(Scene { + anchor: frame(DocVec::ZERO), + place: TaskBarPlace::default(), + bounds: Rect::NOTHING, + area: Rect::NOTHING, + rect: Rect::NOTHING, + })); + let mut fixture = fixture(&scene); + fixture.settle(); + let start = seen(&scene).rect; + let from = fixture.by_label("Move bar").expect("the grip is named").center(); + fixture.frame(vec![moved(from)]); + fixture.frame(vec![press(from)]); + let step = Vec2::new(-30.0, 15.0); + for n in 1..=4 { + let to = start.min + step * n as f32; + fixture.frame(vec![moved(from + step * n as f32)]); + let now = seen(&scene); + assert!((now.rect.min - to).length() < SLACK, "step {n}: the bar stands under the pointer in its frame: {:?}, wanted {to:?}", now.rect); + assert_eq!(fixture.passes(), 1, "step {n}: the frame runs one pass"); + assert_eq!(now.place, TaskBarPlace::default(), "step {n}: the place is not written while the drag runs"); + } + let dropped_at = start.min + step * 4.0; + fixture.frame(vec![release(from + step * 4.0)]); + let dropped = seen(&scene); + assert!((dropped.rect.min - dropped_at).length() < SLACK, "the bar stays where it was dropped: {:?}", dropped.rect); + let at = dropped.place.at.map(|at| dropped.area.min + Vec2::from(at)); + assert!(at.is_some_and(|at| (at - dropped_at).length() < SLACK), "the drop writes the place: {:?}", dropped.place); + fixture.settle(); + assert!((seen(&scene).rect.min - dropped_at).length() < SLACK, "the written place keeps the bar there: {:?}", seen(&scene).rect); +} diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 0f9f07641..9dbc6a121 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -68,7 +68,9 @@ impl ShapeHooks for BodyHooks<'_> { } fn host(&mut self, comp: &C, at: crate::contract::run::HostCx<'_>) -> Box { - let mounted = crate::contract::mount::host(comp.props(Internal::new()), &at, self.open, at.label); + let props = comp.props(Internal::new()); + let moving = overlay_of(props).filter(|overlay| overlay.movable).and_then(|_| self.mode.running_move(at.ui.ctx(), at.id)); + let mounted = crate::contract::mount::host(props, &at, self.open, at.label, moving); if mounted.exiting { self.exiting = true; self.open = true; @@ -185,7 +187,7 @@ impl ShapeHooks for BodyHooks<'_> { Mount::Layer(_) | Mount::Viewport { .. } => { let placement = overlay_of(props).map_or_else(Placement::default, |overlay| { let screen = crate::contract::overlay::screen_for(&ctx, env, overlay); - shown_placement(&ctx, id, save.as_ref(), overlay, screen, env.tokens.space.inset.screen) + shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen) }); // A layer the user sized takes that size, at its saved position or where its anchor places it. placement.size.is_some() diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index 4f885be80..311fe446b 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -28,8 +28,7 @@ impl Placement { /// The placement the caller of `overlay` gives, when it places the layer. fn given(overlay: &crate::contract::Overlay) -> Option { - let kept = |rect: Rect| overlay.bounds.map_or(rect, |bounds| super::window::keep_inside(rect, bounds)); - overlay.placed.map(|rect| Placement::at(kept(rect))).or_else(|| overlay.placed_at.map(Placement::at_pos)) + overlay.placed.map(|rect| Placement::at(super::window::kept_in(rect, overlay.bounds))).or_else(|| overlay.placed_at.map(Placement::at_pos)) } /// The rect it names, taking the position and size it lacks from `rect`. @@ -46,7 +45,9 @@ pub(crate) fn placement_id(id: Id) -> Id { /// is `placed` has the caller's rect instead: the slot reads it and writes nothing, since the caller owns the /// placement and learns of the user's changes from `PlacementChange` reports. A layer hung from its anchor keeps only /// its size, whether or not the user can move it: each opening places it from its anchor at that size, and a caller -/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. +/// that keeps a moved layer where it was dropped places it (`placed_at`) from the change it was told of. While the +/// user drags the move band, the layer host shows the layer at the drag's rect whatever the slot holds +/// ([`shown_placement`]), so a caller places it from the drag's `Commit` alone. pub(super) struct PlacementSlot<'s> { stage: &'s mut MemoryStage, id: Id, @@ -96,7 +97,28 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement { /// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less `screen_inset` on /// each side, centred or at the overlay's float position. A saved size and position win over the default. A size with /// no position places an anchored layer from its anchor at that size. +/// +/// While a drag of the layer's move band runs, `moving` is the rect it puts the layer at in this pass +/// (`WindowMode::running_move`): the layer shows there, within its bounds, at the size the placement gives. The +/// caller's place, the stored one or the anchor applies again once the drag ends. pub(crate) fn shown_placement( + ctx: &Context, + id: Id, + save: Option<&SaveKey>, + overlay: &crate::contract::Overlay, + moving: Option, + screen: Rect, + screen_inset: f32, +) -> Placement { + let mut placement = resting_placement(ctx, id, save, overlay, screen, screen_inset); + if let Some(moving) = moving { + placement.pos = Some(super::window::kept_in(moving, overlay.bounds).min.into()); + } + placement +} + +/// The placement a layer is shown at while no drag moves it ([`shown_placement`]). +fn resting_placement( ctx: &Context, id: Id, save: Option<&SaveKey>, diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 7976228fe..bc1af97e6 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -124,6 +124,9 @@ pub(super) struct WindowMode { kind: Option, restore: Placement, began: Option, + /// The rect the layer had when a press went down on its move band or a grip, until the press ends: a drag that + /// starts from the press runs from it. + pressed: Option, moving: Option, sizing: Option, /// The index in `GRIPS` of the grip a drag holds, from its `DragStart` to its release: `move_parts` keeps it @@ -136,6 +139,23 @@ impl WindowMode { pub(super) fn held(&self) -> Option { self.held } + + /// The rect a drag of the move band of the layer `id` puts the layer at in this pass, before the bounds keep it: + /// the rect the layer had when the press went down, moved by the pointer's travel since. `window_drag` reports the + /// same rect for the step. `None` while no move by the band runs. The layer host shows the layer there + /// (`shown_placement`) before the container's pass runs, so the layer stands under the pointer in the frame of + /// each step, whoever owns its placement. + pub(super) fn running_move(&self, ctx: &Context, id: Id) -> Option { + if self.pressed.is_none() && self.began.is_none() { + return None; + } + let (began, start, pos) = match crate::primitives::sensing::part_press(ctx, id, MOVE_BAND.into()).press.phase { + PressPhase::DragStart { start, pos, .. } => (self.pressed?, start, pos), + PressPhase::Drag { start, pos, .. } | PressPhase::Release { start, pos, .. } => (self.began?, start, pos), + _ => return None, + }; + Some(began.translate(pos - start.origin)) + } } /// A move of a viewport mount's OS window that the app runs (`Overlay::moved_by_app`), from its Begin to its Commit @@ -200,6 +220,11 @@ pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect { rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y))) } +/// `rect` kept inside `bounds`, when the layer has bounds. +pub(super) fn kept_in(rect: Rect, bounds: Option) -> Rect { + bounds.map_or(rect, |bounds| keep_inside(rect, bounds)) +} + /// What every change of a layer's rect keeps to: the least and most size, and the rect it stays inside. struct Limits { min: Vec2, @@ -214,8 +239,7 @@ impl Limits { /// `rect` moved by `delta`, kept inside the bounds. fn moved(&self, rect: Rect, delta: Vec2) -> Rect { - let rect = rect.translate(delta); - self.bounds.map_or(rect, |bounds| keep_inside(rect, bounds)) + kept_in(rect.translate(delta), self.bounds) } /// `rect` with the edges `dx` and `dy` (-1: low edge, 1: high edge, 0: none) moved by `delta`, within the size @@ -377,14 +401,7 @@ impl BodyHooks<'_> { if mode.kind == Some(kind) { mode = WindowMode::default(); } else { - mode = WindowMode { - kind: Some(kind), - restore: current.clone(), - began: Some(current.rect_over(rect)), - moving: None, - sizing: None, - held: None, - }; + mode = WindowMode { kind: Some(kind), restore: current.clone(), began: Some(current.rect_over(rect)), ..WindowMode::default() }; self.reports.push(step(current.rect_over(rect), GesturePhase::Begin)); } } @@ -436,7 +453,8 @@ impl BodyHooks<'_> { } /// A drag of the move band or a grip of a layer (not an OS window): the layer follows the pointer within the - /// limits, and each step is reported. Escape, which cancels the press, restores the placement from before. + /// limits, and each step is reported. The drag runs from the rect the layer had when the press went down. Escape, + /// which cancels the press, restores the placement from before. pub(super) fn window_drag(&mut self, props: &ContainerProps, cx: &mut Cx<'_, C>) { let Some(overlay) = overlay_of(props) else { return }; // A band that moves the window below starts the OS move of the window the layer is shown in. @@ -455,9 +473,11 @@ impl BodyHooks<'_> { let mut pressed = vec![(None, phase((MOVE_BAND, None)))]; pressed.extend((0..GRIPS.len()).map(|index| (Some(index), phase((GRIP, Some(index as u64)))))); let Some((grip, phase)) = pressed.into_iter().find_map(|(grip, phase)| match phase? { - phase @ (PressPhase::DragStart { .. } | PressPhase::Drag { .. } | PressPhase::Release { .. } | PressPhase::Cancel { .. }) => { - Some((grip, phase)) - } + phase @ (PressPhase::Down { .. } + | PressPhase::DragStart { .. } + | PressPhase::Drag { .. } + | PressPhase::Release { .. } + | PressPhase::Cancel { .. }) => Some((grip, phase)), _ => None, }) else { return; @@ -465,8 +485,14 @@ impl BodyHooks<'_> { let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay); let current = slot.read(); let (origin, pos, gesture) = match phase { + PressPhase::Down { .. } => { + self.mode.pressed = Some(current.rect_over(rect)); + return; + } PressPhase::DragStart { start, pos, .. } => { - self.mode.began = Some(current.rect_over(rect)); + // The layer host shows this pass at the step's rect already (`running_move`): the drag runs from where + // the layer stood at the press. + self.mode.began = Some(self.mode.pressed.unwrap_or_else(|| current.rect_over(rect))); self.mode.restore = current.clone(); self.mode.held = grip; (start.origin, Some(pos), GesturePhase::Begin) @@ -476,6 +502,9 @@ impl BodyHooks<'_> { PressPhase::Cancel { start, .. } => (start.origin, None, GesturePhase::Cancel), _ => return, }; + if matches!(gesture, GesturePhase::Commit | GesturePhase::Cancel) { + self.mode.pressed = None; + } let Some(began) = self.mode.began else { return }; let (dx, dy, _) = grip.map_or((0, 0, CursorIcon::Grab), |index| GRIPS[index]); let kind = if grip.is_some() { PlacementKind::Size(edge_of(dx, dy)) } else { PlacementKind::Move }; diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index eb8b2635c..e56a51a47 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -26,7 +26,8 @@ pub(super) struct Mounted { } /// The host for `props.mount`. A layer-like mount of a closed container shows nothing once its exit fade ended. -pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label) -> Mounted { +/// `moving` is the rect a running drag of the container's move band puts its layer at in this pass. +pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label, moving: Option) -> Mounted { let ctx = at.ui.ctx(); let layer = |overlay: &Overlay| { let presence = if at.ui.is_sizing_pass() { @@ -46,7 +47,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & Mount::Pane(pane) => Mounted { host: Box::new(PaneHost(*pane)), exiting: false }, Mount::Window { .. } => Mounted { host: Box::new(WindowContentHost), exiting: false }, Mount::Layer(overlay) => match layer(overlay) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size, moving)), exiting }, (None, _) => closed(), }, Mount::FullWindow => full_window(props.focus), @@ -57,7 +58,9 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & full_window(fallback.focus) } else if !viewports { match layer(fallback) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => { + Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size, moving)), exiting } + } (None, _) => closed(), } } else if open { @@ -196,12 +199,14 @@ struct LayerHost { fade: f32, /// The size the container measured for this pass. size: Vec2, + /// The rect a running drag of the move band puts the layer at in this pass, in screen space. + moving: Option, dismissed: Option, } impl LayerHost { - fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2) -> Self { - LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, dismissed: None } + fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2, moving: Option) -> Self { + LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, moving, dismissed: None } } } @@ -227,7 +232,7 @@ impl Host for LayerHost { overlay = mapped; } let screen = overlay::screen_for(&ctx, env, &overlay); - let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, screen, env.tokens.space.inset.screen); + let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, env.tokens.space.inset.screen); // An anchored resizable layer has no position to seed: its default size is held as its minimum until the // user resizes it. if overlay.fit == overlay::OverlayFit::Resizable diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f7e3aab2d..f495e805f 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1609,8 +1609,11 @@ fn extent_step( let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id); let env = begun.env(); // A body root with parts steps its press machine before its measuring run, so the body reads this pass's part - // presses in both runs (`BodyCx::part_press`). Step 8 finds the outcome. A member of another arena senses at step 8. - if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && (t.arena() || facts.text() || env.arena.is_none()) { + // presses in both runs (`BodyCx::part_press`) and its host reads them before it places the body. Step 8 finds the + // outcome. A member of another arena senses at step 8. A root its host shows on a layer of its own (not in flow) + // senses in its own arena: its steps 6 to 16 run in the layer's env, which is outside its opener's arena. + let own_arena = t.arena() || facts.text() || env.arena.is_none() || !t.in_flow(); + if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && own_arena { sensing::sense_early(ctx, id, resolved.enabled); } let scx = steps::style_cx(ctx, &begun.env, &begun.step1); diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index b48af361b..1e7cd429b 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -167,7 +167,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { struct AreaMemory

{ /// The open flyout when the host binds none. open: Option

, - /// The running move or resize of a floating window. + /// The running resize or keyboard move of a floating window. moving: Option>, } @@ -1333,8 +1333,11 @@ impl Pass<'_, P> { let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl)); self.report.actions.extend(reported); } - } else if let Some(mut change) = output.placed { - // A collapsed window keeps the edge its move began with until the move ends where its strip was dropped. + } else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit) + { + // The layer host shows a window its title row moves under the pointer, so the move reaches the workspace + // once, when it ends: one edit. A collapsed window keeps its edge until then, and the move ends where its + // strip was dropped. let mut keeps = shape.collapsed.map(|_| edge); if change.phase == GesturePhase::Commit && output.collapsed_width.is_none() { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); @@ -1397,8 +1400,9 @@ fn split_changes

(from: &Node

, to: &Node

) -> Vec<(Vec, SplitSize)> /// The workspace edit of a floating window's move or resize, the step `phase` of a gesture that `action` /// (`Action::MoveFloating`) places the window by: the gesture runs from the window's `Begin` to its `Commit`, so one -/// drag is one undo step. `moving` holds the gesture and the workspace it began on; `rights` are the panels' -/// permissions with the lock applied, which refuse the move of a locked workspace. +/// drag is one undo step. A move by the title row arrives only as its `Commit`, which sets the place. `moving` holds +/// the gesture and the workspace it began on; `rights` are the panels' permissions with the lock applied, which refuse +/// the move of a locked workspace. fn window_edit( ctx: &Context, current: &Workspace

, diff --git a/crates/ui-patterns/tests/it/docking/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 94528a104..7373ae821 100644 --- a/crates/ui-patterns/tests/it/docking/floating_area.rs +++ b/crates/ui-patterns/tests/it/docking/floating_area.rs @@ -73,6 +73,10 @@ struct Bed { } fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { + bed_with(layout, rights, DockConfig::default()) +} + +fn bed_with(layout: Layout, rights: fn(&usize) -> Permissions, config: DockConfig) -> Bed { let workspace = Rc::new(RefCell::new(Workspace::new(layout))); let actions: Rc>>> = Rc::default(); let second = Rc::new(Cell::new(false)); @@ -84,7 +88,7 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { let mut fixture = Fixture::new(move |ui| { let mut workspace = held.borrow().clone(); let mut panels = Panels { rights }; - let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + let out = DockArea::new("Floating dock", Bind::bound(&mut workspace), &mut panels, config.clone()).show(ui); *held.borrow_mut() = workspace; seen_actions.borrow_mut().extend(out.actions); if let Some(space) = out.float_space { @@ -145,15 +149,13 @@ fn a_tab_dragged_over_a_floating_window_marks_and_joins_the_window() { assert!(window.panels().any(|panel| *panel == SECOND), "the tab joined the window: {:?}", bed.actions.borrow()); } -/// A window's move is the area's own edit, written each pass, and keeps its drag; a host that replaces the workspace -/// ends the drag, and the release drops nothing. +/// A host that replaces the workspace while a window's move runs ends the drag, and the release drops nothing. #[trial] -fn a_replaced_workspace_ends_the_drag_that_the_areas_own_edits_keep() { +fn a_replaced_workspace_ends_a_window_drag() { let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); let by = Vec2::new(-40.0, 30.0); press_and_move(&mut bed.fixture, window_title(), by); - let moved_to = bed.workspace.borrow().layout.floating[0].rect; - assert!(dragging(&bed) && moved_to != WINDOW_AT, "the window moves under its drag: {moved_to:?}"); + assert!(dragging(&bed), "the window's drag runs"); bed.workspace.borrow_mut().replace(Workspace::new(with_window(Some(Node::tabs(vec![DOCKED, SECOND], 0))))); bed.fixture.frame(vec![moved(window_title() + by * 1.25)]); assert!(!dragging(&bed), "the replacement ended the drag"); @@ -186,7 +188,7 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let mut fixture = Fixture::new(move |ui| { let given = held.borrow().clone(); let mut panels = Requesting; - let out = DockArea::new("Given dock", Bind::given(given), &mut panels, DockConfig::default()).show(ui); + let out = DockArea::new("Given dock", Bind::given(given), &mut panels, DockConfig::default().title_bar_docks(false)).show(ui); held.borrow_mut().apply_all(out.actions, false, |_| Permissions::ALL).expect("the area's actions apply"); seen.borrow_mut().extend(out.requested); }); @@ -196,11 +198,40 @@ fn a_given_workspace_gets_the_window_move_and_the_bodies_requests_as_actions() { let own = |action: &Action| *action == Action::activate(DOCKED) || *action == Action::activate(WINDOW); assert!(!asked.is_empty() && asked.iter().all(own), "each body's request came back: {asked:?}"); assert_eq!(workspace.borrow().layout.floating[0].rect, WINDOW_AT, "nothing moved yet"); - press_and_move(&mut fixture, window_title(), Vec2::new(-40.0, 30.0)); + let by = Vec2::new(-40.0, 30.0); + press_and_move(&mut fixture, window_title(), by); + fixture.frame(vec![release(window_title() + by)]); + fixture.settle(); let moved_to = workspace.borrow().layout.floating[0].rect; assert!(moved_to != WINDOW_AT, "the host's copy took the window's move: {moved_to:?}"); } +/// A drag of a floating window's title row shows the window under the pointer in the frame of each step, in one pass; +/// the workspace takes the move once, on the drop. +#[trial] +fn a_dragged_floating_window_stands_under_the_pointer_in_each_frame_and_moves_on_the_drop() { + let mut bed = bed(with_window(None), |_| Permissions::ALL); + let from = window_title(); + let step = Vec2::new(-10.0, 8.0); + bed.fixture.frame(vec![moved(from)]); + bed.fixture.frame(vec![press(from)]); + for n in 1..=4 { + let to = WINDOW_AT.translate(step * n as f32); + bed.fixture.frame(vec![moved(from + step * n as f32)]); + let shown = layer_rects(bed.fixture.ctx()); + assert!( + shown.iter().any(|rect| (rect.min - to.min).length() < SLACK && (rect.size() - to.size()).length() < SLACK), + "step {n}: the window stands under the pointer in its frame: {shown:?}, wanted {to:?}" + ); + assert_eq!(bed.fixture.passes(), 1, "step {n}: the frame runs one pass"); + assert_eq!(bed.workspace.borrow().layout.floating[0].rect, WINDOW_AT, "step {n}: the workspace is not written while the move runs"); + } + bed.fixture.frame(vec![release(from + step * 4.0)]); + bed.fixture.settle(); + let rect = bed.workspace.borrow().layout.floating.first().map(|window| window.rect); + assert!(rect.is_some_and(|rect| (rect.min - (WINDOW_AT.min + step * 4.0)).length() < SLACK), "the drop moves the window: {rect:?}"); +} + /// A dock area's first pass leaves a drag running in another area alone. #[trial] fn an_areas_first_pass_keeps_a_running_drag() { @@ -258,11 +289,14 @@ fn a_floating_windows_group_starts_under_the_chrome_the_area_sizes_windows_by() ); } -/// The window's rect while a press at `from` drags by `by`, before the release, which would dock a window moved over -/// the docked group. +/// The window's rect after a press at `from` drags by `by` and releases, in an area whose title-row drags only move a +/// window, so the release docks nothing. fn dragged_from(from: Pos2, by: Vec2) -> Rect { - let mut bed = bed(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL); + let config = DockConfig::default().title_bar_docks(false); + let mut bed = bed_with(with_window(Some(Node::tabs(vec![DOCKED], 0))), |_| Permissions::ALL, config); press_and_move(&mut bed.fixture, from, by); + bed.fixture.frame(vec![release(from + by)]); + bed.fixture.settle(); bed.workspace.borrow().layout.floating[0].rect } From b160ac3f878bf6a56ca7dd0d2673eac23af04e73 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 02:58:47 +0000 Subject: [PATCH 44/89] Image Size: chain bracket and Resample row as 0.23.1; New Document: save icon on the Name row A Row can bracket the labelled rows of its first child to the child after them (`Row::bracket(Bracket::Linked | Unlinked)`): the rows report their controls to the row, the child after them sits halfway between the first and the last control, and a linked bracket runs from each control to it. Image Size brackets Width and Height to their chain. Each body's flow records whether it has placed a child yet in the sweep or run under way. The first child of an unwrapped row that is itself a row of a vertical flow counts as a row of that flow, so a check box that starts a row of a form starts in the form's control column. Image Size shows Resample with its method on one row there. New Document's save action is the icon-only square-plus button at the end of the Name row (tooltip "Save Document Preset"), as before the port. Trials: the bracket's ticks and the chain's centre at 1x and 1.25x, the check box that starts a row, Image Size on a host, and the save control painting no text. --- crates/ui-contract/src/contract/body/hooks.rs | 18 ++- .../ui-contract/src/contract/body/inherit.rs | 13 +- .../ui-contract/src/contract/body/regions.rs | 26 +++- crates/ui-contract/src/contract/body/size.rs | 3 + crates/ui-contract/src/contract/container.rs | 24 ++++ crates/ui-contract/src/contract/label/step.rs | 14 ++- crates/ui-contract/src/contract/lazy.rs | 2 + crates/ui-contract/src/contract/mod.rs | 5 +- crates/ui-contract/src/contract/run/typed.rs | 1 + crates/ui-contract/src/layout/arrange.rs | 1 + crates/ui-contract/src/layout/body.rs | 115 +++++++++++++++-- crates/ui-contract/src/layout/mod.rs | 6 +- crates/ui-contract/src/runtime/env.rs | 16 +++ .../ui-contract/src/runtime/layout_memory.rs | 5 + crates/ui-contract/src/runtime/pass_state.rs | 2 + .../form_dialogs/new_document/details.rs | 5 +- .../src/patterns/form_dialogs/sizing.rs | 7 +- .../src/patterns/form_dialogs/sizing/image.rs | 21 ++-- .../tests/it/form_dialogs/hosted.rs | 39 ++++++ .../tests/it/form_dialogs/new_document.rs | 3 +- .../ui-widgets/src/layout_components/mod.rs | 10 +- .../src/layout_components/stories.rs | 27 +++- crates/ui-widgets/tests/it/label/bracket.rs | 116 ++++++++++++++++++ crates/ui-widgets/tests/it/label/mod.rs | 1 + 24 files changed, 439 insertions(+), 41 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/bracket.rs diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 0f9f07641..1ad267b23 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -5,7 +5,7 @@ use super::open::open_now; use super::placement::{Placement, measure_layer, overlay_of, shown_placement}; use super::regions::{ LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_body, footer_in_end, footer_rule_under, - gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, + gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_bracket, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, }; use super::reorder::REORDER_BAND; use super::scroll::{ @@ -1305,12 +1305,12 @@ impl BodyHooks<'_> { && env.values.get::() == label::LabelScheme::Inspector; let (room, content_column, scroll, beside, label_width) = (plan.room, plan.content_column, plan.scroll, plan.regions.beside, plan.label_extra.x); - let first_body = plan.first.1; + let (first_body, layout_id) = (plan.first.1, plan.layout_id); // The slot of a footer the body places takes the size the measuring run's footer took. let footer_slot = footer_in_body(props) .then(|| FooterSlotOf { owner: id, size: if real { self.measured_footer } else { self.footer_size.unwrap_or(Vec2::ZERO) } }); plan.body_env = Some(plan.line_env.derive_local(|scoped| { - self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside }); + self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside, layout: layout_id }); scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held); scoped.cell_fills = cell_fills; if footer_slot.is_some() { @@ -1569,6 +1569,12 @@ impl BodyHooks<'_> { /// size counts the label column. fn after_body(&mut self, ui: &mut Ui, env: &Env, plan: &mut BodyPlan<'_>) { let (props, ctx, real) = (plan.props, &plan.ctx, plan.real); + if let Some(bracket) = props.bracket { + let took = layout::take_bracket(ctx, plan.layout_id); + if let (true, crate::contract::Bracket::Linked, Some(took)) = (real, bracket, took) { + paint_bracket(ui, env, &took, plan.rtl); + } + } // A measuring run decided the label before the control reported its minimum width: it decides again // from the minimum this run recorded, so the extent it measures is the one the real run lays out. if let (false, Some(input)) = (real, plan.label_input.as_mut()) { @@ -1580,6 +1586,12 @@ impl BodyHooks<'_> { plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl); } if let Some(size) = &mut self.body_size { + // A labelled row of a bracketed row reports where its control lies: the bracket runs from it. + if let (Some(row), Some(_)) = (env.bracket, props.label.as_ref()) { + let body = plan.body_rect; + let left = if plan.rtl { body.max.x - size.x } else { body.min.x }; + layout::report_bracket_control(ctx, row, Rect::from_min_size(egui::pos2(left, body.min.y), *size), plan.rtl); + } let label_extra = plan.label_extra; // A body beside its label in a content-sized column of rows reports how far it reaches past the label // column, so that column's container measures its rows at the widest label. diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 660e5ebc8..31bfd65eb 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -19,6 +19,8 @@ pub(super) struct BodyScope { pub(super) label_width: f32, /// The width the regions beside the body take on its line (`Regions::beside`). pub(super) beside: f32, + /// The id the body's layout runs under (`BodyPlan::layout_id`). + pub(super) layout: Id, } /// The surface a container paints under its regions: its props' surface, else its style's in its current state. @@ -96,10 +98,19 @@ impl BodyHooks<'_> { /// What the body inherits on top of the line's env: arena, transform, the room it is offered and its scroll axes. pub(super) fn scope_body(&self, scoped: &mut Scoped, props: &ContainerProps, id: Id, body: BodyScope) { - let BodyScope { room, real, content_column, scroll, label_width, beside } = body; + let BodyScope { room, real, content_column, scroll, label_width, beside, layout } = body; if props.arena { scoped.arena = Some(ArenaId::new(id)); } + scoped.flow_body = None; + scoped.column_row = + self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); + // A bracketed row's rows report to it up to the first labelled container, whose body is its own control. + if props.bracket.is_some() { + scoped.bracket = Some(layout); + } else if props.label.is_some() { + scoped.bracket = None; + } scoped.transform = props.transform; scoped.content_column = content_column; scoped.given_column = !content_column && matches!(props.layout, crate::layout::BodyLayout::Stack); diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 810189cf3..c0ee61ec8 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -11,7 +11,7 @@ use crate::runtime::egui::{alloc, child, style}; use crate::runtime::env::{Env, RowLine}; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; -use crate::style::{RuleKind, UiTokens, rule_look}; +use crate::style::{RuleKind, RuleLook, RuleWidth, UiTokens, rule_look}; use egui::{Align, Id, Layout, Pos2, Rect, Ui, UiBuilder, Vec2}; /// The slots of a container's own header parts at the edges of the header's line (`Container::header_parts`). @@ -217,6 +217,30 @@ pub(super) fn paint_rules(ui: &mut Ui, env: &Env, regions: &Regions) { } } +/// The bracket of a linked `Row` (`Bracket::Linked`) from what its rows reported in `took`: a tick from the end of the +/// first and the last row's controls, `space.gap.tight` past them, to the middle child's centre line, and a stroke +/// along that line from each tick to the middle child's edge. `text.muted`, `stroke.thin` wide. +pub(super) fn paint_bracket(ui: &mut Ui, env: &Env, took: &crate::layout::BracketTook, rtl: bool) { + let (Some(first), Some(last), Some(end), Some(middle)) = (took.first, took.last, took.end, took.middle) else { return }; + if last <= first { + return; + } + let tokens = &env.tokens; + let tight = tokens.tokens().space.gap.tight; + let look = RuleLook { color: crate::style::rgba_color(tokens.color.text.muted), width: RuleWidth::Points(tokens.stroke.thin) }; + let ppp = ui.ctx().pixels_per_point(); + let (start, line) = if rtl { (-end - tight, middle.center().x) } else { (end + tight, middle.center().x) }; + let painter = ui.painter(); + for (from, to) in [ + (Pos2::new(start, first), Pos2::new(line, first)), + (Pos2::new(start, last), Pos2::new(line, last)), + (Pos2::new(line, first), Pos2::new(line, middle.top().max(first))), + (Pos2::new(line, middle.bottom().min(last)), Pos2::new(line, last)), + ] { + painter.extend(Rule::shapes(&look, from, to, ppp)); + } +} + impl BodyHooks<'_> { /// The footer's rect and how far its left edge lies past the container's, under the control column of a /// label-scoped container; along an axis the room leaves unbounded, the footer follows the body and the end region. diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 1c0392f89..58aaacd29 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -29,6 +29,8 @@ pub(super) struct MeasureKey { /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), env: EnvFacts, + /// Whether its parent flow showed the container as a row of a vertical flow (`label::in_column`). + in_column: bool, } /// The props a body was measured under, compared on the fields its measure reads. @@ -92,6 +94,7 @@ impl<'b> BodyHooks<'b> { width, shows: (self.open, self.presence.t), env: EnvFacts::of(env), + in_column: self.in_column, } } diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 142677f22..b7a8f1da8 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -727,6 +727,19 @@ impl EnvValue for InMenu { } } +/// The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and +/// height to their chain): a tick from each of the first and the last row's controls to the middle child's centre +/// line, joined along that line. The middle child sits halfway between the two controls. The value is the link's +/// state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Bracket { + /// The rows are linked: the bracket is drawn. + Linked, + /// The rows are not linked: the middle child keeps its place, with no bracket. + Unlinked, +} + /// What a container or collection adds to `Common`. A builder added here is added to the forwarder list in /// `crates/ui-macros/src/props.rs` too. /// @@ -820,6 +833,9 @@ pub struct ContainerProps { pub label_column: bool, /// How the labelled rows under the container show their labels; `None` keeps the scheme of the scope. pub labels: Option, + /// The bracket an unwrapped `Row` placed from its start draws from its first child's labelled rows to the child + /// after them; any other body draws none. + pub bracket: Option, /// The component whose memory holds the container's shown memory and its layer's bookkeeping, when it is another: /// the body of a popup an `overlay` hook shows belongs to the component that shows it. pub(crate) owner: Option, @@ -860,6 +876,7 @@ impl ContainerProps { && self.outer_edit == other.outer_edit && self.collection_body == other.collection_body && self.labels == other.labels + && self.bracket == other.bracket } /// Props with every field at its default. @@ -901,6 +918,7 @@ impl ContainerProps { collection_body: false, label_column: false, labels: None, + bracket: None, owner: None, } } @@ -1122,6 +1140,12 @@ impl ContainerProps { self } + /// The bracket of a `Row` from its first child's labelled rows to the child after them ([`bracket`](Self::bracket)). + pub const fn bracket(mut self, bracket: Bracket) -> Self { + self.bracket = Some(bracket); + self + } + /// The labelled rows under the container show their labels in `scheme`: its regions, its body and every container /// inside, until one sets a scheme of its own. pub const fn labels(mut self, scheme: LabelScheme) -> Self { diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index e49a5c280..b2c5f1b18 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -116,6 +116,8 @@ impl LeafPlaced { pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { let scope = sub(at.id, "field"); let enabled = at.under.enabled; + // Read before the child measures: nothing it does there may count as a child placed in flow. + let in_column = in_column(ui); let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; let input = LabelIn { scope, @@ -131,7 +133,7 @@ pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: & size: at.under.size, control_min, leaf: true, - in_column: in_column(ui), + in_column, claims: C::LABELLED_AFTER, status: false, trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size), @@ -227,9 +229,15 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< placed } -/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. +/// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. The first child of an +/// unwrapped row that is itself a row of a vertical flow (`Scoped::column_row`) starts where that flow's rows start, +/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. pub(crate) fn in_column(flow: &Ui) -> bool { - !flow.layout().is_horizontal() + if !flow.layout().is_horizontal() { + return true; + } + let env = Env::of(flow); + env.column_row && crate::layout::at_flow_start(flow.ctx(), &env) } /// A control with its label after it that the label step moved into the control column (its `control` starts past diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index d0db84761..bb9ec4da3 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -176,6 +176,7 @@ impl Lazy { if memo { place_view(ui, rect); } else { + crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } if view.is_some() || memo { @@ -268,6 +269,7 @@ fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 { /// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`. fn place_view(ui: &mut Ui, rect: Rect) -> Rect { if take_cell(ui, rect.size()).is_none() { + crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } rect diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 14ea466f7..6642281f5 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -68,8 +68,9 @@ pub use container::InBar; #[doc(hidden)] pub use container::InMenu; 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, + BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, + LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, + WrapWidth, }; pub use craft_tracked::{PlainData, Revision, Tracked}; pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract}; diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 0be4e115f..956401601 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -546,6 +546,7 @@ pub(crate) fn show_container_taking( body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); + crate::layout::close_flow_start_in(ui); crate::runtime::egui::alloc::advance_past(ui, rect); shown } diff --git a/crates/ui-contract/src/layout/arrange.rs b/crates/ui-contract/src/layout/arrange.rs index de37411f3..8a6b9b170 100644 --- a/crates/ui-contract/src/layout/arrange.rs +++ b/crates/ui-contract/src/layout/arrange.rs @@ -71,6 +71,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_> placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect))); } let whole = flow.to_physical(Rect::from_min_size(room.min, taken)); + super::close_flow_start_in(ui); alloc::advance_past(ui, whole); whole } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index c32bee2cb..440476bb1 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -10,7 +10,7 @@ use crate::runtime::measure; use crate::runtime::memory::sub; use crate::runtime::pass_state; use craft_behavior::{Axis, ColumnWidth, Flow, GridCursor, GridMeasure}; -use egui::{Id, IdMap, Rect, Ui, Vec2}; +use egui::{Id, IdMap, IdSet, Rect, Ui, Vec2}; use std::borrow::Cow; /// How a body lays out its children, in reading order: mirrored under a right-to-left direction. @@ -211,6 +211,71 @@ fn report_first_line(ctx: &egui::Context, target: Id, at: Option) { }); } +/// The bodies whose flow has placed nothing yet in the sweep or run under way. +#[derive(Default)] +pub(crate) struct FlowStarts(IdSet); + +/// Whether the next child placed in flow under `env` starts its body's flow: the body that places it has placed +/// nothing yet in this sweep or run. False outside a body. +pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { + env.flow_body.is_some_and(|body| pass_state::with::(ctx, |starts| starts.0.contains(&body))) +} + +/// A child took room in the flow of the body that places the children under `env`: its flow start closes. +pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { + if let Some(body) = env.flow_body { + pass_state::with::(ctx, |starts| starts.0.remove(&body)); + } +} + +/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`. +pub(crate) fn close_flow_start_in(ui: &Ui) { + close_flow_start(ui.ctx(), &Env::of(ui)); +} + +/// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or +/// run under way, and the rect of the row's last child in flow, by the row's layout id. +#[derive(Default)] +pub(crate) struct Brackets(IdMap); + +/// The controls of a bracket's rows and the child after them. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct BracketTook { + /// The centre line of the first row's control. + pub(crate) first: Option, + /// The centre line of the last row's control. + pub(crate) last: Option, + /// How far the rows' controls reach toward the row's end edge, at most: right, or left under right-to-left. + pub(crate) end: Option, + /// The rect of the row's last child placed in flow: the control in the bracket's middle. + pub(crate) middle: Option, +} + +impl BracketTook { + /// The centre line between the first and the last row's controls, once two rows reported. + pub(crate) fn centre(&self) -> Option { + self.first.zip(self.last).filter(|(first, last)| last > first).map(|(first, last)| (first + last) / 2.0) + } +} + +/// Reports the `control` rect of a labelled row to the bracketed row `row`, its end edge `rtl`-aware. +pub(crate) fn report_bracket_control(ctx: &egui::Context, row: Id, control: Rect, rtl: bool) { + pass_state::with::(ctx, |brackets| { + if let Some(took) = brackets.0.get_mut(&row) { + let centre = control.center().y; + took.first.get_or_insert(centre); + took.last = Some(centre); + let end = if rtl { -control.min.x } else { control.max.x }; + took.end = Some(took.end.map_or(end, |was: f32| was.max(end))); + } + }); +} + +/// What the rows of the bracketed row `row` reported in the run that just ended; `None` outside a bracketed row. +pub(crate) fn take_bracket(ctx: &egui::Context, row: Id) -> Option { + pass_state::with::(ctx, |brackets| brackets.0.remove(&row)) +} + /// How a child that fills the main axis of the body it sits in sizes along it. enum MainFill { /// The body is being measured: the child takes no room along the axis and is counted. @@ -1115,9 +1180,16 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); let (line, target) = (env.row_line, env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; - let above = line.and_then(|line| line.centre).zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); + // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its + // rows reported before it. + let bracket = line.filter(|line| env.bracket == Some(line.body)).and_then(|line| { + let took = pass_state::with::(ui.ctx(), |brackets| brackets.0.get(&line.body).copied())?; + Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top()))) + }); + let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); + let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); - let (rect, in_cell) = take_in(ui, env.grid, slot); + let (rect, in_cell) = take_in(ui, &env, slot); let placed = if child.fill && in_cell { rect } else { @@ -1130,6 +1202,9 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { }; Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) }; + if let Some((row, _)) = bracket { + pass_state::with::(ui.ctx(), |brackets| brackets.0.get_mut(&row).map(|took| took.middle = Some(placed))); + } if measure::active(ui.ctx()) { if let Some(line) = line { pass_state::with::(ui.ctx(), |rows| { @@ -1148,7 +1223,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the /// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { - take_in(ui, Env::of(ui).grid, size) + take_in(ui, &Env::of(ui), size) } /// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it. @@ -1158,13 +1233,15 @@ pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { - take_in(ui, grid, Vec2::ZERO); + take_in(ui, &env, Vec2::ZERO); } } -/// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself. -fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { - match cell_in(ui, grid, size) { +/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start +/// closes. +fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { + close_flow_start(ui.ctx(), env); + match cell_in(ui, env.grid, size) { Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } @@ -1173,7 +1250,12 @@ fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { /// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns /// it; `None`, taking nothing, outside such a body. pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { - cell_in(ui, Env::of(ui).grid, size) + let env = Env::of(ui); + let cell = cell_in(ui, env.grid, size); + if cell.is_some() { + close_flow_start(ui.ctx(), &env); + } + cell } fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { @@ -1324,6 +1406,7 @@ fn run_grid( scoped.derive_local(|scoped| { scoped.grid = Some(id); scoped.grid_top = cells == CellAlign::Top; + scoped.flow_body = Some(id); }), ); let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body); @@ -1598,8 +1681,14 @@ pub(crate) fn run_body_measured( // Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh. let target = env.first_line.filter(|_| sizing); let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); + // Each sweep and the real run start the body's flow, and a bracketed row's reports, afresh. + let bracket = env.bracket == Some(id); let body = |ui: &mut Ui| { open_sweep(&ctx, target, row); + pass_state::with::(&ctx, |starts| starts.0.insert(id)); + if bracket { + pass_state::with::(&ctx, |brackets| brackets.0.insert(id, BracketTook::default())); + } body(ui) }; // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. @@ -1627,7 +1716,10 @@ struct RowIn { /// A `Stack` body: each leaf shows at most the stack's room, never below its least. fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); - let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit)); + let env = env.derive_local(|scoped| { + scoped.shrink = Some(Shrink::Fit); + scoped.flow_body = Some(at.id); + }); let installed = Env::install_for(ui, env.clone()); // A held child of a column whose own room is unbounded keeps the width it measured at. let inner = if env.content_column && flow_room(ui).x.is_finite() { @@ -1652,6 +1744,7 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m scoped.grid_top = false; scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_spread(ui, id, gap.x, rtl, &mut body); @@ -1675,6 +1768,7 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu scoped.row_room = Some(room.width()); scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_shrinking(ui, id, &mut body); @@ -1724,6 +1818,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign env.derive_local(|scoped| { scoped.row_room = Some(room.width()); scoped.row_line = line; + scoped.flow_body = Some(id); if line.is_some() { scoped.first_line = None; } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 4f2654e97..fa1419ccd 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,7 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, in_grid_content_column, - leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured, - shares_y, shrink_cap, take_cell, take_in_flow, view_room, + BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, + flow_room, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, report_held, + report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 38a7d029b..c8857cd64 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -138,6 +138,15 @@ pub struct Scoped { /// Where the first child the scope places in flow reports its first line: a container's header or body /// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself. pub(crate) first_line: Option, + /// The body whose flow places the scope's direct children: the flow start a child reads (`layout::flow_start`) + /// and the one a child placed in flow closes. + pub(crate) flow_body: Option, + /// The body is an unwrapped `Row` placed from its start whose container is a row of a vertical flow: its first + /// child in flow starts where the rows of that flow start (`label::in_column`). + pub(crate) column_row: bool, + /// The layout of the bracketed `Row` body (`ContainerProps::bracket`) whose labelled rows report their controls to + /// it: set for the row's body and kept through the containers inside it up to a labelled one. + pub(crate) bracket: Option, /// The container whose footer stands in its body (`FooterPlace::Body`) and the size that footer measured: a /// `FooterSlot` shown under it takes that size and is where the footer is drawn. pub(crate) footer_slot: Option, @@ -358,6 +367,7 @@ impl Scoped { /// layer is no line of a bar it was opened from. A layer's content measures and runs in this. pub(crate) fn start_layer(&mut self) { self.start_room(); + self.bracket = None; self.measure = None; self.arena = None; self.roving = None; @@ -387,6 +397,8 @@ impl Scoped { self.row_room = None; self.row_line = None; self.first_line = None; + self.flow_body = None; + self.column_row = false; self.fill_body = None; self.fill_share = None; self.shrink = None; @@ -555,6 +567,9 @@ impl Env { row_room: None, row_line: None, first_line: None, + flow_body: None, + column_row: false, + bracket: None, footer_slot: None, fill_body: None, fill_share: None, @@ -644,6 +659,7 @@ impl Env { pub(crate) fn new_room(&self) -> Env { self.derive_local(|scoped| { scoped.start_room(); + scoped.bracket = None; scoped.lazy = None; scoped.measure = None; // A pane opened from a bar is not the bar's line. diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index f58c68dd2..22e9b6838 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1239,6 +1239,11 @@ pub(crate) mod guard { ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), + ( + "layout::body::FlowStarts", + "flow starts: opened by each sweep of the body and closed by its first child in flow; a child reads its body's at its own start, and its measure key holds what it read", + ), + ("layout::body::Brackets", "bracket reports: opened by each sweep of the bracketed row and taken after its body"), ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 2dc04e1d0..982cedf9e 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -96,6 +96,8 @@ pass_state! { held_widths: crate::layout::body::HeldWidths, first_lines: crate::layout::body::FirstLines, row_lines: crate::layout::body::RowLines, + flow_starts: crate::layout::body::FlowStarts, + brackets: crate::layout::body::Brackets, cursors: crate::layout::body::Cursors, footer_slots: crate::contract::footer_slot::Slots, column_groups: crate::layout::column_group::Open, diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs index 16d315d52..dfdb6a893 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs @@ -5,7 +5,7 @@ use super::presets::{ BackgroundContents, ColorMode, DocumentOptions, MAX_NAME, MAX_SAVED, Orientation, PIXEL_ASPECTS, RESOLUTION_UNITS, SIZE_UNITS, SQUARE_PIXELS, }; use super::{NewDocumentWords, Read, Session, background_rgb, depth_label, mode_label}; -use crate::buttons::Button; +use crate::buttons::{Button, IconButton}; use crate::choice::{Checkbox, Segmented, Swatch}; use crate::contract::{Bind, Entry, FieldLayout, Gap, MemoProps, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked}; use crate::display::{Shade, Text}; @@ -138,7 +138,8 @@ pub(super) fn show(ui: &mut Ui, session: &mut Session, values: &mut DocumentOpti if std::mem::take(&mut session.focus_name) { focus::request(ui.ctx(), FocusTarget::Id(shown.response.id)); } - let save = Button::new(words.save_preset_title.clone()).painted(words.save_preset.clone()).id_salt("save-preset").show(ui); + let title = words.save_preset_title.clone(); + let save = IconButton::new(IconId::new("square_plus")).label(title.clone()).tooltip(title).id_salt("save-preset").show(ui); if clicked(&save) { session.naming = Some(proposed_name(read)); session.name_tried = false; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs b/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs index 2e8f01b98..84e82f056 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/sizing.rs @@ -3,7 +3,7 @@ use super::FormDialog; use super::size_model::{LinkedSize, MAX_DOCUMENT_SIDE}; -use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; +use crate::contract::{Bind, Bracket, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; use crate::dialog::{DialogResult, FieldRefusal, HeldAnswer}; use crate::display::Text; use crate::form::{Field, FieldGroup}; @@ -412,10 +412,11 @@ impl Kit { } } - /// The width and height rows, with the chain beside them when the model draws one. + /// The width and height rows, with the chain bracketed to them when the model draws one. pub(super) fn sides(&self, ui: &mut Ui, size: &mut LinkedSize) { let chain = size.has_chain(); - Row::new().show(ui, |ui, _| { + let row = if chain { Row::new().bracket(if size.is_linked() { Bracket::Linked } else { Bracket::Unlinked }) } else { Row::new() }; + row.show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { self.row(ui, size, Dimension::Width); self.row(ui, size, Dimension::Height); diff --git a/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs b/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs index 8b47eb526..5b571c966 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/sizing/image.rs @@ -4,7 +4,7 @@ use super::{Kit, LinkedSize, Resample, SizeForm, SizingOutput, set_size_json, sh use crate::choice::Checkbox; use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; -use crate::form::Field; +use crate::layout_components::Row; use crate::pickers::Select; use crate::runtime::env::{ColumnSize, Label, UnitKind}; use crate::runtime::{keys, overlay}; @@ -220,18 +220,19 @@ impl<'a> ImageSize<'a> { } } } - let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui); - if let Some(on) = on.value().copied() { - state.size.resampling(on); - } - if state.size.is_resampling() { - Field::new(words.resample_method.clone()).id_salt("method").show(ui, |ui, _| { - let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).show(ui); + // Resample and its method share a row that starts in the control column. + Row::new().id_salt("resample-row").show(ui, |ui, _| { + let on = Checkbox::new(Bind::given(state.size.is_resampling())).label(words.resample.clone()).id_salt("resample").show(ui); + if let Some(on) = on.value().copied() { + state.size.resampling(on); + } + if state.size.is_resampling() { + let picked = Select::new(words.resample_method.clone(), Bind::given(state.method), &entries).id_salt("method").show(ui); if let Some(method) = picked.value().copied() { state.method = method; } - }); - } + } + }); let styles = Checkbox::new(Bind::given(state.scale_styles)) .label(words.scale_styles.clone()) .id_salt("scale-styles") diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index b2adec9e8..59d1e9ece 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -521,3 +521,42 @@ fn sizing_dialogs_show_width_and_height_beside_their_labels_at_full_height() { } } } + +/// The horizontal line segments one frame of `fixture` paints, as (y, from x, to x). +fn horizontal_lines(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> { + fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < 0.5 => Some((a.y, a.x.min(b.x), a.x.max(b.x))), + _ => None, + }) + .collect() +} + +/// Image Size as 0.23.1 lays it out: the chain sits halfway between Width's and Height's controls with the bracket +/// drawn from each control to it, and Resample starts in the control column with the method on its line. +#[trial] +fn image_size_brackets_width_and_height_and_starts_resample_in_the_control_column() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(image_size()); + fixture.settle(); + let rect = |fixture: &Fixture, name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let (width, height, link) = (rect(&fixture, "Width unit"), rect(&fixture, "Height unit"), rect(&fixture, "Maintain aspect ratio")); + let middle = (width.center().y + height.center().y) / 2.0; + assert!((link.center().y - middle).abs() <= 0.5, "the chain sits halfway between Width and Height: {link:?} {middle}"); + let lines = horizontal_lines(&mut fixture); + for (name, row) in [("Width", width), ("Height", height)] { + assert!( + lines.iter().any(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0), + "a tick runs from {name}'s control to the chain: {lines:?}" + ); + } + let (number, check, method) = (rect(&fixture, "Width"), rect(&fixture, "Resample"), rect(&fixture, "Resample method")); + assert!((check.min.x - number.min.x).abs() <= 0.5, "Resample starts at the control column: {check:?} {number:?}"); + assert!( + method.min.x >= check.max.x - 0.5 && method.min.y < check.max.y && method.max.y > check.min.y, + "the method follows Resample on its line: {method:?} {check:?}" + ); +} diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index 307ad8248..760b341b0 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -270,7 +270,7 @@ fn the_new_document_layout_places_presets_and_details_below_the_tabs() { } /// The fields run Name, size, Color Mode, Background Contents, then the advanced Color Profile and Pixel Aspect Ratio; the -/// save icon sits at the end of the Name row. +/// save icon (no text) sits at the end of the Name row. #[trial] fn the_new_document_fields_run_background_before_the_advanced_ones_and_save_sits_on_the_name_row() { let mut options = DocumentOptions::default(); @@ -287,6 +287,7 @@ fn the_new_document_fields_run_background_before_the_advanced_ones_and_save_sits let save = fixture.by_label("Save Document Preset").expect("the save action").rect; assert!(save.top() < name.bottom() && name.top() < save.bottom(), "the save icon shares the Name row"); assert!(name.right() <= save.left(), "the save icon is at the end of the Name field"); + assert!(!fixture.texts().iter().any(|run| run.text.starts_with("Save ")), "the save control is an icon, with no text"); } /// The caption role sets its text in capitals when it paints; the label stays as written. diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index e5c1c8e73..b0d1a52ba 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -2,7 +2,7 @@ //! lays its children out (6.3). use crate::contract::{ - Access, BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme, + Access, BodyCx, Bracket, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme, LeastWidth, Pad, Role, Scroll, Sizing, ThemeScope, WrapWidth, }; use crate::layout::{BodyLayout, CellAlign, GridFit, RowAlign}; @@ -325,6 +325,14 @@ impl Row { self.props.layout = std::mem::replace(&mut self.props.layout, BodyLayout::Stack).align(align); self } + + /// Links the labelled rows of the first child to the child after them (width and height to their chain): that + /// child sits halfway between the first and the last row's controls, and `Bracket::Linked` draws the bracket + /// from the controls to it. + pub fn bracket(mut self, bracket: Bracket) -> Self { + self.props = self.props.bracket(bracket); + self + } } impl Default for Row { diff --git a/crates/ui-widgets/src/layout_components/stories.rs b/crates/ui-widgets/src/layout_components/stories.rs index 30359b634..511f7f5db 100644 --- a/crates/ui-widgets/src/layout_components/stories.rs +++ b/crates/ui-widgets/src/layout_components/stories.rs @@ -1,11 +1,13 @@ //! Stories of the layout components `Row`, `Stack` and `Grid`. use super::{Grid, Row, Stack}; -use crate::contract::{Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth}; +use crate::contract::{Bind, Bracket, Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth}; use crate::display::Text; +use crate::form::{Field, FieldGroup}; use crate::layout::{CellAlign, GridFit, empty_cell}; use crate::story_kit::sample::{outlined, words}; use crate::testing::{StoryData, StoryOutput, story}; +use crate::text::{NumberField, link_toggle}; use craft_behavior::ColumnWidth; use egui::Ui; @@ -37,6 +39,29 @@ 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()) } +/// A bracketed row: the width and height of a form linked to their chain, which sits halfway between the two fields' +/// controls. The bracket is drawn while they are linked. +#[story(Row, covers = [], title = "Linked rows")] +fn row_bracket(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let linked = *data.choice("linked", true, &[("Linked", true), ("Unlinked", false)]); + outlined(ui, |ui| { + FieldGroup::new("Size") + .show(ui, |ui, _| { + Row::new().bracket(if linked { Bracket::Linked } else { Bracket::Unlinked }).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + for name in ["Width", "Height"] { + Field::new(name).show(ui, |ui, _| { + NumberField::new(name, Bind::given(Some(800.0))).sizing(Sizing::Content).show(ui); + }); + } + }); + link_toggle("Constrain proportions", Bind::given(linked)).show(ui); + }); + }) + .into() + }) +} + /// A side menu beside a page: the menu as wide as its widest item and as tall as the row, its footer at the bottom. #[story(Stack<'static>, covers = [])] fn stack_fill_height(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-widgets/tests/it/label/bracket.rs b/crates/ui-widgets/tests/it/label/bracket.rs new file mode 100644 index 000000000..107d7e8d8 --- /dev/null +++ b/crates/ui-widgets/tests/it/label/bracket.rs @@ -0,0 +1,116 @@ +//! A bracketed row and the row a check box starts: the chain halfway between its fields with the bracket drawn to +//! their controls, and a check box that starts a row of a form in the form's control column. + +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, Bracket, Entry, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::Text; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::layout_components::{Row, Stack}; +use craft_ui::pickers::{Select, UnitSelect}; +use craft_ui::runtime::env::UnitKind; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::{NumberField, link_toggle}; +use egui::{Rect, Shape, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; + +fn control(fixture: &Fixture, name: &str) -> Rect { + fixture.by_label(name).unwrap_or_else(|| panic!("{name:?} names its control")).rect +} + +/// The horizontal line segments of one frame, as (y, from x, to x). +fn ticks(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> { + fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < SLACK => Some((a.y, a.x.min(b.x), a.x.max(b.x))), + _ => None, + }) + .collect() +} + +/// A form with Width and Height (unit selects) stacked in a row with `bracket`, beside their link. +fn linked(bracket: Bracket) -> Fixture { + let units = [Entry::new(UnitKind::Pixels, "Pixels"), Entry::new(UnitKind::Percent, "Percent")]; + Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + FieldGroup::new("Image size").show(ui, |ui, _| { + Row::new().bracket(bracket).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + for name in ["Width", "Height"] { + Field::new(name).show(ui, |ui, _| { + UnitSelect::new(name, Bind::given(Some(8.0)), Bind::given(UnitKind::Pixels), &units) + .unit_label(format!("{name} unit")) + .show(ui); + }); + } + }); + link_toggle("Link", Bind::given(bracket == Bracket::Linked)).show(ui); + }); + }); + }); + }) +} + +/// A linked bracket runs from the end of Width's and Height's controls to the chain's centre line, at each control's +/// centre, and the chain sits halfway between the two; unlinked, the chain keeps its place and no bracket is drawn. +/// At 1x and 1.25x. +#[trial] +fn a_bracketed_row_centres_its_chain_between_the_rows_and_draws_the_bracket_while_linked() { + for scale in [1.0, 1.25] { + for bracket in [Bracket::Linked, Bracket::Unlinked] { + let mut fixture = linked(bracket); + fixture.room(Vec2::new(1000.0, 600.0)).pixels_per_point(scale); + fixture.settle(); + let (width, height, link) = (control(&fixture, "Width unit"), control(&fixture, "Height unit"), control(&fixture, "Link")); + let middle = (width.center().y + height.center().y) / 2.0; + assert!((link.center().y - middle).abs() <= SLACK, "{bracket:?} at {scale}x: the chain sits halfway between the rows: {link:?} {middle}"); + let drawn = ticks(&mut fixture); + for (name, row) in [("Width", width), ("Height", height)] { + let tick = drawn.iter().find(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0); + match bracket { + Bracket::Linked => { + assert!(tick.is_some(), "at {scale}x a tick runs from {name}'s control to the chain: {drawn:?} {row:?} {link:?}"); + } + _ => assert!(tick.is_none(), "unlinked at {scale}x, no tick on {name}'s row: {tick:?}"), + } + } + } + } +} + +/// A check box that starts a row of a form (Resample with its method after it) starts in the form's control column; +/// one after another child of the row stays where the row puts it. +#[trial] +fn a_check_box_that_starts_a_row_of_a_form_starts_in_the_control_column() { + let methods = [Entry::new(0_u8, "Automatic"), Entry::new(1_u8, "Bicubic")]; + let mut fixture = Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + FieldGroup::new("Size").show(ui, |ui, _| { + Field::new("Resolution").show(ui, |ui, _| { + NumberField::new("Resolution", Bind::given(Some(72.0))).show(ui); + }); + Row::new().show(ui, |ui, _| { + Checkbox::new(Bind::given(true)).label("Resample").show(ui); + Select::new("Method", Bind::given(0_u8), &methods).show(ui); + }); + Row::new().show(ui, |ui, _| { + Text::new("Then").show(ui); + Checkbox::new(Bind::given(false)).label("Second").show(ui); + }); + }); + }); + }); + fixture.room(Vec2::new(1000.0, 600.0)); + fixture.settle(); + let (field, check, method) = (control(&fixture, "Resolution"), control(&fixture, "Resample"), control(&fixture, "Method")); + assert!((check.min.x - field.min.x).abs() <= SLACK, "the check box starts at the form's control edge: {check:?} {field:?}"); + assert!( + method.min.x >= check.max.x - SLACK && method.min.y < check.max.y && method.max.y > check.min.y, + "the method follows on its line: {method:?} {check:?}" + ); + let second = control(&fixture, "Second"); + assert!(second.min.x < field.min.x, "a check box after another child of the row is not moved to the control column: {second:?} {field:?}"); +} diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 6facfa093..00b7f7256 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod align; pub(crate) mod baseline; +pub(crate) mod bracket; pub(crate) mod caption; pub mod group; pub(crate) mod hit; From c9172b9ee985574f3d254a29862164adbd12b4bf Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:07:44 +0000 Subject: [PATCH 45/89] Never two rules in a row: a rule above is dropped only right after a rule No rule above a container that follows a rule A container's rule above separates it from what precedes it in flow. A body's flow starts after a rule when its container draws one under its header, or when it draws nothing of its own (no header, surface or mount) and itself started after a rule. A container right after a rule draws no rule above: Canvas Size's Current Size section under the title's own rule. Any other header or surface keeps the next container's rule above. --- crates/ui-contract/src/contract/body.rs | 4 ++++ crates/ui-contract/src/contract/body/hooks.rs | 6 +++-- .../ui-contract/src/contract/body/inherit.rs | 4 ++++ .../ui-contract/src/contract/body/regions.rs | 7 +++--- crates/ui-contract/src/contract/body/size.rs | 7 +++--- crates/ui-contract/src/layout/body.rs | 24 ++++++++++++------- crates/ui-contract/src/layout/mod.rs | 5 ++-- crates/ui-contract/src/runtime/env.rs | 4 ++++ .../tests/it/form_dialogs/hosted.rs | 18 ++++++++++++++ 9 files changed, 61 insertions(+), 18 deletions(-) diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 6533a5127..e03be55cb 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> { /// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent /// flow showed it this run: its own measuring run shows its content in a flow of its own. in_column: bool, + /// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it + /// this run: a rule above its header is not drawn, so two rules never follow each other. + after_rule: bool, /// A bottom-anchored region is following the end of its content. follows_end: bool, } @@ -242,6 +245,7 @@ impl<'b> BodyHooks<'b> { held: false, across: false, in_column: true, + after_rule: false, follows_end: false, } } diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 1ad267b23..f84c5c448 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -157,7 +157,8 @@ impl ShapeHooks for BodyHooks<'_> { self.region_gap = gap_of(&env.tokens, Gap::Tight); self.end_gap = gap_of(&env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); self.header_gap = header_gap_of(props, &env.tokens); - self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx)); + self.after_rule = layout::flow_start(&ctx, env) == Some(true); + self.rules = RuleBands::of(props, &env.tokens, crate::runtime::egui::scale::pixels_per_point(&ctx), self.after_rule); self.least_width = least_of(&env.tokens, props.least_width); let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx); if !matches!(props.mount, Mount::Inline | Mount::Pane(_)) @@ -1813,7 +1814,8 @@ impl BodyHooks<'_> { self.region_gap = gap_of(&at.env.tokens, Gap::Tight); self.end_gap = gap_of(&at.env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); self.header_gap = header_gap_of(&props, &at.env.tokens); - self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx())); + self.after_rule = layout::flow_start(at.ui.ctx(), at.env) == Some(true); + self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx()), self.after_rule); self.least_width = least_of(&at.env.tokens, props.least_width); self.room = match at.width { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 31bfd65eb..8669cc8f0 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -102,6 +102,10 @@ impl BodyHooks<'_> { if props.arena { scoped.arena = Some(ArenaId::new(id)); } + // The body's flow starts after a rule when the container draws one under its header, or when the container + // draws nothing of its own (no header, surface or mount) and itself started after a rule. + scoped.after_rule = props.header.is_some_and(|header| header.rule && !header.inline) + || (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule); scoped.flow_body = None; scoped.column_row = self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start }); diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index c0ee61ec8..6383347dd 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -84,12 +84,13 @@ pub(super) struct RuleBands { } impl RuleBands { - /// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. - pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32) -> Self { + /// The bands of `props`' rules in `tokens` on a display of `pixels_per_point`. A rule above separates the + /// container from what precedes it in flow: right after a rule (`after_rule`) there is none. + pub(super) fn of(props: &ContainerProps, tokens: &UiTokens, pixels_per_point: f32, after_rule: bool) -> Self { let width = rule_look(tokens, RuleKind::Divider).width.points(pixels_per_point); let on = |rule: bool| if rule { width } else { 0.0 }; RuleBands { - above: on(props.header.is_some_and(|header| header.rule_above)), + above: on(!after_rule && props.header.is_some_and(|header| header.rule_above)), under: on(props.header.is_some_and(|header| header.rule && !header.inline)), footer: on(props.footer.is_some_and(|footer| footer.rule)), end: on(props.end.is_some_and(|end| end.rule)), diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 58aaacd29..ca7587876 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -29,8 +29,9 @@ pub(super) struct MeasureKey { /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), env: EnvFacts, - /// Whether its parent flow showed the container as a row of a vertical flow (`label::in_column`). - in_column: bool, + /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), and with a rule + /// just before it (a rule above its header is not drawn). + flow: (bool, bool), } /// The props a body was measured under, compared on the fields its measure reads. @@ -94,7 +95,7 @@ impl<'b> BodyHooks<'b> { width, shows: (self.open, self.presence.t), env: EnvFacts::of(env), - in_column: self.in_column, + flow: (self.in_column, self.after_rule), } } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 440476bb1..39aef7f2b 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -10,7 +10,7 @@ use crate::runtime::measure; use crate::runtime::memory::sub; use crate::runtime::pass_state; use craft_behavior::{Axis, ColumnWidth, Flow, GridCursor, GridMeasure}; -use egui::{Id, IdMap, IdSet, Rect, Ui, Vec2}; +use egui::{Id, IdMap, Rect, Ui, Vec2}; use std::borrow::Cow; /// How a body lays out its children, in reading order: mirrored under a right-to-left direction. @@ -211,14 +211,22 @@ fn report_first_line(ctx: &egui::Context, target: Id, at: Option) { }); } -/// The bodies whose flow has placed nothing yet in the sweep or run under way. +/// The bodies whose flow has placed nothing yet in the sweep or run under way, by body id, each with whether a rule +/// precedes the body's start (`Scoped::after_rule`). #[derive(Default)] -pub(crate) struct FlowStarts(IdSet); +pub(crate) struct FlowStarts(IdMap); -/// Whether the next child placed in flow under `env` starts its body's flow: the body that places it has placed -/// nothing yet in this sweep or run. False outside a body. +/// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed +/// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`); +/// `None` once a child took room there, and outside a body. +pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option { + let body = env.flow_body?; + pass_state::with::(ctx, |starts| starts.0.get(&body).copied()) +} + +/// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`). pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { - env.flow_body.is_some_and(|body| pass_state::with::(ctx, |starts| starts.0.contains(&body))) + flow_start(ctx, env).is_some() } /// A child took room in the flow of the body that places the children under `env`: its flow start closes. @@ -1682,10 +1690,10 @@ pub(crate) fn run_body_measured( let target = env.first_line.filter(|_| sizing); let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); // Each sweep and the real run start the body's flow, and a bracketed row's reports, afresh. - let bracket = env.bracket == Some(id); + let (after_rule, bracket) = (env.after_rule, env.bracket == Some(id)); let body = |ui: &mut Ui| { open_sweep(&ctx, target, row); - pass_state::with::(&ctx, |starts| starts.0.insert(id)); + pass_state::with::(&ctx, |starts| starts.0.insert(id, after_rule)); if bracket { pass_state::with::(&ctx, |brackets| brackets.0.insert(id, BracketTook::default())); } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index fa1419ccd..b5fbb0c2e 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -25,6 +25,7 @@ pub use body::place_in_flow; pub(crate) use body::run_body; pub(crate) use body::{ BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, - flow_room, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, report_held, - report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, view_room, + flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, + report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, + view_room, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index c8857cd64..fd3733682 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -141,6 +141,9 @@ pub struct Scoped { /// The body whose flow places the scope's direct children: the flow start a child reads (`layout::flow_start`) /// and the one a child placed in flow closes. pub(crate) flow_body: Option, + /// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws + /// nothing of its own and itself follows one. The body's layout opens its flow start with it. + pub(crate) after_rule: bool, /// The body is an unwrapped `Row` placed from its start whose container is a row of a vertical flow: its first /// child in flow starts where the rows of that flow start (`label::in_column`). pub(crate) column_row: bool, @@ -568,6 +571,7 @@ impl Env { row_line: None, first_line: None, flow_body: None, + after_rule: false, column_row: false, bracket: None, footer_slot: None, diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index 59d1e9ece..caea87ce1 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -560,3 +560,21 @@ fn image_size_brackets_width_and_height_and_starts_resample_in_the_control_colum "the method follows Resample on its line: {method:?} {check:?}" ); } + +/// Canvas Size draws one rule between its title and Current Size, the title's: the first section's rule above would +/// stand right under it. The rule between the two sections stays. +#[trial] +fn canvas_size_draws_one_rule_under_its_title() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(canvas_size()); + fixture.settle(); + let text = |fixture: &Fixture, text: &str| { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted")) + }; + let (title, current, new) = (text(&fixture, "Canvas Size"), text(&fixture, "Current Size"), text(&fixture, "New Size")); + let lines = horizontal_lines(&mut fixture); + let across = |top: f32, bottom: f32| lines.iter().filter(|(y, from, to)| *y > top && *y < bottom && to - from > current.width()).count(); + assert_eq!(across(title.max.y, current.min.y), 1, "one rule between the title and Current Size: {lines:?}"); + assert_eq!(across(current.max.y, new.min.y), 1, "a rule between Current Size and New Size: {lines:?}"); +} From 3502761b8985ee0e964c84d7031973763bd473b6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 04:12:25 +0000 Subject: [PATCH 46/89] craft-draw, craft-ui-patterns: MemoProps and PlainData on the paint bar, brush picker, symmetry and preset view types PaintValues drops the size and the hardness: the bar shows neither (the preset picker before it does), so a view over it keys only on what it shows. The gradient tile, its style and its focus outline are memo props too: a gradient item carries its tile. --- crates/draw/src/ui/brush_presets/picker.rs | 4 ++-- crates/draw/src/ui/brush_presets/settings.rs | 4 ++-- crates/draw/src/ui/brush_settings/ellipse.rs | 2 +- crates/draw/src/ui/gradient/fill.rs | 2 +- crates/draw/src/ui/gradient/tile.rs | 4 ++-- crates/draw/src/ui/paint_bar.rs | 18 ++++++------------ crates/draw/src/ui/symmetry/menu.rs | 4 ++-- crates/draw/src/ui/symmetry/model.rs | 2 +- crates/ui-contract/src/contract/entry.rs | 6 +++--- .../ui-patterns/src/patterns/presets/state.rs | 4 ++-- 10 files changed, 22 insertions(+), 28 deletions(-) diff --git a/crates/draw/src/ui/brush_presets/picker.rs b/crates/draw/src/ui/brush_presets/picker.rs index fb51e253a..9709d04fe 100644 --- a/crates/draw/src/ui/brush_presets/picker.rs +++ b/crates/draw/src/ui/brush_presets/picker.rs @@ -30,7 +30,7 @@ use crate::ui::brush_settings::{BrushSizeField, TipAngle, TipEllipse}; const DEFAULT_MAX_DIAMETER: f64 = 5000.0; /// The brush values the picker's head edits, given by the app each pass. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct BrushPickerValues { /// The diameter in pixels: the Size field and its log slider. @@ -117,7 +117,7 @@ impl<'a> GearRows<'a> { /// The picker's state, kept by the host while the app runs: the browser's view (search, open groups, scale), the /// parts the presets show and whether the search field shows. [`settings`](Self::settings) is what persists. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct BrushPickerState { /// The browser's view settings; its zoom is the thumbnail scale. diff --git a/crates/draw/src/ui/brush_presets/settings.rs b/crates/draw/src/ui/brush_presets/settings.rs index 33569b7b5..6899a1732 100644 --- a/crates/draw/src/ui/brush_presets/settings.rs +++ b/crates/draw/src/ui/brush_presets/settings.rs @@ -23,7 +23,7 @@ pub enum BrushCardPart { /// /// - The tip alone is the browser's grid of thumbnails with the size as each caption. /// - The name or the stroke is the browser's list: the stroke as the row's picture while it is on, else the tip. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(default)] #[non_exhaustive] pub struct BrushCardParts { @@ -80,7 +80,7 @@ impl BrushCardParts { /// scale. The app saves it in its settings (serde) when /// [`BrushPresetPickerOutput::settings`](super::BrushPresetPickerOutput::settings) is set and restores it with /// [`BrushPickerState::restore`]; the search text, open groups and an open rename are not saved. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::MemoProps)] #[serde(default)] #[non_exhaustive] pub struct BrushPickerSettings { diff --git a/crates/draw/src/ui/brush_settings/ellipse.rs b/crates/draw/src/ui/brush_settings/ellipse.rs index 7c1513a1e..a2beed00d 100644 --- a/crates/draw/src/ui/brush_settings/ellipse.rs +++ b/crates/draw/src/ui/brush_settings/ellipse.rs @@ -34,7 +34,7 @@ const ROUND_STEP: f64 = 0.01; const ROUND_MIN: f64 = 0.01; /// A tip's angle and roundness. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct TipAngle { /// The major axis's angle in whole degrees, counter-clockwise from the right, −180 to 180. diff --git a/crates/draw/src/ui/gradient/fill.rs b/crates/draw/src/ui/gradient/fill.rs index 3ea3a91b8..de9d5179a 100644 --- a/crates/draw/src/ui/gradient/fill.rs +++ b/crates/draw/src/ui/gradient/fill.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use super::fill_editor::GradientFillWords; /// How a gradient runs from its line. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum GradientStyle { /// Along the line. diff --git a/crates/draw/src/ui/gradient/tile.rs b/crates/draw/src/ui/gradient/tile.rs index 97f459520..9f3fc7769 100644 --- a/crates/draw/src/ui/gradient/tile.rs +++ b/crates/draw/src/ui/gradient/tile.rs @@ -18,7 +18,7 @@ const TILE_STEPS: usize = 17; /// /// A tile other than [`Ramp`](GradientTile::Ramp) is one `craft_color_ui::ui::smooth_mesh` sampled through /// [`t_at`](GradientTile::t_at). `p` below is a point in the tile's unit square (0 to 1, y down) and `c` its centre. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum GradientTile { /// The ramp chip: the gradient along its length. @@ -56,7 +56,7 @@ impl GradientTile { } /// The outline a [`GradientTile::Focus`] gradient follows. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum FocusOutline { /// A circle. diff --git a/crates/draw/src/ui/paint_bar.rs b/crates/draw/src/ui/paint_bar.rs index fec07db9e..c589e2e61 100644 --- a/crates/draw/src/ui/paint_bar.rs +++ b/crates/draw/src/ui/paint_bar.rs @@ -30,7 +30,7 @@ pub use words::PaintBarWords; const PRESSURE: &str = "target"; /// The painting tools the bar serves. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum PaintTool { /// The Brush tool. @@ -43,14 +43,10 @@ pub enum PaintTool { MixerBrush, } -/// The bar's values. -#[derive(Clone, Debug, PartialEq)] +/// The bar's values. The size and the hardness are the preset picker's, which comes before the bar. +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct PaintValues { - /// The brush size. - pub size: f64, - /// The brush hardness. - pub hardness: f64, /// The opacity. pub opacity: f64, /// The flow. @@ -78,8 +74,6 @@ impl PaintValues { /// options overwrites every field. pub fn new(mode: M) -> Self { PaintValues { - size: 30.0, - hardness: 0.5, opacity: 1.0, flow: 1.0, smoothing: Smoothing::default(), @@ -95,7 +89,7 @@ impl PaintValues { } /// The stroke smoothing options. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Smoothing { /// The amount, 0 to 1. @@ -118,7 +112,7 @@ impl Default for Smoothing { } /// The Mixer Brush's values. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct MixerValues { /// Load the brush after each stroke. @@ -162,7 +156,7 @@ impl Default for MixerValues { } /// What the Eraser tool erases with. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum EraserMode { /// A brush. diff --git a/crates/draw/src/ui/symmetry/menu.rs b/crates/draw/src/ui/symmetry/menu.rs index abd9f7f24..f34d0ebf6 100644 --- a/crates/draw/src/ui/symmetry/menu.rs +++ b/crates/draw/src/ui/symmetry/menu.rs @@ -28,7 +28,7 @@ craft_ui::words! { } /// The symmetry in force, as the menu marks it. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum SymmetryChoice { /// No symmetry. @@ -40,7 +40,7 @@ pub enum SymmetryChoice { } /// A path the symmetry can come from (the saved paths, the Work Path, the layer's path), in the app's order. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct SymmetryPathRow { /// The app's key ("work", "layer", or the saved path's name). diff --git a/crates/draw/src/ui/symmetry/model.rs b/crates/draw/src/ui/symmetry/model.rs index ad3c79080..6b623ec96 100644 --- a/crates/draw/src/ui/symmetry/model.rs +++ b/crates/draw/src/ui/symmetry/model.rs @@ -9,7 +9,7 @@ pub const TURN_STEP_DEGREES: f64 = 15.0; /// The straight symmetry modes PhotoCraft has (lead call 23). Photoshop's Wavy, Circle, Spiral, /// Parallel Lines, Radial and Mandala modes need engine work and are not built. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "lowercase")] #[non_exhaustive] pub enum SymmetryMode { diff --git a/crates/ui-contract/src/contract/entry.rs b/crates/ui-contract/src/contract/entry.rs index dfffeaf84..1fdf97eeb 100644 --- a/crates/ui-contract/src/contract/entry.rs +++ b/crates/ui-contract/src/contract/entry.rs @@ -10,19 +10,19 @@ 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. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] pub struct Entry { row: Row, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] enum Row { Item(Item), Heading(Label), Separator, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] struct Item { value: T, label: Label, diff --git a/crates/ui-patterns/src/patterns/presets/state.rs b/crates/ui-patterns/src/patterns/presets/state.rs index 47a4a2f7f..405c5fd4d 100644 --- a/crates/ui-patterns/src/patterns/presets/state.rs +++ b/crates/ui-patterns/src/patterns/presets/state.rs @@ -8,7 +8,7 @@ use std::collections::HashSet; use std::hash::Hash; /// How the presets are shown. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, crate::contract::PlainData)] #[serde(rename_all = "lowercase")] #[non_exhaustive] pub enum PresetView { @@ -37,7 +37,7 @@ pub enum DefaultOpen { /// /// A group is open when its default (from [`DefaultOpen`]) differs from membership in `toggled`. While the search /// text is not empty, every group is open. -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, crate::contract::PlainData)] #[serde(default, bound(serialize = "K: serde::Serialize", deserialize = "K: serde::Deserialize<'de> + Eq + std::hash::Hash"))] #[non_exhaustive] pub struct PresetState { From da74cd2c85f415ad74a07c07e02fa0ffa5381f3e Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 04:30:41 +0000 Subject: [PATCH 47/89] craft-color-ui: MemoProps on the Color panel's settings, mode and ramp --- crates/color-ui/src/ui/panel.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 76c85e775..22a624530 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -62,7 +62,7 @@ craft_ui::words! { /// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default; /// the theme never changes it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelMode { @@ -129,7 +129,7 @@ impl ColorPanelMode { } /// The ramp under the sliders. Shift-click on the ramp cycles them in this order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelRamp { @@ -179,7 +179,7 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { From a94a95107f7df65e059370ac9a3a36e0e751ef7a Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:51:34 +0000 Subject: [PATCH 48/89] Memoized views: a held press engages a view only where its layer is the top layer at the press origin A drag on a popover over a memoized view ran the view on every move: the press half of lazy::engaged asked only whether the press origin lay in the view's rect. It now asks whether the view's layer is the top layer there, as the pointer half does through rect_contains_pointer. Trial: a drag on a popover's slider over a view replays the view. --- crates/ui-contract/src/runtime/lazy.rs | 7 ++- crates/ui-widgets/tests/it/body/memo_view.rs | 65 +++++++++++++++++++- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 19b1b46e3..368d5c2c5 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -559,10 +559,13 @@ fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option bool { let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); - ctx.rect_contains_pointer(layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin)) + ctx.rect_contains_pointer(layer, rect) + || input_state::held_press_origin(ctx) + .is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 0c52bb966..4a5d7e01b 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -12,7 +12,8 @@ use craft_ui::runtime::memory::{SaveKey, set_saved_value}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::in_audit_run; use craft_ui::testing::input::key_press; -use craft_ui::testing::layout::{in_region, measured_block}; +use craft_ui::popover::Popover; +use craft_ui::testing::layout::{allocate, in_region, measured_block}; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{ Frames, MemoRun, last_frame_memo_runs, last_pass_measuring_runs, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, @@ -1084,6 +1085,68 @@ fn a_view_replayed_for_frames_keeps_the_layout_memory_it_kept() { assert_eq!(after_replays, after_a_run, "the replays kept the stack's measurements alive"); } +/// A view as large as the region `COVERED` gives it, under the popover of the covered trial. +#[derive(MemoProps)] +struct Board { + title: String, +} + +fn board(props: &mut Board, ui: &mut Ui) { + Button::new(props.title.clone()).show(ui); + allocate(ui, Vec2::new(300.0, 200.0)); +} + +/// Where the board view is: the popover hangs over its middle. +const COVERED: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(410.0, 260.0) }; + +/// A board view with an open popover over it whose slider edits a value the board does not show. +struct Covered { + size: f32, + /// Where the slider in the popover was shown in the last frame. + slider: Option, +} + +impl Covered { + fn show(&mut self, ui: &mut Ui) { + in_region(ui, COVERED, |ui| MemoView::new("board", Board { title: "Board".to_owned() }, board).show(ui)); + let (size, slider) = (&mut self.size, &mut self.slider); + Popover::new("Size", Bind::given(true)).at_point(Pos2::new(80.0, 80.0)).show(ui, |ui, _| { + *slider = Some(Scrub::new(Bind::bound(size)).show(ui).response.rect); + }); + } + + /// One frame with `events`; returns the views that ran in any of its passes, by props type name. + fn frame(&mut self, frames: &mut Frames, events: Vec) -> Vec<&'static str> { + frames.frame(events, |ui| self.show(ui)); + let ran = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran); + ran.map(|(name, _, _)| short_name(name)).collect() + } +} + +/// A drag of a slider on a popover over a memoized view leaves the view replaying: the press is on the popover, the +/// top layer where it started, so it engages nothing beneath it. +#[trial] +fn a_drag_on_a_popover_over_a_view_replays_the_view() { + let mut scene = Covered { size: 10.0, slider: None }; + let mut frames = Frames::new(); + for _ in 0..SETTLE { + scene.frame(&mut frames, vec![]); + } + let slider = scene.slider.expect("the popover shows its slider"); + let from = Pos2::new(slider.left() + 10.0, slider.center().y); + assert!(COVERED.contains(from), "the slider lies over the board"); + scene.frame(&mut frames, vec![moved(from)]); + assert_eq!(scene.frame(&mut frames, vec![press(from)]), Vec::<&str>::new(), "the press runs no view"); + let start = scene.size; + let mut runs = Vec::new(); + for step in 1..=4 { + runs.push(scene.frame(&mut frames, vec![moved(from + Vec2::new(12.0 * step as f32, 0.0))])); + } + scene.frame(&mut frames, vec![release(from + Vec2::new(48.0, 0.0))]); + assert_ne!(scene.size, start, "the drag edited the size"); + assert!(runs.iter().all(Vec::is_empty), "the board replays in every drag frame: {runs:?}"); +} + #[derive(MemoProps)] struct Centred { label: String, From 5734238622eab026418e22e2a3bfa83b81f0c03c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:51:34 +0000 Subject: [PATCH 49/89] Memoized views: the view's content keeps the axes the enclosing body sizes from its content A memoized member of a bar whose content held a vertical rule took the bar's whole open room as its height: the view's layout room started with no content-sized axes, so a child that fills took the room. The room keeps the enclosing body's content axes (they join the scope key), so the view takes what its content used, as without the view. Trial: a bar with a memoized member is as high as the bar with the same content shown plainly. --- Cargo.lock | 1 + crates/ui-contract/src/contract/memo_view.rs | 15 +++++-- crates/ui-contract/src/runtime/env.rs | 7 +-- crates/ui-widgets/tests/it/bars/memo.rs | 47 ++++++++++++++++++-- 4 files changed, 60 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index add7ab337..2fe6988ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4252,6 +4252,7 @@ name = "craft-tracked" version = "0.1.0" dependencies = [ "craft-ui-macros", + "serde", ] [[package]] diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index d866926f6..04fb2ce87 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -3,7 +3,7 @@ use super::lazy::{Lazy, Shown}; use super::memo::{MemoKey, MemoProps}; -use crate::runtime::env::{Env, Scoped}; +use crate::runtime::env::Env; use crate::runtime::shift::Shift; use egui::Ui; use std::fmt; @@ -103,8 +103,17 @@ impl MemoVie let env = Env::of(ui); let key = Self::key(&ctx, &env, &props, show); let shown = lazy.run_keyed(ui, std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { - // The content is a layout room of its own: the flow of the body around it does not reach in. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps the + // axes that body sizes from its content, so the view takes what its content used there, as the same + // content shown without the view would: a child that fills takes its measured size, never the open room. + let installed = Env::install_for( + ui, + env.derive_local(|scoped| { + let content = scoped.content; + scoped.start_room(); + scoped.content = content; + }), + ); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 38a7d029b..8963b05df 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -397,9 +397,10 @@ impl Scoped { /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line - /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The - /// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own - /// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then. + /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of + /// the flow fields of the enclosing body only the axes it sizes from its content are in it: a memoized view's + /// content starts a layout room of its own (`start_room`) that keeps those axes. Computed once per scope, on the + /// first view that asks; the bytes it fed are counted then. pub(crate) fn scope_key(&self) -> u128 { *self.scope_key.get_or_init(|| { use crate::contract::{MemoKey, MemoProps as _}; diff --git a/crates/ui-widgets/tests/it/bars/memo.rs b/crates/ui-widgets/tests/it/bars/memo.rs index a19c16ca3..ec051fa1a 100644 --- a/crates/ui-widgets/tests/it/bars/memo.rs +++ b/crates/ui-widgets/tests/it/bars/memo.rs @@ -3,17 +3,17 @@ //! idle frames replay them, a change to what one holds runs only that one, and an event leaves through an `Outbox`. use craft_behavior::IconId; -use craft_ui::bars::{Bar, BarItem, BarItems, BarKind, StatusMessage, StatusProgress}; +use craft_ui::bars::{Bar, BarHome, BarItem, BarItems, BarKind, StatusMessage, StatusProgress}; use craft_ui::buttons::IconButton; -use craft_ui::contract::{CommandSet, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _}; use craft_ui::display::Text; use craft_ui::layout_components::Stack; use craft_ui::runtime::commands::CommandScope; use craft_ui::runtime::env::Label; use craft_ui::testing::layout::in_region; -use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; +use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, trial}; use egui::{Pos2, Rect, Ui, Vec2}; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; /// The tool commands of the toolbar. @@ -213,3 +213,42 @@ fn a_click_on_the_cancel_button_delivers_its_event_once() { fixture.settle(); assert_eq!(state.borrow().cancelled, 1); } + +/// The lead of an options bar as a member: Home and the vertical rule after it, which fills the bar's line. +#[derive(MemoProps)] +struct LeadProps { + on: bool, +} + +fn lead(props: &mut LeadProps, ui: &mut Ui) -> Rect { + BarHome::new("Home", Bind::given(props.on)).show(ui); + ui.min_rect() +} + +/// A bar offered far more height than its members need. +const TALL_ROOM: Vec2 = Vec2::new(400.0, 300.0); + +/// A memoized member takes what its content used: its rule that fills the line is as long as without the view, so the +/// bar with the member as a memoized view is as high as the bar with the same content shown plainly, both far below +/// the room they are offered. +#[trial] +fn a_memoized_member_takes_the_height_its_content_used_not_the_bars_room() { + let (plain, memo, member) = (Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING)); + Frames::new().idle(4, |ui| { + let at = |x: f32| Rect::from_min_size(Pos2::new(x, 10.0), TALL_ROOM); + plain.set(in_region(ui, at(10.0), |ui| { + Bar::new("Plain", BarKind::Options).show(ui, |ui, _| BarHome::new("Home", Bind::given(false)).show(ui)).output.response.rect + })); + memo.set(in_region(ui, at(420.0), |ui| { + let shown = Bar::new("Memoized", BarKind::Options).show(ui, |ui, _| MemoView::new("lead", LeadProps { on: false }, lead).show(ui)); + if let Some(Some(rect)) = shown.inner { + member.set(rect); + } + shown.output.response.rect + })); + }); + let (plain, memo, member) = (plain.get(), memo.get(), member.get()); + assert!(plain.height() < TALL_ROOM.y / 2.0, "the plain bar sizes from its members: {plain:?}"); + assert!(member.height() < TALL_ROOM.y / 2.0, "the member takes what its content used, not the bar's room: {member:?}"); + assert!((memo.height() - plain.height()).abs() <= 0.5, "the bar is as high with the member memoized: {memo:?} against {plain:?}"); +} From d37c886c2ddd926be5d336e27b005f1d129e6fa2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 07:02:41 +0000 Subject: [PATCH 50/89] Memoized views: rustfmt --- crates/ui-contract/src/runtime/lazy.rs | 3 +-- crates/ui-widgets/tests/it/body/memo_view.rs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 368d5c2c5..a2fba430f 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -564,8 +564,7 @@ fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option bool { let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); ctx.rect_contains_pointer(layer, rect) - || input_state::held_press_origin(ctx) - .is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) + || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 4a5d7e01b..48813d530 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -7,12 +7,12 @@ use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Tracked}; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; +use craft_ui::popover::Popover; use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey}; use craft_ui::runtime::memory::{SaveKey, set_saved_value}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::in_audit_run; use craft_ui::testing::input::key_press; -use craft_ui::popover::Popover; use craft_ui::testing::layout::{allocate, in_region, measured_block}; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{ From 6eae28f167e667f23199a303d29a3e1856276acb Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:07:09 +0000 Subject: [PATCH 51/89] craft-tracked: From, value equality and an optional serde feature for Tracked A Tracked field inside a derived PartialEq or serde type (a brush's tip inside its settings) compares by value and saves as its value; a loaded one starts a new source. --- crates/tracked/Cargo.toml | 8 +++++++- crates/tracked/src/lib.rs | 29 +++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/tracked/Cargo.toml b/crates/tracked/Cargo.toml index 24265919f..ba1d94fe9 100644 --- a/crates/tracked/Cargo.toml +++ b/crates/tracked/Cargo.toml @@ -10,7 +10,13 @@ description = "Tracked: app data whose every write moves a revision, so a rea [lints] workspace = true -# No dependencies, so engine crates can hold and move a revision without the UI. +# No dependencies but an optional serde, so engine crates can hold and move a revision without the UI. +[dependencies] +serde = { workspace = true, optional = true } + +[features] +# `Serialize` and `Deserialize` for `Tracked`: saved as its value, loaded as a new source. +serde = ["dep:serde"] [dev-dependencies] # `#[derive(PlainData)]` in the doc tests. diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs index a56ddbe4f..5587f70e7 100644 --- a/crates/tracked/src/lib.rs +++ b/crates/tracked/src/lib.rs @@ -326,13 +326,38 @@ impl Clone for Tracked { } } -/// Two values are equal when what they hold is: the revision says which writes a value saw, not what it is. +/// `value`, as a new source at count 0 ([`Tracked::new`]). +impl From for Tracked { + fn from(value: T) -> Tracked { + Tracked::new(value) + } +} + +/// Equal values compare equal, whatever their revisions. impl PartialEq for Tracked { - fn eq(&self, other: &Self) -> bool { + fn eq(&self, other: &Tracked) -> bool { self.value == other.value } } +impl Eq for Tracked {} + +/// Saved as its value. +#[cfg(feature = "serde")] +impl serde::Serialize for Tracked { + fn serialize(&self, serializer: S) -> Result { + self.value.serialize(serializer) + } +} + +/// Loaded as a new source. +#[cfg(feature = "serde")] +impl<'de, T: PlainData + serde::Deserialize<'de>> serde::Deserialize<'de> for Tracked { + fn deserialize>(deserializer: D) -> Result, D::Error> { + T::deserialize(deserializer).map(Tracked::new) + } +} + impl Deref for Tracked { type Target = T; From 000a091d4bf0f949ee28f7528a53806116356eb4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 05:09:03 +0000 Subject: [PATCH 52/89] craft-menu: English names on the menu model, the MenuBarUi::english hook goes --- crates/menu/README.md | 2 +- crates/menu/src/bar.rs | 71 ++++++++----------------------- crates/menu/src/context.rs | 24 +++-------- crates/menu/src/layout.rs | 34 +++++++++++---- crates/menu/src/lib.rs | 2 +- crates/menu/src/model.rs | 45 +++++++++++++++++++- crates/menu/src/palette.rs | 22 +++++----- crates/menu/tests/it/mnemonic.rs | 21 +++++---- migration/api-map/craft-menu.toml | 9 +++- 9 files changed, 125 insertions(+), 105 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index a654dbcaf..29167ca57 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -156,7 +156,7 @@ egui::Panel::top("menu-bar").show(ui, |ui| { they are off unless set. `.mnemonics(&[("View", 'W'), ("file.open", 'P')])` names preferred letters by title as shown or by command id. A label without an ASCII letter or digit shows its English label's letter after it, "文件(F)", before a trailing ellipsis ("開く(O)…"), when - `.english(&hook)` returns that English label for the `Labeled::Command` or `Labeled::Title`. + the item, submenu or menu carries that English label (`Item::english`, `Node::english`, `Menu::english`). - **Items:** a command the runtime's gate forbids, or whose state is disabled, is greyed and never fires. A submenu whose items are all disabled is greyed. The shortcut column shows the command's chord, else the item's own shortcut, in the shell's names (⌘ glyphs on a Mac). `.target(..)` diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 35e8fe9ae..00da81878 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -13,8 +13,8 @@ pub(crate) mod stories; use craft_host::target::Os; use craft_i18n::Words; -use craft_keymap::{CommandRef, Platform}; -use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked}; +use craft_keymap::Platform; +use craft_ui::contract::{MemoProps, MemoView, Show as _, Tracked}; use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle}; use craft_ui::runtime::env::{Env, Label}; use egui::{Rect, Ui}; @@ -27,19 +27,6 @@ use crate::palette::entries_of; /// Whether a menu of the bar is open; the app's single-key shortcuts wait while it is true. pub use craft_ui::menu::bar::{is_focused, is_open}; -/// A row or title, as the bar names it to the app's mnemonic hooks ([`MenuBarUi::english`]). -#[derive(Clone, Copy, Debug, PartialEq)] -#[non_exhaustive] -pub enum Labeled<'s> { - /// An item, by its command. - Command(&'s CommandRef), - /// A menu or submenu, by its title as shown. - Title(&'s str), -} - -/// The app's English labels ([`MenuBarUi::english`]). -pub type EnglishHook<'h> = dyn Fn(Labeled<'_>) -> Option + 'h; - craft_ui::words! { /// The words of the in-window bar that the menu family does not hold. struct BarWords { @@ -78,21 +65,16 @@ pub struct MenuBarOutput { pub titles: Rect, } -/// The English-label hook a bar takes by default: none is set, so this type only names the slot. -pub type EnglishFn = fn(Labeled<'_>) -> Option; - /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel. /// The commands chosen come back through the command queue, not from `show`. /// /// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing /// reaches it (pointer, focus, keys, an open menu), it adds that run again in place of running. #[derive(craft_ui::contract::Pattern)] -#[pattern(probe(MenuBarUi<'static, EnglishFn>))] -pub struct MenuBarUi<'a, E = EnglishFn> { +pub struct MenuBarUi<'a> { bar: &'a Tracked, /// The platform set with [`target`](Self::target); the shell's when none is. target: Option, - english: Option>, preferred: &'a [(&'a str, char)], keyboard: Option, help_search: bool, @@ -100,10 +82,9 @@ pub struct MenuBarUi<'a, E = EnglishFn> { /// Every input of the bar's view. #[derive(MemoProps)] -struct BarProps<'a, #[memo_props(stateless)] E> { +struct BarProps<'a> { bar: &'a Tracked, target: Target, - english: Option>, preferred: &'a [(&'a str, char)], keyboard: bool, help: Option, @@ -113,47 +94,37 @@ struct BarProps<'a, #[memo_props(stateless)] E> { impl<'a> MenuBarUi<'a> { /// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]). pub fn new(bar: &'a Tracked) -> MenuBarUi<'a> { - MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false } + MenuBarUi { bar, target: None, preferred: &[], keyboard: None, help_search: false } } } -impl<'a, E: Fn(Labeled<'_>) -> Option + Copy + 'static> MenuBarUi<'a, E> { +impl<'a> MenuBarUi<'a> { /// The platform the bar is on, for the shortcut column ([`craft_keymap::Chord::display`]): ⌘ glyphs on /// [`Target::Mac`] and in a browser on a Mac, Ctrl names everywhere else. On [`Target::Mac`] the native bar /// has the keys, and this one takes none unless [`keyboard`](Self::keyboard) says so. - pub fn target(mut self, target: Target) -> MenuBarUi<'a, E> { + pub fn target(mut self, target: Target) -> MenuBarUi<'a> { self.target = Some(target); self } /// Whether the bar takes F10, Alt and Alt with a letter. By default it does, except on [`Target::Mac`]. The /// app turns it off while a modal dialog or the shortcut recorder has the keys. - pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a, E> { + pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a> { self.keyboard = Some(on); self } - /// The English label of a row or title, for labels the keyboard can't type a letter of (Chinese, Japanese, - /// Korean…): such a label shows its English label's mnemonic after it, "文件(F)", before a trailing ellipsis - /// ("開く(O)…"), as Windows menus do. Without this hook (or when it returns `None`) such a label has no - /// mnemonic. The Help menu's search also matches the English labels, on every target. The hook is a fn item or a - /// closure that captures nothing ([`Stateless`]): the bar's key follows its type. - pub fn english) -> Option + Copy + 'static>(self, english: F) -> MenuBarUi<'a, F> { - let MenuBarUi { bar, target, english: _, preferred, keyboard, help_search } = self; - MenuBarUi { bar, target, english: Some(Stateless::new(english)), preferred, keyboard, help_search } - } - /// Preferred mnemonics, each for a menu or submenu by its title as shown or for an item by its command id: /// the row takes that letter when its label has it and no row before it in its menu took it. Every other row /// takes the first unused letter of its label, word starts first. - pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a, E> { + pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a> { self.preferred = preferred; self } /// Start the [`MenuRole::Help`] menu with a search field over every command of the bar /// ([`MenuBar::help_entries`]). A bar with no Help menu has no field. - pub fn help_search(mut self, on: bool) -> MenuBarUi<'a, E> { + pub fn help_search(mut self, on: bool) -> MenuBarUi<'a> { self.help_search = on; self } @@ -168,24 +139,18 @@ impl<'a, E: Fn(Labeled<'_>) -> Option + Copy + 'static> MenuBarUi<'a, E> let props = BarProps { bar: self.bar, target, - english: self.english, preferred: self.preferred, keyboard: self.keyboard.unwrap_or(target != Target::Mac), help, label: env.words::().label.clone(), }; - MemoView::new("menu-bar", props, show_bar::).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) + MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) } } /// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows. -fn show_bar) -> Option + Copy + 'static>(props: &mut BarProps<'_, E>, ui: &mut Ui) -> MenuBarOutput { - let hook = props.english.map(|english| { - let english = english.get(); - move |labeled: Labeled<'_>| english(labeled) - }); - let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>); - let rows = Rows::new(props.target).english(english).preferred(props.preferred); +fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { + let rows = Rows::new(props.target).preferred(props.preferred); let env = Env::of(ui); let os = env.view().shell().os; // The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it. @@ -194,7 +159,6 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B target: props.target, os, preferred: props.preferred, - english: props.english, words: &env.words, keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()), }; @@ -212,7 +176,7 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B .collect(); // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. let bar_model: &MenuBar = props.bar; - let entries = move || entries_of(bar_model, english); + let entries = move || entries_of(bar_model); let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard); if let Some(menu) = props.help { bar = bar.help(MenuHelp::new(menu, &entries)); @@ -220,15 +184,14 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B MenuBarOutput { titles: bar.show(ui).titles } } -/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English -/// hooks, the language and the keymap. +/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, +/// the language and the keymap. The English names are part of the model. #[derive(MemoProps)] -struct LabelKey<'a, #[memo_props(stateless)] E> { +struct LabelKey<'a> { bar: &'a Tracked, target: Target, os: Os, preferred: &'a [(&'a str, char)], - english: Option>, words: &'a Words, keymap: u64, } diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index 6f6f3ac28..f353a7fe6 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -15,7 +15,7 @@ use craft_ui::runtime::pointer; use craft_ui::runtime::windows::{WindowAction, WindowHost}; use egui::{Ui, ViewportId}; -use crate::bar::{EnglishHook, Labeled, keymap_platform}; +use crate::bar::keymap_platform; use crate::layout::Target; use crate::model::{Builtin, Item, ItemKind, Node}; @@ -54,22 +54,16 @@ pub(crate) struct BarLabels { pub(crate) menus: Vec, } -/// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its -/// preferred mnemonic letters. +/// How the rows of a menu are written: the target that names the shortcuts and the app's preferred mnemonic +/// letters. pub(crate) struct Rows<'a> { target: Target, - english: Option<&'a EnglishHook<'a>>, preferred: &'a [(&'a str, char)], } impl<'a> Rows<'a> { pub(crate) fn new(target: Target) -> Self { - Rows { target, english: None, preferred: &[] } - } - - pub(crate) fn english(mut self, english: Option<&'a EnglishHook<'a>>) -> Self { - self.english = english; - self + Rows { target, preferred: &[] } } pub(crate) fn preferred(mut self, preferred: &'a [(&'a str, char)]) -> Self { @@ -112,10 +106,6 @@ impl<'a> Rows<'a> { self.preferred.iter().find(|(k, _)| *k == key).map(|(_, c)| *c) } - pub(crate) fn english_of(&self, labeled: Labeled<'_>) -> Option { - self.english.and_then(|hook| hook(labeled)) - } - /// The label a node shows as the menu's sibling, for the preferred letters and the English labels. pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec { let shown: Vec<&Node> = nodes.iter().filter(|node| !matches!(node, Node::Separator | Node::Standard { .. })).collect(); @@ -133,8 +123,8 @@ impl<'a> Rows<'a> { _ => "", }, |node| match node { - Node::Item(item) => self.english_of(Labeled::Command(&item.command)), - Node::Submenu { label, .. } => self.english_of(Labeled::Title(label)), + Node::Item(item) => item.english.clone(), + Node::Submenu { english, .. } => english.clone(), _ => None, }, ) @@ -164,7 +154,7 @@ impl<'a> Rows<'a> { /// The text of a whole bar: the titles and each menu's rows. pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels { - let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title))); + let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| menu.english.clone()); BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() } } diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index fd1627385..a12a7d002 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -103,6 +103,11 @@ impl<'a> LayoutOptions<'a> { (self.label)(english).replace("{app}", self.app_name) } + /// The English text of a label `text` writes, `{app}` filled in. + fn english_text(&self, english: &'static str) -> String { + english.replace("{app}", self.app_name) + } + fn standard(&self, kind: Standard) -> Node { Node::Standard { kind, label: self.text(kind.english()) } } @@ -181,6 +186,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout { let mut menu = Vec::new(); if let Some(Node::Item(mut it)) = about { it.label = options.text("About {app}"); + it.english = Some(options.english_text("About {app}")); menu.extend([Node::Item(it), Node::Separator]); } if let Some(s) = settings { @@ -188,8 +194,9 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout { menu.push(settings_node(s, comma, options, &mut clashes)); } if let Some(mut l) = language { - if let Node::Submenu { label, .. } = &mut l { + if let Node::Submenu { label, english, .. } = &mut l { *label = options.text("Language"); + *english = Some("Language".to_owned()); } menu.push(l); } @@ -228,6 +235,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout { _ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit), }; quit.label = options.text("Quit {app}"); + quit.english = Some(options.english_text("Quit {app}")); match taken(CMD_Q, std::slice::from_ref(&quit.command)) { Some(command) => { clashes.push(Clash { shortcut: CMD_Q, system: "Quit", command, resolution: "Quit has no shortcut" }); @@ -349,15 +357,19 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option _ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit), }; it.label = options.text(label); + it.english = Some(options.english_text(label)); ensure_menu(&mut bar, MenuRole::File, "File", options).children.extend([Node::Separator, Node::Item(it)]); } if let Some(s) = settings { let s = match s { Node::Item(mut it) => { it.label = options.text("Preferences…"); + it.english = Some("Preferences…".to_owned()); Node::Item(it) } - Node::Submenu { children, role, platforms, .. } => Node::Submenu { label: options.text("Preferences"), children, role, platforms }, + Node::Submenu { children, role, platforms, .. } => { + Node::Submenu { label: options.text("Preferences"), english: Some("Preferences".to_owned()), children, role, platforms } + } other => other, }; ensure_menu(&mut bar, MenuRole::Edit, "Edit", options).children.extend([Node::Separator, s]); @@ -370,6 +382,7 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option } if let Some(Node::Item(mut it)) = about { it.label = options.text("About {app}"); + it.english = Some(options.english_text("About {app}")); ensure_menu(&mut bar, MenuRole::Help, "Help", options).children.extend([Node::Separator, Node::Item(it)]); } finish(&mut bar, |_| false); @@ -383,9 +396,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar { let shown = nodes.iter().filter_map(|n| match n { Node::Item(it) if !it.platforms.contains(on) => None, Node::Submenu { platforms, .. } if !platforms.contains(on) => None, - Node::Submenu { label, children, role, platforms } => { - Some(Node::Submenu { label: label.clone(), children: keep(children, on, appkit), role: *role, platforms: *platforms }) - } + Node::Submenu { label, english, children, role, platforms } => Some(Node::Submenu { + label: label.clone(), + english: english.clone(), + children: keep(children, on, appkit), + role: *role, + platforms: *platforms, + }), Node::Standard { .. } if !appkit => None, other => Some(other.clone()), }); @@ -420,7 +437,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str, MenuRole::Help => bar.menus.len(), _ => bar.menus.iter().position(|m| m.role == MenuRole::Help).unwrap_or(bar.menus.len()), }; - bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).role(role)); + bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).english(english).role(role)); at } }; @@ -450,6 +467,7 @@ fn settings_node(node: Node, comma_taken: Option, options: &LayoutOp match node { Node::Item(mut it) => { it.label = options.text("Settings…"); + it.english = Some("Settings…".to_owned()); give(&mut it); Node::Item(it) } @@ -457,7 +475,7 @@ fn settings_node(node: Node, comma_taken: Option, options: &LayoutOp if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) { give(first); } - Node::Submenu { label: options.text("Settings"), children, role, platforms } + Node::Submenu { label: options.text("Settings"), english: Some("Settings".to_owned()), children, role, platforms } } other => other, } @@ -478,7 +496,7 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec { children.push(Node::Separator); children.extend(items); } - vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms }] + vec![Node::Submenu { label: options.text("Appearance"), english: Some("Appearance".to_owned()), children, role, platforms }] } _ => items, } diff --git a/crates/menu/src/lib.rs b/crates/menu/src/lib.rs index 17ffce8ee..aeed6522c 100644 --- a/crates/menu/src/lib.rs +++ b/crates/menu/src/lib.rs @@ -114,7 +114,7 @@ pub mod mac; pub mod ribbon; pub mod shortcuts; -pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi}; +pub use bar::{MenuBarOutput, MenuBarUi}; pub use craft_keymap::{Chord, CommandRef}; pub use customize::Customization; pub use documents::DOCUMENT_COMMAND_PREFIX; diff --git a/crates/menu/src/model.rs b/crates/menu/src/model.rs index 867b86bb7..4563bd3c5 100644 --- a/crates/menu/src/model.rs +++ b/crates/menu/src/model.rs @@ -57,6 +57,9 @@ impl Document { pub struct Menu { /// The title in the bar. pub title: String, + /// The title's English name, when `title` is a translation: the bar takes the mnemonic of a title the keyboard + /// can't type from it. + pub english: Option, /// What the menu is for. pub role: MenuRole, /// The menu's entries, top to bottom. @@ -145,6 +148,8 @@ pub enum Node { Submenu { /// The submenu's title. label: String, + /// The title's English name, when `label` is a translation ([`Menu::english`]). + english: Option, /// The submenu's entries. children: Vec, /// The place a layout gives it, if any. @@ -172,6 +177,9 @@ pub struct Item { pub command: CommandRef, /// The text shown. pub label: String, + /// The label's English name, when `label` is a translation. A label the keyboard can't type (Chinese, Japanese, + /// Korean…) takes its mnemonic from it in the in-window bar, and the Help search matches it on every target. + pub english: Option, /// `cmd` is ⌘ and `ctrl` the Control key: ⌃⌘M and ⌘M are different shortcuts. pub shortcut: Option, /// Whether the item can be chosen. @@ -354,6 +362,7 @@ impl Item { Item { command: command.into(), label: label.into(), + english: None, shortcut: None, enabled: true, kind: ItemKind::Plain, @@ -402,6 +411,12 @@ impl Item { self } + /// Set the label's English name ([`Item::english`] field). + pub fn english(mut self, english: impl Into) -> Item { + self.english = Some(english.into()); + self + } + /// Show the item only on `platforms`. pub fn platforms(mut self, platforms: Platforms) -> Item { self.platforms = platforms; @@ -435,7 +450,17 @@ impl Node { /// A submenu shown on every platform. pub fn submenu(label: impl Into, children: Vec) -> Node { - Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL } + Node::Submenu { label: label.into(), english: None, children, role: None, platforms: Platforms::ALL } + } + + /// Set the English name of an item's label or a submenu's title. + pub fn english(mut self, english: impl Into) -> Node { + match &mut self { + Node::Item(it) => it.english = Some(english.into()), + Node::Submenu { english: e, .. } => *e = Some(english.into()), + Node::Separator | Node::Standard { .. } => {} + } + self } /// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`. @@ -462,7 +487,13 @@ impl Node { impl Menu { /// A menu with no special role. pub fn new(title: impl Into, children: Vec) -> Menu { - Menu { title: title.into(), role: MenuRole::Other, children } + Menu { title: title.into(), english: None, role: MenuRole::Other, children } + } + + /// Set the title's English name ([`Menu::english`] field). + pub fn english(mut self, english: impl Into) -> Menu { + self.english = Some(english.into()); + self } /// Set the menu's role. @@ -580,6 +611,8 @@ pub struct Row { pub command: CommandRef, /// The text shown. pub label: String, + /// The label's English name, when `label` is a translation ([`Item::english`]). + pub english: Option, /// The row's shortcut. pub shortcut: Option, /// Whether the row can be chosen. @@ -601,6 +634,7 @@ impl Row { path: path.iter().map(|s| (*s).to_owned()).collect(), command: command.into(), label: label.into(), + english: None, shortcut: None, enabled: true, kind: ItemKind::Plain, @@ -610,6 +644,12 @@ impl Row { } } + /// Set the label's English name. + pub fn english(mut self, english: impl Into) -> Row { + self.english = Some(english.into()); + self + } + /// Whether the row can be chosen. pub fn enabled(mut self, on: bool) -> Row { self.enabled = on; @@ -682,6 +722,7 @@ pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar { match slot { Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator), Slot::Leaf(it) => out.push(Node::Item(Item { + english: it.english.clone(), shortcut: it.shortcut, enabled: it.enabled, kind: it.kind, diff --git a/crates/menu/src/palette.rs b/crates/menu/src/palette.rs index 07e2ab657..99eab3ec2 100644 --- a/crates/menu/src/palette.rs +++ b/crates/menu/src/palette.rs @@ -2,7 +2,6 @@ use craft_ui::menu::HelpEntry; -use crate::bar::{EnglishHook, Labeled}; use crate::model::{Builtin, MenuBar, Node}; use crate::{LayoutOptions, Target, layout}; @@ -18,39 +17,38 @@ impl MenuBar { /// Building the list lays out the whole bar, so a host caches the result and rebuilds it when the bar /// changes, not every frame. /// - /// `english` gives a command's or menu title's English name (as [`crate::MenuBarUi::english`]), asked on - /// every target, so the search finds a translated command by its English name. - pub fn help_entries(&self, target: Target, options: &LayoutOptions, english: Option<&EnglishHook<'_>>) -> Vec { - entries_of(&layout(self, target, options).bar, english) + /// An item's [`english`](crate::Item::english) name is listed with it, on every target, so the search finds a + /// translated command by its English name. + pub fn help_entries(&self, target: Target, options: &LayoutOptions) -> Vec { + entries_of(&layout(self, target, options).bar) } } /// The entries of an already laid-out bar. -pub(crate) fn entries_of(bar: &MenuBar, english: Option<&EnglishHook<'_>>) -> Vec { - let english_of = |labeled: Labeled<'_>| english.and_then(|hook| hook(labeled)); +pub(crate) fn entries_of(bar: &MenuBar) -> Vec { let mut entries = Vec::new(); let mut path: Vec = Vec::new(); for menu in &bar.menus { path.push(menu.title.clone()); - collect(&menu.children, &mut path, &english_of, &mut entries); + collect(&menu.children, &mut path, &mut entries); path.pop(); } entries } -fn collect(nodes: &[Node], path: &mut Vec, english_of: &dyn Fn(Labeled<'_>) -> Option, entries: &mut Vec) { +fn collect(nodes: &[Node], path: &mut Vec, entries: &mut Vec) { for node in nodes { match node { Node::Item(item) if Builtin::of(&item.command).is_none() => { let mut entry = HelpEntry::new(item.command.clone(), item.label.clone()).with_path(path.iter().cloned()); - if let Some(english) = english_of(Labeled::Command(&item.command)) { - entry = entry.with_english(english); + if let Some(english) = &item.english { + entry = entry.with_english(english.clone()); } entries.push(entry); } Node::Submenu { label, children, .. } => { path.push(label.clone()); - collect(children, path, english_of, entries); + collect(children, path, entries); path.pop(); } Node::Item(_) | Node::Separator | Node::Standard { .. } => {} diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index 8a43bc0c7..63c1dc60b 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -5,21 +5,18 @@ use std::sync::Arc; use craft_host::target::Os; use craft_host::{AppInfo, Host}; -use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items}; +use craft_menu::{CommandRef, LayoutOptions, MenuBarUi, Row, Target, from_items}; use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers}; #[trial] fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { - let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")])); - let english = |labeled: Labeled<'_>| match labeled { - Labeled::Title("文件") => Some("File".to_owned()), - Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()), - _ => None, - }; + let mut bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]); + bar.menus[0].english = Some("File".to_owned()); + let bar = Tracked::new(bar); let mut fixture = Fixture::new(move |ui| { - MenuBarUi::new(&bar).english(english).show(ui); + MenuBarUi::new(&bar).show(ui); }); // A Mac bar has no letters. fixture.os(Os::Linux); @@ -30,6 +27,14 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter"); } +#[trial] +fn help_search_lists_an_item_by_its_english_name_in_a_translated_model() { + let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]); + let entries = bar.help_entries(Target::Linux, &LayoutOptions::new("Sample")); + let entry = entries.iter().find(|entry| *entry.command() == CommandRef::new("file.new")).expect("the command is listed"); + assert_eq!(entry.english().map(|label| label.as_str()), Some("New")); +} + /// A host whose interface language is Turkish, with an empty catalog. pub(crate) fn turkish() -> Arc { let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]); diff --git a/migration/api-map/craft-menu.toml b/migration/api-map/craft-menu.toml index 3cb23d23a..72235b1c4 100644 --- a/migration/api-map/craft-menu.toml +++ b/migration/api-map/craft-menu.toml @@ -107,7 +107,12 @@ old = "id(Id)" new = "" note = "Use `Props::id_salt` on the bar's parent scope." +[[call]] +old = "MenuBarUi::english(hook)" +new = "Item::english, Node::english, Menu::english" +note = "The English name is a field of the model, set where the app translates a label." + [[call]] old = "MenuBar::palette_entries(&keymap, target, &options, english, os)" -new = "MenuBar::help_entries(target, &options, english)" -note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go." +new = "MenuBar::help_entries(target, &options)" +note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go, and so does the English hook: set `Item::english` on the model." From bae11d791699c12f9ab51fd8797c03e85871033a Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 21:04:18 +0000 Subject: [PATCH 53/89] Preset lists as sources: PresetSource keys a browser's rows, the list runs as a memoized view PresetBrowser, PresetPicker, PresetManager and BrushPresetPicker take a PresetSource (the host's MemoProps inputs and capture-free fns that build the rows and answer can_rename, can_delete, can_move, accepts and thumb), so the browser's grid or list, its drop zone and row menu run in a memoized view keyed on the inputs. Rows are kept per inputs and scope units (runtime::derived). The Brush Preset picker's head and its search-row tools are memoized views of their own; the gear rows are a fn. Work in progress: the remaining callers (form dialogs, color-ui, draw gradients and patterns, text style panel, imaging layer styles) are not moved yet and do not build. --- crates/draw/src/ui/brush_presets/panel.rs | 26 +- crates/draw/src/ui/brush_presets/picker.rs | 297 +++--- crates/draw/src/ui/brush_presets/stories.rs | 33 +- crates/draw/tests/it/brush_presets.rs | 20 +- crates/ui-contract/src/contract/memo.rs | 14 + crates/ui-contract/src/runtime/drag.rs | 2 +- crates/ui-contract/src/runtime/env/units.rs | 11 + .../src/patterns/presets/browser.rs | 846 +++++++++--------- .../src/patterns/presets/browser/reorder.rs | 40 +- .../src/patterns/presets/browser/stories.rs | 9 +- .../src/patterns/presets/manager.rs | 68 +- .../src/patterns/presets/manager/stories.rs | 24 +- .../ui-patterns/src/patterns/presets/mod.rs | 4 +- .../ui-patterns/src/patterns/presets/model.rs | 4 +- .../ui-patterns/src/patterns/presets/named.rs | 7 +- .../src/patterns/presets/named/stories.rs | 28 +- .../src/patterns/presets/picker.rs | 73 +- .../src/patterns/presets/picker/stories.rs | 19 +- .../src/patterns/presets/source.rs | 214 +++++ .../ui-patterns/src/patterns/presets/state.rs | 6 +- .../ui-patterns/tests/it/presets/browser.rs | 19 +- crates/ui-patterns/tests/it/presets/named.rs | 6 +- crates/ui-patterns/tests/it/presets/picker.rs | 16 +- 23 files changed, 1065 insertions(+), 721 deletions(-) create mode 100644 crates/ui-patterns/src/patterns/presets/source.rs diff --git a/crates/draw/src/ui/brush_presets/panel.rs b/crates/draw/src/ui/brush_presets/panel.rs index 293b35c55..e81884ca9 100644 --- a/crates/draw/src/ui/brush_presets/panel.rs +++ b/crates/draw/src/ui/brush_presets/panel.rs @@ -3,9 +3,9 @@ use std::hash::Hash; use craft_behavior::{EditEvents, IconId}; -use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _}; +use craft_ui::contract::{Bind, EditResponse, MemoProps, Outcome, Props as _, ShowContainer as _}; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState}; +use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetSource, PresetState}; use craft_ui::runtime::drag::DropZone; use craft_ui::runtime::env::{Env, Label}; use craft_ui::sections::FooterAction; @@ -29,9 +29,9 @@ pub(super) const BRUSH_THUMBS: TileZoom = #[must_use = "show the panel with `show`"] #[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)] #[pattern(probe(BrushesPanel<'static, u32>))] -pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { +pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> { label: Label, - rows: &'a [PresetRow], + source: &'a PresetSource<'a, K>, state: Bind<'a, PresetState>, diameter: Bind<'a, f64>, max_size: f64, @@ -67,16 +67,22 @@ impl Outcome for BrushesPanelOutput { } } -impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> { - /// A panel named `label` over the presets in `rows`, with its view in `state` and the brush +impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> BrushesPanel<'a, K> { + /// A panel named `label` over the presets of `source`, with its view in `state` and the brush /// size in `diameter` up to `max_size`. - pub fn new(label: impl Into

{ /// Where a drop target lies: a rect on an egui layer, in that layer's space. A component's own target lies over its /// visible rect on its layer; a component that takes drops over an area it does not draw (a preset browser's canvas) /// names the area with [`DropZone::new`] and registers with [`zone_target`]. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct DropZone { layer: Layer, rect: Rect, diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 914423660..10b6f07bc 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -323,6 +323,17 @@ impl crate::contract::MemoProps for Units { } } +impl Units { + /// Feeds what the readers and writers are built from: the scope's words (the unit words come from them), the + /// number format and the point size. The readers built so far are a cache of these. + pub(crate) fn feed(&self, key: &mut crate::contract::MemoKey) { + use crate::contract::MemoProps as _; + self.scope_words.key(key); + self.format.key(key); + self.point_size.key(key); + } +} + impl Units { /// The codec of a zoom field in percent: the percent reader, up to two decimals (the zoom ladder has rungs such as /// 66.67 %), with zoom typing (`a/b` as a ratio, a second separator cutting the text), so every zoom field reads diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index c01396567..ab01c5d95 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -15,17 +15,18 @@ pub use reorder::PresetReorder; use super::event::{PresetEvent, PresetOutput}; use super::footer::{PresetFooter, PresetFooterEvent, PresetFooterOptions}; use super::model::{CellShape, PresetRow, PresetTiles, ThumbInfo, children_end, has_captions}; +use super::source::PresetSource; use super::state::{DefaultOpen, PresetState, PresetView}; use super::words::PresetWords; use crate::bars::{Bar, BarKind}; use crate::choice::Segmented; use crate::contract::{ - Bind, BodyCx, CollectionEvent, DropMark, DropTarget, DropZone, Entry, ListDrag, OpenChange, Pattern, Props, Rename, ReorderMove, ReorderRule, - RowHeight, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename, + Bind, BodyCx, CollectionEvent, DropMark, DropTarget, DropZone, Entry, ListDrag, MemoProps, MemoView, OpenChange, Outbox, Pattern, Props, Rename, + ReorderMove, ReorderRule, RowHeight, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename, }; use crate::display::Divider; use crate::layout_components::Stack; -use crate::list::{List, ListRow, RowInk, RowTest, ThumbSize}; +use crate::list::{List, ListRow, RowInk, ThumbSize}; use crate::menu::{Menu, MenuItem}; use crate::notices::{Notice, NoticeLayout}; use crate::primitives::{ContentPainterCx, IconSpec}; @@ -126,23 +127,6 @@ fn app_move(mv: ReorderMove>) -> Option> { }) } -type ThumbPainterFn<'a, K> = Box) + 'a>; - -/// Paints a preset's thumbnail: the content painter, the rect and what the browser knows of the preset. -pub struct ThumbPainter<'a, K>(ThumbPainterFn<'a, K>); - -impl<'a, K> ThumbPainter<'a, K> { - /// Runs the painter: how a picker hands its own to the browser it opens. - pub(super) fn paint(&self, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, K>) { - (self.0)(cx, rect, info); - } - - /// The painter that runs `paint`. - pub fn new(paint: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, K>) + 'a) -> Self { - ThumbPainter(Box::new(paint)) - } -} - type BrowserToolsFn<'a> = Box; /// The host's controls at the reading end of the toolbar, after the search field: a picker's buttons and menus. @@ -183,14 +167,14 @@ impl<'a> BrowserTools<'a> { #[must_use = "show the browser with `show`"] #[derive(Pattern, Props)] #[pattern(probe(PresetBrowser<'static, u32>))] -pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { +pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> { label: Label, /// The browser's own id, which `PresetBrowser::request_rename` names; the scope id of the `Ui` it is shown in /// when none is given. #[prop] browser_id: Option, state: Bind<'a, PresetState>, - rows: &'a [PresetRow], + source: &'a PresetSource<'a, K>, /// The selected preset, which the host keeps. #[prop] selected: Option, @@ -223,21 +207,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { /// Fixes the view, whatever the state says; the toolbar then has no view buttons. #[prop] view_lock: Option, - /// Which presets and groups may be renamed; F2 does nothing on another. - #[prop(func = "Fn(&K) -> bool")] - can_rename: Option>, - /// Which presets and groups the context menu may delete; its row is disabled for the others. - #[prop(func = "Fn(&K) -> bool")] - can_delete: Option>, - /// Which presets the row menu's Move to may move; the menu has no such row for the others. - #[prop(func = "Fn(&K) -> bool")] - can_move: Option>, - /// Paints a preset's thumbnail; without it the row's own `preview` paints. - #[prop(func = "Fn(&ContentPainterCx, Rect, ThumbInfo<'_, K>)")] - thumb: Option>, /// Presets (and groups) drag and move by these rules. #[prop] - reorder: Option>, + reorder: Option, /// An area outside the browser (a canvas, a timeline) where a dragged preset drops: a release there reports /// `PresetEvent::DropAt` with the pointer in the zone's layer space. Groups dropped there report nothing. Without /// `reorder` presets still drag, to the zone and to the host's own drop targets only. @@ -266,15 +238,15 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { empty: Option

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { - // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps the - // axes that body sizes from its content, so the view takes what its content used there, as the same - // content shown without the view would: a child that fills takes its measured size, never the open room. - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - let content = scoped.content; - scoped.start_room(); - scoped.content = content; - }), - ); + // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how + // that body sizes from its content, so the view takes what its content used there, as the same content + // shown without the view would. + let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 8963b05df..00c95d128 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -394,12 +394,22 @@ impl Scoped { self.offered = None; } + /// Starts a memoized view's layout room (`start_room`), keeping whether the enclosing body is a content-sized or a + /// given column, as `start_room` keeps the content axes. The view's content then measures and fills as it would + /// shown without the view: a child that fills takes its measured size where the body sizes from content, never the + /// open room. + pub(crate) fn start_view_room(&mut self) { + let (content_column, given_column) = (self.content_column, self.given_column); + self.start_room(); + (self.content_column, self.given_column) = (content_column, given_column); + } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of - /// the flow fields of the enclosing body only the axes it sizes from its content are in it: a memoized view's - /// content starts a layout room of its own (`start_room`) that keeps those axes. Computed once per scope, on the + /// the flow fields of the enclosing body only how it sizes from its content is in it: a memoized view's content + /// starts a layout room of its own (`start_view_room`) that keeps those facts. Computed once per scope, on the /// first view that asks; the bytes it fed are counted then. pub(crate) fn scope_key(&self) -> u128 { *self.scope_key.get_or_init(|| { @@ -407,6 +417,7 @@ impl Scoped { let mut key = MemoKey::of_view(&self.ctx); key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel)); key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded, self.content)); + key.feed_hash(&(self.content_column, self.given_column)); key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view)))); self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key); self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key); diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 4c3d8d51c..27f75e78a 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -1,5 +1,6 @@ //! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's -//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held), each with a generation +//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held, the requests to +//! collections), each with a generation //! that moves when its value changes. The accessor that reads one notes it into the records open around the running //! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation //! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed @@ -34,12 +35,15 @@ pub(crate) enum Input { Focus, /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). Overlays, + /// The requests to collections from outside them (`items::request_rename`), read by the item step that takes + /// them, so a pending request runs the view that takes it. + Requests, /// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value. Scroll, } impl Input { - pub(crate) const ALL: [Input; 10] = [ + pub(crate) const ALL: [Input; 11] = [ Input::Modifiers, Input::Pointer, Input::Keys, @@ -49,6 +53,7 @@ impl Input { Input::Drag, Input::Focus, Input::Overlays, + Input::Requests, Input::Scroll, ]; @@ -117,7 +122,7 @@ pub(crate) fn observe(ctx: &Context, input /// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are /// observed here; the pointer and the modifiers by the pointer's begin hook, the window facts and the layout where -/// the frame's root env is built, the keymap by the command board. +/// the frame's root env is built, the keymap by the command board, the requests by each request. pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { match input { Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)), @@ -125,7 +130,7 @@ pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), Input::Keymap => return crate::runtime::commands::keymap_built(ctx), - Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} + Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} } with(ctx, |generations| generations.gens[input as usize]) } diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index 1ca9ff484..d343f32d3 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -217,6 +217,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 's drop_zone: Option, extra_items: Vec>, actions: Vec

>, @@ -617,7 +619,7 @@ impl Component for IconicColumn<'_, P> { let (opens, auto_collapse, column) = (self.opens, self.auto_collapse, cx.rect); // The screen side the flyouts open on, mirrored in a right-to-left layout. let right = (opens == Side::End) != cx.flow.is_rtl(); - let within = if self.within.is_positive() { self.within } else { cx.core.ctx.content_rect() }; + let within = if self.within.is_positive() { self.within } else { crate::contract::overlay::layer_room(&cx.core.ctx) }; // The column side of the bounds stops at the column, so a saved width wider than the room keeps that side. let bounds = if right { within.with_min_x(within.min.x.max(column.right())) } else { within.with_max_x(within.max.x.min(column.left())) }; if !bounds.is_positive() { diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 1e7cd429b..4ace220ce 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1290,7 +1290,10 @@ impl Pass<'_, P> { while let Some((command, _)) = body.take_command::() { commands.push(command); } - let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within: scene.bounds, open: open.clone() }; + // An OS window's flyouts and other layers take the room around the window (`overlay::layer_room`); an + // in-app window's stay in the float area. + let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds }; + let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone() }; self.column(ui, body, &window.column, at); }); self.dock = area_dock; diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 1ed545c30..21860735c 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -4,6 +4,7 @@ use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; +use craft_ui::contract::Role; use craft_ui::contract::{Bind, BodyCx, DropMark, Show as _, ShowContainer as _, SizeLimits}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec}; @@ -11,11 +12,12 @@ use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::drag; +use craft_ui::testing::access::AccessTree; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; -use craft_ui_test_kit::windows::Windows; +use craft_ui_test_kit::windows::{Out, Windows}; use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; @@ -246,6 +248,8 @@ struct NativeDock { /// The palette window's builder as the integration keeps it: each frame's builder patched onto it, which sends the /// window only the limits a builder carries. builder: Option, + /// The palette's window: the first child window the dock opened. + palette: Option, } impl NativeDock { @@ -266,7 +270,7 @@ impl NativeDock { windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])); - let mut dock = NativeDock { windows, workspace, stepped, builder: None }; + let mut dock = NativeDock { windows, workspace, stepped, builder: None, palette: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -287,7 +291,11 @@ impl NativeDock { let out = self.windows.frame(root, child, |ui| { actions.extend(DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui).actions); }); - for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT) { + if self.palette.is_none() { + self.palette = out.builders.iter().map(|(viewport, _)| *viewport).find(|viewport| *viewport != ViewportId::ROOT); + } + let palette = self.palette; + for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { let _ = kept.patch(builder); @@ -295,7 +303,7 @@ impl NativeDock { None => self.builder = Some(builder), } } - let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); + let commands = out.commands.into_iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command).collect(); (actions, commands) } } @@ -797,6 +805,203 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { assert_eq!(at.size(), FLOAT_AT.size(), "the OS window takes its expanded size"); } +/// Panels whose palette panel's body records, in each of its real runs, the viewport it runs in. +#[derive(Default)] +struct BodyProbe(Vec); + +impl DockPanels for BodyProbe { + fn spec(&self, _: &u32) -> PanelSpec { + PanelSpec::new(PALETTE_TITLE) + } + + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + let ctx = ui.ctx(); + if *panel == 1 && !craft_ui::testing::is_measuring(ctx) { + self.0.push(ctx.viewport_id()); + } + } +} + +/// The scale of the display the collapsed palette trials run on: Windows at 125 %, where the issue was reported. +const COLLAPSED_SCALE: f32 = 1.25; + +/// A native palette collapsed to icons on Windows at 125 %, and the rect its OS window shows the strip at. +fn collapsed_palette() -> (NativeDock, Rect) { + let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + let mut at = FLOAT_AT; + for _ in 0..4 { + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + } + (dock, at) +} + +/// One frame of `dock` with `panels`, `root` events for the main window and `child` events for the palette's window, +/// whose OS window follows its commands at `at`: the frame's output. +fn collapsed_frame(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect, root: Vec, child: Vec) -> Out { + let workspace = &mut dock.workspace; + let out = dock.windows.frame(root, child, |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut *panels, DockConfig::default()).show(ui); + }); + let palette = dock.palette; + let commands: Vec = + out.commands.iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command.clone()).collect(); + *at = placed_by(&commands, *at); + dock.windows.child_info(scaled(true, *at, COLLAPSED_SCALE)); + out +} + +/// The windows the frame showed other than the main window and the palette's: its popup windows. +fn popups(dock: &NativeDock, out: &Out) -> Vec { + out.builders.iter().map(|(viewport, _)| *viewport).filter(|viewport| *viewport != ViewportId::ROOT && Some(*viewport) != dock.palette).collect() +} + +/// The rect of `viewport`'s window in desktop points, as the window system reports it. +fn window_rect(dock: &NativeDock, viewport: ViewportId) -> Rect { + dock.windows.facts(viewport).inner_rect.expect("the window reports its rect") +} + +/// The rect, in its window's points, of the node of `tree` named `name` whose role is `role`. +fn node_rect(tree: &AccessTree, name: &str, role: Role) -> Option { + tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)).and_then(|key| tree.bounds_of(key)) +} + +/// The role and name of each named node of `tree`. +fn nodes(tree: &AccessTree) -> Vec<(Option, String)> { + let mut nodes: Vec<(Option, String)> = + tree.keys().into_iter().filter_map(|key| tree.name_of(key).map(|name| (tree.role_of(key), name.to_owned()))).collect(); + nodes.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + nodes +} + +/// The tree the frame's pass of `viewport` produced. +fn tree_of_viewport(out: &Out, viewport: ViewportId) -> &AccessTree { + &out.trees.iter().find(|(shown, _)| *shown == viewport).expect("the viewport ran a pass").1 +} + +/// Opens the flyout of the collapsed palette's panel by a click on its icon; returns the flyout's popup window. +fn open_flyout(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect) -> ViewportId { + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let icon = node_rect(tree_of_viewport(&out, palette), PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon").center(); + for events in [vec![moved(icon)], vec![press(icon)], vec![release(icon)]] { + collapsed_frame(dock, panels, at, vec![], events); + } + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let opened = popups(dock, &out); + assert_eq!(opened.len(), 1, "the click opens one popup window: {opened:?}"); + opened[0] +} + +/// A click on the icon of a native palette collapsed to icons opens the panel's flyout in a popup OS window of its +/// own, beside the strip against its side away from the edge it keeps to, in desktop points: a palette-level window +/// with no taskbar entry that takes the focus. The flyout's body runs in the popup's pass only, as often in each +/// frame, never in the palette's. +#[trial] +fn a_click_on_an_icon_of_a_collapsed_native_palette_opens_its_flyout_in_an_os_window_beside_it() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let palette = dock.palette.expect("the palette's window opened"); + let strip = nodes(tree_of_viewport(&collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]), palette)); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let flyout = window_rect(&dock, popup); + let end = at.max.x >= FLOAT_AT.max.x - 1.0; + let outer = if end { (flyout.max.x - at.min.x).abs() } else { (flyout.min.x - at.max.x).abs() }; + assert!(outer <= 0.5, "the flyout stands against the strip's side away from its edge: {flyout:?} beside {at:?}"); + assert!(flyout.min.y >= at.min.y - 0.5 && flyout.min.y < at.max.y, "the flyout's top is level with the strip: {flyout:?}, {at:?}"); + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == popup).expect("the popup shows").1; + assert_eq!(builder.window_level, Some(egui::WindowLevel::AlwaysOnTop), "the popup stands as a palette of the active app"); + assert_eq!(builder.taskbar, Some(false), "the popup has no taskbar entry"); + assert_ne!(builder.active, Some(false), "the flyout takes the focus"); + assert_eq!(nodes(tree_of_viewport(&out, palette)), strip, "the palette's window shows none of the flyout"); + assert!(!tree_of_viewport(&out, popup).keys().is_empty(), "the popup window shows the flyout"); + let runs = |probe: &mut BodyProbe, dock: &mut NativeDock, at: &mut Rect| { + probe.0.clear(); + collapsed_frame(dock, probe, at, vec![], vec![]); + std::mem::take(&mut probe.0) + }; + let (first, second) = (runs(&mut probe, &mut dock, &mut at), runs(&mut probe, &mut dock, &mut at)); + assert!(!first.is_empty() && first.iter().all(|viewport| *viewport == popup), "the body runs in the popup's pass: {first:?}"); + assert_eq!(first.len(), second.len(), "the body runs as often in each frame"); +} + +/// The pointer rests on the double arrow of a collapsed native palette past the tooltip delay: the frame that follows. +fn hovered_arrow(dock: &mut NativeDock, at: &mut Rect) -> (Out, Rect) { + let end = at.max.x >= FLOAT_AT.max.x - 1.0 && at.min.x > FLOAT_AT.min.x + 1.0; + let arrow = Pos2::new(if end { at.width() - 4.0 } else { 4.0 }, 4.0); + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![moved(arrow)]); + // The tooltip shows after its delay, at 60 frames a second. + let frames = (craft_ui::contract::tooltip::DELAY * 60.0).ceil() as usize + 2; + for _ in 0..frames { + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + } + let out = collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let name = tree_of_viewport(&out, palette).keys().into_iter().find_map(|key| { + let tree = tree_of_viewport(&out, palette); + tree.name_of(key) + .filter(|name| name.starts_with("Expand")) + .filter(|_| tree.role_of(key) == Some(Role::BUTTON)) + .and_then(|_| tree.bounds_of(key)) + }); + let arrow_rect = name.expect("the title row shows the double arrow"); + (out, arrow_rect) +} + +/// A native palette collapsed to icons paints the icons of its panels and no text cut by its window, also while the +/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it. +#[trial] +fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { + let (mut dock, mut at) = collapsed_palette(); + let (out, _) = hovered_arrow(&mut dock, &mut at); + let palette = dock.palette.expect("the palette's window opened"); + let tree = tree_of_viewport(&out, palette); + let window = Rect::from_min_size(Pos2::ZERO, at.size()); + let icon = node_rect(tree, PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon"); + assert!(window.contains(icon.center()), "the icon shows in the strip: {icon:?} in {window:?}"); + assert!(tree.with_role(Role::TOOLTIP).is_empty(), "no tooltip shows inside the strip"); +} + +/// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop +/// points, on one line: the window takes no focus and lets the pointer through to the palette. +#[trial] +fn a_tooltip_from_a_native_palette_opens_in_a_popup_os_window() { + let (mut dock, mut at) = collapsed_palette(); + let (out, arrow) = hovered_arrow(&mut dock, &mut at); + let shown = popups(&dock, &out); + let tip = shown + .iter() + .copied() + .find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::TOOLTIP).is_empty()) + .expect("the tooltip shows in a popup window"); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == tip).expect("the popup shows").1; + assert_eq!(builder.active, Some(false), "the tooltip's window takes no focus"); + assert_eq!(builder.mouse_passthrough, Some(true), "the pointer passes through the tooltip's window"); + let rect = window_rect(&dock, tip); + assert!(rect.min.y >= at.min.y + arrow.max.y - 0.5, "the tooltip stands below the arrow: {rect:?}, arrow {arrow:?} in {at:?}"); + assert!(rect.width() > at.width() && rect.height() < rect.width(), "the tooltip's text runs on one line, wider than the strip: {rect:?}"); +} + +/// A press in the main window closes the flyout a collapsed native palette opened in a popup window. +#[trial] +fn a_press_in_the_main_window_closes_a_native_palettes_flyout() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let over = OVER_GROUP - MAIN_AT.min.to_vec2(); + for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] { + collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]); + } + // The flyout fades out, then its window closes. + let closed = (0..60).any(|_| { + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + !popups(&dock, &out).contains(&popup) + }); + assert!(closed, "the flyout's window closed"); +} + /// Palettes no smaller than `PALETTE_LEAST`. struct Least; diff --git a/crates/ui-test-kit/src/windows.rs b/crates/ui-test-kit/src/windows.rs index 300940877..01fd11af2 100644 --- a/crates/ui-test-kit/src/windows.rs +++ b/crates/ui-test-kit/src/windows.rs @@ -22,8 +22,11 @@ thread_local! { static CHILD_EVENTS: RefCell> = const { RefCell::new(Vec::new()) }; /// The files hovering over and dropped on the child's window in the next child pass. static CHILD_FILES: RefCell<(Vec, Vec)> = const { RefCell::new((Vec::new(), Vec::new())) }; - /// The window facts every child pass reports. + /// The window facts every child opened from the root reports. static CHILD_INFO: RefCell = RefCell::new(ViewportInfo::default()); + /// The window facts of each child opened from another child (a popup window): it opens where its builder puts it + /// and follows its own commands. + static OWN_INFO: RefCell> = const { RefCell::new(Vec::new()) }; /// The window facts the root reports. static ROOT_INFO: RefCell = RefCell::new(ViewportInfo::default()); /// The children whose windows are open: those that ran a pass and are still shown. Like an integration, every pass's @@ -43,14 +46,30 @@ thread_local! { /// Seconds between two frames. const FRAME_SECONDS: f64 = 1.0 / 60.0; +/// Runs `f` on the facts `id` reports: its own for a child opened from another child, else the ones every child +/// opened from the root shares. +fn with_facts(id: ViewportId, f: impl FnOnce(&mut ViewportInfo) -> R) -> R { + let own = OWN_INFO.with(|own| { + let mut own = own.borrow_mut(); + own.iter().position(|(held, _)| *held == id).map(|at| own.swap_remove(at)) + }); + match own { + Some((_, mut info)) => { + let out = f(&mut info); + OWN_INFO.with(|own| own.borrow_mut().push((id, info))); + out + } + None => CHILD_INFO.with(|info| f(&mut info.borrow_mut())), + } +} + /// The window system's answer to a move or a resize: the children's facts follow the commands (the fake window -/// has no decoration, so its inner and outer rects are one). Every child shares one set of facts. +/// has no decoration, so its inner and outer rects are one). The children opened from the root share one set of facts. fn os_applies(id: ViewportId, command: &ViewportCommand) { if id == ViewportId::ROOT { return; } - CHILD_INFO.with(|info| { - let mut info = info.borrow_mut(); + with_facts(id, |info| { let current = info.outer_rect.or(info.inner_rect).unwrap_or_else(|| Rect::from_min_size(Pos2::ZERO, CHILD_SIZE)); let moved = match command { ViewportCommand::OuterPosition(pos) => Rect::from_min_size(*pos, current.size()), @@ -75,26 +94,40 @@ fn keep_commands(output: &FullOutput) { } /// The window facts of every window the integration knows: the root and the children that ran, each with the -/// facts the trial gave it. -fn all_viewports(child: ViewportInfo) -> egui::ViewportIdMap { +/// facts the trial gave it or its own. +fn all_viewports() -> egui::ViewportIdMap { let mut all = egui::ViewportIdMap::default(); all.insert(ViewportId::ROOT, ROOT_INFO.with(|info| info.borrow().clone())); CHILDREN.with(|children| { for id in children.borrow().iter() { - all.insert(*id, child.clone()); + all.insert(*id, with_facts(*id, |info| info.clone())); } }); all } -/// Patches the window of `id` with `builder`, as an integration does before the child's pass: the fields that -/// changed go to the window as commands. The first builder opens the window. -fn patch_window(id: ViewportId, builder: ViewportBuilder) { +/// Patches the window of `ids.this` with `builder`, as an integration does before the child's pass: the fields that +/// changed go to the window as commands. The first builder opens the window; a window opened from another child opens +/// where the builder puts it, with focus unless the builder opens it inactive. +fn patch_window(ids: egui::ViewportIdPair, builder: ViewportBuilder) { + let id = ids.this; let commands = BUILDERS.with(|kept| { let mut kept = kept.borrow_mut(); match kept.iter_mut().find(|(held, _)| *held == id) { Some((_, window)) => window.patch(builder).0, None => { + if ids.parent != ViewportId::ROOT { + let rect = Rect::from_min_size(builder.position.unwrap_or(Pos2::ZERO), builder.inner_size.unwrap_or(CHILD_SIZE)); + let scale = CHILD_INFO.with(|info| info.borrow().native_pixels_per_point); + let info = ViewportInfo { + focused: Some(builder.active.unwrap_or(true)), + inner_rect: Some(rect), + outer_rect: Some(rect), + native_pixels_per_point: scale, + ..ViewportInfo::default() + }; + OWN_INFO.with(|own| own.borrow_mut().push((id, info))); + } kept.push((id, builder)); Vec::new() } @@ -129,12 +162,12 @@ impl egui::DroppedFile for DroppedPath { } fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { - patch_window(viewport.ids.this, viewport.builder); + patch_window(viewport.ids, viewport.builder); let mut callback = viewport.viewport_ui_cb; let events = CHILD_EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut())); let (hovered_files, dropped) = CHILD_FILES.with(|files| std::mem::take(&mut *files.borrow_mut())); let dropped_files = dropped.into_iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); - let mut info = CHILD_INFO.with(|info| info.borrow().clone()); + let mut info = with_facts(viewport.ids.this, |info| info.clone()); info.parent = Some(viewport.ids.parent); let mut input = RawInput { viewport_id: viewport.ids.this, @@ -152,7 +185,8 @@ fn render_child(ctx: &Context, viewport: egui::ImmediateViewport<'_>) { children.push(viewport.ids.this); } }); - input.viewports = all_viewports(info); + input.viewports = all_viewports(); + input.viewports.insert(viewport.ids.this, info); let mut output = ctx.run_ui(input, |ui| callback(ui)); output.textures_delta.clear(); keep_commands(&output); @@ -205,6 +239,7 @@ impl Windows { CHILD_EVENTS.with(|events| events.borrow_mut().clear()); CHILD_FILES.with(|files| *files.borrow_mut() = Default::default()); CHILD_INFO.with(|info| *info.borrow_mut() = ViewportInfo::default()); + OWN_INFO.with(|own| own.borrow_mut().clear()); CHILDREN.with(|children| children.borrow_mut().clear()); COMMANDS.with(|kept| kept.borrow_mut().clear()); BUILDERS.with(|kept| kept.borrow_mut().clear()); @@ -217,6 +252,12 @@ impl Windows { CHILD_INFO.with(|kept| *kept.borrow_mut() = info); } + /// The window facts `viewport` reports: its own for a child opened from another child, else those + /// [`child_info`](Self::child_info) gave. + pub fn facts(&self, viewport: ViewportId) -> ViewportInfo { + with_facts(viewport, |info| info.clone()) + } + /// The window facts the root viewport reports from now on. pub fn root_info(&self, info: ViewportInfo) { *self.root_info.borrow_mut() = info; @@ -258,11 +299,15 @@ impl Windows { now.get() })); ROOT_INFO.with(|info| *info.borrow_mut() = self.root_info.borrow().clone()); - input.viewports = all_viewports(CHILD_INFO.with(|info| info.borrow().clone())); + input.viewports = all_viewports(); let mut output = self.ctx.run_ui(input, ui); // A child the frame no longer shows has closed: like an integration, the kit drops its window, so later inputs - // stop listing it (and what its last pass left, such as a modal, stops counting). - CHILDREN.with(|children| children.borrow_mut().retain(|id| output.viewport_output.contains_key(id))); + // stop listing it (and what its last pass left, such as a modal, stops counting), and a window opened again + // opens anew. + let shown = |id: &ViewportId| output.viewport_output.contains_key(id); + CHILDREN.with(|children| children.borrow_mut().retain(shown)); + OWN_INFO.with(|own| own.borrow_mut().retain(|(id, _)| shown(id))); + BUILDERS.with(|kept| kept.borrow_mut().retain(|(id, _)| shown(id))); output.textures_delta.clear(); keep_commands(&output); keep_tree(&mut output, ViewportId::ROOT); From 5c6747b5d988fd9c04af51ee79a8678e286c3ab8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:31:24 +0000 Subject: [PATCH 69/89] A floating window's chrome counts the rule under its title row A floating group draws a divider rule under its title row (HeaderRegion::rule), and the container lays the rule out in a band of its own: the divider's width in whole physical pixels (0.8 pt at 125 %). DockSizes::window_chrome left that band out, so a window sized from its content (a collapsed palette, a minimized window, a stepped window) was one pixel short and cut the bottom of its last row. DockSizes::title_rule is the divider rule's band from the same token and display scale the container uses, window_chrome adds it, and FloatingGroup takes its chrome from DockSizes, so the dock and the group size the window with one value. The collapsed and minimized native palette trials check that the window fits its content exactly. --- crates/ui-panels/src/docking/floating.rs | 9 +++-- crates/ui-panels/src/docking/targets.rs | 12 ++++--- crates/ui-patterns/tests/it/docking/native.rs | 33 +++++++++++++++++-- 3 files changed, 43 insertions(+), 11 deletions(-) diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index e8f090e3d..9bc6af0d6 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -9,7 +9,7 @@ use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron}; use super::drop::{DragUnit, start_group_drag}; -use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; +use super::{DockDropTarget, DockDropped, DockSizes, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup, ResizeEdges}; @@ -369,11 +369,10 @@ impl<'a> FloatingGroup<'a> { /// Shows the group; `body` fills the area under the title row unless the group is minimized. pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { let env = Env::of(ui); - let header = title_row(&env.tokens); // A window in the app window keeps the band over its title row that a layer the user moves keeps for its top - // grip; an OS window's grips lie over its title row. - let band = if self.native.is_none() { crate::contract::grip_band(&env.tokens) } else { 0.0 }; - (self.header, self.chrome, self.rtl) = (header, header + band, env.direction.is_rtl()); + // grip; an OS window's grips lie over its title row. The rule under the title row takes a band of its own. + let sizes = DockSizes::style(&StyleCx::of_env(ui.ctx(), &env)); + (self.header, self.chrome, self.rtl) = (sizes.title_row, sizes.window_chrome(self.native.is_none()), env.direction.is_rtl()); let mount = self.mount(); self.props = self.props.mount(mount); let minimized = self.minimized; diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index fc0e75a51..c396eb325 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -7,7 +7,7 @@ use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; -use crate::style::StyleCx; +use crate::style::{RuleKind, StyleCx}; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; use egui::{Context, Id, Pos2, Rect, Vec2}; @@ -53,6 +53,9 @@ pub struct DockSizes { pub bar: f32, /// The height of a floating window's title row, which is the bar of the column the window holds. pub title_row: f32, + /// The band of the divider rule a floating window draws under its title row, in points on the running display: + /// the rule's width in whole physical pixels, as the container lays it out in a band of its own. + pub title_rule: f32, /// The band a floating window in the app window keeps clear over its title row for its top grip /// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's /// height less its chrome ([`Self::window_chrome`]). @@ -96,6 +99,7 @@ impl DockSizes { strip: size.panel_header, bar: size.control.sm, title_row: super::floating::title_row(cx.tokens), + title_rule: cx.rule(RuleKind::Divider).width.points(cx.frame_ctx().pixels_per_point()), top_band: crate::contract::grip_band(cx.tokens), least: size.panel_header, reach: size.hit.target, @@ -106,10 +110,10 @@ impl DockSizes { } } - /// The height above a floating window's body: its title row and, for a window in the app window (`in_app`), the - /// band over it. + /// The height above a floating window's body: its title row, the rule under it and, for a window in the app + /// window (`in_app`), the band over it. pub fn window_chrome(&self, in_app: bool) -> f32 { - self.title_row + if in_app { self.top_band } else { 0.0 } + self.title_row + self.title_rule + if in_app { self.top_band } else { 0.0 } } /// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None` diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 21860735c..c81605020 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -250,6 +250,8 @@ struct NativeDock { builder: Option, /// The palette's window: the first child window the dock opened. palette: Option, + /// The tree the palette window's pass produced in the last frame. + palette_tree: Option, } impl NativeDock { @@ -270,7 +272,7 @@ impl NativeDock { windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])); - let mut dock = NativeDock { windows, workspace, stepped, builder: None, palette: None }; + let mut dock = NativeDock { windows, workspace, stepped, builder: None, palette: None, palette_tree: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -295,6 +297,7 @@ impl NativeDock { self.palette = out.builders.iter().map(|(viewport, _)| *viewport).find(|viewport| *viewport != ViewportId::ROOT); } let palette = self.palette; + self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree); for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { @@ -747,6 +750,9 @@ fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_he follow(&mut dock, &mut at, 3); let strips = at; assert!(strips.height() < expanded.y / 4.0, "{os:?}: the window shrinks to its title row and strip: {strips:?}"); + if let Err(fit) = fits_exactly(dock.palette_tree.as_ref().expect("the palette ran a pass"), strips.size(), Role::TAB_LIST) { + panic!("{os:?}: the minimized window fits its title row and strip: {fit}"); + } assert_eq!((strips.min, strips.width()), (FLOAT_AT.min, expanded.x), "{os:?}: at its place and width"); assert_eq!(recorded(&dock), expanded, "{os:?}: minimized, the model keeps the expanded size"); let builder = dock.builder.clone().expect("the palette's window opened"); @@ -867,6 +873,25 @@ fn node_rect(tree: &AccessTree, name: &str, role: Role) -> Option { tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)).and_then(|key| tree.bounds_of(key)) } +/// How far a node's edge may stray from the window's for float rounding: far under a pixel at any scale. +const FIT_ROUNDING: f32 = 0.05; + +/// Whether a window `size` big fits what its pass shows in `tree` exactly: every node lies inside it, and the lowest +/// node of `role` ends at its bottom, within float rounding. +fn fits_exactly(tree: &AccessTree, size: Vec2, role: Role) -> Result<(), String> { + let window = Rect::from_min_size(Pos2::ZERO, size); + let outside: Vec = + tree.keys().into_iter().filter_map(|key| tree.bounds_of(key)).filter(|rect| !window.expand(FIT_ROUNDING).contains_rect(*rect)).collect(); + let bottom = tree.with_role(role).into_iter().filter_map(|key| tree.bounds_of(key)).map(|rect| rect.max.y).fold(f32::MIN, f32::max); + if !outside.is_empty() { + return Err(format!("nodes past the {size:?} window: {outside:?}")); + } + if (bottom - size.y).abs() > FIT_ROUNDING { + return Err(format!("the content ends at {bottom}, the {size:?} window at {}", size.y)); + } + Ok(()) +} + /// The role and name of each named node of `tree`. fn nodes(tree: &AccessTree) -> Vec<(Option, String)> { let mut nodes: Vec<(Option, String)> = @@ -951,7 +976,8 @@ fn hovered_arrow(dock: &mut NativeDock, at: &mut Rect) -> (Out, Rect) { } /// A native palette collapsed to icons paints the icons of its panels and no text cut by its window, also while the -/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it. +/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it, and the +/// window fits the title row, its rule and the icons exactly. #[trial] fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { let (mut dock, mut at) = collapsed_palette(); @@ -962,6 +988,9 @@ fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { let icon = node_rect(tree, PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon"); assert!(window.contains(icon.center()), "the icon shows in the strip: {icon:?} in {window:?}"); assert!(tree.with_role(Role::TOOLTIP).is_empty(), "no tooltip shows inside the strip"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons: {fit}"); + } } /// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop From 7b104b7d6be24b47f513e9430dab41e7f3c9fd93 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:31:50 +0000 Subject: [PATCH 70/89] Color, Actions and scope panel states derive MemoProps and PlainData, so an app can pass them as memo view props --- crates/automation/src/ui/actions/panel.rs | 8 +++-- crates/color-ui/src/ui/panel.rs | 32 +++++++++++++++++-- crates/imaging/src/ui/histogram/data.rs | 2 +- .../imaging/src/ui/scopes/panel/settings.rs | 18 +++++++++-- 4 files changed, 50 insertions(+), 10 deletions(-) diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 8429d5025..179ff8a17 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -60,7 +60,9 @@ impl ActionsSettings { /// The Actions panel's persisted section: Button Mode and the collapsed sets. /// Selection and expansion are not persisted. -#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ActionsSettings { @@ -72,7 +74,7 @@ pub struct ActionsSettings { /// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at /// a time) and the list's key. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum ActionSelection { /// The set header of this name. @@ -89,7 +91,7 @@ pub enum ActionSelection { /// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder) /// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the /// app clears `selected` (the panel cannot tell which rows the delete removed). -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ActionsPanelState { /// The persisted section. diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 76c85e775..1326059f6 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -62,7 +62,19 @@ craft_ui::words! { /// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default; /// the theme never changes it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelMode { @@ -129,7 +141,19 @@ impl ColorPanelMode { } /// The ramp under the sliders. Shift-click on the ramp cycles them in this order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelRamp { @@ -179,7 +203,9 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { diff --git a/crates/imaging/src/ui/histogram/data.rs b/crates/imaging/src/ui/histogram/data.rs index 6588b6aa6..a8521da70 100644 --- a/crates/imaging/src/ui/histogram/data.rs +++ b/crates/imaging/src/ui/histogram/data.rs @@ -207,7 +207,7 @@ impl HistogramData { } /// A range of whole levels (bin positions) a plot has selected, both ends included. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct LevelRange { /// The first level. diff --git a/crates/imaging/src/ui/scopes/panel/settings.rs b/crates/imaging/src/ui/scopes/panel/settings.rs index 6d14f3fb4..a61305622 100644 --- a/crates/imaging/src/ui/scopes/panel/settings.rs +++ b/crates/imaging/src/ui/scopes/panel/settings.rs @@ -4,7 +4,19 @@ use crate::ui::histogram::LevelRange; use crate::ui::scopes::clipping::{ClippingDiagnostic, ClippingMode, ClippingWarnings}; /// The panel's view (its menu's Compact, Expanded and All Channels View). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ScopeView { @@ -20,7 +32,7 @@ pub enum ScopeView { /// The scope panel's persisted section: the app keeps it with its preferences (PhotoCraft's /// `histogramPanel` and `filter.cameraRaw.scope`). Unknown fields are ignored, missing ones take /// their defaults. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ScopeSettings { @@ -93,7 +105,7 @@ impl ScopeSettings { /// What the panel keeps for the app between passes: the persisted settings and the selected /// level range (not persisted). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ScopePanelState { /// The persisted section. From c10470b3f0f8fd37a4022295fc8b0e07df267113 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:43:11 +0000 Subject: [PATCH 71/89] An OS dock window's chrome is sized at its own display's scale The rule under a floating window's title row takes the divider's width in whole physical pixels on the display the window lays out on. An OS window on another monitor (a laptop at 2x with an external display at 1x) laid its rule out at its own scale while the dock sized it at the main window's, so the window was half a point short and cut its last row. DockSizes keeps the rule's width and the display scale it is for, and at_scale gives the sizes at an OS window's own scale (native::pixels_per_point: its monitor's scale from the window facts with the app's zoom). DockArea::windows sizes each OS window's chrome at that scale and hands it to FloatingGroup; in-app windows keep the main window's. A window's caller place now counts as a change when it moves the window by more than half a physical pixel on its display, not half a point, so a window that changes displays takes a one-pixel correction at 2x. --- .../src/runtime/windows/viewport.rs | 24 +++++++++++------- crates/ui-panels/src/docking/floating.rs | 13 ++++++++++ crates/ui-panels/src/docking/native.rs | 6 +++++ crates/ui-panels/src/docking/targets.rs | 23 ++++++++++++----- crates/ui-patterns/src/patterns/dock/area.rs | 16 ++++++++++-- crates/ui-patterns/tests/it/docking/native.rs | 25 ++++++++++++++++++- 6 files changed, 89 insertions(+), 18 deletions(-) diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index cc337a081..b621430c3 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -172,11 +172,10 @@ pub(crate) fn show_popup(ctx: &Context, open: &PopupOpen<'_>, body: impl FnMut(& pub(crate) fn place_popup(ctx: &Context, id: Id, rect: Rect) { let viewport = viewports::viewport_id(id); let known = PerViewport::::with(ctx, viewport, |record| record.known); - let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING; - if known.is_none_or(|known| differs(rect.min - known.min)) { + if known.is_none_or(|known| differs(ctx, viewport, rect.min - known.min)) { act(ctx, viewport, WindowAction::SetOuterPosition(rect.min)); } - if known.is_none_or(|known| differs(rect.size() - known.size())) { + if known.is_none_or(|known| differs(ctx, viewport, rect.size() - known.size())) { act(ctx, viewport, WindowAction::SetInnerSize(rect.size())); } PerViewport::::with(ctx, viewport, |record| record.known = Some(rect)); @@ -226,9 +225,17 @@ pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool { && PerViewport::::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none()) } -/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a -/// placement records the position in pixels. -const ROUNDING: f32 = 0.5; +/// How far a caller's place may differ from the known place before it is a change, in physical pixels of the window's +/// display: the OS rounds to pixels, and a placement records the position in pixels. +const ROUNDING_PX: f32 = 0.5; + +/// Whether `delta`, in points, moves the window `viewport` by more than rounding on its display: a whole pixel on +/// a 2x display is half a point. +fn differs(ctx: &Context, viewport: ViewportId, delta: Vec2) -> bool { + let facts = PerViewport::::with(ctx, viewport, |record| record.facts); + let scale = facts.and_then(|facts| super::host::scale_of(ctx, &facts)).unwrap_or(1.0); + delta.x.abs() * scale > ROUNDING_PX || delta.y.abs() * scale > ROUNDING_PX +} /// The place of a window with `facts`: its outer top-left corner and its inner size. fn place_of(facts: &viewports::Facts) -> Option { @@ -257,11 +264,10 @@ fn keep_placed(ctx: &Context, viewport: ViewportId, pos: Option, size: Opt (record.known, state || record.moved_pointer.is_some()) }); let Some(known) = known.filter(|_| !held) else { return }; - let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING; - if let Some(pos) = pos.filter(|pos| differs(*pos - known.min)) { + if let Some(pos) = pos.filter(|pos| differs(ctx, viewport, *pos - known.min)) { act(ctx, viewport, WindowAction::SetOuterPosition(pos)); } - if let Some(size) = size.filter(|size| differs(*size - known.size())) { + if let Some(size) = size.filter(|size| differs(ctx, viewport, *size - known.size())) { act(ctx, viewport, WindowAction::SetInnerSize(size)); } } diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 9bc6af0d6..fc6369b3b 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -277,6 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, + /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the + /// running window's. + scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, /// Takes the drops released on the group, on the group's own layer. @@ -323,6 +326,7 @@ impl<'a> FloatingGroup<'a> { rtl: false, placed: None, collapsed_width: None, + scale: None, start_drag: None, take_drop: None, moving: false, @@ -359,6 +363,14 @@ impl<'a> FloatingGroup<'a> { self } + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome is sized at that scale. + #[must_use] + pub fn scale(mut self, pixels_per_point: f32) -> Self { + self.scale = Some(pixels_per_point); + self + } + /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { @@ -372,6 +384,7 @@ impl<'a> FloatingGroup<'a> { // A window in the app window keeps the band over its title row that a layer the user moves keeps for its top // grip; an OS window's grips lie over its title row. The rule under the title row takes a band of its own. let sizes = DockSizes::style(&StyleCx::of_env(ui.ctx(), &env)); + let sizes = self.scale.map_or(sizes, |scale| sizes.at_scale(scale)); (self.header, self.chrome, self.rtl) = (sizes.title_row, sizes.window_chrome(self.native.is_none()), env.direction.is_rtl()); let mount = self.mount(); self.props = self.props.mount(mount); diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index 568e3d011..4ef261889 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -46,6 +46,12 @@ pub fn opens_os_windows(ctx: &Context, config: &DockConfig) -> bool { config.native_windows && host.opens_windows() && host.positions_reported() } +/// The display scale the OS window `viewport` lays out at: its monitor's scale with the app's zoom, as the window +/// reported it (`WindowHost::facts`). `None` before it reported one. +pub fn pixels_per_point(ctx: &Context, viewport: ViewportId) -> Option { + WindowHost::of(ctx).facts(viewport)?.scale.map(|scale| scale * ctx.zoom_factor()) +} + /// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool /// window (a palette level, no taskbar entry). pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec { diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index c396eb325..634716f87 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -7,7 +7,7 @@ use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; -use crate::style::{RuleKind, StyleCx}; +use crate::style::{RuleKind, RuleWidth, StyleCx}; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; use egui::{Context, Id, Pos2, Rect, Vec2}; @@ -53,9 +53,12 @@ pub struct DockSizes { pub bar: f32, /// The height of a floating window's title row, which is the bar of the column the window holds. pub title_row: f32, - /// The band of the divider rule a floating window draws under its title row, in points on the running display: - /// the rule's width in whole physical pixels, as the container lays it out in a band of its own. - pub title_rule: f32, + /// The divider rule a floating window draws under its title row, which the container lays out in a band of its + /// own: the rule's width in whole physical pixels on the window's display ([`Self::pixels_per_point`]). + pub title_rule: RuleWidth, + /// The display scale the sizes that depend on it are for: the running window's, or with [`Self::at_scale`] an OS + /// window's own. + pub pixels_per_point: f32, /// The band a floating window in the app window keeps clear over its title row for its top grip /// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's /// height less its chrome ([`Self::window_chrome`]). @@ -99,7 +102,8 @@ impl DockSizes { strip: size.panel_header, bar: size.control.sm, title_row: super::floating::title_row(cx.tokens), - title_rule: cx.rule(RuleKind::Divider).width.points(cx.frame_ctx().pixels_per_point()), + title_rule: cx.rule(RuleKind::Divider).width, + pixels_per_point: cx.frame_ctx().pixels_per_point(), top_band: crate::contract::grip_band(cx.tokens), least: size.panel_header, reach: size.hit.target, @@ -113,7 +117,14 @@ impl DockSizes { /// The height above a floating window's body: its title row, the rule under it and, for a window in the app /// window (`in_app`), the band over it. pub fn window_chrome(&self, in_app: bool) -> f32 { - self.title_row + self.title_rule + if in_app { self.top_band } else { 0.0 } + self.title_row + self.title_rule.points(self.pixels_per_point) + if in_app { self.top_band } else { 0.0 } + } + + /// The sizes for a window on a display of `pixels_per_point`: an OS window lays out at its own monitor's scale. + #[must_use] + pub fn at_scale(mut self, pixels_per_point: f32) -> Self { + self.pixels_per_point = pixels_per_point; + self } /// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None` diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 4ace220ce..f5f83891d 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1222,6 +1222,14 @@ impl Pass<'_, P> { let dock = scene.dock.with(("floating", window.id)); let group_id = dock.with("window"); let opening = native::opening(&ctx, scene.config, window, &specs, group_id); + // An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the + // main window's. + let scale = opening + .spec + .as_ref() + .and_then(|_| WindowHost::of(&ctx).viewport_of(group_id)) + .and_then(|viewport| native::pixels_per_point(&ctx, viewport)); + let window_sizes = scale.map_or(scene.sizes, |scale| scene.sizes.at_scale(scale)); let movable = rights.iter().all(|rights| rights.movable); // The title row is the column's bar: its double arrow and Close; the menu opens from a context request on // its band. @@ -1270,6 +1278,9 @@ impl Pass<'_, P> { .takes_drops(target, &dropped) .command_scope(DockCommands::SCOPE) .id(group_id); + if let Some(scale) = scale { + group = group.scale(scale); + } group = match opening.spec.clone() { Some(window_spec) => group.native(window_spec), None => group.bounds(scene.bounds), @@ -1303,8 +1314,9 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } - // The height above the window's body: the title row, and in the app window the band over it. - let chrome = scene.sizes.window_chrome(opening.spec.is_none()); + // The height above the window's body at its scale: the title row, the rule under it, and in the app window + // the band over it. + let chrome = window_sizes.window_chrome(opening.spec.is_none()); // A resize of a window whose column has steps: the steps it sets, and the window's rect at them. let resized = output .placed diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index c81605020..6d71e005f 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -834,9 +834,12 @@ const COLLAPSED_SCALE: f32 = 1.25; /// A native palette collapsed to icons on Windows at 125 %, and the rect its OS window shows the strip at. fn collapsed_palette() -> (NativeDock, Rect) { let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + // Both windows report the display at 125 % before the column collapses. dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); - dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE)); + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); for _ in 0..4 { collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); } @@ -993,6 +996,26 @@ fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { } } +/// A native palette on a monitor at 1x while the main window is on one at 2x (a laptop with an external display): +/// collapsed to icons, its window fits the title row, the rule under it and the icons exactly at its own scale. +#[trial] +fn a_collapsed_native_palette_on_a_1x_monitor_beside_a_2x_main_window_fits_its_icons_exactly() { + let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, 2.0)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, 1.0)); + dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..4 { + let commands = dock.frame(vec![]).1; + at = placed_by(&commands, at); + dock.windows.child_info(scaled(true, at, 1.0)); + } + let tree = dock.palette_tree.as_ref().expect("the palette ran a pass"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons at its own scale: {fit}"); + } +} + /// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop /// points, on one line: the window takes no focus and lets the pointer through to the palette. #[trial] From 8d7b0664881db005cdcb9ca7bcdd822e78a2fabf Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:49:31 +0000 Subject: [PATCH 72/89] Sizing trial: name the dialog opener type (clippy type_complexity) --- crates/ui-patterns/tests/it/form_dialogs/hosted.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index caea87ce1..74646a479 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -465,13 +465,16 @@ fn image_size_alt_digits_pick_resample_without_typing_into_a_field() { assert_eq!(resample(&host), Some(json!("nearestNeighbor")), "Alt+7 picks a listed method"); } +/// Opens a dialog on a host. +type Opener = fn(&mut DialogHost); + /// Image Size's and Canvas Size's Width and Height rows (a stack of fields beside the link) show as they measured, at /// 1x and 1.25x (#15483, #15538): each label sits beside its field, each field and unit select is as tall as a direct /// row's control (`reference`), and Height's label starts under Width's controls. #[trial] fn sizing_dialogs_show_width_and_height_beside_their_labels_at_full_height() { for scale in [1.0, 1.25] { - let opens: [(fn(&mut DialogHost), &str); 2] = [ + let opens: [(Opener, &str); 2] = [ ( |host| { host.open(image_size()); From 1f07fbe259e200c24a678c13087d5863dbe526bc Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:50:21 +0000 Subject: [PATCH 73/89] No hidden state in UI crates: the lint's last entries (#2336) Texture identities come from an owner-held Serials; the font picker's family data is a derived value keyed by the catalog generation; face file sizes are read at scan; the LUT scan lives in craft-cms and its rescan reads the stepped clock. --- crates/cms/src/lutfile.rs | 28 +++++++++++ crates/color-ui/src/ui/lut_picker.rs | 43 +++------------- crates/design-lint/README.md | 2 +- crates/design-lint/src/workspace.rs | 31 ++---------- crates/font-catalog/src/catalog.rs | 10 ++++ crates/font-catalog/src/scan.rs | 10 ++++ crates/font-manager/src/panel/faces.rs | 2 +- crates/font-manager/src/picker.rs | 24 ++++++--- crates/font-manager/src/picker/rank.rs | 41 ++++++--------- crates/font-manager/src/picker/rows.rs | 14 +++--- crates/font-manager/tests/it/picker.rs | 50 +++++++++++++++++-- .../imaging/src/ui/transform_preview/mod.rs | 6 ++- .../src/ui/transform_preview/stories.rs | 3 +- .../src/ui/transform_preview/textures.rs | 23 ++++----- crates/imaging/tests/it/transform_preview.rs | 14 +++--- .../src/canvas_controls/brush/mod.rs | 2 + .../src/canvas_controls/brush/stories.rs | 12 +++-- .../src/canvas_controls/brush/trail.rs | 29 ++++------- .../src/canvas_controls/brush/trials.rs | 48 ++++++++++++++++++ .../src/canvas_controls/outline/hover.rs | 9 ++-- .../src/canvas_controls/outline/mod.rs | 8 +-- .../src/canvas_controls/outline/stories.rs | 6 ++- .../tests/it/canvas_controls/brush.rs | 5 +- crates/ui-contract/src/primitives/mod.rs | 6 +-- .../src/primitives/textures/mod.rs | 2 +- .../src/primitives/textures/store.rs | 16 ++++++ 26 files changed, 269 insertions(+), 175 deletions(-) create mode 100644 crates/ui-canvas/src/canvas_controls/brush/trials.rs diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index b640c8dd7..bdc13e7f7 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -124,6 +124,34 @@ impl Format { } } +/// Most files [`list_folder`] lists. +const MAX_FILES: usize = 500; +/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. +const MAX_BYTES: u64 = 64 << 20; + +/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name +/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files +/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. +pub fn list_folder(dir: &std::path::Path) -> Vec<(String, std::path::PathBuf)> { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut out: Vec<(String, std::path::PathBuf)> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); + if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { + return None; + } + let path = entry.path(); + let meta = std::fs::metadata(&path).ok()?; + (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) + }) + .collect(); + out.sort_by_key(|(name, _)| name.to_lowercase()); + out.truncate(MAX_FILES); + out +} + /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { parse_as(Format::detect(file_name, bytes), bytes) diff --git a/crates/color-ui/src/ui/lut_picker.rs b/crates/color-ui/src/ui/lut_picker.rs index afdb6a71d..2937f1207 100644 --- a/crates/color-ui/src/ui/lut_picker.rs +++ b/crates/color-ui/src/ui/lut_picker.rs @@ -4,8 +4,7 @@ //! [`Files`](craft_host::Files) and reads and parses it as a [`Jobs`](craft_host::Jobs) job. use std::path::{Path, PathBuf}; -use std::sync::{Arc, OnceLock}; -use std::time::Instant; +use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, Proposal, Sense}; use craft_cms::lutfile::{LutError, LutFile}; @@ -16,6 +15,7 @@ use craft_ui::contract::{ }; use craft_ui::pickers::Select; use craft_ui::runtime::env::Label; +use craft_ui::runtime::frame; use craft_ui::style::{ComponentStyle, StyleCx}; use egui::{Response, Vec2}; @@ -154,12 +154,6 @@ impl Default for Parsed { } } -/// The seconds since the first scan of the process, for the rescan interval. -fn seconds() -> u64 { - static START: OnceLock = OnceLock::new(); - START.get_or_init(Instant::now).elapsed().as_secs() -} - /// A select of LUTs. /// /// - Rows: Load 3D LUT…, None, the eight built-in looks, the LUT folder's files by name (in the language's @@ -269,9 +263,11 @@ impl Component for LutPicker<'_> { state = LutState { folder: self.folder.clone(), load: state.load, ..LutState::default() }; } if let Some(folder) = self.folder.clone() { - let key = ("lut-scan", folder.clone(), seconds() / RESCAN); + let key = ("lut-scan", folder.clone(), frame::stepped_clock(&cx.response.ctx, RESCAN as f64) as u64 / RESCAN); let started = folder.clone(); - if let Pending::Ready(found) = cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(list_folder(&started))))) { + if let Pending::Ready(found) = + cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(craft_cms::lutfile::list_folder(&started))))) + { let mut files = (**found).clone(); cx.env.collator().sort_by_key(&mut files, |(name, _)| name.as_str()); state.files = Arc::new(files); @@ -378,30 +374,3 @@ fn builtin_name(words: &LutWords, id: &str) -> Label { fn file_name(path: &Path) -> String { path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) } -/// Most files [`list_folder`] lists. -const MAX_FILES: usize = 500; -/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. -const MAX_BYTES: u64 = 64 << 20; - -/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name -/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files -/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. -fn list_folder(dir: &Path) -> FolderFiles { - let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; - let mut out: FolderFiles = entries - .flatten() - .filter_map(|entry| { - let name = entry.file_name().into_string().ok()?; - let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); - if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { - return None; - } - let path = entry.path(); - let meta = std::fs::metadata(&path).ok()?; - (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) - }) - .collect(); - out.sort_by_key(|(name, _)| name.to_lowercase()); - out.truncate(MAX_FILES); - out -} diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 7751a0f6c..20ac95787 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__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` | +| `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 test-data cache that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 22cafcd4f..93407230a 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -138,8 +138,8 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ ]; /// 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. +/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact, environment key or test-data +/// cache that covers it. A new item in these files is flagged. const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // Compile-time registry discovery reads the defining crate's source, never a view input. ("crates/ui-macros/src/registry.rs", FS), @@ -200,30 +200,8 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ ("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 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. + // A cache of pure test data: MockImage is used only by stories and trials. ("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`. @@ -405,9 +383,6 @@ impl RuleScope for WorkspaceScope { 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")); } diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 10663e6af..a3464fed4 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -307,6 +307,7 @@ type FamilyLoad = Arc>>; /// Each family's files load once ([`Catalog::load_family`]): other threads asking for the same /// family wait for that load, other families load at the same time. pub struct Catalog { + id: u64, env: FontEnv, config: RwLock, index: RwLock>, @@ -331,7 +332,9 @@ impl Catalog { /// A catalog of the fonts installed on the system `env` describes, the font store, and the /// files the platform's font service lists (with the `system` feature). pub fn new(env: FontEnv) -> Self { + static NEXT_ID: AtomicU64 = AtomicU64::new(1); Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), env, config: RwLock::new(Config { app_dirs: Vec::new(), listers: Vec::new(), font_service: cfg!(feature = "system") }), index: RwLock::new(Arc::new(Index::default())), @@ -475,6 +478,13 @@ impl Catalog { Watch { stop } } + /// The catalog's identity: unique among the catalogs of the process, fixed at construction. Clones of the `Arc` + /// share it. A holder of derived data keys it by the id and the [`generation`](Catalog::generation), which counts + /// changes of this catalog only. + pub fn id(&self) -> u64 { + self.id + } + /// Counts the catalog's changes: each scan, and each face added or removed. pub fn generation(&self) -> u64 { self.generation.load(Ordering::Acquire) diff --git a/crates/font-catalog/src/scan.rs b/crates/font-catalog/src/scan.rs index 9afd1ac88..5466024e5 100644 --- a/crates/font-catalog/src/scan.rs +++ b/crates/font-catalog/src/scan.rs @@ -98,6 +98,9 @@ pub struct FaceInfo { pub code_pages: [u32; 2], /// The file the face is in; `None` for a face added as bytes. pub path: Option, + /// The size in bytes of the file when it was scanned; `None` for a face added as bytes. A caller that draws with the + /// face checks it before loading, so no file system read happens while it paints. + pub file_bytes: Option, /// The face's number in its file: its index in a collection (0 in a single font), or for a /// Mac suitcase font the number of its `sfnt` resource. pub index: u32, @@ -329,6 +332,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: fs_type, code_pages, path: path.map(Path::to_path_buf), + file_bytes: None, index, source, blob: None, @@ -430,9 +434,11 @@ pub(crate) fn file_faces(path: &Path, max_read: u64, source: Source) -> Vec String { /// The bytes of `face` from `catalog`, unless its file is too large to draw with. fn load(catalog: &Catalog, face: &FaceInfo) -> Option { - let too_large = face.path.as_ref().and_then(|path| std::fs::metadata(path).ok()).is_some_and(|meta| meta.len() > MAX_FILE_BYTES); + let too_large = face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES); if too_large { return None; } diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index dea1d1d7b..1521d943b 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -28,7 +28,8 @@ use egui::{Rect, Response, Vec2}; use serde::{Deserialize, Serialize}; use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts}; -use rank::{Info, infos, shown_name}; +pub use rank::FamilyInfos; +use rank::{Info, shown_name}; craft_ui::words! { /// The picker's words, English by default. @@ -288,9 +289,11 @@ pub struct FamilyRow { /// The families `listing` would show, in list order: recents first (when the query is empty and no filter is on), /// then the matching families, the best match first and ties in the order of `language` (its code, `ja`, `pt-BR`). -/// For apps that draw their own list from the picker's filtering. +/// For apps that draw their own list from the picker's filtering. `infos` is [`FamilyInfos::of`] of `catalog`, built +/// again by the app when the catalog's generation moves. pub fn family_rows( catalog: &Arc, + infos: &FamilyInfos, query: &str, settings: Option<&FontPickerSettings>, filters: &FontFilters, @@ -299,7 +302,12 @@ pub fn family_rows( ) -> Vec { let (folder, collator) = (craft_i18n::Folder::new(language), craft_i18n::Collator::new(language)); let listing = rank::Listing { query, settings, filters, current, language, served: &[] }; - rank::list(catalog, &infos(catalog), &listing, &rank::Language { folder: &folder, collator: &collator }, true).0 + rank::list(catalog, infos, &listing, &rank::Language { folder: &folder, collator: &collator }, true).0 +} + +/// The family data of `catalog` for the component `cx`: kept across passes while the catalog and its generation are unchanged. +pub(super) fn infos_of(ctx: &egui::Context, id: egui::Id, catalog: &Catalog) -> Arc { + craft_ui::runtime::derived::derived(ctx, id, &(catalog.id(), catalog.generation()), || FamilyInfos::of(catalog)) } /// How a [`FontPicker`] lays out its list. @@ -380,7 +388,7 @@ fn text_key() -> TextKey { /// The family field's text: the family's name in the interface language, and a typed name read back as a family. #[derive(Clone)] struct FamilyCodec { - infos: Arc, + infos: Arc, language: String, /// A typed name that is no installed family is a value too (Word's font box applies it as typed). free: bool, @@ -566,13 +574,13 @@ impl<'a> FontPicker<'a> { Some(Label::from(note)) } - fn codec(&self, env: &EnvView<'_>) -> FamilyCodec { - FamilyCodec { infos: infos(self.catalog), language: ui_language(env), free: self.kind == FontPickerKind::Plain } + fn codec(&self, infos: Arc, env: &EnvView<'_>) -> FamilyCodec { + FamilyCodec { infos, language: ui_language(env), free: self.kind == FontPickerKind::Plain } } /// The families in list order without filters or recents, which the arrows and the wheel step through. fn ordered(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>) -> Vec { - let infos = infos(self.catalog); + let infos = infos_of(&cx.response.ctx, cx.id, self.catalog); let (folder, collator) = (cx.env.folder(), cx.env.collator()); let filters = FontFilters::default(); let language = ui_language(&cx.env); @@ -631,7 +639,7 @@ impl Component for FontPicker<'_> { .pointer_only("Alt+Down opens the list") .toggles(POPUP); } - let codec = self.codec(&cx.env); + let codec = self.codec(infos_of(cx.ui.ctx(), cx.id, self.catalog), &cx.env); let mut options = TextOptions::new(); options.select_on_focus = true; cx.text(text_key(), placed.text, &codec, &family, &options); diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 7d6637864..fa1f3f65a 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -2,7 +2,7 @@ //! traits read from the faces' tables, the filtered list and its order, and the sample text of a row. use std::collections::HashMap; -use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::sync::{Arc, Mutex, PoisonError}; use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines}; use craft_i18n::matcher::{Matcher, Rank}; @@ -53,8 +53,10 @@ impl Traits { } } -/// The families of one catalog generation with their traits and sample texts, filled on first use. -pub(super) struct Infos { +/// The families of one catalog generation with their traits and sample texts, filled on first use. Built by +/// [`FamilyInfos::of`] and held by the one that lists with it: the picker keeps it in a derived value keyed by the +/// catalog's generation, and an app that calls [`family_rows`](super::family_rows) keeps its own while the catalog is unchanged. +pub struct FamilyInfos { pub(super) families: HashMap, traits: Mutex>>, samples: Mutex>, @@ -78,8 +80,9 @@ fn has_arabic_sample(drawn: &dyn Fn(&str) -> bool, latin: &str, arabic: &str) -> drawn(latin) && drawn(ARABIC_CORE) && drawn(arabic) } -impl Infos { - fn build(catalog: &Catalog) -> Infos { +impl FamilyInfos { + /// The family data of `catalog` as it is now; build it again when the catalog's generation moves. + pub fn of(catalog: &Catalog) -> FamilyInfos { let mut groups: HashMap> = HashMap::new(); for face in catalog.faces().iter() { groups.entry(face.family.clone()).or_default().push(face.clone()); @@ -99,7 +102,7 @@ impl Infos { Some((family, Info { localized, format, styles: faces.len(), regular })) }) .collect(); - Infos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } + FamilyInfos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } } /// The family's traits, read from its regular face on first use. @@ -147,24 +150,6 @@ fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, arabic: &str, shown: Some(Samples { latin: first, arabic: None }) } -type CacheEntry = (Weak, u64, Arc); -static CACHE: Mutex> = Mutex::new(Vec::new()); - -/// The family data of `catalog`, rebuilt when its generation moves. -pub(super) fn infos(catalog: &Arc) -> Arc { - let generation = catalog.generation(); - let same = |w: &Weak| std::ptr::eq(w.as_ptr(), Arc::as_ptr(catalog)); - let mut cache = lock(&CACHE); - cache.retain(|(w, _, _)| w.strong_count() > 0); - if let Some((_, _, infos)) = cache.iter().find(|(w, g, _)| *g == generation && same(w)) { - return Arc::clone(infos); - } - cache.retain(|(w, _, _)| !same(w)); - let infos = Arc::new(Infos::build(catalog)); - cache.push((Arc::downgrade(catalog), generation, Arc::clone(&infos))); - infos -} - /// The upright face nearest weight 400. pub(super) fn regular_face(faces: &[FaceInfo]) -> Option<&FaceInfo> { faces.iter().min_by_key(|f| (f.italic, (f.weight - 400.0).abs() as u32)) @@ -291,7 +276,13 @@ pub(super) struct Language<'a> { /// The rows the list shows for `listing` and whether Show Similar Fonts had a reference to compare with: recents /// first (when the query is empty and no filter is on), then the matching families, the best match first and ties /// in the interface language's order. A list that is not `narrowed` has no filters and no recents. -pub(super) fn list(catalog: &Arc, infos: &Infos, listing: &Listing<'_>, language: &Language<'_>, narrowed: bool) -> (Vec, bool) { +pub(super) fn list( + catalog: &Arc, + infos: &FamilyInfos, + listing: &Listing<'_>, + language: &Language<'_>, + narrowed: bool, +) -> (Vec, bool) { let default_filters = FontFilters::default(); let filters = if narrowed { listing.filters } else { &default_filters }; let settings = listing.settings; diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index bd76e0aa5..c35f4cac9 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -22,10 +22,10 @@ use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::runtime::env::Label; use egui::Rect; -use super::rank::{Infos, Language, Listing, list, shown_name}; +use super::rank::{FamilyInfos, Language, Listing, list, shown_name}; use super::{ - FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, - ui_language, write, + FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos_of, + read, ui_language, write, }; use crate::panel::faces::{Owner, Shown, paint_sample, shown}; use craft_ui::style::DataColor; @@ -256,7 +256,7 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker /// A thumbnail painting `text` in the regular face of `family`; nothing for a family the catalog lacks or an empty /// text, and nothing until the face is loaded. -fn face_thumb<'a>(catalog: &'a Arc, infos: &'a Infos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a { +fn face_thumb<'a>(catalog: &'a Arc, infos: &'a FamilyInfos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a { move |cx, rect| { let Some(info) = infos.families.get(family) else { return }; if text.is_empty() { @@ -270,7 +270,7 @@ fn face_thumb<'a>(catalog: &'a Arc, infos: &'a Infos, family: &'a str, } /// The banner: `text` in the face of `family`, on one line cut at the end, in a picture as high as the large thumbnail. -fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &Infos, family: &str, shown_name: &str, text: &str) { +fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &FamilyInfos, family: &str, shown_name: &str, text: &str) { Picture::painter(shown_name.to_owned(), ThumbAspect::new(BANNER_ASPECT.0, BANNER_ASPECT.1), face_thumb(catalog, infos, family, text.to_owned())) .extent(PictureSize::Thumb(ThumbSize::Large)) .show(ui); @@ -278,7 +278,7 @@ fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &Infos, family: &str /// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the /// interface language, else the family key. -fn banner_shown_name(slots: &[Slot], infos: &Infos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { +fn banner_shown_name(slots: &[Slot], infos: &FamilyInfos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { let row = slots.iter().find_map(|slot| match slot { Slot::Family { row, .. } if row.family == family => Some(row.shown.clone()), _ => None, @@ -338,7 +338,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: let has_filters = filters.is_some(); let narrowing = filters.clone().unwrap_or_default(); let catalog = picker.catalog; - let infos = infos(catalog); + let infos = infos_of(&cx.response.ctx, cx.id, catalog); let language_code = ui_language(&cx.env); let (folder, collator) = (cx.env.folder(), cx.env.collator()); let listing = Listing { diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 33c4f4775..8ef2bc258 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -9,7 +9,7 @@ use craft_behavior::{PartKey, Preview}; use craft_font_manager::craft_font_catalog::{Limits, Os, Source}; use craft_font_manager::missing::MissingFontsWords; use craft_font_manager::picker::{ - FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows, + FamilyInfos, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows, }; use craft_font_manager::{Catalog, FontEnv}; use craft_ui::buttons::ControlPlace; @@ -18,7 +18,7 @@ use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::env::{Label, with_env}; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::pointer::moved; -use craft_ui::testing::{Fixture, Room, trial}; +use craft_ui::testing::{Fixture, Room, last_frame_derived_builds, trial}; use egui::{Event, Key, Modifiers}; const INTER_REGULAR: &[u8] = include_bytes!("../../../ui-contract/fonts/inter/Inter-Regular.ttf"); @@ -125,14 +125,15 @@ fn similar_fonts_put_the_current_family_first_and_leave_the_list_alone_without_a let catalog = catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR]); let mut similar = FontFilters::default(); similar.similar = true; - let rows = family_rows(&catalog, "", None, &similar, "Inter", "en"); + let infos = FamilyInfos::of(&catalog); + let rows = family_rows(&catalog, &infos, "", None, &similar, "Inter", "en"); let names: Vec<&str> = rows.iter().map(|row| row.family.as_str()).collect(); assert_eq!(names.first(), Some(&"Inter"), "the current family first, though it is not first by name"); assert!(rows.len() <= SIMILAR_COUNT); // A current family the catalog lacks has no traits: the list stays as unfiltered. - let unfiltered = family_rows(&catalog, "", None, &FontFilters::default(), "", "en"); - assert_eq!(family_rows(&catalog, "", None, &similar, "Missing", "en"), unfiltered); + let unfiltered = family_rows(&catalog, &infos, "", None, &FontFilters::default(), "", "en"); + assert_eq!(family_rows(&catalog, &infos, "", None, &similar, "Missing", "en"), unfiltered); } #[trial] @@ -360,3 +361,42 @@ fn a_squeezed_ribbon_font_box_keeps_a_short_fields_name() { assert!(squeezed > short, "the squeezed font box keeps a name field {short} wide and its arrow: {squeezed}"); assert!(squeezed <= picker_width("Inter", true) + 0.5, "and is no wider than where the room allows"); } + +/// The family data builds of the last frame. +fn family_builds(fx: &Fixture) -> u32 { + last_frame_derived_builds(fx.ctx()).iter().map(|(_, builds)| builds).sum() +} + +#[trial] +fn the_family_data_builds_when_the_catalog_changes_and_not_while_it_is_idle() { + let catalog = catalog_of(&[INTER_REGULAR]); + let (mut fx, _) = rig(Arc::clone(&catalog), vec![]); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 0, "an idle open list builds nothing"); + catalog.add_bytes(INTER_SEMIBOLD.to_vec(), Source::Bundled, &Limits::default()).expect("a font file"); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 1, "a changed catalog builds the data once, whatever reads it"); +} + +#[trial] +fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data_once() { + let (one, two) = (catalog_of(&[INTER_REGULAR]), catalog_of(&[INTER_REGULAR])); + assert_eq!(one.generation(), two.generation(), "the two catalogs count alike"); + assert_ne!(one.id(), two.id()); + let shown = Rc::new(RefCell::new(Arc::clone(&one))); + let held = Rc::clone(&shown); + let mut family = String::new(); + let mut fx = Fixture::new(move |ui| { + let catalog = Arc::clone(&held.borrow()); + FontPicker::new("Font family", Bind::bound(&mut family), &catalog).show(ui); + }); + fx.in_room(Room::Window); + fx.settle(); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 0, "the first catalog's data is kept"); + *shown.borrow_mut() = Arc::clone(&two); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once"); +} diff --git a/crates/imaging/src/ui/transform_preview/mod.rs b/crates/imaging/src/ui/transform_preview/mod.rs index 3c2af1c32..0834d3b6a 100644 --- a/crates/imaging/src/ui/transform_preview/mod.rs +++ b/crates/imaging/src/ui/transform_preview/mod.rs @@ -11,9 +11,11 @@ //! ```no_run //! use craft_imaging::ui::transform_preview::{PreviewMap, PreviewPixels, PreviewTextures, TransformPreview}; //! use craft_ui::contract::Show as _; +//! use craft_ui::primitives::Serials; //! # fn demo(ui: &mut egui::Ui, canvas_rect: egui::Rect, image: egui::ColorImage, quad: [kurbo::Point; 4]) { -//! // Once per session: -//! let textures = PreviewTextures::new("ft-preview", PreviewPixels::new(image, [1.0, 1.0])); +//! // Once per session, with the `Serials` the owner of the previews holds: +//! let mut serials = Serials::default(); +//! let textures = PreviewTextures::new(&mut serials, "ft-preview", PreviewPixels::new(image, [1.0, 1.0])); //! // Every pass, in the canvas body under the guides and the box: //! TransformPreview::new("Moving layer", &textures).map(PreviewMap::quad(quad)).opacity(0.8).clip([800, 600]).show_at(ui, canvas_rect); //! # } diff --git a/crates/imaging/src/ui/transform_preview/stories.rs b/crates/imaging/src/ui/transform_preview/stories.rs index 66588c15b..27ee1c2ff 100644 --- a/crates/imaging/src/ui/transform_preview/stories.rs +++ b/crates/imaging/src/ui/transform_preview/stories.rs @@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use craft_behavior::kurbo::{Point, Rect}; use craft_ui::canvas::{PixelRect, RasterSource}; use craft_ui::contract::Show as _; +use craft_ui::primitives::Serials; use craft_ui::testing::canvas_story::StoryDocument; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::{Color32, ColorImage, Ui}; @@ -102,7 +103,7 @@ impl Document { return Arc::clone(textures); } let name = format!("transform-story-{}x{}", size[0], size[1]); - let textures = Arc::new(PreviewTextures::from_levels(name, pyramid(size), [1.0, 1.0])); + let textures = Arc::new(PreviewTextures::from_levels(&mut Serials::default(), name, pyramid(size), [1.0, 1.0])); kept.push((size, Arc::clone(&textures))); textures } diff --git a/crates/imaging/src/ui/transform_preview/textures.rs b/crates/imaging/src/ui/transform_preview/textures.rs index d39c301af..d21bb5683 100644 --- a/crates/imaging/src/ui/transform_preview/textures.rs +++ b/crates/imaging/src/ui/transform_preview/textures.rs @@ -1,12 +1,11 @@ //! [`PreviewPixels`] and [`PreviewTextures`]: the moving pixels of a transform, read once and //! uploaded as a mip chain built on demand, off the UI thread where a finer level can stand in. -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use craft_host::queue::Cancel; use craft_ui::primitives::{ - LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, TextureLoader, TextureState, TextureStatistics, TextureStore, + LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, Serials, TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, }; use egui::{Color32, ColorImage, Context, TextureId, TextureOptions}; @@ -114,9 +113,6 @@ pub struct TextureChoice { /// The key of a preview's level in the shared stores: the preview's name and the level. type LevelKey = (Arc, u32); -/// Tells previews apart in the store revisions: a preview made under an old name with new pixels gets a new serial. -static SERIAL: AtomicU64 = AtomicU64::new(0); - /// The moving pixels uploaded for the preview: level 0 at once, the other mip levels (2 × 2 box filtered) and the /// nearest-filtered level 0 on first use. The CPU levels are kept for the session. /// @@ -137,21 +133,22 @@ pub struct PreviewTextures { } impl PreviewTextures { - /// The preview of `pixels`, named `name`: the store entries are keyed by it. Nothing is - /// uploaded until the preview is painted. - pub fn new(name: impl Into, pixels: PreviewPixels) -> Self { + /// The preview of `pixels`, named `name`: the store entries are keyed by it. `serials` tells this preview from an + /// earlier one of the same name (new pixels under an old name replace its textures); the previews of one owner + /// share it. Nothing is uploaded until the preview is painted. + pub fn new(serials: &mut Serials, name: impl Into, pixels: PreviewPixels) -> Self { let base_uv = pixels.base_uv; - Self::over(name, vec![Arc::new(pixels.image)], base_uv) + Self::over(serials, name, vec![Arc::new(pixels.image)], base_uv) } /// The preview over `levels` already built, level 0 first, covering the source with `base_uv`. #[cfg(feature = "screen-testing")] - pub(crate) fn from_levels(name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - Self::over(name, levels, base_uv) + pub(crate) fn from_levels(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { + Self::over(serials, name, levels, base_uv) } - fn over(name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - let serial = SERIAL.fetch_add(1, Ordering::Relaxed); + fn over(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { + let serial = serials.next(); Self { name: Arc::from(name.into()), serial, images: Arc::new(Mutex::new(levels)), base_uv } } diff --git a/crates/imaging/tests/it/transform_preview.rs b/crates/imaging/tests/it/transform_preview.rs index 882771cb6..ff6757207 100644 --- a/crates/imaging/tests/it/transform_preview.rs +++ b/crates/imaging/tests/it/transform_preview.rs @@ -15,6 +15,7 @@ use craft_imaging::ui::transform_preview::{ use craft_imaging::ui::warp::WarpMesh; use craft_ui::canvas::{Canvas, PixelRect}; use craft_ui::contract::{MemoProps, MemoView, PlainData, Show as _, ShowContainer as _, Tracked}; +use craft_ui::primitives::Serials; use craft_ui::testing::{Fixture, trial}; use egui::{Color32, ColorImage, Shape}; @@ -31,7 +32,7 @@ fn shown(map: fn() -> PreviewMap<'static>, opacity: f32, clip: Option<[u32; 2]>, let meshes = Rc::new(RefCell::new(Vec::new())); let seen_view = Rc::new(Cell::new(None)); let (sink, view_sink) = (Rc::clone(&meshes), Rc::clone(&seen_view)); - let textures = PreviewTextures::new("t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0])); + let textures = PreviewTextures::new(&mut Serials::default(), "t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0])); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let view = CanvasView::new(room, pt(100.0, 100.0), 1.0).rotation(rotation); @@ -224,7 +225,7 @@ fn a_style_plan_stays_within_its_budget_at_screen_size_and_refuses_hostile_boxes fn a_monitor_conversion_changes_only_the_shown_upload() { let ctx = egui::Context::default(); let raw = solid([2, 2], Color32::from_rgb(140, 89, 51)); - let textures = PreviewTextures::new("monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0])); + let textures = PreviewTextures::new(&mut Serials::default(), "monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0])); // The trial stands in for the renderer: it takes the texture deltas it reads and applies none. let uploaded = |id: egui::TextureId| { let mut delta = ctx.tex_manager().write().take_delta(); @@ -316,7 +317,7 @@ fn frame(textures: &PreviewTextures, quad: [Point; 4], zoom: f32) -> StyledFrame } fn styled_textures() -> PreviewTextures { - PreviewTextures::new("styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0])) + PreviewTextures::new(&mut Serials::default(), "styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0])) } fn context() -> (Fixture, egui::Context) { @@ -424,7 +425,7 @@ struct Mips { } fn white(name: &str) -> Rc { - Rc::new(PreviewTextures::new(name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0]))) + Rc::new(PreviewTextures::new(&mut Serials::default(), name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0]))) } impl Mips { @@ -597,11 +598,12 @@ fn a_new_preview_under_the_same_name_shows_its_own_pixels() { delta.clear(); texel }; - let first = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0])); + let mut serials = Serials::default(); + let first = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0])); let (id, _) = first.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded"); assert_eq!(uploaded(id), Some(Color32::WHITE)); drop(first); - let second = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0])); + let second = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0])); let (id, _) = second.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded"); assert_eq!(uploaded(id), Some(Color32::BLACK), "the new pixels go up"); } diff --git a/crates/ui-canvas/src/canvas_controls/brush/mod.rs b/crates/ui-canvas/src/canvas_controls/brush/mod.rs index a71511bc2..02b2588b3 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/mod.rs @@ -30,6 +30,8 @@ pub(crate) mod source_marker; pub(crate) mod stories; mod tip; pub(crate) mod trail; +#[cfg(feature = "testing")] +pub(crate) mod trials; pub use cursor::{BrushCursor, BrushCursorOptions, PaintingCursor, TipCell, TipCellStyle}; pub use falloff::{FalloffPreview, FalloffPreviewStyle, TipFalloff}; diff --git a/crates/ui-canvas/src/canvas_controls/brush/stories.rs b/crates/ui-canvas/src/canvas_controls/brush/stories.rs index 36eaaac89..068089e44 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/stories.rs @@ -11,7 +11,7 @@ use crate::canvas::testing::tool_story::{StoryHost, ToolScript, ToolStory, tool_ use crate::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use crate::canvas_controls::CanvasControlWords; use crate::contract::Show as _; -use crate::primitives::Draw; +use crate::primitives::{Draw, Serials}; use crate::runtime::env::Env; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; @@ -56,8 +56,8 @@ fn hard_tip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } /// A drag-shaped mask whose stroke runs at height `y`. -fn stamped(y: f64) -> CoverageMask { - let mut mask = CoverageMask::new(DocRect::new(40.0, 60.0, 160.0, 140.0), 256); +fn stamped(serials: &mut Serials, y: f64) -> CoverageMask { + let mut mask = CoverageMask::new(serials, DocRect::new(40.0, 60.0, 160.0, 140.0), 256); mask.begin_stroke(); mask.stamp_capsule(Point::new(60.0, y), Point::new(100.0, y + 6.0), 5.0); mask.stamp_capsule(Point::new(100.0, y + 6.0), Point::new(140.0, y - 4.0), 5.0); @@ -66,7 +66,11 @@ fn stamped(y: f64) -> CoverageMask { /// The footprint of one tone. The mask is kept across passes (stamped once), so the trail uploads only what changed. fn footprint_of(ui: &mut Ui, data: &mut StoryData, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput { - let mask = data.note::>("footprint", None).get_or_insert_with(|| stamped(y)); + if data.note::>("footprint", None).is_none() { + let made = stamped(data.note("serials", Serials::default()), y); + *data.note::>("footprint", None) = Some(made); + } + let mask = data.note::>("footprint", None).as_mut().expect("stamped above"); on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, mask).tone(tone).show_at(ui, rect)) } diff --git a/crates/ui-canvas/src/canvas_controls/brush/trail.rs b/crates/ui-canvas/src/canvas_controls/brush/trail.rs index d4998e710..cc79d38f1 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/trail.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/trail.rs @@ -2,26 +2,23 @@ use crate::canvas::canvas_space; use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; -use crate::primitives::{Revision, TextureState, TextureStore, TextureStoreOptions}; +use crate::primitives::{Revision, Serials, TextureState, TextureStore, TextureStoreOptions}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleColor, StyleCx}; use craft_behavior::kurbo::{Point, Rect}; use craft_behavior::{Input, Metrics}; use egui::epaint::{Mesh, Vertex}; use egui::{Color32, ColorImage, Response, Shape, pos2}; -use std::sync::atomic::{AtomicU64, Ordering}; /// The share of the tone's colour a full-coverage texel shows; the texture holds coverage only. const LIGHT_SHARE: f32 = 0.25; const SHADE_SHARE: f32 = 0.5; const DANGER_SHARE: f32 = 0.45; -/// The texture store's salt: one store for every trail of the context, keyed by the mask's id. +/// The texture store's salt: one store for every trail of the context, keyed by the trail's component id and the +/// mask's serial (serials are unique per owner, not per context). const STORE_SALT: &str = "canvas_controls.stroke_trail"; -/// Hands out the ids that keep two masks' textures apart. -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - /// A coverage raster over a document rect: one byte per texel, `scale` document units wide, stamped by the tool as the /// stroke grows and uploaded by [`StrokeTrail`] by its changed rows. #[derive(Debug)] @@ -58,8 +55,9 @@ fn byte(coverage: f32) -> u8 { } impl CoverageMask { - /// A mask over `bounds` with no side longer than `max_side` texels. - pub fn new(bounds: Rect, max_side: u32) -> Self { + /// A mask over `bounds` with no side longer than `max_side` texels. Its texture's key comes from `serials`, which + /// the masks of one owner share. + pub fn new(serials: &mut Serials, bounds: Rect, max_side: u32) -> Self { let bounds = bounds.abs(); let finite = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()); let bounds = if finite { bounds } else { Rect::ZERO }; @@ -68,16 +66,7 @@ impl CoverageMask { let extent = |side: f64| (side / scale).ceil().max(1.0) as u32; let size = (extent(bounds.width()), extent(bounds.height())); let len = size.0 as usize * size.1 as usize; - CoverageMask { - bounds, - scale, - size, - texels: vec![0; len], - base: vec![0; len], - dirty: None, - revision: 0, - id: NEXT_ID.fetch_add(1, Ordering::Relaxed), - } + CoverageMask { bounds, scale, size, texels: vec![0; len], base: vec![0; len], dirty: None, revision: 0, id: serials.next() } } /// Stamps the capsule from `from` to `to` (document units) of radius `radius`, keeping the larger coverage. @@ -270,8 +259,8 @@ impl Component for StrokeTrail<'_> { } let painter = ui.content_painter(cx); let ctx = painter.painter.ctx(); - let store = TextureStore::::in_context(ctx, STORE_SALT, TextureStoreOptions::frames()); - let (key, revision) = (self.mask.id, Revision::new(self.mask.revision)); + let store = TextureStore::<(egui::Id, u64)>::in_context(ctx, STORE_SALT, TextureStoreOptions::frames()); + let (key, revision) = ((cx.id, self.mask.id), Revision::new(self.mask.revision)); // A second paint of the pass finds the entry at this revision and nothing dirty. let texture = match store.state(ctx, &key, revision) { TextureState::Ready(texture) => texture, diff --git a/crates/ui-canvas/src/canvas_controls/brush/trials.rs b/crates/ui-canvas/src/canvas_controls/brush/trials.rs new file mode 100644 index 000000000..6727e6e70 --- /dev/null +++ b/crates/ui-canvas/src/canvas_controls/brush/trials.rs @@ -0,0 +1,48 @@ +//! Trials of the stroke trail's texture keys. +#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] + +use super::{CoverageMask, StrokeTrail}; +use crate::canvas::testing::canvas_story::{on_canvas_view, story_view}; +use crate::contract::Show as _; +use crate::primitives::Serials; +use crate::testing::{Frames, trial}; +use craft_behavior::kurbo::{Point, Rect as DocRect}; +use egui::{Shape, Ui}; + +fn stamped(serials: &mut Serials) -> CoverageMask { + let mut mask = CoverageMask::new(serials, DocRect::new(40.0, 60.0, 160.0, 140.0), 256); + mask.stamp_capsule(Point::new(60.0, 100.0), Point::new(140.0, 100.0), 5.0); + mask +} + +/// Two owners each count from one: their masks have the same serial and revision, and the trials they show at once +/// still upload a texture each. +#[trial] +fn two_owners_masks_with_one_serial_show_two_textures() { + let (mut first, mut second) = (stamped(&mut Serials::default()), stamped(&mut Serials::default())); + let mut frames = Frames::new(); + let mut ui = |ui: &mut Ui| { + for (name, mask) in [("Trail A", &mut first), ("Trail B", &mut second)] { + crate::testing::memory::scoped_by(ui, name, |ui| { + on_canvas_view( + ui, + |room, scale| story_view(room, scale, Point::new(100.0, 100.0), 1.0), + None, + |ui, rect, _| StrokeTrail::new(name, mask).show_at(ui, rect), + ); + }); + } + }; + frames.idle(3, &mut ui); + let shapes = frames.frame_shapes(&mut ui); + let mut textures: Vec<_> = shapes + .iter() + .filter_map(|shape| match shape { + Shape::Mesh(mesh) => Some(mesh.texture_id), + _ => None, + }) + .collect(); + textures.sort_by_key(|id| format!("{id:?}")); + textures.dedup(); + assert_eq!(textures.len(), 2, "two trials with one serial each show their own texture: {textures:?}"); +} diff --git a/crates/ui-canvas/src/canvas_controls/outline/hover.rs b/crates/ui-canvas/src/canvas_controls/outline/hover.rs index fac1fb985..29e69d8dd 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/hover.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/hover.rs @@ -1,8 +1,8 @@ //! `HoverMask`: an object's coverage, reduced for the hover tint. +use crate::primitives::Serials; use craft_behavior::kurbo::Rect; use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; /// An object's coverage reduced for the hover tint: at most [`HoverMask::MAX_TEXELS`] texels on its long side, /// sampled once when the mask is made. Cheap to clone (the texels are shared) and `Send + Sync`, so a lookup job can @@ -16,7 +16,7 @@ pub struct HoverMask { size: [usize; 2], /// Coverage 0..=255 per texel, row by row. coverage: Arc<[u8]>, - /// Unique per mask made, for the texture store. + /// Unique per mask made by one `Serials`, for the texture store. generation: u64, } @@ -35,9 +35,8 @@ impl HoverMask { /// corner of each texel's cell, with one texel per document unit until the long side passes /// [`MAX_TEXELS`](Self::MAX_TEXELS), then `ceil(long side / 768)` units per texel. Coverage outside 0..=1 is /// clamped; one that is not finite reads as 0. Empty or non-finite `bounds` give a 1 × 1 mask with no coverage. - pub fn sampled(bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { - static GENERATIONS: AtomicU64 = AtomicU64::new(0); - let generation = GENERATIONS.fetch_add(1, Ordering::Relaxed); + pub fn sampled(serials: &mut Serials, bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { + let generation = serials.next(); let finite = bounds.x0.is_finite() && bounds.y0.is_finite() && bounds.x1.is_finite() && bounds.y1.is_finite(); if !finite || bounds.width() <= 0.0 || bounds.height() <= 0.0 { return HoverMask { bounds, size: [1, 1], coverage: Arc::from(vec![0u8]), generation }; diff --git a/crates/ui-canvas/src/canvas_controls/outline/mod.rs b/crates/ui-canvas/src/canvas_controls/outline/mod.rs index a0a71e84c..c5a13fc07 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/mod.rs @@ -179,10 +179,10 @@ fn tint(mask: &HoverMask, color: Color32) -> ColorImage { ColorImage::new([width, height], pixels) } -fn paint_mask(painter: &ContentPainterCx<'_>, view: &CanvasView, mask: &HoverMask, color: Color32) { +fn paint_mask(painter: &ContentPainterCx<'_>, id: egui::Id, view: &CanvasView, mask: &HoverMask, color: Color32) { let ctx = painter.painter.ctx(); - let store = TextureStore::::in_context(ctx, "canvas_controls.hover_mask", TextureStoreOptions::frames()); - let texture = store.get_or_put(ctx, mask.generation(), Revision::of(&color.to_array()), || tint(mask, color)); + let store = TextureStore::<(egui::Id, u64)>::in_context(ctx, "canvas_controls.hover_mask", TextureStoreOptions::frames()); + let texture = store.get_or_put(ctx, (id, mask.generation()), Revision::of(&color.to_array()), || tint(mask, color)); let uvs = [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]; let mut mesh = Mesh::with_texture(texture.sized().id); for (pos, uv) in view.quad(mask.bounds()).into_iter().zip(uvs) { @@ -250,7 +250,7 @@ impl Component for HoverOutline { stroke_run(&painter, points, closed, self.color, style.medium); } } - HoverShape::Mask(mask) => paint_mask(&painter, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), + HoverShape::Mask(mask) => paint_mask(&painter, cx.id, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), } } diff --git a/crates/ui-canvas/src/canvas_controls/outline/stories.rs b/crates/ui-canvas/src/canvas_controls/outline/stories.rs index 8019fbb83..f52ac4ecd 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/stories.rs @@ -4,6 +4,7 @@ use super::{HoverMask, HoverOutline, HoverShape, SelectionOutline}; use crate::canvas::RasterSource as _; use crate::canvas::testing::canvas_story::{StoryDocument, StoryPicture, StoryShape, accent, on_canvas, on_picture, paint_shapes}; use crate::contract::Show as _; +use crate::primitives::Serials; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{self, BezPath, Circle, Point, Rect, Shape as _}; use egui::{Color32, Ui}; @@ -36,8 +37,9 @@ fn rollover(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } #[story(HoverOutline, covers = [Default], drive = Drive::Never)] -fn coverage_tint(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - let mask = HoverMask::sampled(bounds(), |x, y| if DISC.contains(Point::new(x, y)) { 1.0 } else { 0.0 }); +fn coverage_tint(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let disc = |x, y| if DISC.contains(Point::new(x, y)) { 1.0 } else { 0.0 }; + let mask = HoverMask::sampled(data.note("serials", Serials::default()), bounds(), disc); let picture = objects(ui, &DISC); on_picture(ui, &picture, |ui, at, _| HoverOutline::new("Object", Some(HoverShape::Mask(mask.clone()))).show_at(ui, at)) } diff --git a/crates/ui-canvas/tests/it/canvas_controls/brush.rs b/crates/ui-canvas/tests/it/canvas_controls/brush.rs index 2ea1284ec..c0d0026b9 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/brush.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/brush.rs @@ -2,10 +2,11 @@ use craft_behavior::kurbo::{Point, Rect}; use craft_ui::canvas_controls::brush::CoverageMask; +use craft_ui::primitives::Serials; use craft_ui::testing::trial; fn mask() -> CoverageMask { - CoverageMask::new(Rect::new(0.0, 0.0, 100.0, 100.0), 100) + CoverageMask::new(&mut Serials::default(), Rect::new(0.0, 0.0, 100.0, 100.0), 100) } #[trial] @@ -44,7 +45,7 @@ fn a_restamp_keeps_earlier_strokes_and_stays_inside_its_rect() { #[trial] fn a_thin_stamp_on_a_large_document_still_shows() { - let mut mask = CoverageMask::new(Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 1000); + let mut mask = CoverageMask::new(&mut Serials::default(), Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 1000); assert_eq!((mask.scale(), mask.size()), (20.0, (1000, 1000))); // A one-unit line on a texel's edge, away from every texel centre. mask.restamp(Rect::new(5000.0, 5000.0, 5200.0, 5020.0), |at| if (at.y - 5000.5).abs() <= 0.5 { 1.0 } else { 0.0 }); diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 895da0217..bb5a5056b 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -67,9 +67,9 @@ pub use tool::ToolIcon; #[cfg(feature = "testing")] pub use textures::FakeThumbSource; pub use textures::{ - CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, TextureBudget, TextureKey, TextureLoader, - TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, ThumbRequest, - ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, + CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, Serials, TextureBudget, TextureKey, + TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, + ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, }; pub(crate) use draw::DataMode; diff --git a/crates/ui-contract/src/primitives/textures/mod.rs b/crates/ui-contract/src/primitives/textures/mod.rs index faabf4501..df9a52a57 100644 --- a/crates/ui-contract/src/primitives/textures/mod.rs +++ b/crates/ui-contract/src/primitives/textures/mod.rs @@ -8,7 +8,7 @@ mod words; pub use limits::{MAX_TEXTURE, fit_image, reduce_image, texture_factor, texture_side}; pub use loader::{LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, TextureLoader}; -pub use store::{CachedTexture, Revision, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; +pub use store::{CachedTexture, Revision, Serials, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; pub use words::TextureWords; /// The tint that leaves a texture's own colours as they are: every texel is multiplied by white. diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index 35fc6c92f..c1b230925 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -371,6 +371,22 @@ impl Default for Stores { } } +/// The numbers that keep apart the textures one owner makes: a mask or preview made anew gets a number no earlier one +/// of the same `Serials` had, so an entry kept under its key is never taken for the new one's. The owner of what the +/// textures show (a tool's state, a model) holds the `Serials`. The numbers are unique per owner, not per context: a +/// texture store that several owners share keys each entry by the owner's component id as well as the serial. Plain +/// data, so it can sit in tracked or model state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Serials(u64); + +impl Serials { + /// The next number: never one this `Serials` gave before. + pub fn next(&mut self) -> u64 { + self.0 += 1; + self.0 + } +} + /// Textures by key and revision, with byte and entry budgets: the one place an app's pictures become egui /// textures. The app never holds a `TextureHandle`. The state lives in runtime memory of the context under the /// salt; the value is a cheap handle that clones share. From 29ce80c9a559d6226984db18e630da13f2f51eff Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:08:45 +0000 Subject: [PATCH 74/89] Motion: a tween's last step keeps the run from replay without asking for another frame A tween that moves in a pass leaves its slot in another state than the run found it in, so a record of the run is not replayed; only a tween still running asks for a repaint. The last step of a modal's nudge asked for one more frame, so the dialog nudge trial saw a repaint after the nudge came to rest. --- crates/ui-contract/src/runtime/motion.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index f52cfa571..5fb7df0be 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -396,7 +396,8 @@ impl Driver<'_> { let now = frame::clock(ctx); let existing = if sizing { store::peek_clone::>(ctx, id) } else { store::take::>(ctx, id) }; // A tween that moves in this pass (a new target, also one it jumps to, or a step, also its last one) leaves the - // slot in another state than the run found it in, which the next run reads (`layer_fading` among others). + // slot in another state than the run found it in, which the next run reads (`layer_fading` among others): a + // record of the run is not replayed. Only a tween still running asks for another frame. let moved = existing.as_ref().is_some_and(|tween| tween.target() != target || !tween.is_settled()); let mut tween = match existing { Some(tween) => tween, @@ -410,8 +411,10 @@ impl Driver<'_> { self.advance(&mut tween, target, spec, now); let shown = tween.shown(); if !sizing { - if moved || !tween.is_settled() { + if !tween.is_settled() { note_unsettled(ctx); + } else if moved { + crate::runtime::replay::note_unsettled(ctx); } store::put(ctx, id, tween); } From c877a0bbe334f2bda7d88277e672ac19659f5d81 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:08:45 +0000 Subject: [PATCH 75/89] craft: the facade's tracked-serde feature, from craft-tracked's optional serde --- crates/craft/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 6a27a4e70..4eaeaa1cf 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -910,6 +910,7 @@ timeline-otio = ["timeline", "craft-timeline/otio"] timeline-xml = ["timeline", "craft-timeline/xml"] tracked = ["dep:craft-tracked"] +tracked-serde = ["tracked", "craft-tracked/serde"] ui-app = ["ui", "craft-ui/app"] ui-cloud = ["ui", "craft-ui/cloud"] From 52b875b623a2c8184124e55ddc342e7f9e591d59 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:08:45 +0000 Subject: [PATCH 76/89] api-map: MenuBarUi::english is a removal; the note names the model's english fields --- migration/api-map/craft-menu.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/migration/api-map/craft-menu.toml b/migration/api-map/craft-menu.toml index 72235b1c4..056edf546 100644 --- a/migration/api-map/craft-menu.toml +++ b/migration/api-map/craft-menu.toml @@ -109,8 +109,8 @@ note = "Use `Props::id_salt` on the bar's parent scope." [[call]] old = "MenuBarUi::english(hook)" -new = "Item::english, Node::english, Menu::english" -note = "The English name is a field of the model, set where the app translates a label." +new = "" +note = "The English name is a field of the model (`Item::english`, `Node::english`, `Menu::english`), set where the app translates a label." [[call]] old = "MenuBar::palette_entries(&keymap, target, &options, english, os)" From c29f9208b48ebfca9718944ec363c41053ef7de9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:19:11 +0000 Subject: [PATCH 77/89] Minimized column height: then_some (clippy unnecessary_lazy_evaluations) --- crates/ui-panels/src/docking/targets.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index e6d436d5b..ab44830f8 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -143,7 +143,7 @@ impl DockSizes { /// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None` /// while a group is open. pub fn minimized_height

(&self, column: &Column

) -> Option { - column.groups.iter().all(|group| group.minimized).then(|| self.strip * column.groups.len() as f32) + column.groups.iter().all(|group| group.minimized).then_some(self.strip * column.groups.len() as f32) } /// The width bounds of an expanded column from the limits of its panels. From 4a063b60836dd07a5468420bfa2bf128b75096f3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:26:33 +0000 Subject: [PATCH 78/89] Serials::mint: the method is not an iterator's next --- crates/imaging/src/ui/transform_preview/textures.rs | 2 +- crates/ui-canvas/src/canvas_controls/brush/trail.rs | 2 +- crates/ui-canvas/src/canvas_controls/outline/hover.rs | 2 +- crates/ui-contract/src/primitives/textures/store.rs | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/imaging/src/ui/transform_preview/textures.rs b/crates/imaging/src/ui/transform_preview/textures.rs index d21bb5683..06272c396 100644 --- a/crates/imaging/src/ui/transform_preview/textures.rs +++ b/crates/imaging/src/ui/transform_preview/textures.rs @@ -148,7 +148,7 @@ impl PreviewTextures { } fn over(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - let serial = serials.next(); + let serial = serials.mint(); Self { name: Arc::from(name.into()), serial, images: Arc::new(Mutex::new(levels)), base_uv } } diff --git a/crates/ui-canvas/src/canvas_controls/brush/trail.rs b/crates/ui-canvas/src/canvas_controls/brush/trail.rs index cc79d38f1..6055625bf 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/trail.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/trail.rs @@ -66,7 +66,7 @@ impl CoverageMask { let extent = |side: f64| (side / scale).ceil().max(1.0) as u32; let size = (extent(bounds.width()), extent(bounds.height())); let len = size.0 as usize * size.1 as usize; - CoverageMask { bounds, scale, size, texels: vec![0; len], base: vec![0; len], dirty: None, revision: 0, id: serials.next() } + CoverageMask { bounds, scale, size, texels: vec![0; len], base: vec![0; len], dirty: None, revision: 0, id: serials.mint() } } /// Stamps the capsule from `from` to `to` (document units) of radius `radius`, keeping the larger coverage. diff --git a/crates/ui-canvas/src/canvas_controls/outline/hover.rs b/crates/ui-canvas/src/canvas_controls/outline/hover.rs index 29e69d8dd..0c8d1b93e 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/hover.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/hover.rs @@ -36,7 +36,7 @@ impl HoverMask { /// [`MAX_TEXELS`](Self::MAX_TEXELS), then `ceil(long side / 768)` units per texel. Coverage outside 0..=1 is /// clamped; one that is not finite reads as 0. Empty or non-finite `bounds` give a 1 × 1 mask with no coverage. pub fn sampled(serials: &mut Serials, bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { - let generation = serials.next(); + let generation = serials.mint(); let finite = bounds.x0.is_finite() && bounds.y0.is_finite() && bounds.x1.is_finite() && bounds.y1.is_finite(); if !finite || bounds.width() <= 0.0 || bounds.height() <= 0.0 { return HoverMask { bounds, size: [1, 1], coverage: Arc::from(vec![0u8]), generation }; diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index c1b230925..8144fa8ea 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -380,8 +380,8 @@ impl Default for Stores { pub struct Serials(u64); impl Serials { - /// The next number: never one this `Serials` gave before. - pub fn next(&mut self) -> u64 { + /// A new number: never one this `Serials` gave before. + pub fn mint(&mut self) -> u64 { self.0 += 1; self.0 } From cdab24a5fc03fdda537e59c516af161d1d251ca5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:31:24 +0000 Subject: [PATCH 79/89] Brush stories: the footprint note holds its serials and mask together --- crates/ui-canvas/src/canvas_controls/brush/stories.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/ui-canvas/src/canvas_controls/brush/stories.rs b/crates/ui-canvas/src/canvas_controls/brush/stories.rs index 068089e44..d2071371a 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/stories.rs @@ -66,11 +66,8 @@ fn stamped(serials: &mut Serials, y: f64) -> CoverageMask { /// The footprint of one tone. The mask is kept across passes (stamped once), so the trail uploads only what changed. fn footprint_of(ui: &mut Ui, data: &mut StoryData, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput { - if data.note::>("footprint", None).is_none() { - let made = stamped(data.note("serials", Serials::default()), y); - *data.note::>("footprint", None) = Some(made); - } - let mask = data.note::>("footprint", None).as_mut().expect("stamped above"); + let (serials, mask) = data.note::<(Serials, Option)>("footprint", (Serials::default(), None)); + let mask = mask.get_or_insert_with(|| stamped(serials, y)); on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, mask).tone(tone).show_at(ui, rect)) } From 683fe06031224725b913c8ad3697d8e8bfec6c90 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:33:02 +0000 Subject: [PATCH 80/89] craft-layers: tree ids are plain data, keyed by their Hash --- crates/layers/src/ui/panel/body/rows.rs | 3 ++- crates/layers/src/ui/tree.rs | 12 ++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/layers/src/ui/panel/body/rows.rs b/crates/layers/src/ui/panel/body/rows.rs index 74e144b32..8709aba62 100644 --- a/crates/layers/src/ui/panel/body/rows.rs +++ b/crates/layers/src/ui/panel/body/rows.rs @@ -31,9 +31,10 @@ pub(in crate::ui::panel) struct DisplayRow { /// What the display order derives from: the tree's tracked revision, the filter and the groups a reveal opens. A /// change of any of them builds the rows again; nothing else does. #[derive(MemoProps)] -pub(in crate::ui::panel) struct RowsKey<'a, Id: MemoProps> { +pub(in crate::ui::panel) struct RowsKey<'a, Id> { pub(in crate::ui::panel) tree: Revision, pub(in crate::ui::panel) filter: &'a LayerFilter, + #[memo_props(hash = "tree ids are plain model ids (LayerTree::Id: PlainData); Hash covers them")] pub(in crate::ui::panel) opened: &'a [Id], } diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index d8f10d5cd..b73560a0e 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -11,7 +11,7 @@ use std::hash::Hash; use craft_behavior::IconId; use craft_keymap::Mods; use craft_theme::LabelColor; -use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove}; +use craft_ui::contract::{Entry, PlainData, ReorderMove}; use craft_ui::list::ThumbTarget; use super::filter::{EffectKind, LayerFilter, SmartSource}; @@ -22,6 +22,9 @@ use super::panel::MenuTarget; /// the panel derives from the tree. /// /// ```ignore +/// #[derive(Clone, PartialEq, Eq, Hash, Debug, PlainData)] +/// struct LayerId(u64); +/// /// #[derive(PlainData)] /// struct PhotoLayers { layers: LayerIndex, open: HashSet } /// impl LayerTree for PhotoLayers { @@ -36,9 +39,10 @@ use super::panel::MenuTarget; /// [`children`](Self::children) and [`is_open`](Self::is_open) are walked to build the display order, and only when the /// tracked revision, the filter or a reveal's opens changed. pub trait LayerTree: PlainData { - /// The app's layer id: the key of a row, of its thumbnails and of every event. It feeds the memo key of the - /// display order when a reveal opens groups. - type Id: Clone + Eq + Hash + Debug + Send + Sync + MemoProps + 'static; + /// The app's layer id: the key of a row, of its thumbnails and of every event. It is plain model data + /// (`#[derive(PlainData)]`), so the panel keys it by its `Hash`, including in the memo key of the display order + /// when a reveal opens groups. + type Id: Clone + Eq + Hash + Debug + Send + Sync + PlainData + 'static; /// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the /// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text. From 6392a6631235045f04c6f309fdd94b6dd2a0381b Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 05:50:51 +0000 Subject: [PATCH 81/89] ui-contract: a memoized view replays only at the opacity it ran at A view inside a layer that fades in or out ran at one opacity and its record holds the faded colours; a replay at another opacity painted them stale (presets picker list after a pick closes the popover). The opacity is part of the view's place, as the layer and layout are. --- crates/ui-contract/src/contract/lazy.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 12 ++++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index d0db84761..41d5b40d5 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -113,6 +113,7 @@ impl Lazy { layout, pixels_per_point: ctx.pixels_per_point(), atlas: ctx.fonts(|fonts| fonts.atlas_generation()), + opacity: ui.opacity(), env: Env::of(ui).key, }; let memo = matches!(key, Key::Memo(_)); diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 01d898b5e..0352f12fb 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -166,8 +166,8 @@ pub(crate) struct Measured { pub(crate) room: Rect, } -/// Where a memoized view ran: it replays only at a place of the same size, layer, layout and environment, and its -/// record moves with the room's position (`Place::shift_to`). +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity and environment, and +/// its record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Place { /// The region its parent offered it. @@ -179,6 +179,9 @@ pub(crate) struct Place { /// The font atlas the run's text points into (`Fonts::atlas_generation`): egui clears the atlas when it fills up /// and rebuilds it for new text options, and a kept galley's glyphs then name other glyphs. pub(crate) atlas: u64, + /// The opacity everything painted in the room is faded to (`Ui::opacity`, a layer fading in or out): the run's + /// colours hold it. + pub(crate) opacity: f32, /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, @@ -193,8 +196,8 @@ struct Moved { impl Place { /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its - /// size, the layer, layout, scale, font atlas and environment are the ones the run had. A record that shows an - /// overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the room's move + /// size, the layer, layout, scale, font atlas, opacity and environment are the ones the run had. A record that shows + /// an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the room's move /// when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and, /// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an /// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow @@ -212,6 +215,7 @@ impl Place { && now.layout == self.layout && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas + && now.opacity == self.opacity && now.env == self.env; let placeable = if record.pinned() { offset == Vec2::ZERO && now.clip == self.clip From 28d9be1f75af9227dcf5d52ad212a7c4fec88e96 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 05:50:51 +0000 Subject: [PATCH 82/89] ui-contract: the replay audit compares journal entries as a replay calls them A replay calls its journal entries unshifted when the shift leaves every record as it is (a pinned record, one that shows an overlay), as egui's records do. The audit shifted them anyway, and RecordShift::clip cut the clip of a menu layer's rows to the clip around the view (TabRow with its menu open). Entry::at holds the rule for the replay and the audit. --- crates/ui-contract/src/runtime/replay.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 2ec9e5ccc..760f5cb47 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -93,6 +93,15 @@ impl PartialEq for Entry { } } +impl Entry { + /// The entry at the place `shift` names. A shift that leaves every record as it is (`RecordShift::is_none`, a + /// pinned record's) leaves the entry too, as it leaves egui's records: a clip a layer the record shows sets lies + /// outside the clip around the record, which `RecordShift::clip` would cut it to. + fn at(&self, shift: &RecordShift) -> Entry { + if shift.is_none() { self.clone() } else { self.0.shifted(shift) } + } +} + impl fmt::Debug for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.describe(f) @@ -350,7 +359,7 @@ impl Record { if let Some(diff) = self.focus.first_difference(&run.focus) { found.push(format!("focus: {diff}")); } - let shifted: Vec = self.journal.iter().map(|entry| entry.0.shifted(shift)).collect(); + let shifted: Vec = self.journal.iter().map(|entry| entry.at(shift)).collect(); let (left, right) = (&shifted, &run.journal); if let Some(index) = left .iter() @@ -416,7 +425,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { let noting = recording(ctx); if noting { pass_state::with::(ctx, |recorder| { - recorder.journal.extend(record.journal.iter().map(|entry| if shift.is_none() { entry.clone() } else { entry.0.shifted(shift) })); + recorder.journal.extend(record.journal.iter().map(|entry| entry.at(shift))); recorder.replaying = true; }); } From 1c6eb5e52ac6366c3444bf76b8ce3c812752636c Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 05:50:51 +0000 Subject: [PATCH 83/89] ui-contract: the replay audit prints both sides of a shape difference egui's display names a shape by its rects only, which looked equal when the fill differed. --- crates/ui-contract/src/runtime/replay.rs | 4 ++++ crates/ui-widgets/tests/it/body/memo_audit.rs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 760f5cb47..c89872ac5 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -350,6 +350,10 @@ impl Record { // The display names a widget by its rect only; the difference may be in its sense, state or interact rect. Some(egui::PassRecordsDiff::Widget { index, left, right }) => found.push(format!("widget rect {index}: left {left:?} / right {right:?}")), // The display names a node by its bounds only; the difference may be in any other property. + // The display names a shape by its rects only; the difference may be in its colour, stroke, texture or text. + Some(egui::PassRecordsDiff::Shape { layer, index, left, right }) => { + found.push(format!("paint: shape {index} on {layer:?}: left {left:?} / right {right:?}")) + } Some(egui::PassRecordsDiff::Node { index, left, right }) => { found.push(format!("AccessKit node {index}: left {left:?} / right {right:?}")) } diff --git a/crates/ui-widgets/tests/it/body/memo_audit.rs b/crates/ui-widgets/tests/it/body/memo_audit.rs index 2183e20e5..c8f1dad69 100644 --- a/crates/ui-widgets/tests/it/body/memo_audit.rs +++ b/crates/ui-widgets/tests/it/body/memo_audit.rs @@ -101,7 +101,7 @@ fn the_audit_names_a_view_whose_paint_went_stale() { }); assert!(message.contains("Swatch"), "names the view: {message}"); assert!(message.contains("paint"), "names the paint difference: {message}"); - assert!(!message.contains("rect:") && !message.contains("output:"), "extent and output are the same: {message}"); + assert!(!message.contains("rect: left") && !message.contains("output:"), "extent and output are the same: {message}"); } /// A view that returns a fraction of `HIDDEN`, which its props do not hold, and paints nothing from it. From 5f11477f6de28589d08d39694754771e47f82acf Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 06:24:14 +0000 Subject: [PATCH 84/89] craft-layers: LayerTree::Id's Hash tells distinct ids apart --- crates/layers/src/ui/tree.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index b73560a0e..61218215d 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -41,7 +41,9 @@ use super::panel::MenuTarget; pub trait LayerTree: PlainData { /// The app's layer id: the key of a row, of its thumbnails and of every event. It is plain model data /// (`#[derive(PlainData)]`), so the panel keys it by its `Hash`, including in the memo key of the display order - /// when a reveal opens groups. + /// when a reveal opens groups. Its `Hash` must tell distinct ids apart (as `#[memo_props(hash)]` requires): + /// two unequal ids that feed the same bytes would share a cached display order. Derived `Hash` on an integer or a + /// tuple of integers does. type Id: Clone + Eq + Hash + Debug + Send + Sync + PlainData + 'static; /// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the From 45ad4f55d790978423d5aba65823dd4c5c9fa4e5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 06:46:13 +0000 Subject: [PATCH 85/89] FloatingGroup::scale is a declared prop (display scale, pixels per point) --- crates/ui-panels/src/docking/floating.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index fc6369b3b..ba0c58ef9 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -277,8 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, - /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the - /// running window's. + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome, the rule under its title row included, is sized at that scale. + #[prop(quantity = "display scale, pixels per point")] scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, @@ -363,14 +364,6 @@ impl<'a> FloatingGroup<'a> { self } - /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the - /// running window's: its chrome is sized at that scale. - #[must_use] - pub fn scale(mut self, pixels_per_point: f32) -> Self { - self.scale = Some(pixels_per_point); - self - } - /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { From 2946b2041a0dc77a2b7a4f58d8744657d867cc3d Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:08:46 +0000 Subject: [PATCH 86/89] Icons on a Brand or Scrim surface paint their accent parts in their own ink; containers pass that ink down (#2569) * #7149 item 4: an icon on a strong fill paints its accent parts in its own ink A container that paints a Brand or Scrim surface now passes the strong-fill ink to what it holds, and Draw::icon paints an app icon accent layer in the icon colour when the ink is OnDark. Co-Authored-By: Claude Sonnet 5.5 * design exceptions: the icon trial has a third fixed-tint site Co-Authored-By: Claude Opus 5.5 * ui-contract: every filled surface sets its own container ink A panel nested in a brand or scrim container no longer inherits the strong-fill ink. A frame or a surfaceless container keeps the ink it sits in. Co-Authored-By: Claude Opus 5.5 * buttons trials: import ShowContainer for the nested Stack trials next dropped ShowContainer from the shared import line, so the merged tree failed to compile (E0599 on Stack::show in accent_icon_tints_in). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .../ui-contract/src/contract/body/inherit.rs | 8 ++- crates/ui-contract/src/primitives/draw.rs | 10 ++- crates/ui-contract/src/primitives/icon.rs | 17 +++-- .../src/primitives/textures/thumbnails.rs | 2 +- crates/ui-contract/src/testing/icon_trials.rs | 30 ++++++++ crates/ui-widgets/tests/it/buttons.rs | 69 ++++++++++++++++++- .../exceptions/craft-ui-contract/testing.toml | 2 +- 7 files changed, 128 insertions(+), 10 deletions(-) diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 8669cc8f0..2e09d9699 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -70,7 +70,13 @@ impl BodyHooks<'_> { if core.resolved.ltr_axis { scoped.direction = Direction::Ltr; } - scoped.ink = core.ink; + // A container that paints a fill reads in that fill's ink, so what it holds (an app icon's accent parts, text with + // no colour of its own) does too: OnDark on a brand rail or scrim, OnPanel on a panel nested inside one. A frame + // paints no fill, and a container with no surface paints none either: both keep the ink they sit in. + scoped.ink = match props.surface { + None | Some(SurfaceKind::Frame) => core.ink, + Some(kind) => kind.ink(), + }; scoped.start_room(); // An inside label and a filling cell are their control's alone: a container shows neither to what it holds. scoped.inside_label = None; diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index b9645b533..972df0013 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -400,7 +400,15 @@ impl<'a> Draw<'a> { self.initial(rect, letter, StyleColor(color)); return; } - _ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon, self.data != DataMode::Full), + _ => super::icon::paint( + self.painter, + self.env.tokens, + self.env.direction, + rect, + icon, + self.data != DataMode::Full, + self.env.ink == Ink::OnDark, + ), } match icon.badge { Some(super::IconMark::Dot(badge)) => { diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 57e414720..6a8bedfc8 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -268,8 +268,10 @@ pub fn icon_names() -> &'static [&'static str] { } /// Paints `spec`'s glyph centred in the square of `rect`'s shorter side; `Draw::icon` adds the badge. `single_ink` paints -/// every layer of an app icon in the one colour: the icon of a component in its disabled state. -pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool) { +/// every layer of an app icon in the one colour: the icon of a component in its disabled state. `on_dark` is whether +/// the icon stands on a strong fill or scrim (the surface's ink is `Ink::OnDark`): its accent parts then paint in the +/// icon's colour, since `accent.solid` would vanish on the brand fill. +pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool, on_dark: bool) { let color = spec.color_in(tokens); let rtl = direction == Direction::Rtl; let side = rect.width().min(rect.height()); @@ -283,7 +285,7 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, IconSource::Glyph(glyph) => glyph.paint(painter, tokens, square, color, rtl && glyph.directional() && spec.mirror == Mirror::Auto), IconSource::Svg(id) => { if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.mirror) { - icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink)); + icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink, on_dark || spec.ink == Ink::OnDark)); } } IconSource::Mark(badge) => super::pointer_art::paint_badge(painter, tokens, direction, square, *badge, color), @@ -396,8 +398,13 @@ impl LayerInks { } /// The inks of an icon painted in `color`: the accent parts in `colors.accent.solid` and the fixed parts as drawn, - /// except that with `single_ink` (a disabled component) every layer paints in `color`. - pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool) -> Self { + /// except that with `single_ink` (a disabled component) every layer paints in `color`, and with `on_dark` (a strong + /// fill or scrim, where the accent colour would vanish) the accent parts paint in `color` and the fixed parts stay + /// as drawn. + pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool, on_dark: bool) -> Self { + if on_dark && !single_ink { + return LayerInks { ink: color, accent: color, fixed: None }; + } if single_ink { return LayerInks::single(color); } diff --git a/crates/ui-contract/src/primitives/textures/thumbnails.rs b/crates/ui-contract/src/primitives/textures/thumbnails.rs index 697befc80..431810161 100644 --- a/crates/ui-contract/src/primitives/textures/thumbnails.rs +++ b/crates/ui-contract/src/primitives/textures/thumbnails.rs @@ -486,7 +486,7 @@ fn paint_placeholder(cx: &ContentPainterCx<'_>, rect: Rect, paper: Option, rect: Rect) { let side = cx.tokens.size.icon.sm.min(rect.width().min(rect.height())); let icon = Rect::from_center_size(rect.center(), vec2(side, side)); - crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false); + crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false, false); } /// A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets, diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index a78daa48e..19c73c055 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -111,6 +111,36 @@ fn texel(image: &ColorImage, x: usize, y: usize) -> Color32 { image.pixels[y * 24 + x] } +/// On a strong fill or scrim (the surface's ink is `OnDark`: a brand rail) the accent parts paint in the icon's own +/// colour, since `accent.solid` would vanish on the brand fill; the fixed parts stay as drawn, and on a panel the +/// accent parts keep the accent ink. +#[trial] +fn an_accent_part_on_a_dark_surface_paints_in_the_icons_ink() { + register_app_icons(&LAYERED_SET); + let tokens = style::tokens(Mode::Light, Contrast::Standard); + let rect = Rect::from_min_max(pos2(10.0, 10.0), pos2(34.0, 34.0)); + let mut frames = Frames::new(); + let mut tints = |surface: Ink, spec_ink: Option| { + let on = ink_color(&tokens, Ink::OnDark); + let mut spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(LAYERED_NAME))).color(StyleColor(on)); + if let Some(ink) = spec_ink { + spec = spec.ink(ink); + } + let record = RefCell::new(PaintRecord::default()); + let shapes = frames.frame_shapes(|ui| { + let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: surface }; + Draw::new(ui.painter(), &record, env).icon(rect, &spec); + }); + textured(&shapes).into_iter().map(|(_, tint)| tint).collect::>() + }; + let on = ink_color(&tokens, Ink::OnDark); + // design: allow[raw-colour/const](a fixed layer keeps the colours it is drawn in: the trial expects the white tint that leaves them unchanged) + let fixed = Color32::WHITE; + assert_eq!(tints(Ink::OnDark, None), [on, on, fixed], "on a brand rail the accent parts read in the icon's ink"); + assert_eq!(tints(Ink::OnPanel, Some(Ink::OnDark)), [on, on, fixed], "an icon that asks for the on-dark ink does the same"); + assert_eq!(tints(Ink::OnPanel, None), [on, rgba_color(tokens.color.accent.solid), fixed], "on a panel the accent ink is kept"); +} + #[trial] fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_the_disabled_ink_when_disabled() { register_app_icons(&LAYERED_SET); diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index e310965ab..5c371a4da 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -7,7 +7,7 @@ use craft_theme::ControlSize; use craft_theme::Variant; use craft_ui::buttons::{Arrangement, Button, ControlPlace, GroupLevel, SplitButton, SplitMenu, ToggleButton}; use craft_ui::contract::tooltip::DELAY; -use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _}; +use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _, ShowContainer as _}; use craft_ui::display::Picture; use craft_ui::list::ThumbAspect; use craft_ui::pickers::ComboBox; @@ -609,3 +609,70 @@ fn a_split_bodys_request_close_closes_the_menu_layer_and_it_opens_again_with_its open_menu(&mut fixture); assert!(fixture.by_label("Red").is_some(), "opened again, the menu shows its body"); } + +/// An app icon with an accent part, named for this test. +const ACCENT_ICON_NAME: &str = "zz_item4_accent_icon"; +static ACCENT_ICONS: craft_ui::primitives::AppIcons = craft_ui::primitives::AppIcons::new( + "buttons-test-accent", + None, + &[( + ACCENT_ICON_NAME, + br##""##, + )], +); + +/// The tints of the textured quads a button with the accent icon paints, in paint order, inside a stack of `surface`. +fn accent_icon_tints(surface: craft_ui::style::SurfaceKind) -> Vec { + accent_icon_tints_in(None, surface) +} + +/// As `accent_icon_tints`, with the stack of `surface` nested inside a stack of `outer`. +fn accent_icon_tints_in(outer: Option, surface: craft_ui::style::SurfaceKind) -> Vec { + craft_ui::primitives::register_app_icons(&ACCENT_ICONS); + let mut fixture = Fixture::new(move |ui| { + let inner = |ui: &mut egui::Ui| { + let _ = craft_ui::layout_components::Stack::new().surface(surface).show(ui, |ui, _| { + let _ = Button::new("Pen").icon(IconId::new(ACCENT_ICON_NAME)).variant(Variant::GHOST).show(ui); + }); + }; + match outer { + Some(outer) => { + let _ = craft_ui::layout_components::Stack::new().surface(outer).show(ui, |ui, _| inner(ui)); + } + None => inner(ui), + } + }); + fixture.settle(); + fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + egui::Shape::Rect(rect) if shape.texture_id() != egui::TextureId::default() => Some(rect.fill), + egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => mesh.vertices.first().map(|vertex| vertex.color), + _ => None, + }) + .collect() +} + +/// An app icon on a brand or scrim surface paints its accent parts in the ink of strong fills, as its plain parts: +/// the accent colour would vanish on the brand fill. On a panel the accent parts keep their own colour. +#[trial] +fn an_icons_accent_parts_on_a_brand_surface_paint_in_the_icons_ink() { + let brand = accent_icon_tints(craft_ui::style::SurfaceKind::Brand); + let panel = accent_icon_tints(craft_ui::style::SurfaceKind::Panel); + assert!(brand.len() >= 2 && panel.len() >= 2, "the icon paints an ink and an accent layer: {brand:?} {panel:?}"); + let (ink, accent) = (brand.len() - 2, brand.len() - 1); + assert_eq!(brand[ink], brand[accent], "on the brand fill the accent parts read in the icon's ink: {brand:?}"); + let (ink, accent) = (panel.len() - 2, panel.len() - 1); + assert_ne!(panel[ink], panel[accent], "on a panel the accent parts keep the accent colour: {panel:?}"); +} + +/// A panel nested inside a brand stack sets its own ink: the icon's accent parts keep the accent colour on it, not the +/// strong-fill ink of the rail around it. +#[trial] +fn an_icons_accent_parts_on_a_panel_inside_a_brand_surface_keep_the_accent_colour() { + let tints = accent_icon_tints_in(Some(craft_ui::style::SurfaceKind::Brand), craft_ui::style::SurfaceKind::Panel); + assert!(tints.len() >= 2, "the icon paints an ink and an accent layer: {tints:?}"); + let (ink, accent) = (tints.len() - 2, tints.len() - 1); + assert_ne!(tints[ink], tints[accent], "on a panel inside a brand stack the accent parts keep the accent colour: {tints:?}"); +} diff --git a/design/exceptions/craft-ui-contract/testing.toml b/design/exceptions/craft-ui-contract/testing.toml index 191f5f806..6f7dba9a5 100644 --- a/design/exceptions/craft-ui-contract/testing.toml +++ b/design/exceptions/craft-ui-contract/testing.toml @@ -6,7 +6,7 @@ kind = "marker" rule = "raw-colour/const" path = "crates/ui-contract/src/testing/icon_trials.rs" reason = "A fixed layer keeps the colours it is drawn in: the trial expects the white tint that leaves them unchanged." -count = 2 +count = 3 [[exception]] name = "face-runs-text-size" From fb8aae1df6cea57f2f2654980c9a2682d9424aa6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 11:43:38 +0100 Subject: [PATCH 87/89] WIP: memoized view in a row sits on the row's line (photocraft#16113) From efb06e99510879fa2be07fda891794d44310b769 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 11:54:42 +0100 Subject: [PATCH 88/89] Home layout: the rail's look from before the PhotoCraft port The desktop Home layout (`StartScreen::home_layout`) drew its rail with the dialog button look and inline links: pill New and Open, Home as a filled pill, Learn and the community links underlined in the link colour, and the page title as a Display heading. The rail is back to how PhotoCraft drew it before it moved onto the framework (photocraft#15449): - New and Open at the control radius. - Every link a full-width row with its icon: muted at rest, normal under the pointer; a URL row opens its URL (its tooltip), a command row fires it. - The selected row (Home) keeps normal ink and has an accent bar at its leading edge. - The page title as a Heading. Only the Home layout changes; the other start-screen layouts keep their links. Part of photocraft#15476 Co-Authored-By: Claude Opus 5.5 --- crates/ui-shell/src/shell/start.rs | 88 +++++++++++++++++++++++-- crates/ui-shell/tests/it/shell/start.rs | 34 ++++++++++ 2 files changed, 118 insertions(+), 4 deletions(-) diff --git a/crates/ui-shell/src/shell/start.rs b/crates/ui-shell/src/shell/start.rs index f9d2447c1..1b3f20f94 100644 --- a/crates/ui-shell/src/shell/start.rs +++ b/crates/ui-shell/src/shell/start.rs @@ -59,6 +59,13 @@ const HOME_DROP_ICON: f32 = 34.0; // design: allow[literal-size/vec2](the desktop Home page's outer margins are larger than any spacing token) const HOME_DESKTOP_INSET: Vec2 = vec2(36.0, 54.0); const HOME_DROP_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-drop", home_drop_look); +/// New and Open on the desktop Home page: the control radius, not the pill of dialog buttons. +const HOME_NEW_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-new", home_new_look); +const HOME_OPEN_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-open", home_open_look); +/// A row of the Home rail (Home, Learn, the community links): no edge or fill at rest, muted ink that turns normal +/// under the pointer. The selected row keeps normal ink and an accent bar at its leading edge. +const HOME_ROW_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-row", home_row_look); +const HOME_ROW_SELECTED_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-row-selected", home_row_selected_look); /// The revealed part of a recent row that takes the file off the list. pub(super) const REMOVE: TrailingPart = TrailingPart::new(0); @@ -586,9 +593,9 @@ impl HomeLayout<'_> { Stack::new().id_salt("home-page").fill().pad(Pad::Regular).gap(gap).scroll(Scroll::vertical()).show_at(ui, content, |ui, cx| { let top = ui.available_rect_before_wrap().top(); if !wide { - let _ = Row::new().gap(Gap::Tight).fill_width().show(ui, |ui, _| new_and_open(page, ui, Sizing::FillWidth)); + let _ = Row::new().gap(Gap::Tight).fill_width().show(ui, |ui, _| home_new_and_open(page, ui)); } - let _ = Text::new(self.title.clone()).role(TypeRole::Display).show(ui); + let _ = Text::new(self.title.clone()).role(TypeRole::Heading).show(ui); home_divider(ui); sections(ui, cx, top + content.height() / 2.0, wide); if !wide { @@ -604,7 +611,7 @@ impl HomeLayout<'_> { let stack = || Stack::new().id_salt("home-rail").pad(Pad::Regular).gap(Gap::Section); let top = |ui: &mut Ui| { let _ = Stack::new().id_salt("home-actions").gap(Gap::Stack).fill_width().show(ui, |ui, _| { - new_and_open(page, ui, Sizing::FillWidth); + home_new_and_open(page, ui); }); home_divider(ui); home_links(ui, page, "home-nav", links, Gap::Section); @@ -654,7 +661,8 @@ fn home_columns(room: Rect, rtl: bool) -> (Rect, Rect) { fn home_links(ui: &mut Ui, page: &Page<'_>, id: &'static str, links: &[StartLink], gap: Gap) { if !links.is_empty() { - let _ = Stack::new().id_salt(id).gap(gap).label(page.words.start_links.clone()).fill_width().show(ui, |ui, _| link_items(ui, links, true)); + let _ = + Stack::new().id_salt(id).gap(gap).label(page.words.start_links.clone()).fill_width().show(ui, |ui, cx| home_link_items(ui, cx, links)); } } @@ -675,6 +683,78 @@ fn home_edge(tokens: &Tokens) -> Rgba { if color.line.divider == color.surface.canvas { color.text.faint } else { color.line.divider } } +fn home_new_look(tokens: &Tokens) -> VariantLook { + Variant::PRIMARY.resolve(tokens).radius(RadiusStep::Control) +} + +fn home_open_look(tokens: &Tokens) -> VariantLook { + home_drop_look(tokens) +} + +fn home_row_look(tokens: &Tokens) -> VariantLook { + let mut look = Variant::GHOST.resolve(tokens).radius(RadiusStep::Control); + look.text.rest = tokens.color.text.muted; + look.muted.rest = tokens.color.text.muted; + look +} + +fn home_row_selected_look(tokens: &Tokens) -> VariantLook { + Variant::GHOST.resolve(tokens).radius(RadiusStep::Control) +} + +/// New and Open on the desktop Home page, filling the rail (or the narrow page's row). +fn home_new_and_open(page: &Page<'_>, ui: &mut Ui) { + let words = page.words; + let new = Button::new(words.new.clone()).id_salt("new").variant(Variant::Custom(HOME_NEW_LOOK)).sizing(Sizing::FillWidth); + if clicked(&new.show(ui)) { + page.push(StartAction::New); + } + let open = Button::new(words.open.clone()).id_salt("open").variant(Variant::Custom(HOME_OPEN_LOOK)).sizing(Sizing::FillWidth); + if clicked(&open.show(ui)) { + page.push(StartAction::Open); + } +} + +/// The rows of a Home rail group: each link is a full-width row with its icon, a URL opening in the browser (the URL +/// is its tooltip) and a command firing as a pointer activation. A selected row has an accent bar at its leading edge. +fn home_link_items(ui: &mut Ui, cx: &mut BodyCx<'_>, links: &[StartLink]) { + for (at, link) in links.iter().enumerate() { + let look = if link.selected { HOME_ROW_SELECTED_LOOK } else { HOME_ROW_LOOK }; + let mut button = + Button::new(link.label.clone()).id_salt(("start-link", at)).variant(Variant::Custom(look)).align(HAlign::Start).sizing(Sizing::FillWidth); + if let Some(icon) = &link.icon { + button = button.icon(icon.clone()); + } + if let StartLinkTarget::Url(url) = &link.target { + button = button.tooltip(url.clone()); + } + let shown = button.show(ui); + if link.selected { + home_selected_bar(ui, shown.response().rect); + } + if clicked(&shown) { + match &link.target { + StartLinkTarget::Url(url) => cx.open_url(url, false), + StartLinkTarget::Command(command) => { + let _ = commands::fire(ui.ctx(), command.clone(), FireSource::Pointer); + } + } + } + } +} + +/// The accent bar at the leading edge of the selected Home row, as tall as its icon. +fn home_selected_bar(ui: &mut Ui, row: Rect) { + let env = Env::of(ui); + let style = StyleCx::of_env(ui.ctx(), &env); + // The accent mark's look: `accent.solid`, `stroke.thick` wide. + let look = style.rule(RuleKind::DropMark); + let scale = ui.ctx().pixels_per_point(); + let bar = Rect::from_center_size(row.center(), vec2(row.width(), env.tokens.size.icon.md.min(row.height()))); + let side = if env.direction.is_rtl() { RectSide::Right } else { RectSide::Left }; + ui.painter().extend(Rule::edge(&look, bar, side, scale)); +} + fn home_drop_look(tokens: &Tokens) -> VariantLook { let mut look = Variant::SECONDARY.resolve(tokens).radius(RadiusStep::Control); if let Some(edge) = &mut look.edge { diff --git a/crates/ui-shell/tests/it/shell/start.rs b/crates/ui-shell/tests/it/shell/start.rs index 877371463..8b648caa8 100644 --- a/crates/ui-shell/tests/it/shell/start.rs +++ b/crates/ui-shell/tests/it/shell/start.rs @@ -210,6 +210,40 @@ fn the_home_screen_places_navigation_to_the_left_of_recent_files() { assert!(rect("GitHub").top() - rect("Discord").bottom() >= 6.0); } +/// The Home rail's links are rows as wide as the rail, as New and Open are, not inline links; the selected row (Home) +/// shows a bar at its leading edge and the others none. +#[trial] +fn the_home_rail_shows_its_links_as_rows_with_a_bar_on_the_selected_one() { + use egui::{Shape, vec2}; + + let (mut fixture, _) = home_screen(true); + fixture.room(vec2(1100.0, 700.0)).settle(); + let new = fixture.by_label("New…").expect("New").rect; + let rows: Vec<_> = + ["Home", "Learn", "Website", "Discord", "GitHub"].into_iter().map(|label| (label, fixture.by_label(label).expect(label).rect)).collect(); + for (label, row) in &rows { + assert!((row.width() - new.width()).abs() < 1.0, "{label} {row:?} is a row as wide as New {new:?}"); + } + let rect = |label: &str| rows.iter().find(|(name, _)| *name == label).map(|(_, row)| *row).expect(label); + // Upright lines at the rail's leading edge: the selected row's bar. + let bars: Vec<_> = fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + Shape::LineSegment { points, .. } if (points[0].x - points[1].x).abs() < 0.5 && (points[0].x - new.left()).abs() <= 2.0 => Some(points), + _ => None, + }) + .collect(); + let on = |label| { + let row = rect(label); + bars.iter().any(|p| row.y_range().contains(p[0].y) && row.y_range().contains(p[1].y)) + }; + assert!(on("Home"), "the selected Home row has a bar at its leading edge: {bars:?}"); + for label in ["Learn", "Website", "Discord", "GitHub"] { + assert!(!on(label), "{label} is not selected and has no bar: {bars:?}"); + } +} + /// A desktop Recent tile gives its picture and filename room while keeping the whole card clickable. #[trial] fn desktop_home_recent_cards_give_the_picture_and_caption_room() { From 02be56cfbb6c455e08b9e1dbb41db9b223bd422b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 12:04:22 +0100 Subject: [PATCH 89/89] A memoized view in a row sits on the row's line A memoized view's content starts a layout room of its own (Env::start_room), so the view sat at the top of the unwrapped Row around it while every other one-line child sits with its centre on the row's line. Since craft-menu's bar became a memoized view, PhotoCraft's menu titles sat about 4 pt above the icon beside them (photocraft#16113). The view's room now moves down by the whole pixels that put the centre of its extent (this pass's measuring run, else its last run) on the row's line. The room keeps its size, so a kept run replays moved with it; a view taller than the line reaches stays at the row's top, as place_in_cell keeps a child of more than one line. --- crates/ui-contract/src/contract/lazy.rs | 19 ++++++++++++ crates/ui-contract/src/runtime/lazy.rs | 6 ++++ crates/ui-contract/tests/it/layout/body.rs | 36 +++++++++++++++++++++- 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index bb9ec4da3..04b5bbaba 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -77,6 +77,7 @@ impl Lazy { None => sub(ui.scope_id(), ("lazy", self.key)), }; let available = flow_region(ui); + let available = if matches!(key, Key::Memo(_)) { on_row_line(ui, id, available) } else { available }; let rtl = ui.layout().prefer_right_to_left(); let sizing = ui.is_sizing_pass(); // The child is not part of its body's transcript: in a real run it counts there by its extent, whether it @@ -275,6 +276,24 @@ fn place_view(ui: &mut Ui, rect: Rect) -> Rect { rect } +/// The room of the memoized view `id` in the flow region `room` of `ui`. Its content starts a layout room of its own +/// (`Env::start_room`), so it would sit at the top of the unwrapped `Row` around it; as a child placed in flow +/// (`place_in_cell`), a view of one line sits with its centre on the row's line instead: its room moves down by the +/// whole pixels that put the centre of the extent it took (in this pass's measuring run, else its last run) there. A +/// view taller than that reaches, and a view no run showed yet, stays at the row's top. The room keeps its size, so a +/// kept run replays moved with it. +fn on_row_line(ui: &Ui, id: egui::Id, room: Rect) -> Rect { + let Some(centre) = Env::of(ui).row_line.and_then(|line| line.centre) else { + return room; + }; + let Some(size) = lazy::last_extent(ui.ctx(), id) else { + return room; + }; + let pixels_per_point = ui.ctx().pixels_per_point(); + let above = ((centre - size.y / 2.0) * pixels_per_point).round() / pixels_per_point; + if above.is_finite() && above > 0.0 { room.translate(Vec2::new(0.0, above)) } else { room } +} + /// What a child came to in a pass. pub(super) enum Shown { /// It ran and returned this. diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 19b1b46e3..42bbcbb10 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -433,6 +433,12 @@ pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, meas }); } +/// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it +/// ran), at whatever room it had; `None` before any run showed it. +pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option { + with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[1].map(|measured| measured.size))) +} + /// Registers what the skipped child `id` registered with the focus service in the last real run that showed it, in /// the real run that skips it. pub(crate) fn replay(ctx: &Context, id: Id) { diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index c5844b134..c5a9edcd7 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -3,7 +3,8 @@ use craft_behavior::{ColumnWidth, Proposal, Sense}; use craft_ui::contract::{ - BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, Sizing, + BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, MemoProps, MemoView, Props as _, Role, Show as _, + ShowContainer as _, Sizing, }; use craft_ui::layout::{BodyLayout, RowAlign}; use craft_ui::runtime::env::{Direction, with_env}; @@ -322,6 +323,39 @@ fn the_end_region_shares_the_members_line() { assert!((end.center().y - member.center().y).abs() < SLACK, "the end region's probe {end:?} is off the members' line {member:?}"); } +/// A memoized view of one short block. +#[derive(MemoProps)] +struct Short {} + +fn short(_: &mut Short, ui: &mut Ui) -> Rect { + Block::new(Vec2::new(40.0, 10.0)).show(ui).rect +} + +/// A memoized view in a row sits on the row's line, as the one-line child beside it does, also while it replays. Its +/// content starts a layout room of its own, which left it at the row's top (a menu bar beside an app icon, +/// storytold/photocraft#16113). +#[trial] +fn a_memoized_view_sits_on_the_rows_line() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).id_salt("row").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; + let view = MemoView::new("short", Short {}, short).show(ui); + if !is_measuring(ui.ctx()) { + shown.set((tall, view.unwrap_or(Rect::NOTHING))); + } + }); + }); + fixture.room(Vec2::splat(400.0)).settle(); + for frame in 0..3 { + let (tall, view) = seen.get(); + assert!(view.height() > 0.0, "frame {frame}: the view showed: {view:?}"); + assert!((view.center().y - tall.center().y).abs() < SLACK, "frame {frame}: the view {view:?} is off the line of {tall:?}"); + fixture.settle(); + } +} + /// A Row in right-to-left holding a vertically scrolling container (content-sized, then filling its height) beside a /// probe: the container, the probe inside it and the probe beside it are finite, and the container lies in the row. #[trial]