diff --git a/Cargo.lock b/Cargo.lock index 9b0fb6bfa..add7ab337 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3118,6 +3118,8 @@ dependencies = [ "craft-host", "craft-i18n", "craft-settings", + "craft-tracked", + "craft-ui-macros", "craft-xml", "egui", "serde", @@ -4174,6 +4176,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/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/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..045d04b98 100644 --- a/crates/behavior/src/dock/layout.rs +++ b/crates/behavior/src/dock/layout.rs @@ -19,26 +19,91 @@ 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)] +#[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 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 + } } 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`. + /// 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 } + 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 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 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 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

) { + 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..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. @@ -126,35 +127,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 +151,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 +187,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 +324,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 +356,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 +405,36 @@ 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, 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 seen = std::collections::HashSet::new(); - for window in &mut windows { - while !seen.insert(window.id) { - window.id = fresh_window_id(); - } + 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(windows) + Ok(out) } } 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..5aba1f0b5 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,83 @@ 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 + } + + /// 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(); + 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 +241,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 +366,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..c4461067d 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,117 @@ 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("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(); + 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"); + + // 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/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/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/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 24e52ea6a..22cafcd4f 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -200,8 +200,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/imaging/src/ui/fill/mod.rs b/crates/imaging/src/ui/fill/mod.rs index e419bc8ec..bbcf23b7e 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, 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, @@ -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 a33eb6154..61e2304eb 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, 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, }; 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) @@ -543,10 +555,10 @@ impl LiquifyWorkspace { let shown = Row::new() .fill() .show(ui, |ui, _| { - let rail = - ToolRail::new(words.tools.clone(), &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; + *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 3d8ed06ce..4e3816acd 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, 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, }; 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 c78d00647..622843c21 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, 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, @@ -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 81cfb07bb..6998bec7b 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, 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, @@ -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/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/layers/src/ui/filter/mod.rs b/crates/layers/src/ui/filter/mod.rs index beb2e9023..854e61161 100644 --- a/crates/layers/src/ui/filter/mod.rs +++ b/crates/layers/src/ui/filter/mod.rs @@ -11,7 +11,7 @@ pub(crate) 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 { 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 94aa032d6..65073fec8 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..d8f10d5cd 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. @@ -240,7 +236,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 +246,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 +280,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 +299,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 +312,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 +374,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 +402,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 +442,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 +459,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 6060bcd6f..cc236b5a0 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -5,6 +5,7 @@ pub(crate) mod comps; pub(crate) mod panel_drag_menu; pub(crate) mod panel_filter; pub(crate) mod panel_input; +pub(crate) mod panel_memo; pub(crate) mod panel_order; pub(crate) mod panel_reveal; pub(crate) 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"); } 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/bar.rs b/crates/menu/src/bar.rs index 1003e6708..35e8fe9ae 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -11,8 +11,10 @@ #[cfg(feature = "suite")] 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}; +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..b59aedca0 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, LazyLock}; + +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,6 +40,12 @@ fn model() -> MenuBar { layout(&bar, Target::Linux, &LayoutOptions::new("Sample")).bar } +/// 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()).target(Target::Linux).show(ui); 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/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/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/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/lib.rs b/crates/menu/src/lib.rs index 544c66114..17ffce8ee 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/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`]. 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/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 f7279b42b..dcbfbbee0 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; +pub(crate) mod from_items; pub(crate) mod keytips; pub(crate) mod layout; pub(crate) mod memo; diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index a07bc1b90..614a6d891 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, last_pass_memo_key_bytes, 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,75 @@ 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"); +} + +/// 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/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/menu/tests/it/native.rs b/crates/menu/tests/it/native.rs index 564f66667..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; @@ -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(); @@ -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"); +} 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/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/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-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-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/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 9b9bacdda..1b6695221 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); + } +} + /// Derived `Hash`. impl MemoProps for craft_theme::ComponentSet { fn key(&self, key: &mut MemoKey) { @@ -1020,6 +1027,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/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 7269f8bc7..70006ff2e 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -1107,11 +1107,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 888392774..bc115bded 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -31,12 +31,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/derived.rs b/crates/ui-contract/src/runtime/derived.rs new file mode 100644 index 000000000..d934215a2 --- /dev/null +++ b/crates/ui-contract/src/runtime/derived.rs @@ -0,0 +1,93 @@ +//! 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`], 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::()); + 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| { + 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 +} + +/// 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/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]) diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index f58c68dd2..5c5b630dc 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..cc9010ece 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -52,6 +52,17 @@ 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)>, + /// 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. #[cfg(feature = "testing")] #[derive(Default)] @@ -540,6 +551,47 @@ 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(); + let frame = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)); + pass_state::with::(ctx, |log| { + if log.frame != frame { + log.frame = frame; + log.frame_builds.clear(); + } + 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")] +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 2dc04e1d0..def4d3915 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/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/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 52ef2f8ac..78d04e2e2 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; diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 9d6b37cf8..fab30e3d4 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -54,9 +54,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_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 new file mode 100644 index 000000000..b981ee7a3 --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/derived.rs @@ -0,0 +1,91 @@ +//! 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, MemoRun, last_frame_memo_runs, 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"); +} + +/// 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"); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 7944a64f2..2567420c8 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod chord_fallthrough; pub(crate) mod clipboard; pub(crate) mod control_click; pub(crate) mod cursor; +pub(crate) mod derived; pub(crate) mod elapsed; pub(crate) mod env; pub(crate) mod frame; 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 0e54c35c6..24bb721fc 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 { @@ -154,7 +155,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..cb265feb5 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,19 @@ 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, + 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), &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 +145,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 +266,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..b953bd304 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; @@ -30,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 { @@ -403,13 +406,17 @@ 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. 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. @@ -433,10 +440,12 @@ 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(), + 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 11f5b9cdd..dde2721b2 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -13,16 +13,16 @@ use craft_ui::canvas::{ tool_pass, }; use craft_ui::canvas_controls::{Guides, Marquee}; -use craft_ui::contract::SizeLimits; 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::contract::{SizeLimits, Tracked}; +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,20 +45,23 @@ 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, - /// 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. 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) => { @@ -67,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() } @@ -92,13 +95,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 +114,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/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index d01fa012f..4e487eefd 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"); @@ -68,7 +68,7 @@ pub enum ColumnArrow { /// Collapses the column to icons, or expands it. #[default] Collapse, - /// Switches a stepped column ([`stepped`]) between one and two steps. Holds the steps it shows. + /// Switches a stepped column ([`DockSizes::stepped`](super::DockSizes::stepped)) between one and two steps. Holds the steps it shows. Steps(u16), /// Nothing: the column neither collapses nor has steps. It shows no double arrow, and its menu offers no /// collapse. @@ -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/drop.rs b/crates/ui-panels/src/docking/drop.rs index 4a94c1131..b08d63c16 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/event.rs b/crates/ui-panels/src/docking/event.rs index 5fdfe8bcc..d0adf5976 100644 --- a/crates/ui-panels/src/docking/event.rs +++ b/crates/ui-panels/src/docking/event.rs @@ -1,7 +1,9 @@ //! `DockEvent`, `FloatSpace` and `HidePanels`: what a dock reports to the host and the host tells a dock. -use super::{DockCommands, DockSizes, DragUnit}; +use super::{DockCommands, DockSizes, DragUnit, PanelKey}; +use crate::contract::{MemoProps, Tracked}; 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)] @@ -42,24 +44,20 @@ pub enum DockEvent

