diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 8d116bd79..b8572fcd0 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -330,6 +330,7 @@ impl Layout

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

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

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

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

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

Default for Layout

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

Layout

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

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

StackEntry

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

Floating

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

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

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

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

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

Floating

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

= (Option, Floating

); + impl

Repr

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

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

, + layout: Layout

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

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

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

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

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

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

Workspace

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

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

, hidden: Vec<(P, Location

)>, floated: Vec<(P, Location

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

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

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

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

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

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

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

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

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

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

From> for WorkspaceSet

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

From> for WorkspaceSet

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

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

`. +pub trait SpecSource

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

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

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

, - panels: &'a dyn DockPanels

, + specs: &'a dyn SpecSource

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

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

, panels: &'a dyn DockPanels

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

, specs: &'a dyn SpecSource

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

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

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

Outcome for DockAreaOutput

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

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

, panels: &'a mut dyn DockPanels

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

>, panels: &'a mut dyn DockPanels

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

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

, panels: &'a mut dyn DockPanels

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

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

{ #[derive(Clone)] struct Moving

{ id: GestureId, - before: Workspace

, + before: Arc>, } impl

Default for AreaMemory

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

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

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

{ + fn of(workspace: &Workspace

, specs: &dyn SpecSource

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

{ events: Vec>, focused: Option

, picked: Option

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

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

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

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

>, - current: &Workspace

, - panels: &dyn DockPanels

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

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

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

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

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

>>, ) -> Passed

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

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

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

(from: &Node

, to: &Node

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

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

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

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

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

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

` for the views: + +| Method | Does | +| --- | --- | | `body` | Shows the panel's body in the group's body, which the group insets by the panel padding (`Pad::Regular`). The group is the body's panel, so the body adds no `Panel` or padding of its own. A document panel's body (`WindowKind::Document`) is shown edge to edge. | | `group_view` | Takes a whole group in place of its tab strip and body, in a `Ui` held to the group's rect; a canvas group draws its document here. Default `None`. | | `group_header` | The host's controls in a group header, before the tab strip. | | `panel_rows` | The host's rows of a panel's menu, before the dock's own. | -The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a layout locked. +The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision. A panel body, or code a body calls, changes the workspace during the pass with `docking::request_actions(ctx, actions)`, never by writing the workspace the area shows. The running area takes them unapplied and returns them in `DockAreaOutput::requested`, in order, for the host to apply after `actions` in the same frame. With no area over that panel type running, `request_actions` hands the actions back for the caller to apply. @@ -103,9 +112,10 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A column collapsed to icons takes drops as an expanded column does: its edges (a new column beside it, docked only), the seams between its icon groups, the top of the first group and the bottom of the last (a new group above or below), and each icon group's cells (join its tabs). The column's state wins: a panel dropped into a collapsed column shows as an icon, one dropped into an expanded column shows expanded. - Nothing goes beside a floating window: its column registers no edge bands, and its groups (`DockGroup::in_window`) take no drop on their start and end sides. - A collapsed column's flyouts open on the side `IconicColumn::opens` names: away from a dock's window edge, and towards the room of the float area for a floating window. A floating window keeps to its edge of the float area: `Floating::edge`, else the one nearer its rect. A move keeps the edge it began with. A collapsed window's move ends at the edge nearer its strip where it was dropped, with the rect that shows the strip there (`WindowColumn::dropped`), and the area records that edge (`Action::MoveFloating`'s `edge`); a unit dragged out of a collapsed column (`start_icon_drag`) floats collapsed the same way, its strip under the pointer (`Target::Float`'s `edge`). Collapsing a floating column and moving an expanded window clear the edge. A column that neither collapses nor has steps shows no double arrow and offers no collapse in its menu (`ColumnArrow::Fixed`). -- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. +- A panel that lays its content in a grid (a toolbar) declares it with `PanelSpec::grid` (`DockGrid`: the width at one content column, the width each further column adds, and the most columns; `DockGrid::rail` for a tool rail, sized by the dock). Its column, given steps (`Column::steps`), is a whole number of content columns wide and as tall as the content measures at that width: docked from the top of the dock, content taller than the dock scrolls inside; floating under the title row, at the window's place. A drag of the column's edge, or of a floating window's side, sets the most steps that fit, and a drag of a floating window's left side keeps its right edge, one of its top its bottom edge; a drag of a floating window's top or bottom sets the fewest whose content fits. When the column's panels do not collapse, its double arrow switches between one and two steps (`ColumnArrow::Steps`), named for the count it switches to and pointing the way the column grows or shrinks. A dock side's total width (`DockSizes::resize_side`) leaves a stepped column's width alone. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. -- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. +- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives. +- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`): it only grows while the layout lives, and `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, so an OS window never passes to another window. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. - Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s.