{ /// 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, MemoProps)] #[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

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..8201517d8 100644 --- a/crates/ui-panels/src/docking/frame.rs +++ b/crates/ui-panels/src/docking/frame.rs @@ -1,5 +1,6 @@ //! What the tree adds around the groups: Maximize Frame, the hidden-panel prune and the outer edge bands. +use super::PanelKey; use super::config::DockConfig; use super::event::HidePanels; use super::targets::{DockSizes, DockSpot, DockTargets}; @@ -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..237c1014a 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,8 @@ 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], + #[memo_props(hash = "its Hash is the content key taken when the titles were made")] + panels: Titles, active: PanelKey, closable: bool, wheel_selects: bool, @@ -598,7 +599,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 ee98e4d2d..e3794a20f 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}; @@ -59,7 +59,7 @@ pub(crate) 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}; @@ -79,12 +79,13 @@ use divider::{Divider, Drag}; use egui::{Rect, Response, Vec2}; use std::fmt::Debug; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; 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,34 @@ pub struct PanelTitle { pub closable: bool, } +/// 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>, + key: u128, +} + +impl Titles { + /// 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) } + } + + /// The titles in tab order. + pub fn as_slice(&self) -> &[PanelTitle] { + &self.list + } +} + +/// 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); + } +} + impl PanelTitle { /// A panel `key` titled `title`, not closable from its tab. pub fn new(key: PanelKey, title: impl Into

: 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/placed.rs b/crates/ui-panels/src/docking/placed.rs index c276de59b..c6f496872 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; @@ -20,7 +20,7 @@ pub struct Placing<'a, P> { /// The panels that always show, such as a canvas. pub protected: &'a dyn Fn(&P) -> bool, /// The panels the area hides, as the shell's visibility leaves them. - pub hide: HidePanels<'a, P>, + pub hide: HidePanels<'a>, /// The panel whose frame the area shows maximized. pub maximized: Option<&'a P>, /// The floating window whose column the dock lays out, by its id; `None` for a dock area's docked tree. @@ -35,7 +35,7 @@ impl<'a, P> Placing<'a, P> { /// The area hides `hide` and shows the frame of `maximized` alone. #[must_use] - pub fn shown(mut self, hide: HidePanels<'a, P>, maximized: Option<&'a P>) -> Self { + pub fn shown(mut self, hide: HidePanels<'a>, maximized: Option<&'a P>) -> Self { self.hide = hide; self.maximized = maximized; self @@ -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/spec.rs b/crates/ui-panels/src/docking/spec.rs index b395cd6f0..2758a1cd1 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. + Content { 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::Content { 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::Content { .. } => 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::Content { 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..3149f9795 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -4,9 +4,11 @@ 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, Titles, 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; @@ -45,7 +47,7 @@ fn dock(ui: &mut Ui, bind: Bind<'_, Layout>, shown: &Layout) -> St let Some(Node::Tabs { panels, .. }) = shown.place(&anchor).and_then(|place| shown.node_of(&place)) else { continue }; let panels = titles(panels); let active = panels.first().map_or(PanelKey::new(0), |panel| panel.key); - DockGroup::new(anchor, &panels, active).show_at(ui, rect, |_, _| ()); + DockGroup::new(anchor, Titles::from_content(panels.clone()), active).show_at(ui, rect, |_, _| ()); } }); area.output.edit.into() @@ -84,14 +86,14 @@ fn a_dock_of_one_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(DockGroup<'static, usize>, covers = [Default])] fn two_panels(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); - DockGroup::new(LAYERS, &panels, panels[0].key).show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).show(ui, |_, _| ()).output.into() } /// A group in a floating window: nothing goes beside it, so a drop on its body joins it or stacks above or below. #[story(DockGroup<'static, usize>, covers = [Default])] fn a_group_in_a_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); - DockGroup::new(LAYERS, &panels, panels[0].key).in_window().show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).in_window().show(ui, |_, _| ()).output.into() } /// A click on the panel menu button opens the group's panel menu. @@ -106,7 +108,7 @@ fn open_panel_menu(fixture: &mut Fixture) { fn panel_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); let rows = [DockCommands::FloatPanel, DockCommands::FloatGroup].map(|command| PanelRow::Command(CommandRef::from(command))).to_vec(); - DockGroup::new(LAYERS, &panels, panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() } #[story(GroupGrip, covers = [Default])] @@ -130,21 +132,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 7ab6ef704..15a9f1c79 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; @@ -69,6 +69,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 { @@ -78,6 +83,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; @@ -103,6 +114,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, } } @@ -120,9 +133,9 @@ impl DockSizes { /// The width an expanded column's panels draw at, whether the column is expanded or iconic (its flyout and a /// floated iconic column use it): the stored width kept within the panels' limits, or a stepped column's width - /// at its steps ([`stepped`]). + /// at its steps ([`DockSizes::stepped`](super::DockSizes::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); @@ -141,7 +154,7 @@ impl DockSizes { pub fn shown_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { if column.iconic { self.iconic_bounds(column, spec) - } 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) @@ -175,7 +188,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| { @@ -201,7 +214,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/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/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 b59097803..900210f47 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -8,8 +8,8 @@ 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::docking::DockGrid; +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}; 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 `first` wide at one column and `step` 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 @@ -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,17 @@ pub struct ToolRail<'a, T: Value + MemoProps + 'static> { #[prop(flag)] editing: bool, /// The tools the user's toolbar settings hide. - #[prop] - hidden: &'a [T], + #[prop(into)] + 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

{ /// 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. @@ -98,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`. @@ -108,18 +110,22 @@ 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. #[prop] - hide: HidePanels<'a, P>, + hide: HidePanels<'a>, /// The panel whose frame shows alone. #[prop] maximized: Option

, @@ -138,13 +144,21 @@ 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. 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

, + config: DockConfig, + ) -> Self { DockArea { label: label.into(), workspace, + specs, panels, config, hide: HidePanels::None, @@ -155,10 +169,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) } } } @@ -169,18 +189,21 @@ struct AreaMemory

{ 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. #[derive(Clone)] struct Moving

{ id: GestureId, - before: Workspace

, + before: Arc>, } impl

Default for AreaMemory

{ fn default() -> Self { - AreaMemory { open: None, moving: None } + AreaMemory { open: None, moving: None, window_floor: 0 } } } @@ -192,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, } @@ -232,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

, @@ -254,6 +287,36 @@ 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 +/// 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) @@ -277,7 +340,7 @@ struct Passed

{ events: Vec>, focused: Option

, picked: Option

, - edit: EditEvents>, + edit: EditEvents>>, space: Option>, columns: Vec<(P, Rect)>, windows: Vec<(P, ViewportId)>, @@ -296,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)>, } @@ -346,7 +409,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 +418,25 @@ 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 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; 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| { @@ -397,26 +451,30 @@ 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, current: ¤t, config: &config, - specs: &specs, + specs: &model.specs, + keys: &model.keys, hide, + model: key, 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 +517,29 @@ 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. New windows take ids above every id the area has shown (`AreaMemory::window_floor`). 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); + 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() { @@ -489,7 +549,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,10 +558,12 @@ fn apply_actions( struct Input<'i, P> { id: Id, ctx: &'i Context, - current: &'i Workspace

, + current: &'i Arc>, config: &'i DockConfig, specs: &'i HashMap, - hide: HidePanels<'i, P>, + keys: &'i HashMap, + hide: HidePanels<'i>, + model: ModelKey, maximized: Option<&'i P>, auto_collapse: bool, sizes: DockSizes, @@ -530,28 +592,30 @@ 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, model, 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 (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(ctx, bounds, &sizes, config, specs); let scene = Scene { dock: id, + view: MemoKey::of(&prune), sizes, config, 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 +661,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 +694,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)); } @@ -857,6 +928,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 @@ -864,10 +936,17 @@ 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)); + // 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::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); @@ -879,7 +958,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()) @@ -1029,7 +1108,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, @@ -1060,7 +1139,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; @@ -1075,7 +1154,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 @@ -1145,7 +1224,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); @@ -1395,22 +1474,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)), @@ -1420,7 +1499,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/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/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index d335a4bd6..458d2df43 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"); @@ -143,10 +144,28 @@ 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; -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 +173,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 +190,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 +205,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 +225,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 +251,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/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/floating_area.rs b/crates/ui-patterns/tests/it/docking/floating_area.rs index 7fad2cfbe..60704d765 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, IconicSizes, PanelSpec, request_actions}; +use craft_ui::docking::{DockConfig, DockPanels, GroupDrag, IconicSizes, request_actions}; use craft_ui::layout_components::Stack; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag::{self, DropMark}; @@ -14,6 +15,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; @@ -30,19 +32,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 => { @@ -63,7 +55,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. @@ -72,19 +64,20 @@ struct Bed { chrome: 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 chrome = 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_chrome = Rc::clone(&chrome); - 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 { @@ -92,7 +85,7 @@ fn bed(layout: Layout, rights: fn(&usize) -> Permissions) -> Bed { seen_chrome.set(space.chrome); } 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(); @@ -109,7 +102,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) { @@ -122,7 +115,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)); @@ -140,7 +133,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()); } @@ -149,12 +142,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)]); @@ -167,10 +160,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"); } @@ -180,14 +169,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(); @@ -195,16 +184,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); @@ -216,7 +205,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(); @@ -231,7 +220,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()); } @@ -240,7 +229,7 @@ fn a_floating_windows_drag_bar_shows_no_title() { /// window draws: the window's group starts right under it. #[trial] fn a_floating_windows_group_starts_under_the_chrome_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,16 +250,16 @@ 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. fn dragged_from(from: Pos2, by: Vec2) -> Rect { - 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, 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 /// production's 18 pt bar over its tabs was. #[trial] fn a_floating_windows_title_row_is_shorter_than_its_tab_strip() { - 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 in_window = |role| bed.fixture.by_role(role).into_iter().find(|node| WINDOW_AT.expand(SLACK).contains_rect(node.rect)).map(|node| node.rect); let row = in_window(Role::HEADING).expect("the window shows its title row"); let tab = in_window(Role::TAB).expect("the window shows its tab"); @@ -296,7 +285,7 @@ fn a_floating_windows_corner_and_edge_grips_reach_as_far_in_as_productions() { /// The top grip never lies over the title row: a press just inside the row's top moves the window, at its size. #[trial] fn the_top_of_a_floating_windows_title_row_moves_it_and_never_resizes_it() { - 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 row = bed.fixture.by_role(Role::HEADING).into_iter().find(|node| WINDOW_AT.expand(SLACK).contains_rect(node.rect)).expect("the title row").rect; let by = Vec2::new(-30.0, 20.0); @@ -309,14 +298,14 @@ fn the_top_of_a_floating_windows_title_row_moves_it_and_never_resizes_it() { /// production's behaviour, which the move already had. #[trial] fn a_click_on_a_floating_windows_bar_neither_moves_nor_docks_it_and_a_drag_moves_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 at = window_title(); bed.fixture.frame(vec![moved(at)]); 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:?}"); @@ -326,14 +315,14 @@ fn a_click_on_a_floating_windows_bar_neither_moves_nor_docks_it_and_a_drag_moves #[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); @@ -350,7 +339,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:?}"); @@ -373,7 +362,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 @@ -387,7 +376,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"); @@ -396,14 +385,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]) } @@ -426,7 +415,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); let band = strip_band(icon); @@ -437,7 +426,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:?}"); } } @@ -449,7 +438,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. @@ -461,7 +450,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"); @@ -490,9 +479,9 @@ fn strip_band(icon: Rect) -> Pos2 { /// collapsing again. #[trial] fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_columns_step() { - let mut bed = bed(collapsed_at(WINDOW_AT), |_| Permissions::ALL); + 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); @@ -507,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:?}"); @@ -521,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. @@ -534,7 +525,7 @@ fn a_collapsed_windows_sides_resize_its_width_and_show_names_from_the_docked_col 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"); @@ -547,16 +538,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_title().y); 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 = strip_band(icon); 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 @@ -564,7 +555,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) @@ -583,7 +574,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()); } } @@ -597,7 +588,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()); @@ -606,15 +597,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"); } @@ -623,7 +614,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..263178cd0 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, PanelKey, 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 keep = |panel: &usize| *panel == TOOLBAR || *panel == PALETTE; - let mut area = DockArea::new("Hidden dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()); + let specs = Tracked::new(Specs); + 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/mod.rs b/crates/ui-patterns/tests/it/docking/mod.rs index d95e562d5..0b6ed9892 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 681d42e1e..8e0fd047e 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"); @@ -667,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![]); } @@ -696,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"); @@ -720,11 +733,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. @@ -734,7 +747,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"); } @@ -744,10 +757,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<'_>) {} } @@ -758,14 +767,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::>() }; @@ -774,7 +790,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)); @@ -793,11 +809,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); }; @@ -816,7 +833,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 {:?}", @@ -828,10 +845,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, |_, _| {}); } @@ -845,15 +858,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(); }); @@ -875,7 +888,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..b3b76895e 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; } @@ -106,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/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 60f7a82f0..ec73100e1 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -6,25 +6,35 @@ 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_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; +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 +47,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 +93,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 +121,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 +157,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 +202,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 +301,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 +330,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 +378,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 +394,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 +411,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 +429,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 +438,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 +448,67 @@ 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"); +} + +/// 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"); +} diff --git a/crates/ui-patterns/tests/it/docking/split.rs b/crates/ui-patterns/tests/it/docking/split.rs index 89df28103..2d89727a4 100644 --- a/crates/ui-patterns/tests/it/docking/split.rs +++ b/crates/ui-patterns/tests/it/docking/split.rs @@ -2,15 +2,16 @@ 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::cell::RefCell; +use std::collections::BTreeSet; use std::rc::Rc; fn spec(panel: &u8) -> PanelSpec { @@ -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); diff --git a/crates/ui-widgets/tests/it/menu/mod.rs b/crates/ui-widgets/tests/it/menu/mod.rs index 8a164d05f..457121437 100644 --- a/crates/ui-widgets/tests/it/menu/mod.rs +++ b/crates/ui-widgets/tests/it/menu/mod.rs @@ -16,6 +16,7 @@ pub(crate) mod pick_focus; pub(crate) mod rows; +pub(crate) mod runs_per_row; pub(crate) mod search; pub(crate) 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}"); +} diff --git a/docs/ui-docking.md b/docs/ui-docking.md index a6ab3fd4f..2bc95b3b8 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`). 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`): | 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 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.