diff --git a/Cargo.lock b/Cargo.lock index 9b0fb6bfa..a0c55e90d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3118,6 +3118,8 @@ dependencies = [ "craft-host", "craft-i18n", "craft-settings", + "craft-tracked", + "craft-ui-macros", "craft-xml", "egui", "serde", @@ -4174,6 +4176,8 @@ name = "craft-theme" version = "0.1.0" dependencies = [ "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", "ecolor", "log", "proptest", @@ -4248,6 +4252,7 @@ name = "craft-tracked" version = "0.1.0" dependencies = [ "craft-ui-macros", + "serde", ] [[package]] @@ -5445,7 +5450,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "bytemuck", "emath", @@ -5501,7 +5506,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "ahash", "bytemuck", @@ -5536,7 +5541,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "accesskit", "ahash", @@ -5555,7 +5560,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "ahash", "bytemuck", @@ -5574,7 +5579,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5594,7 +5599,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "bytemuck", "egui", @@ -5607,7 +5612,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "eframe", "egui", @@ -5684,7 +5689,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "bytemuck", ] @@ -5757,7 +5762,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" dependencies = [ "ahash", "bytemuck", @@ -5783,7 +5788,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" [[package]] name = "equator" @@ -15114,19 +15119,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" diff --git a/Cargo.toml b/Cargo.toml index 984ee25ca..44df434e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 8429d5025..179ff8a17 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -60,7 +60,9 @@ impl ActionsSettings { /// The Actions panel's persisted section: Button Mode and the collapsed sets. /// Selection and expansion are not persisted. -#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ActionsSettings { @@ -72,7 +74,7 @@ pub struct ActionsSettings { /// A row of the tree: a set header, an action or one of its steps. Also the selection (one row at /// a time) and the list's key. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub enum ActionSelection { /// The set header of this name. @@ -89,7 +91,7 @@ pub enum ActionSelection { /// The panel remaps `selected` itself when it reports a [`Reorder`](ActionsEvent::Reorder) /// that moves a row, since it owns the selection. After a [`Delete`](ActionsEvent::Delete) the /// app clears `selected` (the panel cannot tell which rows the delete removed). -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct ActionsPanelState { /// The persisted section. diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index e3ffa2745..af14c260b 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -46,7 +46,7 @@ pub enum CursorIcon { } /// An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui_macros::PlainData)] pub struct IconId(Cow<'static, str>); impl IconId { diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 8d116bd79..b8572fcd0 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -330,6 +330,7 @@ impl Layout

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

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

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

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

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

From> for Layout

{ + fn from(saved: Saved

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

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

Default for Layout

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

Layout

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

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

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

{ /// Names the window across panel moves, and its OS window. - /// Unique within a layout: [`Self::new`] draws a fresh id, [`Self::with_id`] sets one, - /// loading keeps the saved id (or draws one when it is missing or taken), and merging - /// windows keeps the receiving window's. + /// Unique within a layout: [`Self::new`] and [`Self::with_id`] take one from the caller (a window a layout adds + /// takes [`Layout::fresh_window_id`](super::Layout::fresh_window_id)), loading keeps the saved id (or gives one + /// above every saved id when it is missing or taken), and merging windows keeps the receiving window's. pub id: u64, /// The window's groups, top to bottom, and its collapsed state. Its `width` is unused: the window's width is /// `rect`'s. @@ -126,35 +127,20 @@ impl

StackEntry

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

Floating

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

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

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

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

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

Floating

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

= (Option, Floating

); + impl

Repr

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

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

, + layout: Layout

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

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

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

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

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

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

Workspace

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

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

, hidden: Vec<(P, Location

)>, floated: Vec<(P, Location

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

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

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

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

) -> Self { + self.layout = layout; + self.touch(); + self + } + + /// Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + /// workspace an undo brings back to it, so no id, and no OS window, goes to a second window. + pub fn raise_window_floor(&mut self, floor: u64) { + if self.layout.raise_window_floor(floor) { + self.touch(); + } + } + + /// Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. + pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool) { + let before = self.hidden.len(); + self.hidden.retain(|(panel, _)| !forget(panel)); + if self.hidden.len() != before { + self.touch(); + } + } + + /// Moves the revision. Every method that writes the workspace calls it. + fn touch(&mut self) { + self.revision.edit(|()| ()); + } + + /// Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this + /// workspace never gave out, so no OS window passes to another window. pub fn replace(&mut self, with: Workspace

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

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

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

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

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

From> for WorkspaceSet

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

From> for WorkspaceSet

{ if let Some(layout) = stored.saved && let Some(named) = saved.iter_mut().find(|w| w.id == id) { - named.layout.layout = layout; + named.layout = std::mem::take(&mut named.layout).with_layout(layout); } edited.insert(id, stored.workspace); } diff --git a/crates/behavior/tests/dock.rs b/crates/behavior/tests/dock.rs index e9d825400..2858bb282 100644 --- a/crates/behavior/tests/dock.rs +++ b/crates/behavior/tests/dock.rs @@ -32,7 +32,10 @@ fn docked() -> Layout { DockEdge::End, vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)]).with_width(180.0), Column::new(vec![g(&[5], 0)]).with_width(120.0)], ); - Layout::new(Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], WINDOW).unwrap()]) + Layout::new( + Some(hsplit(SplitSize::FixedSecond(300.0), middle, dock)), + vec![Floating::stack(100, vec![g(&[6, 7], 1), g(&[8], 0)], WINDOW).unwrap()], + ) } fn with_column(column: Column) -> Layout { @@ -165,7 +168,7 @@ fn without(skip: Option) -> Layout { let windows: Vec> = [group(&[6], 0), tall].into_iter().flatten().collect(); Layout::new( Some(hsplit(SplitSize::FixedSecond(300.0), tabs(&[1], 0), end)), - vec![Floating::stack(windows, area(10.0, 10.0, 200.0, 300.0)).unwrap()], + vec![Floating::stack(101, windows, area(10.0, 10.0, 200.0, 300.0)).unwrap()], ) } @@ -203,7 +206,7 @@ fn a_layout_saved_with_the_physical_names_loads_and_writes_back_in_reading_order tabs(&[1, 2], 1), Node::dock(DockEdge::End, vec![Column::new(vec![g(&[3], 0)]).with_width(180.0)]), )), - vec![Floating::single(vec![4], 0, area(1.0, 2.0, 300.0, 200.0)).with_id(5)], + vec![Floating::single(5, vec![4], 0, area(1.0, 2.0, 300.0, 200.0))], ); assert_eq!(layout, expected); let written = serde_json::to_value(&layout).unwrap(); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 59d764ad3..c4461067d 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -32,7 +32,7 @@ fn docked() -> Layout { vec![Column::new(vec![g(&[2, 3], 1), g(&[4], 0)]).with_width(180.0), Column::new(vec![g(&[5], 0)]).with_width(120.0)], ); let root = Node::split(Axis::X, SplitSize::FixedSecond(300.0), middle, dock); - Layout::new(Some(root), vec![Floating::stack(vec![g(&[6, 7], 1), g(&[8], 0)], window()).unwrap()]) + Layout::new(Some(root), vec![Floating::stack(100, vec![g(&[6, 7], 1), g(&[8], 0)], window()).unwrap()]) } const ALL: [u32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 11, 12]; @@ -79,32 +79,33 @@ fn apply_all_changes_everything_or_nothing_and_reports_the_closed_panels() { #[test] fn reconcile_drops_unknown_panels_and_places_missing_registered_ones() { let default = Workspace::new(docked()); - let mut workspace = default.clone(); - workspace.layout.apply(Action::close(5)).unwrap(); - workspace.layout.apply(Action::close(12)).unwrap(); - workspace.layout.apply(Action::open_at(99, 2, DockPlacement::tab(None))).unwrap(); - let stray = workspace.layout.location(&99).unwrap(); - workspace.hidden.push((98, stray)); + let mut layout = docked(); + layout.apply(Action::close(5)).unwrap(); + layout.apply(Action::close(12)).unwrap(); + layout.apply(Action::open_at(99, 2, DockPlacement::tab(None))).unwrap(); + let stray = layout.location(&99).unwrap(); + let mut workspace = Workspace::from_parts(layout, vec![(98, stray)], Vec::new()); let registered = |p: &u32| *p < 90; workspace.reconcile(registered, allow, &default); workspace.validate().unwrap(); // Unregistered panels wait in `hidden` and come back once registered. - assert_eq!(workspace.hidden.iter().map(|(p, _)| *p).collect::>(), [98, 99]); - assert_eq!(sorted(&workspace.layout), ALL); + assert_eq!(workspace.hidden().iter().map(|(p, _)| *p).collect::>(), [98, 99]); + assert_eq!(sorted(workspace.layout()), ALL); workspace.set_visible(99, true, None, false, allow).unwrap(); - assert_eq!(group_members(&workspace.layout, 2), [2, 3, 99]); - assert_eq!(end_dock(&workspace.layout).len(), 2); - assert_eq!(group_members(&workspace.layout, 11), [11, 12]); + assert_eq!(group_members(workspace.layout(), 2), [2, 3, 99]); + assert_eq!(end_dock(workspace.layout()).len(), 2); + assert_eq!(group_members(workspace.layout(), 11), [11, 12]); - let mut broken = default.clone(); - broken.layout.floating[0].rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(-1.0, 400.0)); + let mut layout = docked(); + layout.floating[0].rect = Rect::from_min_size(pos2(100.0, 100.0), vec2(-1.0, 400.0)); + let mut broken = Workspace::new(layout); broken.reconcile(registered, allow, &default); - assert_eq!(broken.layout, default.layout); + assert_eq!(broken.layout(), default.layout()); } #[test] fn a_workspace_set_with_a_floating_group_round_trips_through_json() { - let layout = Layout::new(Some(Node::tabs(vec![1u32, 2], 0)), vec![Floating::single(vec![3u32], 0, rect(1.0, 2.0, 300.0, 200.0)).with_id(5)]); + let layout = Layout::new(Some(Node::tabs(vec![1u32, 2], 0)), vec![Floating::single(5, vec![3u32], 0, rect(1.0, 2.0, 300.0, 200.0))]); let mut set = WorkspaceSet::new(vec![NamedWorkspace::new("essentials", "Essentials", Workspace::default())]); set.save("Mine", Workspace::new(layout), WorkspaceChrome::default(), WorkspaceKeeps::new(false, true, true)).unwrap(); let saved = serde_json::to_string(&set).unwrap(); @@ -134,18 +135,18 @@ fn a_workspace_with_a_bottom_pane_opens_and_closes_it_on_switch() { ]); let mut live = photography; set.select("motion", &mut live).unwrap(); - let bottom = live.layout.place(&TIMELINE).unwrap(); + let bottom = live.layout().place(&TIMELINE).unwrap(); assert_eq!(bottom, PanelPlace::Node(vec![true]), "the Timeline is the second (bottom) frame of the split"); set.select("photography", &mut live).unwrap(); - assert!(!live.layout.contains(&TIMELINE), "leaving Motion closes the Timeline"); + assert!(!live.layout().contains(&TIMELINE), "leaving Motion closes the Timeline"); set.select("motion", &mut live).unwrap(); - assert!(live.layout.contains(&TIMELINE), "coming back opens it again"); + assert!(live.layout().contains(&TIMELINE), "coming back opens it again"); } -/// Switching and resetting replace the live workspace and move it to a new revision; edits and selecting the shown -/// workspace keep it, and the revision is neither saved nor compared. +/// Switching and resetting replace the live workspace and move it to a new generation; edits and selecting the shown +/// workspace keep it, and the generation is neither saved nor compared. #[test] -fn only_a_replacement_changes_the_live_revision() { +fn only_a_replacement_changes_the_live_generation() { let essentials = Workspace::new(Layout::new(Some(tabs(&[1, 2], 0)), Vec::new())); let painting = Workspace::new(Layout::new(Some(tabs(&[3], 0)), Vec::new())); let mut set = WorkspaceSet::new(vec![ @@ -153,20 +154,20 @@ fn only_a_replacement_changes_the_live_revision() { NamedWorkspace::new("painting", "Painting", painting), ]); let mut live = essentials.clone(); - let start = live.revision(); + let start = live.generation(); live.apply(Action::activate(2), false, allow).unwrap(); live.set_visible(1, false, None, false, allow).unwrap(); set.select("essentials", &mut live).unwrap(); - assert_eq!(live.revision(), start, "edits and selecting the shown workspace keep the revision"); + assert_eq!(live.generation(), start, "edits and selecting the shown workspace keep the generation"); set.select("painting", &mut live).unwrap(); - let switched = live.revision(); - assert!(switched != start && live.layout.contains(&3), "a switch replaces the live workspace"); + let switched = live.generation(); + assert!(switched != start && live.layout().contains(&3), "a switch replaces the live workspace"); set.reset(&mut live).unwrap(); - assert!(live.revision() != switched, "a reset replaces it again"); + assert!(live.generation() != switched, "a reset replaces it again"); set.select("essentials", &mut live).unwrap(); - assert!(!live.layout.contains(&1), "the switch back shows the edited essentials"); + assert!(!live.layout().contains(&1), "the switch back shows the edited essentials"); let loaded: Workspace = serde_json::from_str(&serde_json::to_string(&live).unwrap()).unwrap(); - assert_eq!(loaded, live, "the revision is not saved and not part of equality"); + assert_eq!(loaded, live, "the generation is not saved and not part of equality"); } /// Open of a hidden panel follows its record: a floating panel returns to its window; a record whose anchor is gone @@ -175,39 +176,39 @@ fn only_a_replacement_changes_the_live_revision() { fn opening_a_closed_floating_panel_restores_its_window_place() { let mut workspace = Workspace::new(docked()); workspace.apply(Action::close(8), false, allow).unwrap(); - assert!(workspace.layout.place(&8).is_none()); + assert!(workspace.layout().place(&8).is_none()); workspace.apply(Action::open(8, Some(11)), false, allow).unwrap(); - assert!(matches!(workspace.layout.place(&8), Some(PanelPlace::Floating { .. })), "back in its window"); - assert!(workspace.hidden.is_empty()); + assert!(matches!(workspace.layout().place(&8), Some(PanelPlace::Floating { .. })), "back in its window"); + assert!(workspace.hidden().is_empty()); - let mut stray = workspace.layout.location(&5).unwrap(); + let mut stray = workspace.layout().location(&5).unwrap(); stray.anchor = Some(99); - workspace.hidden.push((50, stray)); + let mut workspace = Workspace::from_parts(workspace.layout().clone(), vec![(50, stray)], Vec::new()); workspace.apply(Action::open(50, Some(11)), false, allow).unwrap(); - assert_eq!(group_members(&workspace.layout, 11), [11, 12, 50]); + assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]); } /// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first. #[test] fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { let mut workspace = Workspace::new(docked()); - let docked_at = workspace.layout.location(&2).unwrap(); + let docked_at = workspace.layout().location(&2).unwrap(); workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated, [(2, docked_at.clone())]); + assert_eq!(workspace.floated(), [(2, docked_at.clone())]); workspace.apply(Action::float(2, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated, [(2, docked_at)], "floating again from the float keeps the first record"); + assert_eq!(workspace.floated(), [(2, docked_at)], "floating again from the float keeps the first record"); workspace.apply(Action::move_beside(2, 11, DockPlacement::tab(None)), false, allow).unwrap(); - assert!(workspace.floated.is_empty(), "docking drops the record"); + assert!(workspace.floated().is_empty(), "docking drops the record"); workspace.apply(Action::float(3, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); - assert_eq!(workspace.floated.len(), 1); + assert_eq!(workspace.floated().len(), 1); workspace.apply(Action::close(3), false, allow).unwrap(); - assert!(workspace.floated.is_empty(), "closing drops the record"); + assert!(workspace.floated().is_empty(), "closing drops the record"); } /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); - Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(vec![6], 0, window())]) + Layout::new(Some(Node::split(Axis::X, SplitSize::FixedSecond(300.0), tabs(&[1], 0), dock)), vec![Floating::single(101, vec![6], 0, window())]) } fn floats(layout: &Layout, panel: u32) -> bool { @@ -318,12 +319,13 @@ fn a_panel_that_does_not_collapse_keeps_its_column_expanded() { layout.apply_with_permissions(Action::set_iconic(3, false), rigid).unwrap(); layout.apply_with_permissions(Action::move_group(2, Target::at(3, DockPlacement::group(true, None))), rigid).unwrap(); - let mut saved = Workspace::new(columns()); - saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); - assert!(column_of(&saved.layout, 2).iconic); + let mut layout = columns(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + let mut saved = Workspace::new(layout); + assert!(column_of(saved.layout(), 2).iconic); saved.reconcile(|_| true, rigid, &Workspace::new(columns())); - assert!(!column_of(&saved.layout, 2).iconic, "reconcile expands the column"); - assert_eq!(group_members(&saved.layout, 2), [2]); + assert!(!column_of(saved.layout(), 2).iconic, "reconcile expands the column"); + assert_eq!(group_members(saved.layout(), 2), [2]); } /// A panel that shares no column (a toolbar) refuses every placement that puts it beside other panels in a column @@ -348,11 +350,12 @@ fn a_panel_that_shares_no_column_moves_only_to_a_column_of_its_own() { assert_eq!(column_of(&moved, 2).panels().count(), 1, "{to:?}"); } - let mut saved = Workspace::new(columns()); - saved.layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + let mut layout = columns(); + layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap(); + let mut saved = Workspace::new(layout); saved.reconcile(|_| true, alone, &Workspace::new(columns())); - assert_eq!(column_of(&saved.layout, 2).panels().collect::>(), [&2], "reconcile gives it a column of its own"); - assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]); + assert_eq!(column_of(saved.layout(), 2).panels().collect::>(), [&2], "reconcile gives it a column of its own"); + assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]); } /// A panel that docks only in dock columns (a toolbar, photocraft#12517) refuses every placement that leaves it in a @@ -395,9 +398,9 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() { other.apply_with_permissions(Action::move_group(6, Target::at(3, DockPlacement::column(false))), strip).unwrap(); let mut saved = Workspace::new(split); saved.reconcile(|_| true, strip, &Workspace::new(columns())); - assert!(matches!(saved.layout.place(&2), Some(PanelPlace::Dock { .. })), "reconcile docks it in a column: {:?}", saved.layout); - assert_eq!(column_of(&saved.layout, 2).panels().collect::>(), [&2]); - assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]); + assert!(matches!(saved.layout().place(&2), Some(PanelPlace::Dock { .. })), "reconcile docks it in a column: {:?}", saved.layout()); + assert_eq!(column_of(saved.layout(), 2).panels().collect::>(), [&2]); + assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]); } /// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only @@ -420,3 +423,117 @@ fn a_stepped_column_keeps_its_step_count_and_refuses_a_width() { let saved: Layout = serde_json::from_str(&serde_json::to_string(&layout).unwrap()).unwrap(); assert_eq!(saved, layout); } + +/// The names of the `pub fn` methods in `source` whose receiver is `&mut self`. +fn mutating_methods(source: &str) -> Vec<&str> { + let mut names: Vec<&str> = source + .split("pub fn ") + .skip(1) + .filter_map(|rest| { + let name = &rest[..rest.find(|c: char| !(c.is_alphanumeric() || c == '_'))?]; + let receiver = rest[rest.find('(')? + 1..].trim_start(); + receiver.starts_with("&mut self").then_some(name) + }) + .collect(); + names.sort_unstable(); + names +} + +/// Every method that writes a workspace moves its revision, and only `replace` moves its generation. The trial reads +/// the workspace's source for its `&mut self` methods, so a new one fails here until it is walked. +#[test] +fn every_workspace_mutator_moves_the_revision() { + let mut walked: Vec<&str> = Vec::new(); + let mut moves = |name: &'static str, edit: &dyn Fn(&mut Workspace)| { + let mut workspace = Workspace::new(docked()); + let (revision, generation) = (workspace.revision(), workspace.generation()); + edit(&mut workspace); + assert_ne!(workspace.revision(), revision, "`{name}` moves the revision"); + assert_eq!(workspace.generation() != generation, name == "replace", "only `replace` moves the generation, `{name}` included"); + walked.push(name); + }; + moves("replace", &|workspace| workspace.replace(Workspace::new(columns()))); + moves("apply", &|workspace| drop(workspace.apply(Action::activate(6), false, allow).unwrap())); + moves("apply_all", &|workspace| drop(workspace.apply_all([Action::close(5), Action::close(4)], false, allow).unwrap())); + moves("set_visible", &|workspace| workspace.set_visible(5, false, None, false, allow).unwrap()); + moves("reconcile", &|workspace| workspace.reconcile(|panel| *panel != 5, allow, &Workspace::new(docked()))); + moves("raise_window_floor", &|workspace| workspace.raise_window_floor(1000)); + moves("forget_hidden", &|workspace| { + workspace.apply(Action::close(5), false, allow).unwrap(); + let revision = workspace.revision(); + workspace.forget_hidden(|panel| *panel == 5); + assert_ne!(workspace.revision(), revision, "`forget_hidden` moves the revision by itself"); + }); + walked.sort_unstable(); + assert_eq!(walked, mutating_methods(include_str!("../src/dock/workspace.rs")), "every `&mut self` method of `Workspace` is walked"); + + let workspace = Workspace::new(docked()); + assert_ne!(workspace.clone().revision(), workspace.revision(), "a clone is a new source"); + let mut settled = Workspace::new(docked()); + let revision = settled.revision(); + settled.reconcile(|_| true, allow, &Workspace::new(docked())); + assert_eq!(settled.revision(), revision, "a reconcile that changes nothing keeps the revision"); +} + +fn window_ids(workspace: &Workspace) -> Vec { + workspace.layout().floating.iter().map(|window| window.id).collect() +} + +/// Window ids come from a counter each layout owns: two workspaces edited side by side each keep their windows' ids +/// unique, a closed window's id is never drawn again, and a replacement's windows take ids the old layout never gave. +#[test] +fn window_ids_stay_unique_within_each_layout_and_are_never_reused() { + let (mut a, mut b) = (Workspace::new(docked()), Workspace::new(docked())); + for workspace in [&mut a, &mut b] { + workspace.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + workspace.apply(Action::float(5, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap(); + let mut ids = window_ids(workspace); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3, "three windows, three ids: {:?}", window_ids(workspace)); + } + + let seen = window_ids(&a); + a.apply(Action::close(5), false, allow).unwrap(); + a.apply(Action::float(3, rect(50.0, 50.0, 200.0, 200.0)), false, allow).unwrap(); + let fresh: Vec = window_ids(&a).into_iter().filter(|id| !seen.contains(id)).collect(); + assert!(fresh.len() == 1 && fresh[0] > seen.iter().copied().max().unwrap(), "a new window takes a new id: {fresh:?} after {seen:?}"); + + let held: Vec = seen.iter().chain(&fresh).copied().collect(); + a.replace(Workspace::new(docked())); + let replaced = window_ids(&a); + assert!(replaced.iter().all(|id| !held.contains(id)), "the replacement's window takes an id no earlier window had: {replaced:?} after {held:?}"); + + let saved = r#"{"layout":{"root":null,"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":7,"panels":[2],"active":0,"rect":[0,0,100,100]},{"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#; + let loaded: Workspace = serde_json::from_str(saved).unwrap(); + assert_eq!(window_ids(&loaded), [7, 8, 9], "a load keeps the first of a duplicate id and numbers the rest above every saved id"); + + // A loaded layout draws above the ids it loaded with, not only the ones it drew: a closed window's id stays used. + let saved = r#"{"layout":{"root":{"Tabs":{"panels":[4,5],"active":0}},"floating":[{"id":7,"panels":[1],"active":0,"rect":[0,0,100,100]},{"id":9,"panels":[3],"active":0,"rect":[0,0,100,100]}]}}"#; + let mut loaded: Workspace = serde_json::from_str(saved).unwrap(); + loaded.apply(Action::close(3), false, allow).unwrap(); + loaded.apply(Action::float(4, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert_eq!(window_ids(&loaded), [7, 10], "the new window does not take the closed window's id 9"); + + // An undo brings back an older workspace whose counter is lower: raised to the floor the dock has shown, it draws + // no id a later window had. + let older = Workspace::new(docked()); + let mut later = older.clone(); + later.apply(Action::float(2, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + let drawn: Vec = window_ids(&later).into_iter().filter(|id| !window_ids(&older).contains(id)).collect(); + let mut undone = older.clone(); + undone.raise_window_floor(later.layout().window_floor()); + undone.apply(Action::float(5, rect(30.0, 30.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(window_ids(&undone).iter().all(|id| !drawn.contains(id)), "the undone workspace draws past {drawn:?}: {:?}", window_ids(&undone)); + + // A saved id at the top of the range loads without overflow, and the windows still get unique ids. + let saved = format!( + r#"{{"layout":{{"root":null,"floating":[{{"id":{},"panels":[1],"active":0,"rect":[0,0,100,100]}},{{"panels":[2],"active":0,"rect":[0,0,100,100]}}]}}}}"#, + u64::MAX + ); + let loaded: Workspace = serde_json::from_str(&saved).unwrap(); + assert_eq!(window_ids(&loaded), [u64::MAX, 0], "a window without an id takes the least free one once the range above is used"); + let mut layout = loaded.layout().clone(); + let fresh = layout.fresh_window_id(); + assert!(!window_ids(&loaded).contains(&fresh), "a draw past the top of the range takes a free id: {fresh}"); +} diff --git a/crates/cloud-ui/src/esign/mod.rs b/crates/cloud-ui/src/esign/mod.rs index 64087bbd5..e574a7c67 100644 --- a/crates/cloud-ui/src/esign/mod.rs +++ b/crates/cloud-ui/src/esign/mod.rs @@ -240,11 +240,11 @@ impl Default for EsignDialog { } /// A send operation id no other send in this process has used, from a random -/// start so one saved by an earlier process is unlikely to repeat either. -/// Mirrors `docking::model::fresh_window_id`: a counter kept on one -/// [`EsignDialog`] repeats across two dialog instances (two windows, or one -/// replaced after a document closes), and two sends sharing an idempotency -/// key have a conforming provider return the first envelope for the second. +/// start so one saved by an earlier process is unlikely to repeat either. A +/// counter kept on one [`EsignDialog`] would repeat across two dialog instances +/// (two windows, or one replaced after a document closes), and two sends +/// sharing an idempotency key have a conforming provider return the first +/// envelope for the second. fn fresh_send_id() -> u64 { use std::hash::{BuildHasher, Hasher}; use std::sync::OnceLock; diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index b640c8dd7..bdc13e7f7 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -124,6 +124,34 @@ impl Format { } } +/// Most files [`list_folder`] lists. +const MAX_FILES: usize = 500; +/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. +const MAX_BYTES: u64 = 64 << 20; + +/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name +/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files +/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. +pub fn list_folder(dir: &std::path::Path) -> Vec<(String, std::path::PathBuf)> { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut out: Vec<(String, std::path::PathBuf)> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); + if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { + return None; + } + let path = entry.path(); + let meta = std::fs::metadata(&path).ok()?; + (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) + }) + .collect(); + out.sort_by_key(|(name, _)| name.to_lowercase()); + out.truncate(MAX_FILES); + out +} + /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { parse_as(Format::detect(file_name, bytes), bytes) diff --git a/crates/color-ui/src/gradient/value.rs b/crates/color-ui/src/gradient/value.rs index a0d70a8fc..76819b4c2 100644 --- a/crates/color-ui/src/gradient/value.rs +++ b/crates/color-ui/src/gradient/value.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; /// How a gradient's opacity is stored, which decides the rows of its stop bar. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[non_exhaustive] pub enum StopRows { /// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is @@ -36,6 +37,7 @@ pub enum StopRow { /// A colour stop. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct ColorStop { @@ -56,6 +58,7 @@ pub struct ColorStop { /// An opacity stop of a [`StopRows::Split`] gradient. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct OpacityStop { @@ -120,6 +123,7 @@ impl OpacityStop { /// A gradient's stops, each list sorted by location. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct GradientStops { diff --git a/crates/color-ui/src/palette.rs b/crates/color-ui/src/palette.rs index b8d97267e..fb7b69230 100644 --- a/crates/color-ui/src/palette.rs +++ b/crates/color-ui/src/palette.rs @@ -97,6 +97,7 @@ impl SwatchFormat { /// A swatch colour in its own model. #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(tag = "model", content = "values", rename_all = "camelCase")] pub enum SwatchColor { /// Encoded RGB, 0–1 each, in the RGB working space. @@ -148,6 +149,7 @@ impl SwatchColor { /// How an `.ase` file marks a colour. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] pub enum SwatchKind { #[default] @@ -161,6 +163,7 @@ pub enum SwatchKind { /// One named swatch. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct SwatchEntry { /// The swatch's label. pub name: String, @@ -181,6 +184,7 @@ impl SwatchEntry { /// A named group of swatches, as the Swatches panel shows them. A file without groups reads as /// one group named after the file. #[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct SwatchGroup { /// The group's label. pub name: String, diff --git a/crates/color-ui/src/ui/lut_picker.rs b/crates/color-ui/src/ui/lut_picker.rs index afdb6a71d..2937f1207 100644 --- a/crates/color-ui/src/ui/lut_picker.rs +++ b/crates/color-ui/src/ui/lut_picker.rs @@ -4,8 +4,7 @@ //! [`Files`](craft_host::Files) and reads and parses it as a [`Jobs`](craft_host::Jobs) job. use std::path::{Path, PathBuf}; -use std::sync::{Arc, OnceLock}; -use std::time::Instant; +use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, Proposal, Sense}; use craft_cms::lutfile::{LutError, LutFile}; @@ -16,6 +15,7 @@ use craft_ui::contract::{ }; use craft_ui::pickers::Select; use craft_ui::runtime::env::Label; +use craft_ui::runtime::frame; use craft_ui::style::{ComponentStyle, StyleCx}; use egui::{Response, Vec2}; @@ -154,12 +154,6 @@ impl Default for Parsed { } } -/// The seconds since the first scan of the process, for the rescan interval. -fn seconds() -> u64 { - static START: OnceLock = OnceLock::new(); - START.get_or_init(Instant::now).elapsed().as_secs() -} - /// A select of LUTs. /// /// - Rows: Load 3D LUT…, None, the eight built-in looks, the LUT folder's files by name (in the language's @@ -269,9 +263,11 @@ impl Component for LutPicker<'_> { state = LutState { folder: self.folder.clone(), load: state.load, ..LutState::default() }; } if let Some(folder) = self.folder.clone() { - let key = ("lut-scan", folder.clone(), seconds() / RESCAN); + let key = ("lut-scan", folder.clone(), frame::stepped_clock(&cx.response.ctx, RESCAN as f64) as u64 / RESCAN); let started = folder.clone(); - if let Pending::Ready(found) = cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(list_folder(&started))))) { + if let Pending::Ready(found) = + cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(craft_cms::lutfile::list_folder(&started))))) + { let mut files = (**found).clone(); cx.env.collator().sort_by_key(&mut files, |(name, _)| name.as_str()); state.files = Arc::new(files); @@ -378,30 +374,3 @@ fn builtin_name(words: &LutWords, id: &str) -> Label { fn file_name(path: &Path) -> String { path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) } -/// Most files [`list_folder`] lists. -const MAX_FILES: usize = 500; -/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. -const MAX_BYTES: u64 = 64 << 20; - -/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name -/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files -/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. -fn list_folder(dir: &Path) -> FolderFiles { - let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; - let mut out: FolderFiles = entries - .flatten() - .filter_map(|entry| { - let name = entry.file_name().into_string().ok()?; - let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); - if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { - return None; - } - let path = entry.path(); - let meta = std::fs::metadata(&path).ok()?; - (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) - }) - .collect(); - out.sort_by_key(|(name, _)| name.to_lowercase()); - out.truncate(MAX_FILES); - out -} diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 4f08f463d..7d3c18cc6 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -87,7 +87,7 @@ pub use screen_picker::{CaptureResult, CaptureSource, LOUPE_PIXELS, LOUPE_ZOOM, pub use strip::{ColorStrip, ColorStripStyle}; pub use swatches::{ MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput, - SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, + SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, swatch_source, }; pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle}; pub use wheel::{ diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index 8db24aab3..2893b5a41 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -14,14 +14,14 @@ use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey}; use craft_cms::convert::CmykConverter; use craft_theme::Srgba; use craft_ui::buttons::Button; -use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace}; +use craft_ui::choice::{ChoiceWords, Segmented, Swatch}; use craft_ui::contract::{ Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, }; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Row; -use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo}; +use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState}; use craft_ui::primitives::textures::CachedTexture; use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Env, Label}; @@ -30,7 +30,7 @@ use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx} use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2}; use super::popover::compact_picker; -use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, SwatchesWords, swatch_rows}; +use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, swatch_source}; use crate::palette::{SwatchColor, SwatchGroup}; pub(crate) mod paint_list; @@ -475,7 +475,6 @@ impl Component for PaintChip<'_> { let solid = cx.memory::().0.unwrap_or(self.fallback); let current = FillKind::of(&paint); let sampled = self.sampled; - let swatch_words = cx.words::(); let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); let full_picker = self.full_picker; let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated()); @@ -514,21 +513,14 @@ impl Component for PaintChip<'_> { } if let Some((groups, state)) = swatches.as_mut() { let groups: &[SwatchGroup] = groups; - let rows = swatch_rows(groups, &swatch_words); + let source = swatch_source(groups, cmyk); let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); - let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows) + let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &source) .toolbar(false) .row_menu(false) .default_open(DefaultOpen::None) .room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS) - .thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { - if let SwatchKey::Swatch(name) = info.key - && let Some(color) = colors.get(name.as_str()) - { - SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect); - } - }) .show(ui); for event in out.events { if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event diff --git a/crates/color-ui/src/ui/pair/stories.rs b/crates/color-ui/src/ui/pair/stories.rs index 3941bdef6..c4c0279f7 100644 --- a/crates/color-ui/src/ui/pair/stories.rs +++ b/crates/color-ui/src/ui/pair/stories.rs @@ -3,7 +3,7 @@ use super::{PairWell, SwatchPair, Well}; use craft_behavior::Mixed; use craft_theme::Srgba; -use craft_ui::contract::{Show as _, Validity}; +use craft_ui::contract::{Show as _, Tracked, Validity}; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -101,7 +101,7 @@ fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (active, active_at) = data.value_at("active", Well::Primary); - let (slots, last): (Vec>, LastUsed) = (Vec::new(), LastUsed::default()); + let (slots, last): (Tracked>>, Tracked>) = (Tracked::default(), Tracked::default()); let wells = [PairWell::new("Foreground colour", Srgba::rgb(0.0, 0.0, 0.0)), PairWell::new("Background colour", Srgba::rgb(1.0, 1.0, 1.0))]; let mut shown = None; ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| { diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 76c85e775..1326059f6 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -62,7 +62,19 @@ craft_ui::words! { /// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default; /// the theme never changes it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelMode { @@ -129,7 +141,19 @@ impl ColorPanelMode { } /// The ramp under the sliders. Shift-click on the ramp cycles them in this order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, + craft_ui::contract::MemoProps, + craft_ui::contract::PlainData, +)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelRamp { @@ -179,7 +203,9 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, +)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { diff --git a/crates/color-ui/src/ui/swatches.rs b/crates/color-ui/src/ui/swatches.rs index 17bed44a5..d66a11bab 100644 --- a/crates/color-ui/src/ui/swatches.rs +++ b/crates/color-ui/src/ui/swatches.rs @@ -11,7 +11,7 @@ pub(crate) mod panel; #[cfg(feature = "suite")] pub(crate) mod stories; -pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows}; +pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows, swatch_source}; pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput}; pub use panel::{SwatchesPanel, SwatchesPanelOutput}; diff --git a/crates/color-ui/src/ui/swatches/library.rs b/crates/color-ui/src/ui/swatches/library.rs index b5ca7d726..2ab31c803 100644 --- a/crates/color-ui/src/ui/swatches/library.rs +++ b/crates/color-ui/src/ui/swatches/library.rs @@ -2,8 +2,15 @@ use std::collections::HashSet; +use craft_cms::convert::CmykConverter; +use craft_theme::Srgba; +use craft_ui::choice::SwatchFace; use craft_ui::contract::ReorderMove; -use craft_ui::patterns::presets::{PresetRow, PresetState}; +use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, PresetState, ThumbInfo}; +use craft_ui::primitives::ContentPainterCx; +use craft_ui::runtime::env::Env; +use egui::Rect; +use std::collections::BTreeMap; use super::{MAX_GROUPS, MAX_SWATCHES, SWATCH_ZOOM, SwatchesWords}; use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport}; @@ -11,7 +18,7 @@ use crate::ui::PickedColor; /// What the browser names its rows by. Swatch names are unique across the library and group names among groups, so /// both survive reordering. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum SwatchKey { /// A group, by name. @@ -556,8 +563,27 @@ impl SwatchLibrary { } } -/// The rows of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as its -/// tooltip and accessible name. `SwatchesPanel` and `PaintChip`'s swatches list build their rows with it. +/// The swatch list's inputs: the library's groups and each swatch's colour as drawn, by name. +#[derive(craft_ui::contract::MemoProps)] +struct SwatchInputs<'a> { + groups: &'a [SwatchGroup], + drawn: BTreeMap<&'a str, Srgba>, +} + +/// The presets of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as +/// its tooltip and accessible name, painted in its colour through `cmyk`. `SwatchesPanel` and `PaintChip`'s swatches +/// list show it. +pub fn swatch_source<'a>(groups: &'a [SwatchGroup], cmyk: &CmykConverter) -> PresetSource<'a, SwatchKey> { + let drawn = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), e.color.to_srgb(cmyk)))).collect(); + PresetSource::new(SwatchInputs { groups, drawn }, PresetFns::new(source_rows).thumb(paint_swatch)) +} + +fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec> { + swatch_rows(inputs.groups, &env.words::()) +} + +/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and +/// colour value. pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec> { let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::()); for group in groups { @@ -570,6 +596,14 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>) { + if let SwatchKey::Swatch(name) = info.key + && let Some(color) = inputs.drawn.get(name.as_str()) + { + SwatchFace::new(*color).selected(info.selected).paint(cx, rect); + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; diff --git a/crates/color-ui/src/ui/swatches/panel.rs b/crates/color-ui/src/ui/swatches/panel.rs index f0bef8ce9..1347ece3d 100644 --- a/crates/color-ui/src/ui/swatches/panel.rs +++ b/crates/color-ui/src/ui/swatches/panel.rs @@ -1,24 +1,20 @@ //! `SwatchesPanel`: the panel body, its state and what it reports. -use std::collections::HashMap; - use craft_cms::convert::CmykConverter; use craft_i18n::Format; use craft_theme::Srgba; use craft_theme::variant::Tone; use craft_ui::bars::StatusMessage; -use craft_ui::choice::SwatchFace; use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _, request_rename}; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords, ThumbInfo}; -use craft_ui::primitives::ContentPainterCx; +use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords}; use craft_ui::runtime::env::{Count, Env}; -use egui::{Rect, Response, Ui}; +use egui::{Response, Ui}; use super::library::{find_swatch, has}; use super::menu::event_edits; -use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows}; -use crate::palette::{SwatchColor, SwatchGroup, SwatchNote, SwatchReport}; +use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_source}; +use crate::palette::{SwatchGroup, SwatchNote, SwatchReport}; /// What [`SwatchesPanel::show`] reports. #[derive(Debug)] @@ -99,21 +95,13 @@ impl<'a> SwatchesPanel<'a> { if st.selected.as_ref().is_some_and(|k| !has(groups, k)) { st.selected = None; } - let rows = swatch_rows(groups, &words); + let source = swatch_source(groups, cmyk); let out = { - let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); - let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows) + let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source) .thumb_range(SWATCH_ZOOM) .toolbar(true) .reorder(PresetReorder::items_and_groups()) - .footer(PresetFooterOptions::new().can_delete(st.selected.is_some())) - .thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { - if let SwatchKey::Swatch(name) = info.key - && let Some(color) = colors.get(name.as_str()) - { - SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(cx, rect); - } - }); + .footer(PresetFooterOptions::new().can_delete(st.selected.is_some())); if let Some(key) = &st.selected { browser = browser.selected(key.clone()); } diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 6a27a4e70..4eaeaa1cf 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -910,6 +910,7 @@ timeline-otio = ["timeline", "craft-timeline/otio"] timeline-xml = ["timeline", "craft-timeline/xml"] tracked = ["dep:craft-tracked"] +tracked-serde = ["tracked", "craft-tracked/serde"] ui-app = ["ui", "craft-ui/app"] ui-cloud = ["ui", "craft-ui/cloud"] diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 32efeff02..660ca8fe4 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "6525c87923ca47465aac244460fe4b1139349060"; +pub const REV: &str = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 817b02e7a..20ac95787 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,13 +75,13 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or test-data cache that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. Names are resolved through the file's `use` items, per module scope: grouped imports, renames (`use egui::Margin as M`), module aliases (`use crate::theme as t`) and glob imports (`use crate::theme::*`) all reach the rule table, so `margin(4.0)` is flagged after `use crate::theme::margin`. A bare name that a fn in the same module defines is not extended through globs. Imports in a module do not apply in sibling modules. -A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero. +A literal is a number, optionally negated, parenthesised, cast or in arithmetic; zero is never flagged. A name is flagged when a `const` or `static` in the same file with that name has such a value, unless it is a component constant: a module- or impl-level `const` with a doc comment, the named place for a dimension of one component's own drawing (craft-framework.md 5.4). A name that resolves to a component constant is not a literal size, and its initializer is its definition, so the literals in it are not flagged either. A `const` inside a fn body, a `static` and an undocumented `const` are flagged as literals. Consts are keyed by module and impl scope: a bare name takes the innermost scope that defines it, `Self::X`, `self::X`, `super::X`, `crate::X`, `Type::X` and `module::X` (last two segments) the scope they name, and a name with several candidates is flagged when any is non-zero. ## Markers diff --git a/crates/design-lint/src/rules.rs b/crates/design-lint/src/rules.rs index 58720f847..d3dec56b4 100644 --- a/crates/design-lint/src/rules.rs +++ b/crates/design-lint/src/rules.rs @@ -150,6 +150,7 @@ pub(crate) fn analyze_file(src: &str, file: &syn::File, include_tests: bool) -> imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), + in_named_const: false, out: Analysis::default(), include_tests, }; @@ -184,6 +185,9 @@ struct ConstDef { line: usize, expr: Expr, value: Option, + /// A component constant: a module- or impl-level `const` with a doc comment. A name that resolves to it is not a + /// literal size, and its initializer is its definition, not a call site. + named: bool, } /// A `use` declaration: `alias` is the name it brings in, `None` for a glob (`path::*`). @@ -202,6 +206,8 @@ struct Linter<'a> { fns: Vec<(Vec, String)>, /// The modules and impl blocks around the item being visited. scope: Vec, + /// Inside the initializer of a named const, where `literal-size/*` does not apply. + in_named_const: bool, out: Analysis, include_tests: bool, } @@ -212,17 +218,21 @@ struct ConstCollector { imports: Vec, fns: Vec<(Vec, String)>, scope: Vec, + /// How many fn bodies enclose the item being visited. + fn_depth: usize, include_tests: bool, } impl ConstCollector { - fn add(&mut self, name: &syn::Ident, expr: &Expr) { + /// Records a const or static; `documented` is whether it is a `const` with a doc comment. + fn add(&mut self, name: &syn::Ident, expr: &Expr, documented: bool) { self.defs.push(ConstDef { scope: self.scope.clone(), name: name.to_string(), line: name.span().start().line, expr: expr.clone(), value: None, + named: documented && self.fn_depth == 0, }); } @@ -256,9 +266,21 @@ impl<'ast> Visit<'ast> for ConstCollector { fn visit_item_fn(&mut self, i: &'ast syn::ItemFn) { if !self.skipped(&i.attrs) { self.fns.push((module_scope(&self.scope).to_vec(), i.sig.ident.to_string())); + self.fn_depth += 1; visit::visit_item_fn(self, i); + self.fn_depth -= 1; } } + fn visit_impl_item_fn(&mut self, i: &'ast syn::ImplItemFn) { + self.fn_depth += 1; + visit::visit_impl_item_fn(self, i); + self.fn_depth -= 1; + } + fn visit_trait_item_fn(&mut self, i: &'ast syn::TraitItemFn) { + self.fn_depth += 1; + visit::visit_trait_item_fn(self, i); + self.fn_depth -= 1; + } fn visit_item_use(&mut self, i: &'ast syn::ItemUse) { if !self.skipped(&i.attrs) { let mut found = Vec::new(); @@ -268,15 +290,15 @@ impl<'ast> Visit<'ast> for ConstCollector { } } fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, has_doc(&i.attrs)); visit::visit_item_const(self, i); } fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, false); visit::visit_item_static(self, i); } fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) { - self.add(&i.ident, &i.expr); + self.add(&i.ident, &i.expr, has_doc(&i.attrs)); visit::visit_impl_item_const(self, i); } } @@ -349,6 +371,11 @@ fn last_ident(path: &syn::Path) -> Option { path.segments.last().map(|s| s.ident.to_string()) } +/// Whether an item carries a doc comment (`///` or `#[doc = ...]`). +fn has_doc(attrs: &[Attribute]) -> bool { + attrs.iter().any(|a| a.path().is_ident("doc")) +} + fn cfg_is_test(meta: &Meta) -> bool { match meta { Meta::Path(p) => p.is_ident("test"), @@ -420,8 +447,14 @@ impl Linter<'_> { } fn resolve_consts(&mut self, file: &syn::File) { - let mut collector = - ConstCollector { defs: Vec::new(), imports: Vec::new(), fns: Vec::new(), scope: Vec::new(), include_tests: self.include_tests }; + let mut collector = ConstCollector { + defs: Vec::new(), + imports: Vec::new(), + fns: Vec::new(), + scope: Vec::new(), + fn_depth: 0, + include_tests: self.include_tests, + }; collector.visit_file(file); self.defs = collector.defs; self.imports = collector.imports; @@ -431,7 +464,8 @@ impl Linter<'_> { .defs .iter() .enumerate() - .filter(|(_, d)| d.value.is_none()) + // A named const keeps no literal value: a name that resolves to it reads like a token. + .filter(|(_, d)| d.value.is_none() && !d.named) .filter_map(|(i, d)| self.eval_in(&d.expr, &d.scope).map(|v| (i, v))) .collect(); if resolved.is_empty() { @@ -552,12 +586,21 @@ impl Linter<'_> { Some((shown, def.line)) } + /// Whether the const item named `ident` is a named const (`ConstDef::named`). + fn is_named_const(&self, ident: &syn::Ident) -> bool { + let line = ident.span().start().line; + self.defs.iter().any(|d| d.named && d.line == line && *ident == d.name) + } + fn is_flagged_size(&self, e: &Expr) -> bool { self.eval(e).is_some_and(|v| v != 0.0) } /// Reports `what` when any of `args` is a non-zero literal size. fn size_rule<'e>(&mut self, rule: &'static str, what: proc_macro2::Span, args: impl IntoIterator) { + if self.in_named_const { + return; + } let args: Vec<&Expr> = args.into_iter().collect(); // A vector of literal -1, 0 and 1 is a direction, not a size. if rule == VEC2 && args.iter().all(|a| is_unit_literal(a)) { @@ -726,11 +769,21 @@ fn is_unit_literal(e: &Expr) -> bool { fn hint(rule: &str) -> &'static str { match rule { - VEC2 => "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`) or mark `// design: allow()`", - ADD_SPACE => "use a spacing token (`Tokens::of(ui).space.gap.inline`) or mark `// design: allow()`", - CORNER_RADIUS => "use a radius token from `Tokens::of(ui)` or mark `// design: allow()`", - STROKE => "use a stroke width token from `Tokens::of(ui)` or mark `// design: allow()`", - MARGIN => "use a spacing token (`Tokens::of(ui).space`) or mark `// design: allow()`", + VEC2 => { + "use a size token (`Tokens::of(ui).size.control.md`, `space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + ADD_SPACE => { + "use a spacing token (`Tokens::of(ui).space.gap.inline`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + CORNER_RADIUS => { + "use a radius token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + STROKE => { + "use a stroke width token from `Tokens::of(ui)`, a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } + MARGIN => { + "use a spacing token (`Tokens::of(ui).space`), a documented module-level const for a dimension of the component's own drawing, or mark `// design: allow()`" + } TOOLTIP => "use `craft_ui::contract::Props::tooltip` or `craft_ui::contract::Show::show_with_tip` or mark `// design: allow()`", STYLE_MUTATION => "set styles through the theme (craft-ui installs them from the tokens) or mark `// design: allow()`", _ => "use a type-size token from `Tokens::of(ui)` or mark `// design: allow()`", @@ -774,9 +827,18 @@ impl<'ast> Visit<'ast> for Linter<'_> { } fn visit_item_const(&mut self, i: &'ast syn::ItemConst) { if !self.skips(&i.attrs, i.span()) { + let named = self.in_named_const || self.is_named_const(&i.ident); + let outer = std::mem::replace(&mut self.in_named_const, named); visit::visit_item_const(self, i); + self.in_named_const = outer; } } + fn visit_impl_item_const(&mut self, i: &'ast syn::ImplItemConst) { + let named = self.in_named_const || self.is_named_const(&i.ident); + let outer = std::mem::replace(&mut self.in_named_const, named); + visit::visit_impl_item_const(self, i); + self.in_named_const = outer; + } fn visit_item_static(&mut self, i: &'ast syn::ItemStatic) { if !self.skips(&i.attrs, i.span()) { visit::visit_item_static(self, i); diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 3dab5fe16..a2436797c 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -58,6 +58,7 @@ const CLOSED: &[&str] = &[ "ReorderMove", // built or matched in craft-ui-patterns "RowState", // built or matched in craft-ui-widgets "RuleLook", // built or matched in craft-ui-canvas + "RulerFace", // matched by every ruler (craft-text, craft-pages, craft-ui-canvas): a new face must be drawn by each "ShellRegions", // built or matched in craft-ui-shell "SizeLimits", // built or matched in craft-ui-panels "StoryOutput", // built or matched in craft-ui-widgets @@ -137,8 +138,8 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ ]; /// The reviewed per-item allowlist of `contract/no-global-state`: a file and what it may hold, either the identifier of -/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that -/// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. +/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact, environment key or test-data +/// cache that covers it. A new item in these files is flagged. const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // Compile-time registry discovery reads the defining crate's source, never a view input. ("crates/ui-macros/src/registry.rs", FS), @@ -160,6 +161,9 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ ("crates/ui-patterns/src/patterns/presets/model/library.rs", "MemoProps"), // Settled fact: a name check keys by its inputs and its `fn` behind `dyn NameChecker`, as `Bind::check_with` does. ("crates/ui-patterns/src/patterns/presets/named.rs", "MemoProps"), + // Settled fact: `PresetSource` erases its inputs behind a trait object; it keys on those inputs (themselves + // `MemoProps`) and on the addresses of its capture-free `fn`s, which stand for the code that reads them. + ("crates/ui-patterns/src/patterns/presets/source.rs", "MemoProps"), // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. ("crates/ui-contract/src/fonts/defaults.rs", "HACK"), ("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"), @@ -199,32 +203,8 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ ("crates/imaging/src/ui/layer_style/hosted.rs", "PAINT"), // Settled fact: a test fake of the font store; it writes a temporary folder. ("crates/font-manager/src/store/fake.rs", FS), - // later task of #2336: the dock node id counter is hidden state. - ("crates/behavior/src/dock/node.rs", "NEXT"), - // later task of #2336: the brush trail id counter is hidden state. - ("crates/ui-canvas/src/canvas_controls/brush/trail.rs", "NEXT_ID"), - // later task of #2336: the outline hover generation counter is hidden state. - ("crates/ui-canvas/src/canvas_controls/outline/hover.rs", "GENERATIONS"), - // later task of #2336: the texture serial counter is hidden state. - ("crates/imaging/src/ui/transform_preview/textures.rs", "SERIAL"), - // later task of #2336: the mock image read cache is hidden state. + // A cache of pure test data: MockImage is used only by stories and trials. ("crates/imaging/src/ui/mock_image.rs", "READS"), - // later task of #2336: the ranking cache is hidden state. - ("crates/font-manager/src/picker/rank.rs", "CACHE"), - // later task of #2336: the face loader reads file sizes during the pass. - ("crates/font-manager/src/panel/faces.rs", FS), - // later task of #2336: the gallery's set of seen names is hidden state. - ("crates/ui-gallery/src/viewer/layout.rs", "NAMES"), - // later task of #2336: the LUT picker reads the process clock and scans folders during the pass. - ("crates/color-ui/src/ui/lut_picker.rs", "START"), - ("crates/color-ui/src/ui/lut_picker.rs", FS), -]; - -/// Files that may read a clock (`contract/motion:clock`) beyond the runtime's motion module. A file key, because -/// color-ui has no layer map. -const MOTION_CLOCK_FILES: &[&str] = &[ - // later task of #2336: the LUT picker reads the process clock during the pass. - "crates/color-ui/src/ui/lut_picker.rs", ]; /// Whether `what` (an item identifier or [`FS`]) may be declared or used in `file` for `contract/no-global-state`. @@ -406,9 +386,6 @@ impl RuleScope for WorkspaceScope { if let Some(what) = key.strip_prefix("contract/no-global-state:") { return no_global_state_allows(what, file); } - if key == "contract/motion:clock" && MOTION_CLOCK_FILES.iter().any(|f| file == Path::new(f)) { - return true; - } if key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); } diff --git a/crates/design-lint/tests/rules.rs b/crates/design-lint/tests/rules.rs index 11b6b8efc..cba0e2fe9 100644 --- a/crates/design-lint/tests/rules.rs +++ b/crates/design-lint/tests/rules.rs @@ -67,6 +67,20 @@ fn consts_resolve_by_module_and_impl_scope() { assert_eq!(run(src).len(), 3); } +#[test] +fn documented_consts_are_component_constants() { + // A documented module or impl const is a named value, its initializer included; arithmetic on it reads like a token. + let src = "/// The tick.\nconst TICK: f32 = 3.0;\n/// The room.\nconst ROOM: Vec2 = vec2(30.0, 40.0);\nstruct A;\nimpl A {\n /// The pad.\n const PAD: f32 = 6.0;\n fn f(&self, ui: &mut Ui) { ui.add_space(Self::PAD); ui.add_space(TICK * 2.0); let v = vec2(TICK, ROOM.y); }\n}\n"; + assert!(clean(src)); + + // An undocumented const, a documented const in a fn body and a literal stay flagged. + let src = "const GAP: f32 = 4.0;\nfn f(ui: &mut Ui) { ui.add_space(GAP); }\nfn g(ui: &mut Ui) {\n /// The gap.\n const LOCAL: f32 = 4.0;\n ui.add_space(LOCAL);\n}\nfn h(ui: &mut Ui) { ui.add_space(4.0); }\n"; + assert_eq!(run(src).iter().map(|f| f.line).collect::>(), [2, 6, 8]); + + // The initializer of an undocumented const is a call site. + assert!(flagged("const ROOM: Vec2 = vec2(30.0, 40.0);\n", "literal-size/vec2")); +} + #[test] fn clippy_allow_attributes_are_counted_and_inner_ones_flagged() { let src = "#![allow(clippy::disallowed_methods, reason = \"stock widgets\")]\n#[expect(clippy::disallowed_types)]\nstruct S;\n#[allow(clippy::too_many_arguments)]\nfn f() {}\nmod m {\n #![expect(clippy::disallowed_methods)]\n}\n"; diff --git a/crates/draw/src/ui/brush_presets/panel.rs b/crates/draw/src/ui/brush_presets/panel.rs index 293b35c55..e81884ca9 100644 --- a/crates/draw/src/ui/brush_presets/panel.rs +++ b/crates/draw/src/ui/brush_presets/panel.rs @@ -3,9 +3,9 @@ use std::hash::Hash; use craft_behavior::{EditEvents, IconId}; -use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _}; +use craft_ui::contract::{Bind, EditResponse, MemoProps, Outcome, Props as _, ShowContainer as _}; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState}; +use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetSource, PresetState}; use craft_ui::runtime::drag::DropZone; use craft_ui::runtime::env::{Env, Label}; use craft_ui::sections::FooterAction; @@ -29,9 +29,9 @@ pub(super) const BRUSH_THUMBS: TileZoom = #[must_use = "show the panel with `show`"] #[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)] #[pattern(probe(BrushesPanel<'static, u32>))] -pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { +pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> { label: Label, - rows: &'a [PresetRow], + source: &'a PresetSource<'a, K>, state: Bind<'a, PresetState>, diameter: Bind<'a, f64>, max_size: f64, @@ -67,16 +67,22 @@ impl Outcome for BrushesPanelOutput { } } -impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> { - /// A panel named `label` over the presets in `rows`, with its view in `state` and the brush +impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> BrushesPanel<'a, K> { + /// A panel named `label` over the presets of `source`, with its view in `state` and the brush /// size in `diameter` up to `max_size`. - pub fn new(label: impl Into

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { - // The content is a layout room of its own: the flow of the body around it does not reach in. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how + // that body sizes from its content, so the view takes what its content used there, as the same content + // shown without the view would. + let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 14ea466f7..7b44688d6 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -60,16 +60,17 @@ pub use body::{STRIP_BACK, STRIP_FORWARD}; pub use collection::{ ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove, ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest, - ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, RowState, - SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, + HoverLead, ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, + RowState, SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit, }; #[doc(hidden)] pub use container::InBar; #[doc(hidden)] pub use container::InMenu; pub use container::{ - BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth, - Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth, + BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, + LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, + WrapWidth, }; pub use craft_tracked::{PlainData, Revision, Tracked}; pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract}; diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index eb8b2635c..34137bf9a 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -26,7 +26,8 @@ pub(super) struct Mounted { } /// The host for `props.mount`. A layer-like mount of a closed container shows nothing once its exit fade ended. -pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label) -> Mounted { +/// `moving` is the rect a running drag of the container's move band puts its layer at in this pass. +pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: &Label, moving: Option) -> Mounted { let ctx = at.ui.ctx(); let layer = |overlay: &Overlay| { let presence = if at.ui.is_sizing_pass() { @@ -46,7 +47,7 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & Mount::Pane(pane) => Mounted { host: Box::new(PaneHost(*pane)), exiting: false }, Mount::Window { .. } => Mounted { host: Box::new(WindowContentHost), exiting: false }, Mount::Layer(overlay) => match layer(overlay) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(overlay.clone(), props, exiting, fade, at.size, moving)), exiting }, (None, _) => closed(), }, Mount::FullWindow => full_window(props.focus), @@ -57,7 +58,9 @@ pub(super) fn host(props: &ContainerProps, at: &HostCx<'_>, open: bool, title: & full_window(fallback.focus) } else if !viewports { match layer(fallback) { - (Some(fade), exiting) => Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size)), exiting }, + (Some(fade), exiting) => { + Mounted { host: Box::new(LayerHost::new(fallback.clone(), props, exiting, fade, at.size, moving)), exiting } + } (None, _) => closed(), } } else if open { @@ -196,12 +199,14 @@ struct LayerHost { fade: f32, /// The size the container measured for this pass. size: Vec2, + /// The rect a running drag of the move band puts the layer at in this pass, in screen space. + moving: Option, dismissed: Option, } impl LayerHost { - fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2) -> Self { - LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, dismissed: None } + fn new(overlay: Overlay, props: &ContainerProps, exiting: bool, fade: f32, size: Vec2, moving: Option) -> Self { + LayerHost { overlay, save: props.save.clone(), owner: props.owner, exiting, fade, size, moving, dismissed: None } } } @@ -227,7 +232,7 @@ impl Host for LayerHost { overlay = mapped; } let screen = overlay::screen_for(&ctx, env, &overlay); - let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, screen, env.tokens.space.inset.screen); + let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, env.tokens.space.inset.screen); // An anchored resizable layer has no position to seed: its default size is held as its minimum until the // user resizes it. if overlay.fit == overlay::OverlayFit::Resizable @@ -337,6 +342,8 @@ impl Host for ViewportHost { return; } let ctx = parent.ctx().clone(); + // The window's content runs in its own viewport's pass, which no record of this one holds. + crate::runtime::replay::block(&ctx); let focus = self.overlay.focus; let mut window_rules = self.overlay.clone(); window_rules.dismiss.outside = Outside::Keep; diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index 7622c5596..215f7a0e7 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -23,7 +23,7 @@ pub(crate) use host::{Layer, forget_layer, host, host_window}; pub(crate) use opener::{LayerFloor, anchor_floor}; pub use opener::{Opener, Trigger}; pub use place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; -pub use placement::PopupRegion; +pub use placement::{PopupRegion, layer_room}; pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for}; pub(crate) use popups::dwell; pub use popups::{HOLD, Overlays, PopupHandle}; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index b6790cd12..e2c8379e3 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -73,10 +73,30 @@ pub(super) fn dismissal( None } +/// The dismissal of a layer shown in the popup window `popup`, decided in its opener's pass, beside what the popup's +/// own pass decides: a layer that closes on outside presses closes on one in the opener outside it and its anchor +/// (absorbed or not, as its rule says), and on one in any other window of the app; a popup also closes once the app +/// has no focus. An absorbing layer can't keep a press in another OS window from reaching that window. +pub(super) fn popup_dismissal( + ctx: &Context, + layer: &Layer<'_>, + rect: Rect, + anchor: Rect, + popup: egui::ViewportId, + appears: bool, +) -> Option { + let here = match layer.overlay.dismiss.outside { + Outside::Keep => return None, + Outside::Absorb => overlay::absorbed_press(ctx).is_some(), + Outside::Close => press_outside(ctx, layer, rect, anchor), + }; + let away = layer.overlay.rank == Rank::Popup && crate::runtime::windows::app_away(ctx); + (here || away || crate::runtime::windows::pressed_elsewhere(ctx, popup, appears)).then_some(CloseReason::Outside) +} + /// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { - let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) - else { + let Some(press) = pointer::primary_press(ctx) else { return false; }; let inside_family = overlay::family(ctx, layer.id).iter().filter_map(|id| overlay::entry(ctx, *id)).any(|entry| entry.rect.contains(press)); @@ -104,6 +124,8 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) { return None; } + // The focus may be in no record of the layer's host: the Escape is read from the events of the frame. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent); let step = keys::scope_escape(ctx, policy.cancel, pointer::press_captured(ctx), false)?; matches!(step, craft_behavior::focus::EscapeStep::CloseScope).then_some(CloseReason::Escape) } diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 9c2ab20fc..1fffe99f1 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -1,6 +1,6 @@ //! The overlay host: shows a layer on an egui layer, remembers it while shown and closes its family. -use super::dismissal::dismissal; +use super::dismissal::{dismissal, popup_dismissal}; use super::opener::{Opening, Trigger}; use super::place::{OverlayFit, Place}; use super::placement::{anchor_rect, opened_overlay, placement}; @@ -13,6 +13,7 @@ use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::motion::{self, Driver}; use crate::runtime::overlay::{self, Backdrop, CloseReason, OpenEntry, Rank}; +use crate::runtime::windows::{self, PopupOpen, PopupRoom, WindowSpec}; use craft_behavior::{MotionKind, Playback}; use egui::{Context, Id, Pos2, Rect, Ui, Vec2}; @@ -90,6 +91,7 @@ pub(crate) fn forget_layer(ctx: &Context, id: Id, owner: Id) { if taken.is_some_and(|memory| !memory.family_closed) { overlay::close_descendants(ctx, id); } + windows::close_popup(ctx, id); } /// Asks the layers opened from inside `layer` to close once the layer closes or starts to fade out, in the pass that @@ -106,8 +108,14 @@ fn area_id(id: Id) -> Id { sub(id, "area") } -/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. +/// The overlay host: shows `body` on an egui layer for `layer` and decides its dismissal. A layer opened in a palette +/// window shows in a popup window of its own ([`host_in_popup`]); a full-window layer covers its own window. pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut Ui)) -> LayerOut { + if !layer.overlay.is_full_window() + && let Some(popup) = windows::popup_room(ctx) + { + return host_in_popup(ctx, layer, popup, body); + } // A layer that appears starts with nothing it remembered while shown before, also when it opens again during its // exit fade or its host never saw it hide: the focus that was inside it does not close it as `focus_left`. let appears = overlay::appears(ctx, layer.id, layer.exiting); @@ -172,7 +180,12 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U }; let parent = overlay::drawing_parent(ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); - let spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting }; + let mut spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + // A popup's or a modal's layer, and any layer while it fades out, has a root node, made before its `Area` shows so + // egui hangs the layer's content below it. A sizing pass of the `Area` reports nothing. + if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { + spec.root = areas::content_rect(ctx, &spec).map(|rect| access::report_layer(ctx, layer.id, rect, layer.exiting)); + } // The opener of the layer's scope is the stop focused when the layer first appears: egui's modal gate takes focus // from the widgets below a modal layer by the first pass that shows the layer. A dropdown that keeps its anchor's key // focus belongs to the component that opened it: a press moves the key focus onto that component only at the end of @@ -199,8 +212,8 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U // from the opener's inherited env with the layer-local fields fresh, and outside the opener's scopes. let installed = Env::install_for(ui, layer.env.capture().env()); let real = !ui.is_sizing_pass(); - if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) { - access::report_layer(ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting); + if spec.root.is_some() && layer.exiting { + access::hide_exiting_content(ctx, ui.unique_id()); } // Every layer is a focus scope, one without a policy (`FocusPolicy::NONE`) included: its stops are the layer's, // not those of the scope it was opened in, so a trap around it leaves them out (a menu's companion bar). @@ -217,6 +230,9 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U // checks them. Without the boundary a tooltip's text was checked against the body's kept transcript, which // asked for a discard pass every other frame while the tooltip showed. access::scope::outside(ctx, || layout_memory::boundary(ctx, true, || body(ui))); + if real && overlay.rank.is_modal() { + access::report_modal(ctx, layer.id); + } if real { focus::pop_scope(ctx); } @@ -237,6 +253,10 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U entry.absorbs = overlay.dismiss.outside == Outside::Absorb; overlay::record(ctx, entry); let dismissed = if layer.exiting { None } else { dismissal(ctx, layer, shown.rect, anchor, scope, &mut memory) }; + // The layer closes after its body ran: the run shows it open, so a record of the run is not replayed. + if dismissed.is_some() { + crate::runtime::replay::note_unsettled(ctx); + } if let Some(nudge) = &nudge { // `dismissal` above records the press beside the layer (`dismissal.rs`, `note_pressed_outside`), so the nudge // starts after it and moves the layer from the next pass on. @@ -248,6 +268,150 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U LayerOut { dismissed } } +/// A layer opened in a palette window, shown in a popup window of its own (`WindowSpec::popup`): placed in the +/// opener's points within the work area around it, the window at that place in desktop points. +/// +/// The layer's bookkeeping is split between the two windows. The popup's pass shows the layer at the window's origin +/// and records it in the popup's stack, with its focus scope and the dismissal its own input decides (Escape, Enter, +/// activations, focus, timeout). The opener's pass records an entry that stands for the window (`OpenEntry::popup`), +/// so its family, its anchor and the presses in the opener are judged where they happen; a press in any other window +/// of the app, and for a popup the app losing focus, close it too ([`popup_dismissal`]). +/// +/// A layer whose size its container measured is placed before the window opens. A layer without one (a tooltip) is +/// laid out in the popup's pass first, in the room its unplaced form has, and placed by the size it took there. +/// A popup that takes keys (a menu, a flyout) takes the OS focus; a tooltip takes none and lets the pointer through. +fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut dyn FnMut(&mut Ui)) -> LayerOut { + let appears = overlay::appears(ctx, layer.id, layer.exiting); + let mut memory = if appears { LayerMemory::default() } else { recall(layer, ctx) }; + let opened = opened_overlay(ctx, layer.overlay, memory.opening); + if let Some((_, opening)) = &opened { + memory.opening.get_or_insert(*opening); + } + // The popup window lies outside any region of the opener: the work area is its room. + let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer }; + let overlay = layer.overlay; + let bounds = popup.room; + let anchor = anchor_rect(ctx, layer, bounds, &mut memory); + let min_width = overlay.least_width(anchor.width()); + let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y)); + let unplaced = placement(ctx, layer, measured, bounds, anchor); + let parent = overlay::drawing_parent(ctx); + let tier = overlay::layer_tier(ctx, overlay.rank); + let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); + if overlay.rank.is_modal() && appears { + overlay::close_popups_outside(ctx, &[layer.id]); + } + // The body reports in its parent's space: the popup's points are the opener's screen less the layer's place. + let to_parent = overlay::parent_space(ctx, layer.id); + let tooltip = overlay.rank == Rank::Tooltip; + let spec = WindowSpec::popup().takes_focus(!tooltip && (scope.is_some() || overlay.rank.takes_keys())).passes_pointer(tooltip); + let known = measured.map(|size| Rect::from_min_size(unplaced.at, size)); + let open = PopupOpen { id: layer.id, spec: &spec, rect: known.map(|rect| rect.translate(popup.origin.to_vec2())) }; + let mut shown = None; + windows::show_popup(ctx, &open, |ui| { + let at = unplaced.at.to_vec2(); + overlay::note_parent_space(ui.ctx(), layer.id, egui::emath::TSTransform::from_translation(-at) * to_parent); + shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body)); + }); + let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None)); + let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) }; + let rect = Rect::from_min_size(placed.at, size); + if known.is_none() { + windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2())); + } + let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, rect, areas::layer_of(tier, area_id(layer.id))); + entry.parent = parent; + entry.anchor = matches!(overlay.place, Place::Anchored { .. }).then_some(anchor); + entry.side = placed.side; + entry.exiting = layer.exiting; + entry.scoped = scope.is_some(); + entry.absorbs = overlay.dismiss.outside == Outside::Absorb; + entry.window = true; + entry.popup = true; + overlay::record(ctx, entry); + let viewport = crate::runtime::egui::viewports::viewport_id(layer.id); + let dismissed = if layer.exiting { None } else { dismissed.or_else(|| popup_dismissal(ctx, layer, rect, anchor, viewport, appears)) }; + close_family(ctx, layer, layer.exiting || dismissed.is_some(), &mut memory); + remember(layer, ctx, memory); + LayerOut { dismissed } +} + +/// The popup window's pass of [`host_in_popup`]: the layer at the window's origin, offered the room `placed` leaves, +/// its entry in the popup's stack and the dismissal the popup's own input decides. Returns the size the layer took +/// and that dismissal. +fn show_in_popup( + ui: &mut Ui, + layer: &Layer<'_>, + placed: &super::placement::Placed, + min_width: f32, + scope: Option, + memory: &mut LayerMemory, + body: &mut dyn FnMut(&mut Ui), +) -> (Vec2, Option) { + let ctx = ui.ctx().clone(); + let overlay = layer.overlay; + let window = ctx.content_rect(); + let area = area_id(layer.id); + let tier = overlay::layer_tier(&ctx, overlay.rank); + let cover = match overlay.rank { + Rank::Modal { backdrop } => { + let scrim = match backdrop { + Backdrop::Scrim => crate::style::scrim_color(&layer.env.tokens).gamma_multiply(layer.fade), + Backdrop::None => egui::Color32::TRANSPARENT, + }; + let cover_id = sub(layer.id, "cover"); + let through = crate::runtime::sampler::through(&ctx, crate::runtime::egui::pass::current_viewport(&ctx), layer.id); + areas::show_cover_layer(&ctx, areas::CoverLayer { id: cover_id, tier, screen: window, scrim, through, absorbs: !layer.exiting }); + Some(areas::layer_of(tier, cover_id)) + } + _ => None, + }; + // The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts. + let opener = layer.env.capture().env(); + let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root)); + let mut spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + // The layer's root node, made before its `Area` shows, as in `host`. + if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { + spec.root = areas::content_rect(&ctx, &spec).map(|rect| access::report_layer(&ctx, layer.id, rect, layer.exiting)); + } + overlay::begin_layer(&ctx, layer.id, tier, layer.exiting, placed.side); + let shown = areas::show_layer(&ctx, &spec, |ui| { + areas::fade(ui, layer.fade * overlay.opacity); + let installed = Env::install_for(ui, env.clone()); + let real = !ui.is_sizing_pass(); + if spec.root.is_some() && layer.exiting { + access::hide_exiting_content(&ctx, ui.unique_id()); + } + // The focused stop the scope returns to is in the opener's window; the opener's window takes the OS focus + // back when the popup closes (`windows::close_popup`). + if real { + let entering = !std::mem::replace(&mut memory.scope_entered, true); + focus::push_scope_from(&ctx, layer.id, overlay.focus, None, None, layer.exiting, Some(entering)); + } + areas::bound(ui, placed.room, min_width.min(placed.room.x)); + if overlay.fit == OverlayFit::Resizable { + ui.set_min_size(overlay.size_limits.min.min(placed.room)); + } + access::scope::outside(&ctx, || layout_memory::boundary(&ctx, true, || body(ui))); + if real && overlay.rank.is_modal() { + access::report_modal(&ctx, layer.id); + } + if real { + focus::pop_scope(&ctx); + } + Env::restore(&ctx, installed); + }); + overlay::end_layer(&ctx); + let mut entry = OpenEntry::new(layer.id, overlay.rank, overlay.keys, shown.rect, shown.layer); + entry.side = placed.side; + entry.exiting = layer.exiting; + entry.cover = cover; + entry.scoped = scope.is_some(); + overlay::record(&ctx, entry); + let dismissed = if layer.exiting { None } else { dismissal(&ctx, layer, shown.rect, Rect::NOTHING, scope, memory) }; + (shown.rect.size(), dismissed) +} + /// The motion slot of a layer's nudge, under the layer's id. // PLAN: the decision names a `NUDGE_SPEC`; `MotionSpec::new` (`runtime/motion.rs:39`) is a private `const fn` of a file outside this set, so // the nudge runs on `spec::OPEN_FADE` (a fade, which reduced motion still runs) over the open token's duration. @@ -342,6 +506,8 @@ impl Nudge { /// The layer-stack side of an OS-window mount: records the window as an entry of its viewport's stack (rank, key /// class, scope; no egui layer) and decides its dismissal after the body ran. `rect` is the window's inner rect. pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> LayerOut { + // The entry stands for a window of another viewport, whose pass no record of this one holds. + crate::runtime::replay::block(ctx); let overlay = layer.overlay; let mut memory = recall(layer, ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index c4100569e..526a2fdda 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -82,10 +82,16 @@ pub(crate) fn region_for(env: &Env, overlay: &Overlay) -> Option { } } -/// The screen rect a layer of `overlay` opened in `env` keeps inside: the safe rect, or the part of it a contained -/// layer's region leaves. +/// The room a layer opened in the running viewport may take, in its points: the work area around a palette window, +/// whose layers show in popup windows of their own (`windows::popup_room`), else the window's safe rect. +pub fn layer_room(ctx: &Context) -> Rect { + crate::runtime::windows::popup_room(ctx).map_or_else(|| areas::safe_rect(ctx), |popup| popup.room) +} + +/// The screen rect a layer of `overlay` opened in `env` keeps inside: the layer room ([`layer_room`]), or the part +/// of it a contained layer's region leaves. pub(crate) fn screen_for(ctx: &Context, env: &Env, overlay: &Overlay) -> Rect { - let safe = areas::safe_rect(ctx); + let safe = layer_room(ctx); region_for(env, overlay).map_or(safe, |region| region.intersect(safe)) } diff --git a/crates/ui-contract/src/contract/overlay/ui.rs b/crates/ui-contract/src/contract/overlay/ui.rs index 34728c9f3..4f428911d 100644 --- a/crates/ui-contract/src/contract/overlay/ui.rs +++ b/crates/ui-contract/src/contract/overlay/ui.rs @@ -76,10 +76,10 @@ impl<'a> OverlayUi<'a> { } /// Keeps the popups this component shows from here on, and every popup opened from them, below the component: - /// inside the safe rect less the part above the component's bottom edge. A menu bar's menus and their submenus + /// inside the layer room less the part above the component's bottom edge. A menu bar's menus and their submenus /// never cover the bar. pub fn contain_popups_below(&mut self) { - let safe = areas::safe_rect(self.ctx); + let safe = super::layer_room(self.ctx); let top = (self.to_screen * self.anchor).bottom().clamp(safe.top(), safe.bottom()); let region = Rect::from_min_max(egui::pos2(safe.left(), top), safe.max); self.env = self.env.derive(|scoped| { diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 09f95b994..ea47928a7 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1610,8 +1610,11 @@ fn extent_step( let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id); let env = begun.env(); // A body root with parts steps its press machine before its measuring run, so the body reads this pass's part - // presses in both runs (`BodyCx::part_press`). Step 8 finds the outcome. A member of another arena senses at step 8. - if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && (t.arena() || facts.text() || env.arena.is_none()) { + // presses in both runs (`BodyCx::part_press`) and its host reads them before it places the body. Step 8 finds the + // outcome. A member of another arena senses at step 8. A root its host shows on a layer of its own (not in flow) + // senses in its own arena: its steps 6 to 16 run in the layer's env, which is outside its opener's arena. + let own_arena = t.arena() || facts.text() || env.arena.is_none() || !t.in_flow(); + if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && own_arena { sensing::sense_early(ctx, id, resolved.enabled); } let scx = steps::style_cx(ctx, &begun.env, &begun.step1); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 0be4e115f..956401601 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -546,6 +546,7 @@ pub(crate) fn show_container_taking( body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); + crate::layout::close_flow_start_in(ui); crate::runtime::egui::alloc::advance_past(ui, rect); shown } diff --git a/crates/ui-contract/src/contract/steps/value.rs b/crates/ui-contract/src/contract/steps/value.rs index 0618346c3..e3e265fb8 100644 --- a/crates/ui-contract/src/contract/steps/value.rs +++ b/crates/ui-contract/src/contract/steps/value.rs @@ -10,12 +10,11 @@ use craft_behavior::{CancelReason, EditEvent, Gesture, Mixed, Value}; use egui::{Context, Id}; use std::sync::Arc; -/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the pass its value -/// step last ran in, the `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased +/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the +/// `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased /// hover, press and on. pub(crate) struct Shown { pub copy: Option>, - pub drawn: u64, pub state: ShownState, } @@ -38,13 +37,13 @@ impl ShownState { impl Clone for Shown { fn clone(&self) -> Self { - Shown { copy: self.copy.clone(), drawn: self.drawn, state: self.state.clone() } + Shown { copy: self.copy.clone(), state: self.state.clone() } } } impl Default for Shown { fn default() -> Self { - Shown { copy: None, drawn: 0, state: ShownState::default() } + Shown { copy: None, state: ShownState::default() } } } @@ -99,10 +98,9 @@ fn resolve_value(comp: &mut dyn ValueSource, stage: &mut MemoryStag let slot = gesture_key(id); let (serial, all_reason) = crate::runtime::edit::latest(stage.ctx()); let mut cancelled = None; - // A component not drawn for a pass loses its press at the end hook; its running gesture ends here, the first pass it is - // drawn again. - let pass_nr = crate::runtime::pointer::pass_of(stage.ctx()); - let removed = std::mem::replace(&mut stage.shown::>(id).drawn, pass_nr).saturating_add(1) < pass_nr; + // A component not shown for a pass, by a run or a replay of one, loses its press at the end hook; its running gesture + // ends here, the first pass it is shown again. + let removed = !crate::runtime::memory::shown_last_pass(stage.ctx(), id); if stage.shown::>(slot).is_running() { // `(given, value)` of a single-valued binding the app owns. let host = comp.binding().and_then(|bind| match bind.get() { diff --git a/crates/ui-contract/src/layout/arrange.rs b/crates/ui-contract/src/layout/arrange.rs index de37411f3..8a6b9b170 100644 --- a/crates/ui-contract/src/layout/arrange.rs +++ b/crates/ui-contract/src/layout/arrange.rs @@ -71,6 +71,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_> placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect))); } let whole = flow.to_physical(Rect::from_min_size(room.min, taken)); + super::close_flow_start_in(ui); alloc::advance_past(ui, whole); whole } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index c32bee2cb..39aef7f2b 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -211,6 +211,79 @@ fn report_first_line(ctx: &egui::Context, target: Id, at: Option) { }); } +/// The bodies whose flow has placed nothing yet in the sweep or run under way, by body id, each with whether a rule +/// precedes the body's start (`Scoped::after_rule`). +#[derive(Default)] +pub(crate) struct FlowStarts(IdMap); + +/// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed +/// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`); +/// `None` once a child took room there, and outside a body. +pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option { + let body = env.flow_body?; + pass_state::with::(ctx, |starts| starts.0.get(&body).copied()) +} + +/// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`). +pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool { + flow_start(ctx, env).is_some() +} + +/// A child took room in the flow of the body that places the children under `env`: its flow start closes. +pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { + if let Some(body) = env.flow_body { + pass_state::with::(ctx, |starts| starts.0.remove(&body)); + } +} + +/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`. +pub(crate) fn close_flow_start_in(ui: &Ui) { + close_flow_start(ui.ctx(), &Env::of(ui)); +} + +/// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or +/// run under way, and the rect of the row's last child in flow, by the row's layout id. +#[derive(Default)] +pub(crate) struct Brackets(IdMap); + +/// The controls of a bracket's rows and the child after them. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct BracketTook { + /// The centre line of the first row's control. + pub(crate) first: Option, + /// The centre line of the last row's control. + pub(crate) last: Option, + /// How far the rows' controls reach toward the row's end edge, at most: right, or left under right-to-left. + pub(crate) end: Option, + /// The rect of the row's last child placed in flow: the control in the bracket's middle. + pub(crate) middle: Option, +} + +impl BracketTook { + /// The centre line between the first and the last row's controls, once two rows reported. + pub(crate) fn centre(&self) -> Option { + self.first.zip(self.last).filter(|(first, last)| last > first).map(|(first, last)| (first + last) / 2.0) + } +} + +/// Reports the `control` rect of a labelled row to the bracketed row `row`, its end edge `rtl`-aware. +pub(crate) fn report_bracket_control(ctx: &egui::Context, row: Id, control: Rect, rtl: bool) { + pass_state::with::(ctx, |brackets| { + if let Some(took) = brackets.0.get_mut(&row) { + let centre = control.center().y; + took.first.get_or_insert(centre); + took.last = Some(centre); + let end = if rtl { -control.min.x } else { control.max.x }; + took.end = Some(took.end.map_or(end, |was: f32| was.max(end))); + } + }); +} + +/// What the rows of the bracketed row `row` reported in the run that just ended; `None` outside a bracketed row. +pub(crate) fn take_bracket(ctx: &egui::Context, row: Id) -> Option { + pass_state::with::(ctx, |brackets| brackets.0.remove(&row)) +} + /// How a child that fills the main axis of the body it sits in sizes along it. enum MainFill { /// The body is being measured: the child takes no room along the axis and is counted. @@ -1115,9 +1188,16 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); let (line, target) = (env.row_line, env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; - let above = line.and_then(|line| line.centre).zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); + // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its + // rows reported before it. + let bracket = line.filter(|line| env.bracket == Some(line.body)).and_then(|line| { + let took = pass_state::with::(ui.ctx(), |brackets| brackets.0.get(&line.body).copied())?; + Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top()))) + }); + let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); + let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); - let (rect, in_cell) = take_in(ui, env.grid, slot); + let (rect, in_cell) = take_in(ui, &env, slot); let placed = if child.fill && in_cell { rect } else { @@ -1130,6 +1210,9 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { }; Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) }; + if let Some((row, _)) = bracket { + pass_state::with::(ui.ctx(), |brackets| brackets.0.get_mut(&row).map(|took| took.middle = Some(placed))); + } if measure::active(ui.ctx()) { if let Some(line) = line { pass_state::with::(ui.ctx(), |rows| { @@ -1148,7 +1231,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the /// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { - take_in(ui, Env::of(ui).grid, size) + take_in(ui, &Env::of(ui), size) } /// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it. @@ -1158,13 +1241,15 @@ pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { - take_in(ui, grid, Vec2::ZERO); + take_in(ui, &env, Vec2::ZERO); } } -/// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself. -fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { - match cell_in(ui, grid, size) { +/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start +/// closes. +fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { + close_flow_start(ui.ctx(), env); + match cell_in(ui, env.grid, size) { Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } @@ -1173,7 +1258,12 @@ fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { /// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns /// it; `None`, taking nothing, outside such a body. pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { - cell_in(ui, Env::of(ui).grid, size) + let env = Env::of(ui); + let cell = cell_in(ui, env.grid, size); + if cell.is_some() { + close_flow_start(ui.ctx(), &env); + } + cell } fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { @@ -1324,6 +1414,7 @@ fn run_grid( scoped.derive_local(|scoped| { scoped.grid = Some(id); scoped.grid_top = cells == CellAlign::Top; + scoped.flow_body = Some(id); }), ); let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body); @@ -1598,8 +1689,14 @@ pub(crate) fn run_body_measured( // Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh. let target = env.first_line.filter(|_| sizing); let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); + // Each sweep and the real run start the body's flow, and a bracketed row's reports, afresh. + let (after_rule, bracket) = (env.after_rule, env.bracket == Some(id)); let body = |ui: &mut Ui| { open_sweep(&ctx, target, row); + pass_state::with::(&ctx, |starts| starts.0.insert(id, after_rule)); + if bracket { + pass_state::with::(&ctx, |brackets| brackets.0.insert(id, BracketTook::default())); + } body(ui) }; // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. @@ -1627,7 +1724,10 @@ struct RowIn { /// A `Stack` body: each leaf shows at most the stack's room, never below its least. fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); - let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit)); + let env = env.derive_local(|scoped| { + scoped.shrink = Some(Shrink::Fit); + scoped.flow_body = Some(at.id); + }); let installed = Env::install_for(ui, env.clone()); // A held child of a column whose own room is unbounded keeps the width it measured at. let inner = if env.content_column && flow_room(ui).x.is_finite() { @@ -1652,6 +1752,7 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m scoped.grid_top = false; scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_spread(ui, id, gap.x, rtl, &mut body); @@ -1675,6 +1776,7 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu scoped.row_room = Some(room.width()); scoped.row_line = Some(line); scoped.first_line = None; + scoped.flow_body = Some(id); }), ); let inner = run_shrinking(ui, id, &mut body); @@ -1724,6 +1826,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign env.derive_local(|scoped| { scoped.row_room = Some(room.width()); scoped.row_line = line; + scoped.flow_body = Some(id); if line.is_some() { scoped.first_line = None; } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 4f2654e97..b5fbb0c2e 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, in_grid_content_column, - leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured, - shares_y, shrink_cap, take_cell, take_in_flow, view_room, + BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, + flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, + report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, + view_room, }; diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index b9645b533..972df0013 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -400,7 +400,15 @@ impl<'a> Draw<'a> { self.initial(rect, letter, StyleColor(color)); return; } - _ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon, self.data != DataMode::Full), + _ => super::icon::paint( + self.painter, + self.env.tokens, + self.env.direction, + rect, + icon, + self.data != DataMode::Full, + self.env.ink == Ink::OnDark, + ), } match icon.badge { Some(super::IconMark::Dot(badge)) => { diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 57e414720..6a8bedfc8 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -268,8 +268,10 @@ pub fn icon_names() -> &'static [&'static str] { } /// Paints `spec`'s glyph centred in the square of `rect`'s shorter side; `Draw::icon` adds the badge. `single_ink` paints -/// every layer of an app icon in the one colour: the icon of a component in its disabled state. -pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool) { +/// every layer of an app icon in the one colour: the icon of a component in its disabled state. `on_dark` is whether +/// the icon stands on a strong fill or scrim (the surface's ink is `Ink::OnDark`): its accent parts then paint in the +/// icon's colour, since `accent.solid` would vanish on the brand fill. +pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool, on_dark: bool) { let color = spec.color_in(tokens); let rtl = direction == Direction::Rtl; let side = rect.width().min(rect.height()); @@ -283,7 +285,7 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, IconSource::Glyph(glyph) => glyph.paint(painter, tokens, square, color, rtl && glyph.directional() && spec.mirror == Mirror::Auto), IconSource::Svg(id) => { if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.mirror) { - icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink)); + icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink, on_dark || spec.ink == Ink::OnDark)); } } IconSource::Mark(badge) => super::pointer_art::paint_badge(painter, tokens, direction, square, *badge, color), @@ -396,8 +398,13 @@ impl LayerInks { } /// The inks of an icon painted in `color`: the accent parts in `colors.accent.solid` and the fixed parts as drawn, - /// except that with `single_ink` (a disabled component) every layer paints in `color`. - pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool) -> Self { + /// except that with `single_ink` (a disabled component) every layer paints in `color`, and with `on_dark` (a strong + /// fill or scrim, where the accent colour would vanish) the accent parts paint in `color` and the fixed parts stay + /// as drawn. + pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool, on_dark: bool) -> Self { + if on_dark && !single_ink { + return LayerInks { ink: color, accent: color, fixed: None }; + } if single_ink { return LayerInks::single(color); } diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index f53b7b778..053c41e4c 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -30,18 +30,100 @@ pub enum TickEdge { Right, } +impl TickEdge { + /// Whether positions run along x (a top or bottom edge). + pub const fn horizontal(self) -> bool { + matches!(self, TickEdge::Bottom | TickEdge::Top) + } +} + +/// How a ruler lays out its marks and numbers. A ruler takes a face from its `face` prop, else from the scope's +/// component set ([`RulerFace::of`]); the face changes the arrangement only, every value still comes from the same +/// tokens. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum RulerFace { + /// Marks rise from the strip's inner edge, a major one across the strip's depth, and each number sits beside its + /// major mark. + #[default] + Edge, + /// A bar inset in the strip by `BAR_INSET` carries the marks centred on it, and a number stands in place of + /// each major mark; a major mark shows only where its number is dropped. + Centred, +} + +impl RulerFace { + /// The face the component set `set` shows: the creative set the edge face, the productivity set the centred one. + pub const fn of(set: craft_theme::ComponentSet) -> Self { + match set { + craft_theme::ComponentSet::Creative => RulerFace::Edge, + craft_theme::ComponentSet::Productivity => RulerFace::Centred, + } + } + + /// Where the marks of a strip along `edge` sit: the whole strip for the edge face, the strip inset across its + /// depth by `BAR_INSET` on each side for the centred face. + pub fn bar(self, strip: Rect, edge: TickEdge) -> Rect { + match self { + RulerFace::Edge => strip, + RulerFace::Centred => { + if edge.horizontal() { + strip.shrink2(Vec2::new(0.0, BAR_INSET)) + } else { + strip.shrink2(Vec2::new(BAR_INSET, 0.0)) + } + } + } + } + + /// The marks of `marks` this face shows beside the numbers in `numbers` (screen boxes): the edge face shows every + /// mark, the centred face leaves out each one whose position lies inside a number widened by `pad` along `edge`'s + /// axis, so a number stands in place of its own mark and no mark runs through one. `origin` is the screen position + /// the marks' `at` counts from. + pub fn beside_numbers(self, edge: TickEdge, origin: f32, marks: Vec, numbers: &[Rect], pad: f32) -> Vec { + match self { + RulerFace::Edge => marks, + RulerFace::Centred => marks + .into_iter() + .filter(|mark| { + let at = origin + mark.at; + !numbers.iter().any(|number| { + let along = if edge.horizontal() { number.x_range() } else { number.y_range() }; + (along.min - pad..=along.max + pad).contains(&at) + }) + }) + .collect(), + } + } + + /// The box a centred number of `size` takes for the mark at `at` (a screen position along `edge`'s axis): centred + /// on the mark and on the bar. + pub fn centred_number(bar: Rect, edge: TickEdge, at: f32, size: Vec2) -> Rect { + let centre = if edge.horizontal() { pos2(at, bar.center().y) } else { pos2(bar.center().x, at) }; + Rect::from_center_size(centre, size) + } +} + /// How long a tick is: the rank it has among its neighbours. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum TickRank { - /// The shortest, `size.ruler.tick.minor`. + /// The shortest, `TICK_MINOR` long. Minor, - /// Halfway between two major ticks, `size.ruler.tick.mid`. + /// Halfway between two major ticks, `TICK_MID` long. Mid, - /// The longest, `space.gap.inline`. + /// The longest: across the depth of the rect the marks are painted in. Major, } +/// The length of a minor tick, in points. The same in every density, as in the apps' rulers. +const TICK_MINOR: f32 = 3.0; + +/// The length of the tick halfway between two major ticks, in points, in every density. +const TICK_MID: f32 = 6.0; + +/// How far the centred face's bar sits inside the ruler strip on each side across its depth. +const BAR_INSET: f32 = 2.0; + /// One tick: where it sits along its edge and how long it is. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -618,28 +700,38 @@ pub fn grid_lines_with(look: &GridLook, grid: &GridLines, ink: &GridInk, pixels_ shapes } -/// The tick marks of `ticks` on one edge of `rect` that `clip` shows, `stroke.thin` lines of `text.faint`: minor ones -/// `size.ruler.tick.minor` long, mid ones `size.ruler.tick.mid`, major ones across the whole depth of `rect`, beside their labels. -pub fn ticks(tokens: &UiTokens, rect: Rect, edge: TickEdge, ticks: &[Tick], clip: Rect, pixels_per_point: f32) -> Vec { +/// The tick marks of `ticks` along `edge` of `rect` that `clip` shows, `stroke.thin` lines of `text.faint`: minor ones +/// `TICK_MINOR` long, mid ones `TICK_MID`, major ones across the whole depth of `rect`. The edge +/// face hangs them from `edge`; the centred face centres them on `rect`'s middle line (`rect` is then the face's bar). +pub fn ticks(tokens: &UiTokens, rect: Rect, edge: TickEdge, face: RulerFace, ticks: &[Tick], clip: Rect, pixels_per_point: f32) -> Vec { let look = RuleLook { color: rgba_color(tokens.color.text.faint), width: RuleWidth::Points(tokens.stroke.thin) }; let depth = match edge { TickEdge::Bottom | TickEdge::Top => rect.height(), TickEdge::Left | TickEdge::Right => rect.width(), }; - let (minor, mid, major) = (tokens.size.ruler.tick.minor, tokens.size.ruler.tick.mid, depth); ticks .iter() .filter_map(|tick| { let length = match tick.rank { - TickRank::Minor => minor, - TickRank::Mid => mid, - TickRank::Major => major, + TickRank::Minor => TICK_MINOR, + TickRank::Mid => TICK_MID, + TickRank::Major => depth, }; - let (from, to) = match edge { - TickEdge::Bottom => (pos2(rect.left() + tick.at, rect.bottom()), pos2(rect.left() + tick.at, rect.bottom() - length)), - TickEdge::Top => (pos2(rect.left() + tick.at, rect.top()), pos2(rect.left() + tick.at, rect.top() + length)), - TickEdge::Left => (pos2(rect.left(), rect.top() + tick.at), pos2(rect.left() + length, rect.top() + tick.at)), - TickEdge::Right => (pos2(rect.right(), rect.top() + tick.at), pos2(rect.right() - length, rect.top() + tick.at)), + let (from, to) = match (face, edge) { + (RulerFace::Edge, TickEdge::Bottom) => { + (pos2(rect.left() + tick.at, rect.bottom()), pos2(rect.left() + tick.at, rect.bottom() - length)) + } + (RulerFace::Edge, TickEdge::Top) => (pos2(rect.left() + tick.at, rect.top()), pos2(rect.left() + tick.at, rect.top() + length)), + (RulerFace::Edge, TickEdge::Left) => (pos2(rect.left(), rect.top() + tick.at), pos2(rect.left() + length, rect.top() + tick.at)), + (RulerFace::Edge, TickEdge::Right) => (pos2(rect.right(), rect.top() + tick.at), pos2(rect.right() - length, rect.top() + tick.at)), + (RulerFace::Centred, TickEdge::Bottom | TickEdge::Top) => { + let (x, y) = (rect.left() + tick.at, rect.center().y); + (pos2(x, y - length / 2.0), pos2(x, y + length / 2.0)) + } + (RulerFace::Centred, TickEdge::Left | TickEdge::Right) => { + let (x, y) = (rect.center().x, rect.top() + tick.at); + (pos2(x - length / 2.0, y), pos2(x + length / 2.0, y)) + } }; clip.intersects(Rect::from_two_pos(from, to)).then(|| Rule::shapes(&look, from, to, pixels_per_point)) }) @@ -923,9 +1015,14 @@ impl ContentPainterCx<'_> { super::draw::data_checker(&self.painter, self.tokens, self.data, checker, rect, radius); } - /// Paints tick marks on one edge of `rect`. - pub fn ticks(&self, rect: Rect, edge: TickEdge, marks: &[Tick]) { - self.painter.extend(ticks(self.tokens, rect, edge, marks, self.painter.clip_rect(), self.ppp())); + /// Where the marks of a ruler strip along `edge` sit in `face`; see [`RulerFace::bar`]. + pub fn ruler_bar(&self, strip: Rect, edge: TickEdge, face: RulerFace) -> Rect { + face.bar(strip, edge) + } + + /// Paints tick marks along `edge` of `rect` in `face`; see [`ticks`]. + pub fn ticks(&self, rect: Rect, edge: TickEdge, face: RulerFace, marks: &[Tick]) { + self.painter.extend(ticks(self.tokens, rect, edge, face, marks, self.painter.clip_rect(), self.ppp())); } /// Paints a halo-and-line outline of `shape`. diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 3d75e3d4e..bb5a5056b 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -40,8 +40,8 @@ pub(crate) use icon::SvgIcon; pub use icon::{Glyph, IconMark, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; pub use ime_surface::ImeSurface; pub use kit::{ - Checker, CheckerArea, GridAxis, GridCrowding, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, - ellipse, fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, + Checker, CheckerArea, GridAxis, GridCrowding, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, RulerFace, Tick, TickEdge, TickRank, dashed, + drop_mark, ellipse, fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, }; pub use marker::{Marker, MarkerSize}; pub use paint_slot::PaintSlot; @@ -67,9 +67,9 @@ pub use tool::ToolIcon; #[cfg(feature = "testing")] pub use textures::FakeThumbSource; pub use textures::{ - CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, TextureBudget, TextureKey, TextureLoader, - TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, ThumbRequest, - ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, + CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, Serials, TextureBudget, TextureKey, + TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, + ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, }; pub(crate) use draw::DataMode; diff --git a/crates/ui-contract/src/primitives/pointer_art.rs b/crates/ui-contract/src/primitives/pointer_art.rs index 0fd7be528..412666dde 100644 --- a/crates/ui-contract/src/primitives/pointer_art.rs +++ b/crates/ui-contract/src/primitives/pointer_art.rs @@ -412,7 +412,6 @@ pub(crate) fn type_on(pen: &Pen, path: bool) { /// The locator: a square frame centred on the pointer between halo frames a hairline outside and inside it. pub(crate) fn locator(pen: &Pen) { - // design: allow[literal-size/vec2](pointer art is a fixed bitmap-like drawing around the hotspot, not a layout size) let rect = Rect::from_center_size(Pos2::ZERO, Vec2::splat(LOCATOR_SIDE)); let halo = Stroke::new(pen.thin, pen.halo); pen.push(Mark::Frame(rect.expand(pen.thin), halo)); diff --git a/crates/ui-contract/src/primitives/scroll_bar.rs b/crates/ui-contract/src/primitives/scroll_bar.rs index f0c62a441..8027b18d5 100644 --- a/crates/ui-contract/src/primitives/scroll_bar.rs +++ b/crates/ui-contract/src/primitives/scroll_bar.rs @@ -11,6 +11,9 @@ pub struct ScrollBar; /// The opacity of an edge fade at the view's edge, once at least the fade's length of content is hidden past it. const FADE_STRENGTH: f32 = 0.5; +/// The length of an edge fade, in points, in every density. +const FADE_LENGTH: f32 = 20.0; + /// How far a scroll view's content runs past each of its edges, in points. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] @@ -62,13 +65,13 @@ impl ScrollBar { } } - /// The fades over `view` at each edge past which content is hidden: `look.fade` long, from `background` at the + /// The fades over `view` at each edge past which content is hidden: `FADE_LENGTH` long, from `background` at the /// edge to clear inward, the more opaque the more is hidden, up to `FADE_STRENGTH` once a fade's length is. - pub fn fades(look: &ScrollBarLook, view: Rect, hidden: HiddenContent, background: Color32) -> Vec { + pub fn fades(view: Rect, hidden: HiddenContent, background: Color32) -> Vec { let across = |hidden: f32, extent: f32, edge: fn(Rect, f32) -> Rect, direction: Direction| { - let length = look.fade.min(extent); + let length = FADE_LENGTH.min(extent); (hidden > 0.0 && length > 0.0).then(|| { - let at = background.gamma_multiply((hidden / look.fade).clamp(0.0, 1.0) * FADE_STRENGTH); + let at = background.gamma_multiply((hidden / FADE_LENGTH).clamp(0.0, 1.0) * FADE_STRENGTH); Shape::gradient_rect(edge(view, length), direction, [at, Color32::TRANSPARENT]) }) }; diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 9b36826d8..d09cc6ea9 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -5,7 +5,7 @@ use crate::runtime::egui::memory; use crate::runtime::egui::text_layout; pub use crate::style::Span; use crate::style::text_measure::{paragraph_job, span_format}; -use crate::style::{StyleColor, TypeRole, UiTokens}; +use crate::style::{LetterCase, StyleColor, TypeRole, UiTokens}; use craft_i18n::Direction; use egui::epaint::text::FontCacheRevision; use egui::text::{LayoutJob, TextWrapping}; @@ -118,6 +118,11 @@ impl<'a> TextRun<'a> { /// Sets the type role. pub fn role(mut self, role: TypeRole) -> Self { self.role = role; + if role.letter_case() == LetterCase::Upper { + for span in &mut self.spans { + span.text = Cow::Owned(span.text.to_uppercase()); + } + } self } diff --git a/crates/ui-contract/src/primitives/textures/mod.rs b/crates/ui-contract/src/primitives/textures/mod.rs index faabf4501..df9a52a57 100644 --- a/crates/ui-contract/src/primitives/textures/mod.rs +++ b/crates/ui-contract/src/primitives/textures/mod.rs @@ -8,7 +8,7 @@ mod words; pub use limits::{MAX_TEXTURE, fit_image, reduce_image, texture_factor, texture_side}; pub use loader::{LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, TextureLoader}; -pub use store::{CachedTexture, Revision, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; +pub use store::{CachedTexture, Revision, Serials, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; pub use words::TextureWords; /// The tint that leaves a texture's own colours as they are: every texel is multiplied by white. diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index 35fc6c92f..8144fa8ea 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -371,6 +371,22 @@ impl Default for Stores { } } +/// The numbers that keep apart the textures one owner makes: a mask or preview made anew gets a number no earlier one +/// of the same `Serials` had, so an entry kept under its key is never taken for the new one's. The owner of what the +/// textures show (a tool's state, a model) holds the `Serials`. The numbers are unique per owner, not per context: a +/// texture store that several owners share keys each entry by the owner's component id as well as the serial. Plain +/// data, so it can sit in tracked or model state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Serials(u64); + +impl Serials { + /// A new number: never one this `Serials` gave before. + pub fn mint(&mut self) -> u64 { + self.0 += 1; + self.0 + } +} + /// Textures by key and revision, with byte and entry budgets: the one place an app's pictures become egui /// textures. The app never holds a `TextureHandle`. The state lives in runtime memory of the context under the /// salt; the value is a cheap handle that clones share. diff --git a/crates/ui-contract/src/primitives/textures/thumbnails.rs b/crates/ui-contract/src/primitives/textures/thumbnails.rs index 697befc80..431810161 100644 --- a/crates/ui-contract/src/primitives/textures/thumbnails.rs +++ b/crates/ui-contract/src/primitives/textures/thumbnails.rs @@ -486,7 +486,7 @@ fn paint_placeholder(cx: &ContentPainterCx<'_>, rect: Rect, paper: Option, rect: Rect) { let side = cx.tokens.size.icon.sm.min(rect.width().min(rect.height())); let icon = Rect::from_center_size(rect.center(), vec2(side, side)); - crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false); + crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false, false); } /// A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets, diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 1f80642c2..5864bd09e 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -22,10 +22,12 @@ pub use crate::runtime::egui::access::bounds; #[doc(hidden)] pub use emit::SubDecl; #[doc(hidden)] +pub use emit::layer_root; +#[doc(hidden)] pub use emit::report_sub; #[doc(hidden)] pub use emit::sub_node_id; -pub(crate) use emit::{FaceFacts, Own, PopupShown, report, report_layer}; +pub(crate) use emit::{FaceFacts, Own, PopupShown, hide_exiting_content, report, report_layer, report_modal}; pub use live::announce; pub(crate) use live::{begin_pass as begin_live_pass, end_pass as end_live_pass}; pub use scope::{FieldLabel, FieldLabelRole}; diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index 1631aefad..4cb7b5585 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -52,7 +52,7 @@ pub(crate) struct Own<'a> { /// A popup an anchor shows this pass. #[derive(Clone, Copy, Debug)] pub(crate) struct PopupShown { - /// The popup's layer id: the id of its root node. + /// The popup's layer id (its root node is [`layer_root`]'s). pub id: Id, pub kind: PopupKind, pub open: bool, @@ -257,7 +257,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) { let expanded = expanded_of(own.flags, access.expanded.or_else(|| popup.filter(|_| !own.popups_by_part).map(|popup| popup.open))); let mut relations = access.relations.clone(); relations.labelled_by.extend(name.labelled_by.iter().copied()); - relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| popup.id)); + relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| layer_root(popup.id))); let numeric = access.numeric.as_ref(); let mut spec = NodeSpec::new(own.role); spec.rect = Some(own.rect); @@ -419,19 +419,34 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { } } -/// The root node of an overlay layer: the layer's content attaches below it, and a modal layer's root is modal. An -/// exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported while it still -/// paints; the ids stay the same if the layer reopens. -pub(crate) fn report_layer(ctx: &Context, id: Id, content: Id, rect: Rect, modal: bool, exiting: bool) { - adapter::register_parent(ctx, content, id); +/// The id of the root node of the overlay layer `id`. The root has an id of its own: the layer's container component +/// takes the layer's id for its widget and node, inside the layer's content, which attaches below the root. +pub fn layer_root(id: Id) -> Id { + sub(id, "layer") +} + +/// Writes the root node of the overlay layer `id`, whose content takes `rect`, and returns its id. The layer's content +/// hangs below it. An exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported +/// while it still paints; the ids stay the same if the layer reopens. Called before the layer's `Area` shows, which +/// egui hangs below the root. The root is a plain container: a modal layer's flag sits on its container component's +/// node ([`report_modal`]), which carries the role, since screen readers drop a container without one. +pub(crate) fn report_layer(ctx: &Context, id: Id, rect: Rect, exiting: bool) -> Id { + let root = layer_root(id); let mut spec = NodeSpec::layer_root(); spec.rect = Some(rect); - spec.modal = modal; spec.hidden = exiting; - write_node(ctx, id, &spec); - if exiting { - // The content `Ui` can attach to the viewport rather than to the root (a popup body that names its own - // parent), so it is hidden itself. - adapter::hide(ctx, content); - } + write_node(ctx, root, &spec); + root +} + +/// Marks the node of the modal overlay layer `id` modal: the node its container component wrote with the layer's id +/// and its role. Called after the layer's body ran, so the node exists when the component reported it. +pub(crate) fn report_modal(ctx: &Context, id: Id) { + adapter::set_modal(ctx, id); +} + +/// Hides the node of the content `Ui` of an exiting overlay layer: a popup body that names its own parent can hang +/// its content outside the layer's root. +pub(crate) fn hide_exiting_content(ctx: &Context, content: Id) { + adapter::hide(ctx, content); } diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 7269f8bc7..70006ff2e 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -1107,11 +1107,18 @@ pub(crate) fn edit_chords(ctx: &Context) -> Arc<[(EditCommand, Chord)]> { with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.edit_chords)).unwrap_or_default()) } -/// The generation of the window's keymap: it moves each time a new keymap is built. -pub(crate) fn keymap_generation(ctx: &Context) -> u64 { +/// The generation of the window's keymap without noting a read: it moves each time a new keymap is built. +pub(crate) fn keymap_built(ctx: &Context) -> u64 { with(ctx, |board| board.keymaps) } +/// The generation of the window's keymap, for a key that holds what is derived from its chords: it moves each time a +/// new keymap is built. The caller's view reads the keymap, so a change of it runs the view. +pub fn keymap_generation(ctx: &Context) -> u64 { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); + keymap_built(ctx) +} + /// Whether the queue holds a command for one of `instances`: only a run of the view they registered in takes it. pub(crate) fn queued_for(ctx: &Context, instances: &[Id]) -> bool { !instances.is_empty() && with(ctx, |board| board.queue.iter().any(|fired| fired.target.is_some_and(|target| instances.contains(&target)))) diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 888392774..bc115bded 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -31,12 +31,12 @@ pub(crate) use board::{ begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts, }; #[doc(hidden)] -pub use board::{bound_around, take_around}; +pub use board::{bound_around, keymap_generation, take_around}; #[cfg(feature = "testing")] #[doc(hidden)] pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; -pub(crate) use board::{keymap_generation, queued_for}; +pub(crate) use board::{keymap_built, queued_for}; use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked}; use craft_behavior::CommandFlags; diff --git a/crates/ui-contract/src/runtime/derived.rs b/crates/ui-contract/src/runtime/derived.rs new file mode 100644 index 000000000..d934215a2 --- /dev/null +++ b/crates/ui-contract/src/runtime/derived.rs @@ -0,0 +1,93 @@ +//! Derived values: data a component computes from its inputs and keeps across passes. [`derived`] keeps one value per +//! component id and value type, and builds it again only when its key changes. The key implements +//! [`MemoProps`], so it can only be made of checked inputs (`Tracked` revisions, framework +//! revisions, plain values), and a kept value is never stale while the key compiles. +//! +//! A value no pass asks for is dropped by the rule memoized views follow for absent entries (`lazy::absent_past_room`). + +use crate::contract::{MemoKey, MemoProps}; +use crate::runtime::egui::pass; +use crate::runtime::frame::PerViewport; +use egui::{Context, Id, IdMap}; +use std::any::{Any, TypeId}; +use std::sync::Arc; + +/// A kept value: the key it was built from and the frame a pass last asked for it. +struct Entry { + key: u128, + value: Arc, + touched: u64, +} + +/// The kept values of one viewport. +#[derive(Default)] +pub(crate) struct Store { + entries: IdMap, + /// The frame the entries were last pruned in. + pruned: u64, +} + +impl Store { + /// Drops the absent entries past the memo rule's room, once per frame. An entry asked for in this frame or the one + /// before is shown. + fn prune(&mut self, frame: u64) { + if self.pruned == frame { + return; + } + self.pruned = frame; + let shown = self.entries.values().filter(|entry| entry.touched + 1 >= frame).count(); + let absent = self.entries.iter().filter(|(_, entry)| entry.touched + 1 < frame).map(|(id, entry)| (entry.touched, *id)); + for id in super::lazy::absent_past_room(shown, absent) { + self.entries.remove(&id); + } + } +} + +/// The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else +/// `build`'s, which is kept in its place. One value is kept per id and value type `V`; a component that derives two +/// values of one type gives each its own id. +pub fn derived(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc { + let mut memo = MemoKey::of_view(ctx); + memo.feed_hash(&K::identity()); + key.key(&mut memo); + #[cfg(feature = "testing")] + crate::runtime::measure::count_memo_key_bytes(ctx, memo.bytes()); + let key = memo.finish(); + let slot = id.with(TypeId::of::()); + crate::runtime::replay::note_derived_keep(ctx, slot); + let viewport = pass::current_viewport(ctx); + let frame = pass::frame_nr(ctx, viewport); + let kept = PerViewport::::with(ctx, viewport, |store| { + store.prune(frame); + let entry = store.entries.get_mut(&slot).filter(|entry| entry.key == key)?; + entry.touched = frame; + Arc::clone(&entry.value).downcast::().ok() + }); + if let Some(value) = kept { + return value; + } + #[cfg(feature = "testing")] + crate::runtime::measure::count_derived(ctx, id); + // Built outside the store, so a build may derive values of its own. + let value = Arc::new(build()); + let entry = Entry { key, value: Arc::clone(&value) as Arc, touched: frame }; + PerViewport::::with(ctx, viewport, |store| store.entries.insert(slot, entry)); + value +} + +/// Keeps the values under `slots` through this frame, for a replayed run that asked for them: the replay asks for +/// nothing, and an entry no pass asked for in a frame is dropped by the memo rule. +pub(crate) fn keep(ctx: &Context, slots: &[Id]) { + if slots.is_empty() { + return; + } + let viewport = pass::current_viewport(ctx); + let frame = pass::frame_nr(ctx, viewport); + PerViewport::::with(ctx, viewport, |store| { + for slot in slots { + if let Some(entry) = store.entries.get_mut(slot) { + entry.touched = frame; + } + } + }); +} diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 0f109e029..7e68df41a 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -180,7 +180,7 @@ pub trait WindowDropTarget

{ /// Where a drop target lies: a rect on an egui layer, in that layer's space. A component's own target lies over its /// visible rect on its layer; a component that takes drops over an area it does not draw (a preset browser's canvas) /// names the area with [`DropZone::new`] and registers with [`zone_target`]. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct DropZone { layer: Layer, rect: Rect, diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index be6d1ac13..dd78c1a09 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -167,8 +167,17 @@ pub(crate) fn pass_through(ctx: &Context, id: Id) { }); } -/// Reports `id` as the focused node of this pass. +/// Marks the node of `id` modal, when the pass has written it. +pub(crate) fn set_modal(ctx: &Context, id: Id) { + if ctx.has_accesskit_node(id) { + ctx.accesskit_node_builder(id, accesskit::Node::set_modal); + } +} + +/// Reports `id` as the focused node of this pass. A replay of the run that reported it reports it again: a view that +/// holds focus replays while nothing reaches it. pub(crate) fn set_focus(ctx: &Context, id: Id) { + crate::runtime::replay::journal(ctx, || id, |ctx, &id| set_focus(ctx, id)); with_emitted(ctx, |emitted| emitted.focus_set = true); ctx.set_accesskit_focus(id); } @@ -209,6 +218,37 @@ pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) { emit(ctx, id); } +/// The trials' pass-end check that egui's AccessKit parents of the pass hold no cycle; panics naming the ids of the +/// first one found. egui places a node under the first ancestor that has a node by walking the parents, which a cycle +/// sends into endless recursion when no node of the cycle exists yet: a replay adds a run's nodes in the order they +/// were created, and a run only tolerates a cycle while some node of it already exists. +#[cfg(feature = "testing")] +pub(crate) fn check_parents_acyclic(ctx: &Context) { + let cycle = ctx.with_accesskit_parents(|parents| { + let mut acyclic = IdSet::default(); + for &start in parents.keys() { + let mut path: Vec = Vec::new(); + let mut on_path = IdSet::default(); + let mut at = Some(start); + while let Some(id) = at.filter(|id| !acyclic.contains(id)) { + if !on_path.insert(id) { + let from = path.iter().position(|on| *on == id).unwrap_or_default(); + return Some(path.split_off(from)); + } + path.push(id); + at = parents.get(&id).copied(); + } + acyclic.extend(path); + } + None + }); + let cycle = cycle.flatten(); + assert!( + cycle.is_none(), + "the AccessKit parents of the pass hold a cycle: {cycle:?}, each the parent of the one before and the first the parent of the last" + ); +} + /// Notes that the runtime emitted the node of `id`. fn emit(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| emitted.emit(id)); diff --git a/crates/ui-contract/src/runtime/egui/access/node.rs b/crates/ui-contract/src/runtime/egui/access/node.rs index 6fcfcab2f..85a51ef96 100644 --- a/crates/ui-contract/src/runtime/egui/access/node.rs +++ b/crates/ui-contract/src/runtime/egui/access/node.rs @@ -86,7 +86,6 @@ pub(crate) struct NodeSpec { pub disabled: bool, pub read_only: bool, pub required: bool, - pub modal: bool, pub actions: Vec, pub custom_actions: Vec<(i32, String)>, /// The content keeps its left-to-right order under a right-to-left interface. @@ -133,7 +132,6 @@ impl NodeSpec { disabled: false, read_only: false, required: false, - modal: false, actions: Vec::new(), custom_actions: Vec::new(), ltr_axis: false, @@ -295,7 +293,6 @@ fn write_states(node: &mut accesskit::Node, spec: &NodeSpec) { (spec.disabled, accesskit::Node::set_disabled), (spec.read_only, accesskit::Node::set_read_only), (spec.required, accesskit::Node::set_required), - (spec.modal, accesskit::Node::set_modal), ] { if on { set(node); diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index c17ad475d..4b3140e17 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -1,5 +1,6 @@ //! `Area` with its left-top pivot, `Order`, sublayers, transform layers and `set_layer_order`. +use crate::runtime::shift::Shift; #[cfg(feature = "testing")] use egui::Ui; use egui::emath::TSTransform; @@ -238,6 +239,9 @@ pub(crate) struct LayerSpec { pub at: Pos2, /// Whether the layer takes input; a tooltip and the ghost layer never do. pub interactable: bool, + /// The accessibility node the layer's content hangs under, created before the layer shows: egui attaches the + /// layer's `Area`, and through it the content, below it. + pub root: Option, } /// What `show_layer` reports. @@ -251,20 +255,81 @@ pub(crate) struct LayerShown { /// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. The motion /// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off. pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut egui::Ui)) -> LayerShown { - let shown = egui::Area::new(spec.id) + let mut sizing = false; + let mut area = egui::Area::new(spec.id) .fade_in(false) .order(spec.tier.order()) .pivot(egui::Align2::LEFT_TOP) .fixed_pos(spec.at) .constrain(false) - .interactable(spec.interactable) - .show(ctx, body); + .interactable(spec.interactable); + if let Some(root) = spec.root { + area = area.accessibility_parent(root); + } + let shown = area.show(ctx, |ui| { + sizing = ui.is_sizing_pass(); + body(ui); + }); + register_area(ctx, shown.response.layer_id, sizing); // The `Area`'s own widget senses a click over the whole layer, beneath the layer's widgets: it stands for none of // the layer's components. crate::runtime::pointer::record_layer_widget(ctx, shown.response.id); LayerShown { rect: shown.response.rect, layer: shown.response.layer_id } } +/// The rect the content of the layer `spec` shows takes in this pass, before the layer shows: its left-top and the size +/// egui keeps for its `Area`. `None` when the layer shows in an egui sizing pass, which paints and reports nothing. +pub(crate) fn content_rect(ctx: &Context, spec: &LayerSpec) -> Option { + egui::AreaState::load(ctx, spec.id).and_then(|state| state.size).map(|size| Rect::from_min_size(spec.at, size)) +} + +/// What an overlay layer's `Area` keeps in egui's memory for a pass it shows in: its egui layer, its left-top in +/// screen space, its size and whether it takes input. +#[derive(Clone, Copy, Debug, PartialEq)] +struct AreaRecord { + layer: LayerId, + at: Pos2, + size: Vec2, + interactable: bool, +} + +/// A replay moves the left-top; the size stays. +impl Shift for AreaRecord { + fn shifted(&self, by: &egui::RecordShift) -> Self { + AreaRecord { at: self.at.shifted(by), ..*self } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + AreaRecord { at: self.at.snapped(&to.at, within), ..*self } + } +} + +/// Registers the `Area` of `layer` that was shown now (an egui sizing pass of it when `sizing`) as an overlay of the +/// records open around it, which journal the registration: a replay shows the area again in egui's memory, as shown +/// this pass with the place, size and input it had, so egui finds the layer and orders it. A sizing pass paints +/// nothing and asks for the next pass, so the run that made it runs again. +fn register_area(ctx: &Context, layer: LayerId, sizing: bool) { + let Some(state) = egui::AreaState::load(ctx, layer.id) else { return }; + if sizing { + crate::runtime::replay::note_unsettled(ctx); + } + show_again(ctx, &AreaRecord { layer, at: state.left_top_pos(), size: state.size.unwrap_or_default(), interactable: state.interactable }); +} + +fn show_again(ctx: &Context, area: &AreaRecord) { + crate::runtime::replay::journal(ctx, || *area, show_again); + crate::runtime::replay::note_overlay(ctx, area.layer, Rect::from_min_size(area.at, area.size)); + let became = egui::AreaState::load(ctx, area.layer.id).and_then(|state| state.last_became_visible_at); + let state = egui::AreaState { + pivot_pos: Some(area.at), + pivot: egui::Align2::LEFT_TOP, + size: Some(area.size), + interactable: area.interactable, + last_became_visible_at: became, + }; + ctx.memory_mut(|memory| memory.areas_mut().set_state(area.layer, state)); +} + /// What [`show_cover_layer`] shows: the layer's id and tier, the `screen` it covers, its `scrim`, the `through` canvas /// left open, and whether it `absorbs` pointer hits. pub(crate) struct CoverLayer { @@ -290,6 +355,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { Some(clear) => bands(screen, clear).into_iter().filter(|band| band.is_positive()).collect(), None => vec![screen], }; + let mut sizing = false; egui::Area::new(id) .fade_in(false) .order(tier.order()) @@ -299,6 +365,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { .interactable(absorbs) .sense(Sense::hover()) .show(ctx, |ui| { + sizing = ui.is_sizing_pass(); for rect in covered { ui.painter().rect_filled(rect, 0.0, scrim); let absorber = ui.allocate_rect(rect, Sense::click_and_drag()); @@ -306,6 +373,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { crate::runtime::egui::access::hide(ui.ctx(), absorber.id); } }); + register_area(ctx, layer_of(tier, id), sizing); } /// The four rects of `screen` around `hole`: above, below, left of and right of it. @@ -324,8 +392,15 @@ pub(crate) fn layer_rect(ctx: &Context, id: Id) -> Option { } /// The viewport's safe rect: the room overlays must stay inside, the part of the content rect the user can see on -/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. +/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. A tracked input +/// (`Input::Shell`), which the frame's root env observes. pub(crate) fn safe_rect(ctx: &Context) -> Rect { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Shell); + safe_rect_raw(ctx) +} + +/// `safe_rect` without noting the read: for the root env, which moves `Input::Shell` by it. +pub(crate) fn safe_rect_raw(ctx: &Context) -> Rect { let content = ctx.content_rect(); ctx.input(|input| { let viewport = input.viewport(); diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index 65f0231d6..e20acbb1e 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -35,8 +35,12 @@ pub(crate) struct Spec<'a> { pub resizable: bool, /// Whether the window has a taskbar or Dock entry. pub taskbar: bool, - /// Whether the window opens hidden; [`show`] reveals it. + /// Whether the window opens hidden; [`set_visible`] reveals it. pub hidden: bool, + /// Whether the window takes OS focus when it opens. + pub active: bool, + /// Whether pointer input passes through the window. + pub passes_pointer: bool, /// The app id the OS window carries (dock icon, Wayland compositor rules); empty carries none. pub app_id: &'a str, } @@ -48,6 +52,12 @@ pub(crate) fn show_immediate(ctx: &Context, id: ViewportId, spec: &Spec<'_>, if spec.hidden { builder = builder.with_visible(false); } + if !spec.active { + builder = builder.with_active(false); + } + if spec.passes_pointer { + builder = builder.with_mouse_passthrough(true); + } if !spec.app_id.is_empty() { builder = builder.with_app_id(spec.app_id); } @@ -74,9 +84,9 @@ pub(crate) fn show_immediate(ctx: &Context, id: ViewportId, spec: &Spec<'_>, ctx.show_viewport_immediate(id, builder, |ui, _| body(ui)) } -/// Makes the hidden viewport `id` visible. -pub(crate) fn show(ctx: &Context, id: ViewportId) { - ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(true)); +/// Shows or hides the window of viewport `id`. +pub(crate) fn set_visible(ctx: &Context, id: ViewportId, visible: bool) { + ctx.send_viewport_cmd_to(id, egui::ViewportCommand::Visible(visible)); } /// The viewport id of the container `id`. @@ -168,6 +178,16 @@ pub(crate) fn raise(ctx: &Context, viewport: ViewportId) { ctx.request_repaint_of(viewport); } +/// Brings `viewport`'s window in front of the app's other windows without giving it focus, by standing it above every +/// window and then back at `level`, its own level. egui-winit ignores `Focus` for a window that has focus, and the +/// window holding a modal usually has it; on Windows the level change also puts the window in front of the ordinary +/// windows that were made ordinary before it. A Wayland compositor gives clients no stacking control. +pub(crate) fn raise_above(ctx: &Context, viewport: ViewportId, level: WindowLevel) { + command(ctx, viewport, ViewportCommand::WindowLevel(WindowLevel::AlwaysOnTop)); + command(ctx, viewport, ViewportCommand::WindowLevel(level)); + ctx.request_repaint_of(viewport); +} + /// Cancels an OS close request of the running viewport so the owner can decide. pub(crate) fn cancel_close(ctx: &Context) { ctx.send_viewport_cmd(ViewportCommand::CancelClose); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 38a7d029b..2e0794919 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -138,6 +138,18 @@ pub struct Scoped { /// Where the first child the scope places in flow reports its first line: a container's header or body /// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself. pub(crate) first_line: Option, + /// The body whose flow places the scope's direct children: the flow start a child reads (`layout::flow_start`) + /// and the one a child placed in flow closes. + pub(crate) flow_body: Option, + /// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws + /// nothing of its own and itself follows one. The body's layout opens its flow start with it. + pub(crate) after_rule: bool, + /// The body is an unwrapped `Row` placed from its start whose container is a row of a vertical flow: its first + /// child in flow starts where the rows of that flow start (`label::in_column`). + pub(crate) column_row: bool, + /// The layout of the bracketed `Row` body (`ContainerProps::bracket`) whose labelled rows report their controls to + /// it: set for the row's body and kept through the containers inside it up to a labelled one. + pub(crate) bracket: Option, /// The container whose footer stands in its body (`FooterPlace::Body`) and the size that footer measured: a /// `FooterSlot` shown under it takes that size and is where the footer is drawn. pub(crate) footer_slot: Option, @@ -358,6 +370,7 @@ impl Scoped { /// layer is no line of a bar it was opened from. A layer's content measures and runs in this. pub(crate) fn start_layer(&mut self) { self.start_room(); + self.bracket = None; self.measure = None; self.arena = None; self.roving = None; @@ -387,6 +400,8 @@ impl Scoped { self.row_room = None; self.row_line = None; self.first_line = None; + self.flow_body = None; + self.column_row = false; self.fill_body = None; self.fill_share = None; self.shrink = None; @@ -394,18 +409,30 @@ impl Scoped { self.offered = None; } + /// Starts a memoized view's layout room (`start_room`), keeping whether the enclosing body is a content-sized or a + /// given column, as `start_room` keeps the content axes. The view's content then measures and fills as it would + /// shown without the view: a child that fills takes its measured size where the body sizes from content, never the + /// open room. + pub(crate) fn start_view_room(&mut self) { + let (content_column, given_column) = (self.content_column, self.given_column); + self.start_room(); + (self.content_column, self.given_column) = (content_column, given_column); + } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line - /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The - /// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own - /// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then. + /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of + /// the flow fields of the enclosing body only how it sizes from its content is in it: a memoized view's content + /// starts a layout room of its own (`start_view_room`) that keeps those facts. Computed once per scope, on the + /// first view that asks; the bytes it fed are counted then. pub(crate) fn scope_key(&self) -> u128 { *self.scope_key.get_or_init(|| { use crate::contract::{MemoKey, MemoProps as _}; let mut key = MemoKey::of_view(&self.ctx); key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel)); key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded, self.content)); + key.feed_hash(&(self.content_column, self.given_column)); key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view)))); self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key); self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key); @@ -502,8 +529,9 @@ impl Env { let shell = Arc::new(windows::shell_of(ctx, pass::current_viewport(ctx))); let active = shell.window.active; let keyboard = Arc::new(crate::runtime::keys::layout_of(ctx)); - // The window facts and the layout are tracked inputs: a view that read them runs when they change. - crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, (*shell).clone()); + // The window facts, the safe rect and the layout are tracked inputs: a view that read them runs when they change. + let safe = crate::runtime::egui::areas::safe_rect_raw(ctx); + crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, ((*shell).clone(), safe)); crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Keyboard, (*keyboard).clone()); let words = host_words(ctx, host.as_ref()); let key = EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash()) @@ -555,6 +583,10 @@ impl Env { row_room: None, row_line: None, first_line: None, + flow_body: None, + after_rule: false, + column_row: false, + bracket: None, footer_slot: None, fill_body: None, fill_share: None, @@ -644,6 +676,7 @@ impl Env { pub(crate) fn new_room(&self) -> Env { self.derive_local(|scoped| { scoped.start_room(); + scoped.bracket = None; scoped.lazy = None; scoped.measure = None; // A pane opened from a bar is not the bar's line. diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index d2433b696..23fc27c0b 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -8,7 +8,7 @@ use craft_behavior::MotionMode; use craft_i18n::CalendarDate; use craft_i18n::Direction; use craft_theme::{ - AppSizes, Appearance, Contrast, ContrastChoice, Mode, ModeChoice, MotionChoice, Size, SystemAppearance, TextSize, ThemeDef, ThemeId, + AppSizes, Appearance, ComponentSet, Contrast, ContrastChoice, Mode, ModeChoice, MotionChoice, Size, SystemAppearance, TextSize, ThemeDef, ThemeId, }; use egui::Context; use std::sync::Arc; @@ -198,6 +198,17 @@ impl RootEnv { self } + /// Sets the component set (`Selection::set`): a root app value, so a container can set another for its subtree. + pub fn set(mut self, set: ComponentSet) -> Self { + self.values.set(set); + self + } + + /// The component set the root's values carry. + pub fn component_set(&self) -> ComponentSet { + self.values.get::() + } + /// Sets today's date, as the host's clock and time zone give it. pub fn today(mut self, date: CalendarDate) -> Self { self.today = Some(date); diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 591bec6f1..f0eac57f0 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -1,4 +1,4 @@ -//! The library values the env carries: scale, motion policy and arena id. +//! The library values the env carries: scale, motion policy, arena id and the component set. use super::EnvValue; use craft_behavior::{ColumnKey, MotionMode}; @@ -140,6 +140,27 @@ impl EnvValue for InBar { } } +/// The component set: an app sets it on its root (`RootEnv::set`) and a container may set another for its subtree +/// (`Overrides::values`); every window, layer and popup opened inside takes the scope's. A component with variants +/// reads it in `style` (`StyleCx::set`) and maps it to one of them. It is in the style key, so a change restyles as a +/// theme or density change does. +impl EnvValue for craft_theme::ComponentSet { + const AFFECTS_STYLE: bool = true; + + fn root() -> Self { + craft_theme::ComponentSet::default() + } + + fn style_hash(&self) -> Option { + use std::hash::Hasher as _; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + self.hash(&mut hasher); + Some(hasher.finish()) + } +} + +impl super::StyleValue for craft_theme::ComponentSet {} + /// Where a shell pane sits. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index ac9e6f5ab..1adf515be 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -386,7 +386,8 @@ pub(crate) fn replay(ctx: &Context, transcript: &Transcript) { with(ctx, |state| { let placed = transcript.placed(state.open.last().map(|(id, _)| *id)); for (id, mut scope) in placed.scopes { - // No replayed scope has a noted opener: an overlay, which notes one, blocks its record. + // A replayed scope keeps the opener the last pass held: an overlay's scope, the one kind that notes an opener, + // took it in the pass that first showed the layer, which ran. scope.opener = opener(state, id, None, focused); if scope.entering.is_none() { state.seen.insert(id, frame); diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index b6804a2b8..57b6b3b11 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -197,6 +197,13 @@ pub struct Stamped { value: T, } +impl Stamped { + /// The record as its viewport's latest pass left it. + pub(crate) fn value(&self) -> &T { + &self.value + } +} + impl PerViewport { fn record(&mut self, viewport: ViewportId) -> &mut T { let at = match self.records.iter().position(|(id, _)| *id == viewport) { @@ -257,6 +264,11 @@ impl PerViewport { } } + /// Runs `f` on the record of `viewport` when it has one; creates none. + pub(crate) fn with_existing(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut T) -> R) -> Option { + T::records(ctx, |records| records.records.iter_mut().find(|(id, _)| *id == viewport).map(|(_, record)| f(record))) + } + /// Runs `f` on the record of every viewport that has one. pub(crate) fn each(ctx: &Context, mut f: impl FnMut(&mut T)) { T::records(ctx, |records| records.records.iter_mut().for_each(|(_, record)| f(record))); @@ -633,7 +645,9 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { // H0: one press per pass. let frame = pass::frame_nr(ctx, viewport); let held_back = PerViewport::::with(ctx, viewport, |record| raw_input::hold_back_presses(&mut events, frame, &mut record.held)); - // H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. + // H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. The events sent + // to the focus are counted first, before the IME and key stages take theirs. + keys::count_sent(ctx, viewport, &events); ime::input_hook(ctx, &mut events, viewport); let (stripped, later) = keys::input_hook(ctx, input, &mut events); if !later.is_empty() { @@ -743,6 +757,8 @@ pub(crate) fn end_pass(ui: &mut Ui) { for prune in prunes { prune(&ctx, &live); } + #[cfg(feature = "testing")] + crate::runtime::egui::access::check_parents_acyclic(&ctx); RUNNING.with(|running| { let mut running = running.borrow_mut(); if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) { diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index 0e19f1a6d..48705289b 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -373,8 +373,14 @@ pub(crate) fn composing(ctx: &Context, owner: Id) -> bool { current(ctx, |engine| engine.owner == Some(owner) && engine.composing) } -/// Records the caret rect for the OS candidate window. +/// Records the caret rect for the OS candidate window. A replay of the run that recorded it records it again, so the +/// pass writes the IME output and the OS keeps the IME open for a focused field that replays. pub(crate) fn note_caret(ctx: &Context, owner: Id, field: Rect, caret: Rect, password: bool) { + crate::runtime::replay::journal( + ctx, + || (owner, field, caret, password), + |ctx, &(owner, field, caret, password)| note_caret(ctx, owner, field, caret, password), + ); current(ctx, |engine| engine.caret = Some((owner, field, caret, password))); } diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 8b4e3eb3d..a4d543eeb 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -1,6 +1,7 @@ -//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's -//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held), each with a generation -//! that moves when its value changes. The accessor that reads one notes it into the records open around the running +//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, its presses, the +//! window's facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the toast queues, the keys held, +//! the events sent to the focus, the requests to collections), each with a generation that moves when its value +//! changes. The accessor that reads one notes it into the records open around the running //! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation //! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed //! runs when it is shown again. @@ -20,9 +21,14 @@ pub(crate) enum Input { Modifiers, /// The pointer's frame (`pointer::frame`, `pointer::with_pass_pointer`). Pointer, + /// The pointer's presses and releases, an outside press the layer stack absorbed included (`pointer::primary_press`, + /// `overlay::absorbed_press`): a layer's dismissal reads them, so a press anywhere runs the views that show layers, + /// and a pointer move does not. + Press, /// The keys held, Caps Lock and whether a key arrived (`keys::input::down`, `keyed`, `lock_keys::caps_lock`). Keys, - /// The platform and window facts (`EnvView::shell`). + /// The platform and window facts (`EnvView::shell`) and the viewport's safe rect (`areas::safe_rect`): its + /// content rect and the visible part of its monitor. Shell, /// The keyboard layout (`EnvView::keyboard_layout`). Keyboard, @@ -32,23 +38,36 @@ pub(crate) enum Input { Drag, /// Where key focus is (`focus::focused_rec`, `focus_in_scope`, `commands::focus_within`). Focus, + /// The key, text, IME, clipboard and AccessKit action events of the frame: a run that ends holding focus reads them + /// (`replay::close`), so any such event runs the views the focus is in, and an idle frame replays them. + Sent, /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). Overlays, + /// The cards queued in the running viewport's toast queues (`toast::cards`): a post, a close or an expiry runs the + /// views that show them. + Toasts, + /// The requests to collections from outside them (`items::request_rename`), read by the item step that takes + /// them, so a pending request runs the view that takes it. + Requests, /// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value. Scroll, } impl Input { - pub(crate) const ALL: [Input; 10] = [ + pub(crate) const ALL: [Input; 14] = [ Input::Modifiers, Input::Pointer, + Input::Press, Input::Keys, Input::Shell, Input::Keyboard, Input::Keymap, Input::Drag, Input::Focus, + Input::Sent, Input::Overlays, + Input::Toasts, + Input::Requests, Input::Scroll, ]; @@ -115,17 +134,20 @@ pub(crate) fn observe(ctx: &Context, input }); } -/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are -/// observed here; the pointer and the modifiers by the pointer's begin hook, the window facts and the layout where -/// the frame's root env is built, the keymap by the command board. +/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers, toast +/// queues) are observed here, and so are the events sent to the focus, which the key stage counts; the pointer, its +/// presses and the modifiers by the pointer's begin hook, the window facts and the layout where the frame's root env is built, the +/// keymap by the command board, the requests by each request. pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { match input { Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)), + Input::Sent => observe(ctx, input, crate::runtime::keys::sent(ctx)), Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)), Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), - Input::Keymap => return crate::runtime::commands::keymap_generation(ctx), - Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} + Input::Toasts => observe(ctx, input, crate::runtime::toast::queued(ctx)), + Input::Keymap => return crate::runtime::commands::keymap_built(ctx), + Input::Modifiers | Input::Pointer | Input::Press | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} } with(ctx, |generations| generations.gens[input as usize]) } diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index f8d80f3f1..b4a350730 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -27,7 +27,7 @@ pub use claims::take_claimed; pub(crate) use claims::take_first_claimed; /// The types `Intents` reads and returns, for an app that reads the window's intents (`with_window_intents`). pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef}; -pub(crate) use input::{claims_press, input_hook, keys_state, queue_nav, take_menu_keys, take_nav}; +pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, queue_nav, sent, take_menu_keys, take_nav}; #[doc(hidden)] pub use input::{down, keyed}; pub use intents::Intents; @@ -242,6 +242,8 @@ pub(crate) struct Stage { down: Vec, /// The input hook read a key press, typed text or a clipboard event in this pass, withheld ones included. keyed: bool, + /// How many inputs of the viewport held an event sent to the focus (`count_sent`). + sent: u64, /// The keys whose press the strip took and whose release it is still to drop. consumed: Vec, shortcuts: Shortcuts, diff --git a/crates/ui-contract/src/runtime/keys/claims.rs b/crates/ui-contract/src/runtime/keys/claims.rs index 587c00366..874f05c6d 100644 --- a/crates/ui-contract/src/runtime/keys/claims.rs +++ b/crates/ui-contract/src/runtime/keys/claims.rs @@ -2,6 +2,8 @@ use super::current; use craft_keymap::Chord; + +crate::stays!(Chord); use egui::{Context, Id}; /// Reads the claimed chord: whether it arrived this pass for `id`, consuming it. Also true for a chord @@ -32,8 +34,10 @@ pub(crate) fn take_first_claimed(ctx: &Context, id: Id, chords: &[Chord]) -> Opt }) } -/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. +/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. Like the +/// claims below, a replay of the run that recorded it records it again: a focused view replays while nothing reaches it. pub(crate) fn hold_escape(ctx: &Context, owner: Id) { + crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| hold_escape(ctx, owner)); current(ctx, |stage| stage.open_edits.push(owner)); } @@ -41,6 +45,7 @@ pub(crate) fn hold_escape(ctx: &Context, owner: Id) { /// component. #[doc(hidden)] pub fn claim(ctx: &Context, owner: Id, chord: Chord) { + crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| claim(ctx, owner, chord)); current(ctx, |stage| stage.claims.push((owner, chord))); } @@ -49,6 +54,9 @@ pub fn claim(ctx: &Context, owner: Id, chord: Chord) { /// keys, Enter and Escape (the window move and size modes, 16.3); the claim lapses when it is not renewed. #[doc(hidden)] pub fn capture(ctx: &Context, owner: Id, chord: Chord) { + crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| capture(ctx, owner, chord)); + // The captured chord reaches `owner` wherever the focus is: a run that captures reads what is sent. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent); current(ctx, |stage| { if !stage.captures.contains(&(owner, chord)) { stage.captures.push((owner, chord)); diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 78074d5fb..d508086ee 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -593,6 +593,33 @@ pub(crate) fn keys_state(ctx: &Context) -> (Vec, bool, bool) { (down, keyed, crate::runtime::lock_keys::caps_on(ctx)) } +/// Counts an input of `viewport` whose `events` hold one sent to the focus: a key, text, IME, clipboard or AccessKit +/// action event (`Input::Sent`). Read before any stage takes events, so the IME's and the ones a shortcut takes count. +pub(crate) fn count_sent(ctx: &Context, viewport: ViewportId, events: &[Arrived]) { + let sent = events.iter().any(|arrived| { + matches!( + arrived.event, + egui::Event::Key { .. } + | egui::Event::Text(_) + | egui::Event::Ime(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::MiddleClickPaste { .. } + | egui::Event::AccessKitActionRequest(_) + ) + }); + if sent { + with(ctx, viewport, |stage| stage.sent += 1); + } +} + +/// How many inputs of the running viewport held an event sent to the focus: its value moves with each one. +pub(crate) fn sent(ctx: &Context) -> u64 { + current(ctx, |stage| stage.sent) +} + /// Whether the running viewport's input hook read a key press, typed text or a clipboard event in this pass, the ones /// the key stage took from egui's input included: an app that redraws state after input asks this, not egui's events. pub fn keyed(ctx: &Context) -> bool { diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index f58c68dd2..3894fd46b 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1239,6 +1239,11 @@ pub(crate) mod guard { ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), + ( + "layout::body::FlowStarts", + "flow starts: opened by each sweep of the body and closed by its first child in flow; a child reads its body's at its own start, and its measure key holds what it read", + ), + ("layout::body::Brackets", "bracket reports: opened by each sweep of the bracketed row and taken after its body"), ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), @@ -1270,6 +1275,7 @@ pub(crate) mod guard { "runtime::lazy::Store", "lazy extents: the kept extent of content out of view, its own mechanism; a pass a kept transcript serves decides in its real run, which compares each row by its backstop", ), + ("runtime::derived::Store", "derived values: a pure function of their key, so a value a measuring run builds is the one a real run builds"), ("contract::steps::scroll_owner::", "scroll reveals and moves: read; taken through take_queued"), ("contract::body::scroll::Jumps", "scroll jumps: taken through take_queued"), ("runtime::edit::CancelAll", "edit cancels: read; a measuring run ends nothing"), diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 3a46b3231..f05c8ad86 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -15,7 +15,7 @@ //! framework tracks has changed for it since (`settled`). Its entry outlives a few frames of absence. use crate::runtime::egui::areas::Layer; -use crate::runtime::egui::{focus as focus_state, input as input_state, pass}; +use crate::runtime::egui::{input as input_state, pass}; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; use crate::runtime::inputs::{self, Input}; @@ -166,8 +166,8 @@ pub(crate) struct Measured { pub(crate) room: Rect, } -/// Where a memoized view ran: it replays only at a place of the same size, layer, layout and environment, and its -/// record moves with the room's position (`Place::shift_to`). +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity and environment, and +/// its record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Place { /// The region its parent offered it. @@ -179,6 +179,9 @@ pub(crate) struct Place { /// The font atlas the run's text points into (`Fonts::atlas_generation`): egui clears the atlas when it fills up /// and rebuilds it for new text options, and a kept galley's glyphs then name other glyphs. pub(crate) atlas: u64, + /// The opacity everything painted in the room is faded to (`Ui::opacity`, a layer fading in or out): the run's + /// colours hold it. + pub(crate) opacity: f32, /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, @@ -193,9 +196,10 @@ struct Moved { impl Place { /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its - /// size, the layer, layout, scale, font atlas and environment are the ones the run had. The record moves by the - /// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there - /// gives) and, for a move, the record holds nothing a move cannot place (`movable`: no paint callback) on an + /// size, the layer, layout, scale, font atlas, opacity and environment are the ones the run had. A record that shows + /// an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the room's move + /// when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and, + /// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an /// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow /// the clip when either: /// - the clip moved with the room (`with_clip`): every rect and clip moves exactly, whatever the clip cut; @@ -204,15 +208,20 @@ impl Place { /// so the run's clip becomes the clip now and inner clips move (`RecordShift::clip`). /// /// Otherwise it runs: a run cut by its clip lacks what was culled. - fn shift_to(&self, rect: Rect, now: Place, movable: bool, transformed: bool) -> Option { + fn shift_to(&self, rect: Rect, now: Place, record: &Record, transformed: bool) -> Option { let offset = now.room.min - self.room.min; let same = now.room.size() == self.room.size() && now.layer == self.layer && now.layout == self.layout && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas + && now.opacity == self.opacity && now.env == self.env; - let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed); + let placeable = if record.pinned() { + offset == Vec2::ZERO && now.clip == self.clip + } else { + offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && record.movable() && !transformed) + }; if !same || !placeable { return None; } @@ -335,6 +344,20 @@ impl Store { } } +/// The memo rule for absent entries, shared by every memo store (memoized views, `runtime::derived`): an entry +/// outlives its absence while the absent ones are at most twice as many as the shown ones, the longest absent dropped +/// first. Takes the absent entries as (frame last touched, id) and returns the ones to drop. +pub(crate) fn absent_past_room(shown: usize, absent: impl IntoIterator) -> Vec { + let mut absent: Vec<(u64, Id)> = absent.into_iter().collect(); + let room = 2 * shown; + if absent.len() <= room { + return Vec::new(); + } + absent.sort_unstable_by_key(|(touched, _)| *touched); + absent.truncate(absent.len() - room); + absent.into_iter().map(|(_, id)| id).collect() +} + fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { let viewport = pass::current_viewport(ctx); let (pass_nr, frame) = (pass::pass_nr(ctx, viewport), pass::frame_nr(ctx, viewport)); @@ -345,16 +368,12 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { store.pruned = frame; let reached = &store.reached; store.entries.retain(|_, entry| entry.memo() || entry.live(frame, reached)); - // A memoized view's entry outlives its absence while the absent ones are at most twice as many as the shown - // ones, the longest absent dropped first: a view shown again with the same props replays. + // A memoized view's entry outlives its absence by the memo rule: a view shown again with the same props + // replays. let shown = store.entries.values().filter(|entry| entry.memo() && entry.live(frame, reached)).count(); - let mut absent: Vec<(u64, Id)> = - store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)).collect(); - if absent.len() > 2 * shown { - absent.sort_unstable_by_key(|(touched, _)| *touched); - for (_, id) in &absent[..absent.len() - 2 * shown] { - store.entries.remove(id); - } + let absent = store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)); + for id in absent_past_room(shown, absent) { + store.entries.remove(&id); } let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect(); store.reached.retain(|owner, _| owners.contains(owner)); @@ -423,6 +442,12 @@ pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, meas }); } +/// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it +/// ran), at whatever room it had; `None` before any run showed it. +pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option { + with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[1].map(|measured| measured.size))) +} + /// Registers what the skipped child `id` registered with the focus service in the last real run that showed it, in /// the real run that skips it. pub(crate) fn replay(ctx: &Context, id: Id) { @@ -444,9 +469,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then: /// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still /// loading, no wake time reached; -/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and -/// none of that held in its last run; -/// - none of its stops holds focus or is the target of a focus request, now or in its last run; +/// - the pointer is not over it or an overlay layer it shows, no press started on either and none of its widgets is +/// dragged, and none of that held in its last run; +/// - the focus is where its run left it (`replay::Held`: the same stop and egui widget of it, or none), and while the +/// focus is in it no key, text, IME, clipboard or AccessKit event came (`Input::Sent`, which such a run reads); +/// - none of its stops is the target of a focus request, now or in its last run; /// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes); /// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or, /// replaying a run of this frame, after that run started; @@ -457,8 +484,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is /// gone; /// - no framework input its run read outside its props has moved (`runtime::inputs`), the scroll view a nested `Lazy` -/// child of it decided by is the same (moved with it, `moved`), and no command waits for a command scope instance of -/// it. +/// child of it decided by is the same (moved with it, `moved`), no command waits for a command scope instance of +/// it, and no close waits for a layer it shows. pub(crate) fn settled( ctx: &Context, owner: Option, @@ -468,10 +495,11 @@ pub(crate) fn settled( view: Option, key: Key, ) -> Option<(Vec2, Rect, RecordShift)> { - let targets = focus::targets(ctx); + let revealed = focus::targets(ctx)[1]; let routed = crate::runtime::keys::routed_to(ctx); let now = frame::clock(ctx); - let held = (input_state::dragged(ctx), focus_state::focused(ctx)); + let dragged = input_state::dragged(ctx); + let focused = replay::Held::focused(ctx); let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some()); let settled = write(ctx, id, |store, pass_nr, frame| { let changes = &store.changes; @@ -491,9 +519,10 @@ pub(crate) fn settled( && !facts.blocked && !facts.discards && facts.quiet(now, edited.as_ref()) - && !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)) || routed.contains(&stop)) + && !settled.record.focus.stop_ids().any(|stop| revealed == Some(stop) || routed.contains(&stop)) && !routed.iter().any(|id| settled.record.widgets.contains(id)) - && ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget)) + && !dragged.is_some_and(|widget| settled.record.widgets.contains(&widget)) + && focused.within(&settled.record.focus, &settled.record.widgets) == settled.record.held }); entry.replays = Some((pass_nr, replays)); replays @@ -501,7 +530,7 @@ pub(crate) fn settled( }; // A measuring run cannot tell the place: it replays where the run was. let moved = |settled: &Settled| match place { - Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed), + Some(place) => settled.place.shift_to(settled.rect, place, &settled.record, transformed), None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }), }; let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled))); @@ -524,7 +553,7 @@ pub(crate) fn settled( // The scroll view a nested child decided by: the run's, moved with the record, while the clip moved with it; a run // that lay wholly in its clip ran every nested child, which holds at any view. let view = place.and_then(|_| with_clip.then(|| (settled.view.map(|ran| ran.moved(shift.offset)), view))); - if engaged(ctx, settled.place.layer, rect.intersect(shift.clip)) + if engaged(ctx, settled.place.layer, rect.intersect(shift.clip), &settled.record.facts.overlays) || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) || moved(ctx, &settled, view) { @@ -541,18 +570,26 @@ pub(crate) fn settled( /// Whether something a memoized view's run read outside its props moved since: a framework input it read has another /// generation, the scroll view a nested `Lazy` child decided by is another than the one it needs (`view`: the view it /// needs and the view now, in a real run whose record replays only in that view; a measuring run lays the content out -/// from offset zero, so its view is not the one the real run decided by), or a command waits for one of its instances. +/// from offset zero, so its view is not the one the real run decided by), a command waits for one of its instances, +/// or a close waits for a layer it shows. fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option)>) -> bool { let facts = &settled.record.facts; inputs::moved(ctx, facts.inputs, &settled.seen) || (facts.inputs.contains(Input::Scroll) && view.is_some_and(|(needs, now)| needs != now)) || crate::runtime::commands::queued_for(ctx, &facts.instances) + || crate::runtime::overlay::close_queued(ctx, &facts.layers) } -/// Whether the pointer is over `rect` (shown) on `layer`, or a press that is held started there. -fn engaged(ctx: &Context, layer: Layer, rect: Rect) -> bool { - let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); - ctx.rect_contains_pointer(layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin)) +/// Whether the pointer is over `rect` (shown) on `layer` or over one of the overlay layers `overlays` shown, or a +/// press that is held started there. Both halves ask whether the layer is the top layer at the point, so a pointer or +/// a press on an overlay above the view leaves it alone. +fn engaged(ctx: &Context, layer: Layer, rect: Rect, overlays: &[replay::ShownLayer]) -> bool { + let over = |layer: Layer, rect: Rect| { + let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); + ctx.rect_contains_pointer(layer, rect) + || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) + }; + over(layer, rect) || overlays.iter().any(|shown| over(shown.layer, shown.rect)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` @@ -618,11 +655,11 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec if ctx.will_discard() { return; } - let targets = focus::targets(ctx); - let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); + let revealed = focus::targets(ctx)[1]; + let engaged_now = record.focus.stop_ids().any(|stop| revealed == Some(stop)); let lives = crate::runtime::memory::ended_generation(ctx); let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, key, pass: 0, edits, output, lives, seen, view }; - settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip)); + settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip), &settled.record.facts.overlays); with(ctx, |store, pass_nr, frame| { settled.frame = frame; settled.pass = pass_nr; diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 6a789786a..cc9010ece 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -52,6 +52,17 @@ struct BodyRuns { runs: Vec<(Id, u32)>, } +/// The derived values built in a pass, by component id, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +pub(crate) struct DerivedBuilds { + pass: u64, + builds: Vec<(Id, u32)>, + /// The frame `frame_builds` counts, and the builds of every pass of it. + frame: u64, + frame_builds: Vec<(Id, u32)>, +} + /// How many contributions the measuring runs of a pass made that stand, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -540,6 +551,47 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { last_totals(ctx, |log| log.key_bytes, 0) } +/// Counts a build of a derived value of the component `id` in this pass (`runtime::derived`). +#[cfg(feature = "testing")] +pub(crate) fn count_derived(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } + let pass = ctx.cumulative_pass_nr(); + let frame = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)); + pass_state::with::(ctx, |log| { + if log.frame != frame { + log.frame = frame; + log.frame_builds.clear(); + } + if log.pass != pass { + log.pass = pass; + log.builds.clear(); + } + for builds in [&mut log.builds, &mut log.frame_builds] { + match builds.iter_mut().find(|(of, _)| *of == id) { + Some((_, count)) => *count += 1, + None => builds.push((id, 1)), + } + } + }); +} + +/// The components that built a derived value in any pass of the last frame, and how many builds each. +#[cfg(feature = "testing")] +pub fn last_frame_derived_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)).saturating_sub(1); + pass_state::with::(ctx, |log| if log.frame == last { log.frame_builds.clone() } else { Vec::new() }) +} + +/// The components that built a derived value in the last pass, and how many builds each; empty when that pass built +/// none. +#[cfg(feature = "testing")] +pub fn last_pass_derived_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + pass_state::with::(ctx, |log| if log.pass == last { log.builds.clone() } else { Vec::new() }) +} + /// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. #[cfg(feature = "testing")] pub(crate) fn count_text_layout(ctx: &Context) { diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 27ed98177..a7667d012 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -203,6 +203,8 @@ struct OwnerRecord { viewport: ViewportId, pass: u64, at: f64, + /// The pass of the owner's registration before `pass`, in the same viewport. + before: Option, } /// One entry the runtime keeps for a component, and the owner that is tested for its eviction. @@ -270,11 +272,28 @@ pub(crate) fn register_owner(ctx: &Context, owner: Id) { crate::runtime::replay::note_owner(ctx, owner); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { - reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); + let before = match reg.owners.get(&owner) { + Some(last) if last.viewport == facts.viewport && last.pass == facts.pass_nr => last.before, + Some(last) if last.viewport == facts.viewport => Some(last.pass), + _ => None, + }; + reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now, before }); reg.ended.remove(&owner); }); } +/// Whether `owner` was registered in the pass before the running one of its viewport, by a run or a replay: its +/// component was shown there. +pub(crate) fn shown_last_pass(ctx: &Context, owner: Id) -> bool { + let facts = frame::facts(ctx); + pass_state::with::(ctx, |reg| { + reg.owners.get(&owner).filter(|last| last.viewport == facts.viewport).is_some_and(|last| { + let shown = if last.pass == facts.pass_nr { last.before } else { Some(last.pass) }; + shown.is_some_and(|shown| shown + 1 >= facts.pass_nr) + }) + }) +} + /// The generation of ended shown lives now: a kept run stores it, and `ended_since` compares with it. pub(crate) fn ended_generation(ctx: &Context) -> u64 { pass_state::with::(ctx, |reg| reg.ended_generation) diff --git a/crates/ui-contract/src/runtime/mod.rs b/crates/ui-contract/src/runtime/mod.rs index e789997cc..9a52166f6 100644 --- a/crates/ui-contract/src/runtime/mod.rs +++ b/crates/ui-contract/src/runtime/mod.rs @@ -5,6 +5,7 @@ pub mod access; pub(crate) mod audit; pub mod commands; pub mod cursor; +pub mod derived; pub mod drag; pub mod edit; pub mod egui; diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index 9f73466f1..5fb7df0be 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -395,6 +395,10 @@ impl Driver<'_> { let sizing = self.stage.is_peek(); let now = frame::clock(ctx); let existing = if sizing { store::peek_clone::>(ctx, id) } else { store::take::>(ctx, id) }; + // A tween that moves in this pass (a new target, also one it jumps to, or a step, also its last one) leaves the + // slot in another state than the run found it in, which the next run reads (`layer_fading` among others): a + // record of the run is not replayed. Only a tween still running asks for another frame. + let moved = existing.as_ref().is_some_and(|tween| tween.target() != target || !tween.is_settled()); let mut tween = match existing { Some(tween) => tween, None => { @@ -409,6 +413,8 @@ impl Driver<'_> { if !sizing { if !tween.is_settled() { note_unsettled(ctx); + } else if moved { + crate::runtime::replay::note_unsettled(ctx); } store::put(ctx, id, tween); } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index d43456fd0..ea79ef4d5 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -9,6 +9,7 @@ use crate::runtime::egui::pass; use crate::runtime::frame::{PassStep, PerViewport, Stamped}; use crate::runtime::pass_state; use crate::runtime::pointer; +use crate::runtime::shift::Shift; use craft_behavior::OwnerClass; use craft_behavior::overlay::Side; use egui::emath::TSTransform; @@ -75,7 +76,7 @@ impl Rank { /// Whether a layer of this rank takes keys without a focus scope. Modal chrome takes none: Cancel and Enter stay /// with the modal under it. - const fn takes_keys(self) -> bool { + pub(crate) const fn takes_keys(self) -> bool { matches!(self, Rank::Popup | Rank::Modal { .. }) } @@ -120,7 +121,7 @@ pub enum OpenFilter { } /// One shown egui layer. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[doc(hidden)] pub struct OpenEntry { /// The layer's id. @@ -152,6 +153,10 @@ pub struct OpenEntry { /// The entry is an OS window of the integration: it takes its place in the stack's order and facts, and no egui /// layer is shown for it. pub(crate) window: bool, + /// The entry stands in its opener's stack for a layer shown in a popup window of its own (with `window`): the + /// family, the anchor and the presses in the opener's window are judged here, and the popup's own stack holds the + /// layer, so the entry blocks nothing here. + pub(crate) popup: bool, /// The screen rect the layer is contained in: its scrim, placement, clip and input blocking stop at it. pub(crate) region: Option, /// The layer's place on its dialog stack (`stack_place`): the modal families of one stack stack in its order. @@ -160,6 +165,29 @@ pub struct OpenEntry { dialog: Option, } +/// A replay moves the entry's screen rects with its record; the rest stays. +impl Shift for OpenEntry { + fn shifted(&self, by: &egui::RecordShift) -> Self { + OpenEntry { + anchor: self.anchor.shifted(by), + peers: self.peers.shifted(by), + rect: self.rect.shifted(by), + region: self.region.shifted(by), + ..self.clone() + } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + OpenEntry { + anchor: self.anchor.snapped(&to.anchor, within), + peers: self.peers.snapped(&to.peers, within), + rect: self.rect.snapped(&to.rect, within), + region: self.region.snapped(&to.region, within), + ..self.clone() + } + } +} + impl OpenEntry { /// An entry for the layer `id` of `rank`. pub(crate) fn new(id: Id, rank: Rank, keys: OwnerClass, rect: Rect, layer: Layer) -> Self { @@ -178,6 +206,7 @@ impl OpenEntry { scoped: false, absorbs: false, window: false, + popup: false, region: None, place: None, dialog: None, @@ -187,7 +216,7 @@ impl OpenEntry { /// Whether the layer is a modal over its whole window: a modal contained in a region blocks only inside it, and the /// window's keys, commands and hits stay with the rest. pub(crate) fn blocks_window(&self) -> bool { - self.rank.is_modal() && self.region.is_none() + self.rank.is_modal() && self.region.is_none() && !self.popup } /// Whether the layer takes keys: the layers `top` can name. A layer with a focus scope takes keys whatever its rank. @@ -479,7 +508,8 @@ pub(crate) fn appears(ctx: &Context, id: Id, exiting: bool) -> bool { /// Marks the layer `id`'s body as running, so layers opened from inside it become its children, with the `side` of /// its anchor it was placed on. A layer shown again while it fades out opens anew: it appears in this frame and pass. pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side: Option) { - crate::runtime::replay::block(ctx); + // Which layers a press opened reads the presses and releases. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); let reopened = reopened(ctx, id, exiting); with_pass(ctx, |pass| { pass.drawing.push((id, tier)); @@ -535,11 +565,38 @@ pub fn opening(ctx: &Context, id: Id) -> bool { /// not outlive it. The closes are carried: with no motion the layer's body hides in the same frame, so the owner of /// a popup in it runs again only when the layer reopens, and takes the close then. pub(crate) fn close_descendants(ctx: &Context, id: Id) { - for descendant in family(ctx, id).into_iter().filter(|member| *member != id) { + let mut members: Vec = family(ctx, id).into_vec(); + // A member shown in a popup window keeps the layers opened from inside it in that window's stack. + let mut at = 0; + while at < members.len() { + let member = members[at]; + for inner in family_in(ctx, crate::runtime::egui::viewports::viewport_id(member), member) { + if !members.contains(&inner) { + members.push(inner); + } + } + at += 1; + } + for descendant in members.into_iter().filter(|member| *member != id) { push_close(ctx, descendant, CloseReason::Requested, true); } } +/// `id` and everything opened from inside it, as `viewport`'s latest pass showed them (a popup window's: its pass of +/// this frame, or its last one once it is no longer shown); none for a viewport that has no stack. +fn family_in(ctx: &Context, viewport: ViewportId, id: Id) -> Vec { + let Some(last) = PerViewport::>::with_existing(ctx, viewport, |pass| pass.value().current.clone()) else { + return Vec::new(); + }; + let mut out: Vec = last.iter().filter(|entry| entry.id == id).map(|entry| entry.id).collect(); + for entry in &last { + if entry.parent.is_some_and(|parent| out.contains(&parent)) && !out.contains(&entry.id) { + out.push(entry.id); + } + } + out +} + /// Records that a primary press landed outside the layer `id`, its anchor and its family in this pass. pub(crate) fn note_pressed_outside(ctx: &Context, id: Id) { with_pass(ctx, |pass| pass.pressed_outside.push(id)); @@ -617,13 +674,27 @@ pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::in input.events.len() != before } -/// The outside press the input hook removed for the running pass. +/// The outside press the input hook removed for the running pass. A tracked input (`Input::Press`). pub(crate) fn absorbed_press(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); + absorbed_press_raw(ctx) +} + +/// `absorbed_press` without noting the read: for the pointer's begin hook, which moves `Input::Press` by it. +pub(crate) fn absorbed_press_raw(ctx: &Context) -> Option { with_persist(ctx, pass::current_viewport(ctx), |persist| persist.outside_press) } -/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. +/// Whether a close is queued for one of the layers `ids`: only a run of the layer's owner takes it, so a memoized view +/// that showed one of them runs while it waits. +pub(crate) fn close_queued(ctx: &Context, ids: &[Id]) -> bool { + !ids.is_empty() && pass_state::with::(ctx, |closes| closes.0.iter().any(|(closed, ..)| ids.contains(closed))) +} + +/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. A replay of the run +/// that showed the layer records them again. pub(crate) fn note_peers(ctx: &Context, id: Id, peers: Vec) { + crate::runtime::replay::journal(ctx, || (id, peers.clone()), |ctx, (id, peers)| note_peers(ctx, *id, peers.clone())); with_pass(ctx, |pass| { if let Some(entry) = pass.current.iter_mut().find(|entry| entry.id == id) { entry.peers = peers; @@ -665,12 +736,16 @@ pub fn end_stack_dialog(ctx: &Context, dialog: Id) { /// Records the layer shown in this pass, parent first: a layer is recorded once its body ran, after the layers opened /// from inside it, so it goes in front of them, and every layer then stacks above the layer it was opened from. A -/// layer shown again in a discarded pass replaces its entry. +/// layer shown again in a discarded pass replaces its entry. A replay of the run that showed the layer records the +/// entry again, its stack place and dialog filled, and the records open around it note the layer as one they show. pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) { - crate::runtime::replay::block(ctx); with_pass(ctx, |pass| { entry.place = entry.place.or(pass.place); entry.dialog = entry.dialog.or(pass.dialog); + }); + crate::runtime::replay::note_layer(ctx, entry.id); + crate::runtime::replay::journal(ctx, || entry.clone(), |ctx, entry| record(ctx, entry.clone())); + with_pass(ctx, |pass| { if let Some(at) = pass.current.iter().position(|recorded| recorded.id == entry.id) { pass.current[at] = entry; return; @@ -810,7 +885,7 @@ pub(crate) fn end_pass(ctx: &Context) { } fn modal_in_other_viewports(ctx: &Context, running: ViewportId) -> bool { - pass::live_viewports(ctx).into_iter().filter(|viewport| *viewport != running).any(|viewport| with_persist(ctx, viewport, |persist| persist.modal)) + modal_viewport(ctx, running).is_some() } /// Whether a modal layer is open in a viewport other than `viewport`: the global open-modal fact the input hook @@ -886,9 +961,19 @@ pub(crate) fn beneath(ctx: &Context, layer: Id) -> (bool, Option) { (root.is_some() || modal_in_other_viewports(ctx, viewport), root) } +/// The live viewports with a modal layer open as of their last finished pass. +fn modal_viewports(ctx: &Context) -> impl Iterator + '_ { + pass::live_viewports(ctx).into_iter().filter(|viewport| with_persist(ctx, *viewport, |persist| persist.modal)) +} + /// A viewport other than `viewport` that has a modal layer open: the window a blocked press raises. pub(crate) fn modal_viewport(ctx: &Context, viewport: ViewportId) -> Option { - pass::live_viewports(ctx).into_iter().filter(|other| *other != viewport).find(|other| with_persist(ctx, *other, |persist| persist.modal)) + modal_viewports(ctx).find(|other| *other != viewport) +} + +/// A viewport that has a modal layer open: the window that blocks the app's other windows. +pub(crate) fn app_modal_viewport(ctx: &Context) -> Option { + modal_viewports(ctx).next() } /// Whether a layer of key class `class` that is not fading out was shown last frame and the screen point `at` lies in diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 2dc04e1d0..d616909a5 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -96,6 +96,8 @@ pass_state! { held_widths: crate::layout::body::HeldWidths, first_lines: crate::layout::body::FirstLines, row_lines: crate::layout::body::RowLines, + flow_starts: crate::layout::body::FlowStarts, + brackets: crate::layout::body::Brackets, cursors: crate::layout::body::Cursors, footer_slots: crate::contract::footer_slot::Slots, column_groups: crate::layout::column_group::Open, @@ -119,6 +121,8 @@ pass_state! { memo_log: crate::runtime::measure::MemoLog, #[cfg(feature = "testing")] pass_totals: crate::runtime::measure::PassTotals, + #[cfg(feature = "testing")] + derived_builds: crate::runtime::measure::DerivedBuilds, } records { focus: crate::runtime::focus::State, @@ -126,6 +130,7 @@ pass_state! { cursor: crate::runtime::cursor::State, layout: crate::runtime::layout_memory::Entries, lazy: crate::runtime::lazy::Store, + derived: crate::runtime::derived::Store, arenas: crate::primitives::sensing::Arenas, envs: crate::runtime::env::ViewportEnvs, pointer: crate::runtime::pointer::Memory, diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index d32f5b886..7e99402fb 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -237,6 +237,10 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if events { inputs::bump(ctx, Input::Pointer); } + // A press or release, or an outside press the layer stack's input hook took before egui saw it. + if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() { + inputs::bump(ctx, Input::Press); + } } PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { @@ -325,6 +329,13 @@ pub fn mods(ctx: &Context) -> Mods { with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods)) } +/// Where the primary press of the running pass started. A tracked input (`Input::Press`): a layer's dismissal decides by +/// it, so a memoized view that shows a layer runs on a press anywhere, and a pointer move leaves it alone. +pub(crate) fn primary_press(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, Input::Press); + frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) +} + /// `frame` without noting the read: for the steps of the component under the pointer and the pass machinery. pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame { with_pass_raw(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame { @@ -444,6 +455,7 @@ pub(crate) fn record_text_widget(ctx: &Context, widget: Id, owner: Id) { /// it the press where no widget on the layer is, and the press and hover there go to the layer's shapes as if egui /// had named no target. pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) { + crate::runtime::replay::journal(ctx, || widget, |ctx, &widget| record_layer_widget(ctx, widget)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_grounds.insert(widget); }); diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index b22730d9a..c89872ac5 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -9,8 +9,11 @@ //! //! The record also holds the facts the settled test reads (`runtime::lazy`): the values the run read, whether //! something in it still moves (an animation that is not at its end, a repaint request) and the earliest time it asked -//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another -//! layer, a label scope open around it). Such a record is never replayed: the view runs. +//! to be shown again, the overlay layers it shows and where the focus was in it, and whether it did something a replay +//! cannot repeat (paint on a layer that is neither its own nor an overlay it shows, such as a raw egui popup or a +//! transformed body; a window of another viewport; a label scope open around it). Such a record is never replayed: +//! the view runs. An overlay it shows is journaled as every other registration is (its `Area`, its layer stack +//! entry), so its record replays only where it ran (`Record::pinned`). use crate::runtime::egui::areas::Layer; use crate::runtime::focus::{self, Transcript}; @@ -19,7 +22,7 @@ use crate::runtime::inputs::{Input, Inputs}; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; use crate::runtime::shift::Shift; -use egui::{Context, IdSet, RecordShift}; +use egui::{Context, IdSet, RecordShift, Rect}; use std::any::Any; use std::collections::HashSet; use std::fmt; @@ -90,6 +93,15 @@ impl PartialEq for Entry { } } +impl Entry { + /// The entry at the place `shift` names. A shift that leaves every record as it is (`RecordShift::is_none`, a + /// pinned record's) leaves the entry too, as it leaves egui's records: a clip a layer the record shows sets lies + /// outside the clip around the record, which `RecordShift::clip` would cut it to. + fn at(&self, shift: &RecordShift) -> Entry { + if shift.is_none() { self.clone() } else { self.0.shifted(shift) } + } +} + impl fmt::Debug for Entry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.describe(f) @@ -157,11 +169,50 @@ pub(crate) struct Facts { pub(crate) owners: Vec, /// The layout memory entries the run kept (`note_layout_keep`): a replay keeps them (`layout_memory::keep`). pub(crate) layout_keeps: Vec, + /// The derived values the run asked for (`note_derived_keep`): a replay keeps them, since it asks for none. + pub(crate) derived_keeps: Vec, /// The framework inputs the run read outside its props (`runtime::inputs`). pub(crate) inputs: Inputs, /// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one /// is taken only by a run, so a replay waits until the queue holds none. pub(crate) instances: Vec, + /// The overlay layers the run showed (`note_overlay`): their paint and widgets are the record's, and the pointer over + /// one of them engages the record. + pub(crate) overlays: Vec, + /// The layer stack entries the run recorded (`note_layer`): a close queued for one is taken only by a run. + pub(crate) layers: Vec, +} + +/// An overlay layer a run showed: its egui layer and its rect in screen space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct ShownLayer { + pub(crate) layer: Layer, + pub(crate) rect: Rect, +} + +/// Where the focus was in a run: the component of the focused stop when the run registered it, and the egui widget +/// that held egui focus when the run made it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Held { + pub(crate) stop: Option, + pub(crate) widget: Option, +} + +impl Held { + /// Where the focus is now: the component of the focused stop and the egui widget that holds egui focus. + pub(crate) fn focused(ctx: &Context) -> Held { + Held { stop: focus::focused_stop(ctx).map(|key| key.0), widget: crate::runtime::egui::focus::focused(ctx) } + } + + /// The part of the focus `self` that is among the stops of `focus` and the egui widgets `widgets`. + pub(crate) fn within(self, focus: &Transcript, widgets: &IdSet) -> Held { + Held { stop: self.stop.filter(|stop| focus.stop_ids().any(|id| id == *stop)), widget: self.widget.filter(|widget| widgets.contains(widget)) } + } + + /// Whether the focus is in the run at all. + pub(crate) fn any(self) -> bool { + self.stop.is_some() || self.widget.is_some() + } } /// What one real run of a region added to its pass. @@ -171,14 +222,22 @@ pub(crate) struct Record { egui: egui::PassRecords, /// The egui widgets of the run. pub(crate) widgets: IdSet, + /// Where the focus was in the run when it ended. + pub(crate) held: Held, pub(crate) facts: Facts, } impl Record { /// Whether a replay can add the record at another place: egui's records hold no paint callback - /// (`PassRecords::paints_callback`). + /// (`PassRecords::paints_callback`) and the record is not pinned. pub(crate) fn movable(&self) -> bool { - !self.egui.paints_callback() + !self.egui.paints_callback() && !self.pinned() + } + + /// Whether the record replays only where it ran, at the offset and clip of its run: it shows an overlay, which a + /// host places in screen space by its anchor, so a move of the record is no move of the layer. + pub(crate) fn pinned(&self) -> bool { + !self.facts.overlays.is_empty() } } @@ -216,7 +275,8 @@ pub(crate) fn in_audit_run(ctx: &Context) -> bool { OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| recorder.open.iter().any(|open| open.audit)) } -/// Ends the innermost record, the one around a run on `layer`: paint or widgets on another layer block it. +/// Ends the innermost record, the one around a run on `layer`: paint or widgets on a layer that is neither `layer` nor +/// an overlay the run showed block it. pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { OPEN.fetch_sub(1, Ordering::AcqRel); let (open, journal) = pass_state::with::(ctx, |recorder| { @@ -234,11 +294,14 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.discards |= open.facts.discards; outer.facts.owners.extend(open.facts.owners.iter().copied()); outer.facts.layout_keeps.extend(open.facts.layout_keeps.iter().copied()); + outer.facts.derived_keeps.extend(open.facts.derived_keeps.iter().copied()); outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake); let kept = outer.kept; outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..)))); outer.facts.inputs.extend(open.facts.inputs); outer.facts.instances.extend(open.facts.instances.iter().copied()); + outer.facts.overlays.extend(open.facts.overlays.iter().copied()); + outer.facts.layers.extend(open.facts.layers.iter().copied()); } else { recorder.journal.clear(); } @@ -249,13 +312,25 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { // Every measure of an entry keeps it again: the record keeps each one once. facts.layout_keeps.sort_unstable_by_key(|id| id.value()); facts.layout_keeps.dedup(); - // A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees: - // its run is never replayed. - facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback(); + facts.derived_keeps.sort_unstable_by_key(|id| id.value()); + facts.derived_keeps.dedup(); + // Paint on a layer that is neither the run's own nor an overlay it showed (a raw egui popup, a transformed body) + // comes from code that registers nothing to replay it with. A paint callback's output depends on what its closure + // holds, which neither a view's key nor a comparison sees. Either run is never replayed. + facts.blocked |= egui.layers().any(|on| on != layer && !facts.overlays.iter().any(|shown| shown.layer == on)) || egui.paints_callback(); // Every discard request reaches egui's output (`sizing::request_discard` and egui's own); layout memory's waits // for the end of the pass and notes itself (`note_discard`). facts.discards |= discard_requests(ctx) > open.discards; - Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts } + let focus = focus::transcript(ctx, open.focus); + let widgets = egui.widgets().iter().map(|widget| widget.id).collect(); + // A run that ends holding focus reads where the focus is and what is sent to it: a focus move, and the next key, + // text, IME, clipboard or AccessKit event wherever the framework routes it, run it. + let held = Held::focused(ctx).within(&focus, &widgets); + if held.any() { + facts.inputs.insert(Input::Focus); + facts.inputs.insert(Input::Sent); + } + Record { focus, journal, widgets, held, egui, facts } } #[cfg(feature = "testing")] @@ -275,6 +350,10 @@ impl Record { // The display names a widget by its rect only; the difference may be in its sense, state or interact rect. Some(egui::PassRecordsDiff::Widget { index, left, right }) => found.push(format!("widget rect {index}: left {left:?} / right {right:?}")), // The display names a node by its bounds only; the difference may be in any other property. + // The display names a shape by its rects only; the difference may be in its colour, stroke, texture or text. + Some(egui::PassRecordsDiff::Shape { layer, index, left, right }) => { + found.push(format!("paint: shape {index} on {layer:?}: left {left:?} / right {right:?}")) + } Some(egui::PassRecordsDiff::Node { index, left, right }) => { found.push(format!("AccessKit node {index}: left {left:?} / right {right:?}")) } @@ -284,7 +363,7 @@ impl Record { if let Some(diff) = self.focus.first_difference(&run.focus) { found.push(format!("focus: {diff}")); } - let shifted: Vec = self.journal.iter().map(|entry| entry.0.shifted(shift)).collect(); + let shifted: Vec = self.journal.iter().map(|entry| entry.at(shift)).collect(); let (left, right) = (&shifted, &run.journal); if let Some(index) = left .iter() @@ -350,7 +429,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { let noting = recording(ctx); if noting { pass_state::with::(ctx, |recorder| { - recorder.journal.extend(record.journal.iter().map(|entry| if shift.is_none() { entry.clone() } else { entry.0.shifted(shift) })); + recorder.journal.extend(record.journal.iter().map(|entry| entry.at(shift))); recorder.replaying = true; }); } @@ -361,11 +440,13 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { pass_state::with::(ctx, |recorder| recorder.replaying = false); } crate::runtime::layout_memory::keep(ctx, &record.facts.layout_keeps); + crate::runtime::derived::keep(ctx, &record.facts.derived_keeps); if let Some(at) = record.facts.wake { crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); } with_open(ctx, |facts| { facts.layout_keeps.extend(record.facts.layout_keeps.iter().copied()); + facts.derived_keeps.extend(record.facts.derived_keeps.iter().copied()); facts.reads.extend(record.facts.reads.iter().copied()); facts.inputs.extend(record.facts.inputs); facts.wake = min_wake(facts.wake, record.facts.wake); @@ -464,6 +545,17 @@ pub(crate) fn note_wake(ctx: &Context, at: f64) { with_open(ctx, |facts| facts.wake = min_wake(facts.wake, Some(at))); } +/// Notes that the running code showed the overlay layer `layer` at the screen rect `rect`. Called by the journaled +/// registration of the layer's `Area`, so a record that replays it notes it again in the records open around it. +pub(crate) fn note_overlay(ctx: &Context, layer: Layer, rect: Rect) { + with_open(ctx, |facts| facts.overlays.push(ShownLayer { layer, rect })); +} + +/// Notes that the running code recorded the layer stack entry `id`, by a run or a replay. +pub(crate) fn note_layer(ctx: &Context, id: egui::Id) { + with_open(ctx, |facts| facts.layers.push(id)); +} + /// Notes that the running code did something a replay cannot repeat. pub(crate) fn block(ctx: &Context) { with_open(ctx, |facts| facts.blocked = true); @@ -481,6 +573,12 @@ pub(crate) fn note_layout_keep(ctx: &Context, id: egui::Id) { with_open(ctx, |facts| facts.layout_keeps.push(id)); } +/// Notes that the running code asked for the derived value kept under `slot`: a replay of the records open around it +/// keeps it too, as the replay asks for nothing and an entry no pass asked for in a frame is dropped. +pub(crate) fn note_derived_keep(ctx: &Context, slot: egui::Id) { + with_open(ctx, |facts| facts.derived_keeps.push(slot)); +} + /// Notes that the memory owner `owner` registered in the running code. pub(crate) fn note_owner(ctx: &Context, owner: egui::Id) { with_open(ctx, |facts| facts.owners.push(owner)); diff --git a/crates/ui-contract/src/runtime/toast.rs b/crates/ui-contract/src/runtime/toast.rs index be51a8b36..4649ad0b9 100644 --- a/crates/ui-contract/src/runtime/toast.rs +++ b/crates/ui-contract/src/runtime/toast.rs @@ -285,14 +285,22 @@ pub fn keep(ctx: &Context, id: ToastId) { } } -/// The cards of the window `window` in the running viewport, oldest first. +/// The cards of the window `window` in the running viewport, oldest first. A tracked input (`Input::Toasts`). pub fn cards(ctx: &Context, window: &WindowKey) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Toasts); PerViewport::::with(ctx, pass::current_viewport(ctx), |queue| { let cards = queue.windows.iter().find(|(key, _)| key == window); cards.map_or_else(Vec::new, |(_, live)| live.iter().map(|live| live.card.clone()).collect()) }) } +/// The ids of the cards each window of the running viewport queues: what `Input::Toasts` observes. +pub(crate) fn queued(ctx: &Context) -> Vec<(WindowKey, Vec)> { + PerViewport::::with(ctx, pass::current_viewport(ctx), |queue| { + queue.windows.iter().map(|(key, live)| (key.clone(), live.iter().map(|live| live.card.id).collect())).collect() + }) +} + /// Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's. pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)> { let mut cards = Vec::new(); diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index a5d117b24..42409d37c 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -48,9 +48,9 @@ pub use shell::shell_of; use shell::{refresh, window_info}; #[cfg(feature = "testing")] pub(crate) use shell::{set_chrome, set_os}; -use spec::chrome_of; +use spec::{AppState, chrome_of}; pub use spec::{WindowLevel, WindowSpec}; -pub(crate) use viewport::{ViewportOpen, show_viewport, take_close_request, unplaced}; +pub(crate) use viewport::{PopupOpen, ViewportOpen, close_popup, place_popup, show_popup, show_viewport, take_close_request, unplaced}; /// Seconds between writes of a changed placement store. const FLUSH_SECONDS: f64 = 1.0; @@ -86,11 +86,17 @@ pub(crate) struct Shared { desktop: Option, /// Whether the root window had focus in the last root pass. root_focused: bool, - /// Whether no window of the app had focus when the last frame's windows had all reported. - away: bool, + /// The app's state when the last frame's windows had all reported, which its palettes follow. + app: AppState, + /// Whether a palette window stood lowered under an app-modal layer in this frame. + lowered: bool, + /// Where the raise of the modal's window above the palettes it lowered stands. + raise: Raise, /// The app's windows from the one focused longest ago to the one focused last: the stacking order of /// overlapping windows. stacking: Vec, + /// The windows that got a primary press, each with the root frame of the press, in this root frame and the last. + presses: Vec<(ViewportId, u64)>, } /// One viewport's window record. @@ -105,8 +111,10 @@ pub(crate) struct Record { chrome: Option, /// The caption buttons the app draws in this window. captions: Option, - /// The level the window was opened with or last set to; a palette's egui level follows the app's activity. + /// The level the window was opened with or last set to; a palette's egui level follows the app's state. level: Option, + /// Whether the window is hidden because the app's state hides it (a palette while the main window is minimized). + hidden: bool, /// H4: whether the primary button is down as the viewport's events left the input hook. primary_down: bool, /// Whether the user can resize the window; unknown for a window not opened by `show_viewport`. @@ -146,6 +154,22 @@ pub(crate) struct Record { seen: Option, /// The smallest inner size its caller asks for, as the window's builder carries it. min_size: Option, + /// For a popup window ([`show_popup`]): the window its layer was opened from, while the layer shows. + opener: Option, +} + +/// The raise of the window holding an app-modal layer above the palettes the modal lowered. The raise goes out in the +/// frame after a palette was built lowered: a raise in the same frame may reach the OS before the palette's new level +/// does, and the palette, made an ordinary window after it, would stand in front again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Raise { + /// No palette has stood lowered under the open modal yet, or no modal is open. + #[default] + Waiting, + /// A palette stood lowered in the last frame: the modal's window is raised in this one. + Due, + /// The modal's window was raised. + Done, } /// Passes between searches for an OS window that was not found. @@ -294,6 +318,15 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) -> bool { if handed_off && tracked == Some(viewport) { shared(ctx, |shared| shared.tracked_move = None); } + let pressed = + input.events.iter().any(|event| matches!(event, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })); + if pressed { + let frame = pass::root_frame_nr(ctx); + shared(ctx, |shared| { + shared.presses.retain(|(_, at)| at + 1 >= frame); + shared.presses.push((viewport, frame)); + }); + } released } @@ -350,6 +383,73 @@ fn opens_over(ctx: &Context, opener: ViewportId) -> bool { !covers } +/// Where the layers opened in a palette window show: in popup windows of their own, placed in desktop points. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PopupRoom { + /// The palette window's inner top-left corner in desktop points: the origin of its viewport's points. + pub origin: Pos2, + /// The room its layers may take, in its viewport's points: the work area of the monitor the window is on, or where + /// no monitor is listed, the area the app's windows other than popups span. + pub room: Rect, +} + +/// The room of the layers opened in the running viewport when it is a palette window (a dock window or a popup +/// window, both at [`WindowLevel::Palette`]) that opens OS windows ([`opens_over`]) where the platform places them: +/// every such layer shows in a popup window of its own. `None` in every other window, whose layers stay in it. +pub(crate) fn popup_room(ctx: &Context) -> Option { + let viewport = pass::current_viewport(ctx); + if !base_shell(ctx).window_positions() || !opens_over(ctx, viewport) { + return None; + } + let facts = PerViewport::::with_existing(ctx, viewport, |record| record.facts.filter(|_| record.level == Some(WindowLevel::Palette)))??; + let origin = facts.inner?.min; + let scale = host::scale_of(ctx, &facts).unwrap_or(1.0).max(f32::EPSILON); + let work = host::monitor_of(ctx, &facts).map(|monitor| { + let (pos, size) = monitor.work_px.unwrap_or((monitor.pos_px, monitor.size_px)); + let min = Pos2::new(pos[0] as f32, pos[1] as f32) / scale; + Rect::from_min_size(min, Vec2::new(size[0] as f32, size[1] as f32) / scale) + }); + // The popup windows themselves don't count: a popup's room never depends on where a popup stands. + let spanned = || { + let popup = |viewport: ViewportId| PerViewport::::with_existing(ctx, viewport, |record| record.opener.is_some()).unwrap_or(false); + viewports::reported(ctx) + .iter() + .filter(|(viewport, _)| !popup(*viewport)) + .filter_map(|(_, facts)| facts.inner) + .fold(Rect::NOTHING, Rect::union) + }; + let room = work.unwrap_or_else(spanned).translate(-origin.to_vec2()); + Some(PopupRoom { origin, room }) +} + +/// Whether a primary press landed, in this root frame (or in the last one, unless the popup window `popup` just +/// `appeared`), in a window of the app other than the running viewport (the popup's opener, whose own presses its +/// layer stack judges) and the popup window and the popup windows opened from it. +pub(crate) fn pressed_elsewhere(ctx: &Context, popup: ViewportId, appeared: bool) -> bool { + let opener = pass::current_viewport(ctx); + let frame = pass::root_frame_nr(ctx); + let presses = shared(ctx, |shared| shared.presses.clone()); + presses.into_iter().filter(|(_, at)| *at == frame || (!appeared && at + 1 == frame)).any(|(viewport, _)| { + if viewport == opener { + return false; + } + // A press in a popup window opened from the popup, at any depth, is inside its family. + let mut at = Some(viewport); + while let Some(window) = at { + if window == popup { + return false; + } + at = PerViewport::::with_existing(ctx, window, |record| record.opener).flatten(); + } + true + }) +} + +/// Whether no window of the app has focus, as the last frame's windows reported. +pub(crate) fn app_away(ctx: &Context) -> bool { + shared(ctx, |shared| shared.app.away) +} + /// Refuses the close request of the running viewport while an app-modal layer blocks it, and raises the modal's /// window. True when it refused. fn refuse_close_under_modal(ctx: &Context) -> bool { @@ -465,12 +565,14 @@ fn flush_store(ctx: &Context) { } } -/// Keeps the app's activity and the stacking order of its windows current from the windows' focus. A palette's -/// window level follows the activity: the mounts build their viewports with the level of the moment, and a change +/// Keeps the app's state and the stacking order of its windows current from the windows' facts. A palette's window +/// level and visibility follow the state: the mounts build their viewports with the state of the moment, and a change /// asks for the next frame. Runs at the end of the root pass, inside which every child window's pass of the frame /// has run, so each window's focus is the one its own pass reported after its input batch. The root input's list of /// windows holds each child as of its previous pass, so it is not read for focus. The app is inactive when no /// window reports focus: the batch that took focus from one window gave it to no other. +/// +/// Once a palette has stood lowered under an app-modal layer, the modal's window is raised above it, once per modal. fn follow_activity(ctx: &Context) { let windows = viewports::reported(ctx); let focused: Vec = windows @@ -478,13 +580,27 @@ fn follow_activity(ctx: &Context) { .map(|(viewport, _)| *viewport) .filter(|viewport| PerViewport::::with(ctx, *viewport, |record| record.facts.is_some_and(|facts| facts.focused))) .collect(); - let changed = shared(ctx, |shared| { + let modal = overlay::app_modal_viewport(ctx); + let minimized = viewports::current(ctx).minimized; + let (repaint, raise) = shared(ctx, |shared| { shared.stacking.retain(|viewport| windows.iter().any(|(open, _)| open == viewport) && !focused.contains(viewport)); shared.stacking.extend(&focused); - let away = focused.is_empty(); - std::mem::replace(&mut shared.away, away) != away + let app = AppState { away: focused.is_empty(), modal, minimized }; + let lowered = std::mem::take(&mut shared.lowered); + let (step, raise) = match shared.raise { + _ if app.modal != shared.app.modal => (Raise::Waiting, None), + Raise::Waiting if lowered => (Raise::Due, None), + Raise::Due => (Raise::Done, app.modal), + step => (step, None), + }; + shared.raise = step; + let changed = std::mem::replace(&mut shared.app, app) != app; + (changed || step == Raise::Due, raise) }); - if changed { + if let Some(modal) = raise { + act(ctx, modal, WindowAction::Raise); + } + if repaint { ctx.request_repaint(); } } diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 5e15aac8d..84ed27cde 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -421,7 +421,7 @@ pub(super) fn monitors(ctx: &Context) -> Vec { /// The monitor the top-left corner of a window with `facts` lies on. A corner is on a monitor when its pixel position /// at that monitor's scale is inside the monitor. -fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option { +pub(super) fn monitor_of(ctx: &Context, facts: &viewports::Facts) -> Option { let corner = facts.outer.or(facts.inner)?.min; monitors(ctx).into_iter().find(|monitor| monitor.rect_px().contains(corner * monitor.scale)) } diff --git a/crates/ui-contract/src/runtime/windows/native.rs b/crates/ui-contract/src/runtime/windows/native.rs index b13db3737..9974910df 100644 --- a/crates/ui-contract/src/runtime/windows/native.rs +++ b/crates/ui-contract/src/runtime/windows/native.rs @@ -5,7 +5,7 @@ use super::host::scale_of; #[cfg(doc)] use super::logic; use super::shell::{base_shell, os_of, window_info}; -use super::spec::WindowLevel; +use super::spec::{Standing, WindowLevel}; use super::{HandOff, Record, SEARCH_EVERY, shared}; use crate::runtime::egui::{pass, viewports}; use crate::runtime::frame::{PerViewport, Stored}; @@ -40,6 +40,9 @@ pub enum WindowAction { SetMaximized(bool), /// Raises the window and gives it OS focus. Focus, + /// Brings the window in front of the app's other windows without giving it focus, as the window holding an + /// app-modal layer comes in front of the palettes the modal lowered. + Raise, /// The OS starts moving the window with the pointer. StartMove, /// The OS starts resizing the window from `edge`. @@ -100,7 +103,8 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { | WindowAction::Restore | WindowAction::SetMinInnerSize(_) | WindowAction::SetLevel(_) - | WindowAction::SetTitle(_) => commands, + | WindowAction::SetTitle(_) + | WindowAction::Raise => commands, WindowAction::SetOpacity(_) => false, }; if !allowed { @@ -109,6 +113,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { match action { WindowAction::Close => viewports::close(ctx, viewport), WindowAction::Focus => viewports::raise(ctx, viewport), + WindowAction::Raise => viewports::raise_above(ctx, viewport, standing(ctx, viewport, level_of(ctx, viewport)).level), WindowAction::Minimize => viewports::command(ctx, viewport, egui::ViewportCommand::Minimized(true)), WindowAction::ToggleMaximize => viewports::command(ctx, viewport, egui::ViewportCommand::Maximized(window.state != WindowState::Maximized)), WindowAction::ToggleFullscreen => { @@ -147,8 +152,7 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { if opened { ctx.request_repaint_of(viewport); } else { - let active = !shared(ctx, |shared| shared.away); - viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(level.for_egui(active, os_of(ctx)))); + viewports::command(ctx, viewport, egui::ViewportCommand::WindowLevel(standing(ctx, viewport, level).level)); } } WindowAction::SetTitle(title) => { @@ -172,6 +176,16 @@ pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool { true } +/// The level `viewport`'s window was opened with or last set to. +fn level_of(ctx: &Context, viewport: ViewportId) -> WindowLevel { + PerViewport::::with(ctx, viewport, |record| record.level.unwrap_or_default()) +} + +/// How `viewport`'s window at `level` stands in the app's current state. +fn standing(ctx: &Context, viewport: ViewportId, level: WindowLevel) -> Standing { + level.standing(viewport, shared(ctx, |shared| shared.app), os_of(ctx)) +} + /// Applies `opacity` to the OS window. A faded window is told again in every pass, because the window system's own /// style changes can drop the layered style; an opaque one only when it was faded. Returns whether the platform applied /// it now. diff --git a/crates/ui-contract/src/runtime/windows/spec.rs b/crates/ui-contract/src/runtime/windows/spec.rs index cb8277a54..af9e889e6 100644 --- a/crates/ui-contract/src/runtime/windows/spec.rs +++ b/crates/ui-contract/src/runtime/windows/spec.rs @@ -4,7 +4,7 @@ use super::shared; use super::shell::{base_shell, os_of}; use craft_host::target::{Os, WindowChrome, WindowKind}; use craft_window::policy::{CaptionFamily, Captions, Frame, MacInset, tool_frame}; -use egui::Context; +use egui::{Context, ViewportId}; /// Where a window stands in the stack of windows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -13,26 +13,53 @@ pub enum WindowLevel { /// An ordinary window. #[default] Normal, - /// A palette: above the app's other windows while the app is active, and an ordinary window (behind other - /// apps' windows on Windows) once none of the app's windows has focus, so it stays shown without covering - /// other apps. + /// A palette: above the app's other windows while the app is active, an ordinary window while an app-modal layer + /// in another window blocks it, and an ordinary window (behind other apps' windows on Windows) once none of the + /// app's windows has focus, so it stays shown without covering other apps or the modal. Hidden while the main + /// window is minimized, except on macOS, where the app stays active and its palettes stay. Palette, /// Above every other window. AlwaysOnTop, } +/// The app's state that its palettes follow, as its windows reported it in the last frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct AppState { + /// No window of the app has focus. + pub away: bool, + /// The window that holds an app-modal layer, which blocks the app's other windows. + pub modal: Option, + /// The main window is minimized. + pub minimized: bool, +} + +/// How a window stands among the windows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Standing { + /// The level egui is given. + pub level: egui::WindowLevel, + /// Whether the window is shown. + pub shown: bool, + /// Whether the window stands as an ordinary window because an app-modal layer in another window blocks it. + pub lowered: bool, +} + impl WindowLevel { - /// The level egui is given while the app is `active` or not, on `os`. An inactive app's palette goes behind - /// other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the - /// activated app's included, so the palette goes to the bottom. - pub(super) fn for_egui(self, active: bool, os: Os) -> egui::WindowLevel { - match self { + /// How `viewport`'s window at this level stands while the app is in `app`, on `os`. An inactive app's palette goes + /// behind other apps' windows: on Windows `Normal` puts a window in front of every window that is not topmost, the + /// activated app's included, so the palette goes to the bottom. A palette blocked by a modal stands as an ordinary + /// window, so the modal's window can be raised above it. + pub(super) fn standing(self, viewport: ViewportId, app: AppState, os: Os) -> Standing { + let palette = self == WindowLevel::Palette; + let lowered = palette && !app.away && app.modal.is_some_and(|modal| modal != viewport); + let level = match self { WindowLevel::Normal => egui::WindowLevel::Normal, WindowLevel::AlwaysOnTop => egui::WindowLevel::AlwaysOnTop, - WindowLevel::Palette if active => egui::WindowLevel::AlwaysOnTop, - WindowLevel::Palette if os == Os::Windows => egui::WindowLevel::AlwaysOnBottom, - WindowLevel::Palette => egui::WindowLevel::Normal, - } + WindowLevel::Palette if app.away && os == Os::Windows => egui::WindowLevel::AlwaysOnBottom, + WindowLevel::Palette if app.away || lowered => egui::WindowLevel::Normal, + WindowLevel::Palette => egui::WindowLevel::AlwaysOnTop, + }; + Standing { level, shown: !(palette && app.minimized && os != Os::Mac), lowered } } } @@ -58,6 +85,10 @@ pub struct WindowSpec { pub taskbar: bool, /// Whether the window opens hidden and appears once its first pass has been laid out and painted. pub shown_after_first_paint: bool, + /// Whether the window takes OS focus when it opens. + pub takes_focus: bool, + /// Whether pointer input passes through the window to the window below it. + pub passes_pointer: bool, } impl WindowSpec { @@ -67,6 +98,13 @@ impl WindowSpec { WindowSpec { kind: WindowKind::Tool, level: WindowLevel::Palette, taskbar: false, ..Self::dialog() } } + /// A popup window: a layer opened from a palette window (a flyout, menu or tooltip) in an OS window of its own. It + /// has no frame, no taskbar entry and a palette level, and appears once its first pass ran, at the size and place + /// its layer took in that pass. + pub fn popup() -> Self { + WindowSpec { chrome: Some(WindowChrome::Integrated), shown_after_first_paint: true, ..Self::tool() } + } + /// A document window with the installed decision's frame. pub fn document() -> Self { WindowSpec { kind: WindowKind::Document, ..Self::dialog() } @@ -81,6 +119,8 @@ impl WindowSpec { level: WindowLevel::Normal, taskbar: true, shown_after_first_paint: false, + takes_focus: true, + passes_pointer: false, } } @@ -130,6 +170,20 @@ impl WindowSpec { self } + /// Sets whether the window takes OS focus when it opens. + #[must_use] + pub fn takes_focus(mut self, takes_focus: bool) -> Self { + self.takes_focus = takes_focus; + self + } + + /// Sets whether pointer input passes through the window to the window below it (a tooltip's). + #[must_use] + pub fn passes_pointer(mut self, passes_pointer: bool) -> Self { + self.passes_pointer = passes_pointer; + self + } + /// Sets whether the window opens hidden and appears after its first paint, so a window that shows a capture or /// other content that must be ready does not flash an empty frame. #[must_use] diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index a037488a7..b621430c3 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -54,10 +54,10 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im keep_placed(ctx, viewport, pos, size.filter(|_| open.follows_size)); } let spec = open.spec; - let active = !shared(ctx, |shared| shared.away); + let state = shared(ctx, |shared| shared.app); let os = os_of(ctx); let (chrome, captions) = frame_of_spec(ctx, spec); - let level = PerViewport::::with(ctx, viewport, |record| { + let standing = PerViewport::::with(ctx, viewport, |record| { record.kind = Some(spec.kind); record.chrome = Some(chrome); record.captions = captions.clone(); @@ -73,8 +73,11 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im record.searched = None; } } - record.level.get_or_insert(spec.level).for_egui(active, os) + record.level.get_or_insert(spec.level).standing(viewport, state, os) }); + if standing.lowered { + shared(ctx, |shared| shared.lowered = true); + } let app = app_id(ctx); let opens = viewports::Spec { title: open.title, @@ -88,10 +91,12 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im // egui sends a limit only when it has one: an open window always carries its maximum, unbounded when the // caller has none, so a lifted maximum reaches the OS. max_size: open.limits.1.or(opened.then_some(Vec2::INFINITY)), - level, + level: standing.level, resizable: open.resizable, taskbar: spec.taskbar, hidden: PerViewport::::with(ctx, viewport, |record| record.awaiting_first_paint), + active: spec.takes_focus, + passes_pointer: spec.passes_pointer, app_id: &app, }; viewports::show_immediate(ctx, viewport, &opens, |ui| { @@ -115,8 +120,77 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im record_placement(&ctx, viewport, key, &at_known(&ctx, viewport, viewports::current(&ctx))); } }); - if PerViewport::::with(ctx, viewport, |record| std::mem::take(&mut record.awaiting_first_paint)) { - viewports::show(ctx, viewport); + // A window opened hidden appears once its first pass ran; a window the app's state hides goes and comes back with + // it. The builder's visibility only opens the window: egui sends no change of it once the window is open. + let hidden = !standing.shown; + let (reveal, changed) = PerViewport::::with(ctx, viewport, |record| { + let first = std::mem::take(&mut record.awaiting_first_paint); + let changed = std::mem::replace(&mut record.hidden, hidden) != hidden; + (first || changed, changed) + }); + if hidden && changed { + viewports::set_visible(ctx, viewport, false); + } else if !hidden && reveal { + viewports::set_visible(ctx, viewport, true); + } +} + +/// What a layer shown in a popup window asks for ([`show_popup`]). +pub(crate) struct PopupOpen<'a> { + /// The layer's id; the popup's viewport derives from it. + pub id: Id, + /// How the window opens: a [`WindowSpec::popup`]. + pub spec: &'a WindowSpec, + /// The window's place in desktop points (outer top-left corner and inner size) when the layer's size is known + /// before its pass; otherwise the caller places it after the pass ([`place_popup`]). + pub rect: Option, +} + +/// Opens the popup window of a layer opened in the running viewport (its opener) and runs `body` in its pass. The +/// window is a viewport mount without a container: it opens at `open.rect` and follows it, and the opener gets the OS +/// focus back when it closes ([`close_popup`]). +pub(crate) fn show_popup(ctx: &Context, open: &PopupOpen<'_>, body: impl FnMut(&mut Ui)) { + let opener = crate::runtime::egui::pass::current_viewport(ctx); + PerViewport::::with(ctx, viewports::viewport_id(open.id), |record| record.opener = Some(opener)); + let mount = ViewportOpen { + id: open.id, + title: "", + size: open.rect.map(|rect| rect.size()), + follows_size: true, + save: None, + spec: open.spec, + limits: (None, None), + position: open.rect.map(|rect| rect.min), + resizable: false, + moved_by_app: false, + }; + show_viewport(ctx, &mount, body); +} + +/// Sends the popup window of layer `id` to `rect` (desktop points) where it is not there already: a layer whose size +/// its pass measured is placed once that pass ran. +pub(crate) fn place_popup(ctx: &Context, id: Id, rect: Rect) { + let viewport = viewports::viewport_id(id); + let known = PerViewport::::with(ctx, viewport, |record| record.known); + if known.is_none_or(|known| differs(ctx, viewport, rect.min - known.min)) { + act(ctx, viewport, WindowAction::SetOuterPosition(rect.min)); + } + if known.is_none_or(|known| differs(ctx, viewport, rect.size() - known.size())) { + act(ctx, viewport, WindowAction::SetInnerSize(rect.size())); + } + PerViewport::::with(ctx, viewport, |record| record.known = Some(rect)); +} + +/// The layer `id` is hidden: when it showed in a popup window that still has the OS focus, the window it was opened +/// from takes the focus back. Once per close; a layer that never showed in a popup does nothing. +pub(crate) fn close_popup(ctx: &Context, id: Id) { + let viewport = viewports::viewport_id(id); + let closed = PerViewport::::with_existing(ctx, viewport, |record| { + let focused = record.facts.is_some_and(|facts| facts.focus_reported); + record.opener.take().filter(|_| focused) + }); + if let Some(opener) = closed.flatten() { + act(ctx, opener, WindowAction::Focus); } } @@ -151,9 +225,17 @@ pub(crate) fn unplaced(ctx: &Context, id: Id) -> bool { && PerViewport::::with(ctx, viewports::viewport_id(id), |record| record.kind.is_some() && record.seen.is_none()) } -/// How far a caller's place may differ from the known place before it is a change: the OS rounds to pixels, and a -/// placement records the position in pixels. -const ROUNDING: f32 = 0.5; +/// How far a caller's place may differ from the known place before it is a change, in physical pixels of the window's +/// display: the OS rounds to pixels, and a placement records the position in pixels. +const ROUNDING_PX: f32 = 0.5; + +/// Whether `delta`, in points, moves the window `viewport` by more than rounding on its display: a whole pixel on +/// a 2x display is half a point. +fn differs(ctx: &Context, viewport: ViewportId, delta: Vec2) -> bool { + let facts = PerViewport::::with(ctx, viewport, |record| record.facts); + let scale = facts.and_then(|facts| super::host::scale_of(ctx, &facts)).unwrap_or(1.0); + delta.x.abs() * scale > ROUNDING_PX || delta.y.abs() * scale > ROUNDING_PX +} /// The place of a window with `facts`: its outer top-left corner and its inner size. fn place_of(facts: &viewports::Facts) -> Option { @@ -182,11 +264,10 @@ fn keep_placed(ctx: &Context, viewport: ViewportId, pos: Option, size: Opt (record.known, state || record.moved_pointer.is_some()) }); let Some(known) = known.filter(|_| !held) else { return }; - let differs = |delta: Vec2| delta.x.abs() > ROUNDING || delta.y.abs() > ROUNDING; - if let Some(pos) = pos.filter(|pos| differs(*pos - known.min)) { + if let Some(pos) = pos.filter(|pos| differs(ctx, viewport, *pos - known.min)) { act(ctx, viewport, WindowAction::SetOuterPosition(pos)); } - if let Some(size) = size.filter(|size| differs(*size - known.size())) { + if let Some(size) = size.filter(|size| differs(ctx, viewport, *size - known.size())) { act(ctx, viewport, WindowAction::SetInnerSize(size)); } } diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index db46b47fc..d82c9f33b 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -136,6 +136,11 @@ impl<'a> StyleCx<'a> { self.tokens.density() } + /// The component set of the scope, for a component that maps it to one of its named variants. + pub fn set(&self) -> craft_theme::ComponentSet { + self.env::() + } + /// A style context for the scope the pipeline or an app colour hook runs in. #[expect(clippy::too_many_arguments, reason = "one argument per input the style cache key covers")] #[doc(hidden)] diff --git a/crates/ui-contract/src/style/mod.rs b/crates/ui-contract/src/style/mod.rs index dc5783d61..a2fd71549 100644 --- a/crates/ui-contract/src/style/mod.rs +++ b/crates/ui-contract/src/style/mod.rs @@ -18,6 +18,7 @@ pub use cache::{Accepted, accepted_variant}; pub use craft_behavior::{ControlMetrics, Insets, Metrics}; #[doc(hidden)] pub use craft_theme::GroupValues; +pub use craft_theme::LetterCase; pub use craft_theme::{FlagMask, Flags, Mix, Resolve, State, StateMix, Stateful, States, TokenGroup, Tokens, TypeRole, Variant}; pub use craft_ui_macros::{ComponentStyle, TokenGroup}; pub(crate) use cx::control_metrics; diff --git a/crates/ui-contract/src/style/paint.rs b/crates/ui-contract/src/style/paint.rs index 73db34566..59066a5a9 100644 --- a/crates/ui-contract/src/style/paint.rs +++ b/crates/ui-contract/src/style/paint.rs @@ -199,8 +199,6 @@ pub struct ScrollBarLook { pub thumb_width: Stateful, /// The shortest the thumb gets along the bar. pub min_thumb: f32, - /// The length of the fade at an edge past which content is hidden. - pub fade: f32, } /// The shortest a scroll bar's thumb gets along the bar, whatever the bar's kind. @@ -245,7 +243,6 @@ pub(crate) fn scroll_bar_look_of(tokens: &UiTokens, kind: ScrollBarKind) -> Scro thickness, thumb_width: Stateful::new(rest).off(craft_theme::States::new(rest, thickness, thickness, rest)), min_thumb: min_thumb(tokens), - fade: tokens.size.scroll_fade, } } diff --git a/crates/ui-contract/src/testing/access.rs b/crates/ui-contract/src/testing/access.rs index 2d05eb316..e6e343f64 100644 --- a/crates/ui-contract/src/testing/access.rs +++ b/crates/ui-contract/src/testing/access.rs @@ -3,6 +3,7 @@ use crate::runtime::access::{FieldLabel, scope}; use egui::{Context, Id}; +pub use crate::runtime::access::layer_root; pub use crate::runtime::egui::access::{AccessTree, Declared, NodeKey, prune_controls}; /// The AccessKit tree a finished pass of a viewport produced, taken out of its output; empty when it made none. diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index b2165c890..78d04e2e2 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -298,6 +298,14 @@ impl Fixture { self } + /// Sets the user's binding overrides for every following pass, as an app's `FrameInput.commands` does: the keymap is + /// rebuilt when the `Arc` is another one. + pub fn overrides(&mut self, overrides: std::sync::Arc) -> &mut Self { + self.commands = self.commands.clone().overrides(overrides); + self.frames.commands(self.commands.clone()); + self + } + /// The room the story is shown in. pub fn room(&mut self, room: Vec2) -> &mut Self { self.room = room; @@ -343,6 +351,11 @@ impl Fixture { self.set_root(|root| root.density = density) } + /// The component set. + pub fn set(&mut self, set: craft_theme::ComponentSet) -> &mut Self { + self.root_value(set) + } + /// The interface scale. pub fn scale(&mut self, scale: Scale) -> &mut Self { self.set_root(|root| root.scale = scale) diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index a78daa48e..19c73c055 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -111,6 +111,36 @@ fn texel(image: &ColorImage, x: usize, y: usize) -> Color32 { image.pixels[y * 24 + x] } +/// On a strong fill or scrim (the surface's ink is `OnDark`: a brand rail) the accent parts paint in the icon's own +/// colour, since `accent.solid` would vanish on the brand fill; the fixed parts stay as drawn, and on a panel the +/// accent parts keep the accent ink. +#[trial] +fn an_accent_part_on_a_dark_surface_paints_in_the_icons_ink() { + register_app_icons(&LAYERED_SET); + let tokens = style::tokens(Mode::Light, Contrast::Standard); + let rect = Rect::from_min_max(pos2(10.0, 10.0), pos2(34.0, 34.0)); + let mut frames = Frames::new(); + let mut tints = |surface: Ink, spec_ink: Option| { + let on = ink_color(&tokens, Ink::OnDark); + let mut spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(LAYERED_NAME))).color(StyleColor(on)); + if let Some(ink) = spec_ink { + spec = spec.ink(ink); + } + let record = RefCell::new(PaintRecord::default()); + let shapes = frames.frame_shapes(|ui| { + let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: surface }; + Draw::new(ui.painter(), &record, env).icon(rect, &spec); + }); + textured(&shapes).into_iter().map(|(_, tint)| tint).collect::>() + }; + let on = ink_color(&tokens, Ink::OnDark); + // design: allow[raw-colour/const](a fixed layer keeps the colours it is drawn in: the trial expects the white tint that leaves them unchanged) + let fixed = Color32::WHITE; + assert_eq!(tints(Ink::OnDark, None), [on, on, fixed], "on a brand rail the accent parts read in the icon's ink"); + assert_eq!(tints(Ink::OnPanel, Some(Ink::OnDark)), [on, on, fixed], "an icon that asks for the on-dark ink does the same"); + assert_eq!(tints(Ink::OnPanel, None), [on, rgba_color(tokens.color.accent.solid), fixed], "on a panel the accent ink is kept"); +} + #[trial] fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_the_disabled_ink_when_disabled() { register_app_icons(&LAYERED_SET); diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 12c245f68..fab30e3d4 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -54,16 +54,17 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ - MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs, - last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, - last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, + MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds, + last_frame_memo_runs, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, + last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, + run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; pub use frames::Frames; #[cfg(feature = "suite")] pub use registry::{Registered, Registry}; -pub use stage::{room_height, stage, stage_fitting, stage_width}; +pub use stage::{least_stage_width, room_height, stage, stage_fitting, stage_width}; #[doc(hidden)] pub use story::{ CollectionKind, Drive, EditKind, Grip, Required, Story, StoryData, StoryOutput, StoryRegistration, StorySnapshot, ValueAt, show_as_only_item, diff --git a/crates/ui-contract/src/testing/stage.rs b/crates/ui-contract/src/testing/stage.rs index 89759f814..c295901d2 100644 --- a/crates/ui-contract/src/testing/stage.rs +++ b/crates/ui-contract/src/testing/stage.rs @@ -2,13 +2,33 @@ use crate::layout::flow_room; use crate::runtime::env::Env; +use craft_theme::Tokens; use egui::{Rect, Ui}; +/// The stage's height, in control heights (`size.control.md`): 360 in Compact. +const HEIGHT_IN_CONTROLS: f32 = 15.0; + +/// The stage's least width, in control heights: 240 in Compact. +const WIDTH_MIN_IN_CONTROLS: f32 = 10.0; + +/// The stage's greatest width, in control heights: 720 in Compact. +const WIDTH_MAX_IN_CONTROLS: f32 = 30.0; + +/// The height of a story's stage. +fn stage_height(tokens: &Tokens) -> f32 { + HEIGHT_IN_CONTROLS * tokens.size.control.md +} + +/// The least width of a story's stage, which is also the least width of a column of a story grid. +pub fn least_stage_width(tokens: &Tokens) -> f32 { + WIDTH_MIN_IN_CONTROLS * tokens.size.control.md +} + /// Allocates the stage of a story of a canvas control or a root that fills both axes, and returns its rect: the width -/// left in `ui` between the least and greatest stage width, and the stage height, all from the size tokens. Show the +/// left in `ui` between the least and greatest stage width, and the stage height, all in control heights. Show the /// story's root over it with `show_at`. pub fn stage(ui: &mut Ui) -> Rect { - let height = Env::of(ui).tokens.tokens().size.story.height; + let height = stage_height(&Env::of(ui).tokens); stage_fitting(ui, |_| height) } @@ -16,7 +36,7 @@ pub fn stage(ui: &mut Ui) -> Rect { /// canvas): the room its card's view gives, or the stage height where the room is unbounded. pub fn room_height(ui: &Ui) -> f32 { let room = flow_room(ui).y; - if room.is_finite() { room } else { Env::of(ui).tokens.tokens().size.story.height } + if room.is_finite() { room } else { stage_height(&Env::of(ui).tokens) } } /// Allocates a stage as wide as [`stage`]'s and as tall as the story's content at that width, which `height` gives, @@ -29,8 +49,8 @@ pub fn stage_fitting(ui: &mut Ui, height: impl FnOnce(f32) -> f32) -> Rect { /// The width of the stage [`stage_fitting`] allocates: the width left in `ui` between the least and greatest stage /// width. A story whose content measures itself at a width (through `ui`) reads it before allocating. pub fn stage_width(ui: &Ui) -> f32 { - let story = Env::of(ui).tokens.tokens().size.story; + let tokens = &Env::of(ui).tokens; let room = flow_room(ui).x; let room = if room.is_finite() { room } else { ui.available_width() }; - room.clamp(story.width_min, story.width_max) + room.clamp(least_stage_width(tokens), WIDTH_MAX_IN_CONTROLS * tokens.size.control.md) } diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index c5844b134..c5a9edcd7 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -3,7 +3,8 @@ use craft_behavior::{ColumnWidth, Proposal, Sense}; use craft_ui::contract::{ - BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, Sizing, + BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, MemoProps, MemoView, Props as _, Role, Show as _, + ShowContainer as _, Sizing, }; use craft_ui::layout::{BodyLayout, RowAlign}; use craft_ui::runtime::env::{Direction, with_env}; @@ -322,6 +323,39 @@ fn the_end_region_shares_the_members_line() { assert!((end.center().y - member.center().y).abs() < SLACK, "the end region's probe {end:?} is off the members' line {member:?}"); } +/// A memoized view of one short block. +#[derive(MemoProps)] +struct Short {} + +fn short(_: &mut Short, ui: &mut Ui) -> Rect { + Block::new(Vec2::new(40.0, 10.0)).show(ui).rect +} + +/// A memoized view in a row sits on the row's line, as the one-line child beside it does, also while it replays. Its +/// content starts a layout room of its own, which left it at the row's top (a menu bar beside an app icon, +/// storytold/photocraft#16113). +#[trial] +fn a_memoized_view_sits_on_the_rows_line() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).id_salt("row").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; + let view = MemoView::new("short", Short {}, short).show(ui); + if !is_measuring(ui.ctx()) { + shown.set((tall, view.unwrap_or(Rect::NOTHING))); + } + }); + }); + fixture.room(Vec2::splat(400.0)).settle(); + for frame in 0..3 { + let (tall, view) = seen.get(); + assert!(view.height() > 0.0, "frame {frame}: the view showed: {view:?}"); + assert!((view.center().y - tall.center().y).abs() < SLACK, "frame {frame}: the view {view:?} is off the line of {tall:?}"); + fixture.settle(); + } +} + /// A Row in right-to-left holding a vertically scrolling container (content-sized, then filling its height) beside a /// probe: the container, the probe inside it and the probe beside it are finite, and the container lies in the row. #[trial] diff --git a/crates/ui-contract/tests/it/runtime/derived.rs b/crates/ui-contract/tests/it/runtime/derived.rs new file mode 100644 index 000000000..b981ee7a3 --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/derived.rs @@ -0,0 +1,91 @@ +//! Derived values: built once per key, kept while the key is unchanged, and dropped by the memo rule once absent. + +use craft_ui::runtime::derived::derived; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, trial}; +use egui::Id; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +/// A fixture whose pass derives a value under each id `ids` holds, keyed by `key`; `seen` collects the values. +fn deriving(ids: Rc>>, key: Rc>, seen: Rc>>>) -> Fixture { + Fixture::new(move |ui| { + seen.borrow_mut().clear(); + for id in ids.borrow().iter() { + let value = derived(ui.ctx(), Id::NULL.with(("derived", *id)), &key.get(), || format!("{id} at {}", key.get())); + seen.borrow_mut().push(value); + } + }) +} + +/// The number of builds in the last pass. +fn builds(fixture: &Fixture) -> u32 { + last_pass_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum() +} + +/// An unchanged key returns the kept value without a build; a changed key builds once, then keeps that. +#[trial] +fn a_derived_value_builds_once_per_key() { + let (ids, key, seen) = (Rc::new(RefCell::new(vec![1])), Rc::new(Cell::new(7)), Rc::default()); + let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen)); + fixture.frame(Vec::new()); + let first = Arc::clone(&seen.borrow()[0]); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "an unchanged key builds nothing"); + assert!(Arc::ptr_eq(&seen.borrow()[0], &first), "and returns the kept value"); + } + key.set(8); + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 1, "a changed key builds once"); + assert_eq!(*seen.borrow()[0], "1 at 8"); + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "then keeps the new value"); +} + +/// A value no pass asks for is kept while the absent ones are at most twice the shown ones, and dropped past that. +#[trial] +fn an_absent_derived_value_is_dropped_by_the_memo_rule() { + let (ids, key, seen) = (Rc::new(RefCell::new(vec![1, 2, 3])), Rc::new(Cell::new(0)), Rc::default()); + let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen)); + fixture.frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1]; + fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1, 2, 3]; + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "two absent values beside one shown are kept"); + *ids.borrow_mut() = Vec::new(); + fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1]; + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 1, "with none shown, every absent value was dropped"); +} + +/// A memoized view that replays asks for no derived value, and its values stay kept: when the pointer then runs the +/// view, it finds them. +#[trial] +fn a_replayed_view_keeps_the_values_it_derived() { + use craft_ui::contract::MemoView; + use craft_ui::testing::pointer; + let at: Rc> = Rc::default(); + let shown = Rc::clone(&at); + let mut fixture = Fixture::new(move |ui| { + let out = MemoView::new("deriving", 1u32, |key: &mut u32, ui: &mut egui::Ui| { + let value = derived(ui.ctx(), Id::NULL.with("derived"), key, || key.to_string()); + ui.label(value.as_str()).rect.center() + }) + .show(ui); + if let Some(out) = out { + shown.set(out); + } + }); + fixture.room(egui::Vec2::new(200.0, 100.0)); + fixture.settle().idle(3); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "an idle frame builds nothing"); + } + fixture.frame(vec![pointer::moved(at.get())]); + assert_eq!(last_frame_memo_runs(fixture.ctx()).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count(), 1, "the pointer runs the view"); + assert_eq!(builds(&fixture), 0, "the view runs for the pointer and finds its value kept"); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 7944a64f2..2567420c8 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod chord_fallthrough; pub(crate) mod clipboard; pub(crate) mod control_click; pub(crate) mod cursor; +pub(crate) mod derived; pub(crate) mod elapsed; pub(crate) mod env; pub(crate) mod frame; diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 924eed4d6..6b86efe0f 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -1,8 +1,8 @@ //! `runtime::windows`: the input hook per viewport, window info per viewport, the press release after an OS //! resize (H4), the raise of a modal's window, the mount of a full-window container (in a window of its own, or in a -//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, -//! injected keys across a focus loss, non-finite injected points, a repeated injected press, the window that has the -//! keys, and `act`. +//! full-screen or Wayland-maximized main window), the size of a content-sized window, the app id of child windows, a +//! palette's level under a modal and its visibility while the main window is minimized, injected keys across a focus +//! loss, non-finite injected points, a repeated injected press, the window that has the keys, and `act`. use craft_behavior::{Cursor, CursorIcon, PointerButton}; use craft_host::target::{Backend, Caps, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind}; @@ -302,6 +302,81 @@ fn a_palette_drops_its_level_while_the_app_is_inactive() { assert_eq!(frame(true, false), on_top, "the frame after the main window took focus again"); } +/// A palette stands as an ordinary window while an app-modal layer in the main window blocks it, so the modal is never +/// behind a palette: the frame after the modal opens builds the palette's window at the ordinary level, a later frame +/// raises the main window above it once, by its level (egui ignores `Focus` for a window that has focus), and the +/// palette stands above the app's windows again once the modal closes. +#[trial] +fn a_palette_stands_behind_the_window_that_holds_a_modal() { + let windows = Windows::new(); + windows.root_info(ViewportInfo { focused: Some(true), ..ViewportInfo::default() }); + let frame = |modal: bool| { + let out = windows.frame(vec![], vec![], |ui| { + windows.child_info(ViewportInfo { focused: Some(false), ..ViewportInfo::default() }); + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + if modal { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("save prompt").show(ui, |_, _| {}); + } + }); + let raise: Vec = out + .commands + .iter() + .filter(|(id, command)| *id == ViewportId::ROOT && matches!(command, ViewportCommand::WindowLevel(_) | ViewportCommand::Focus)) + .map(|(_, command)| command.clone()) + .collect(); + (builder_titled(&out, "tool").1.window_level, raise) + }; + let (on_top, normal) = (Some(egui::WindowLevel::AlwaysOnTop), Some(egui::WindowLevel::Normal)); + assert_eq!(frame(false), (on_top, vec![]), "no modal: the palette stands above the main window"); + let frames: Vec<_> = (0..4).map(|_| frame(true)).collect(); + assert_eq!(frames.last().map(|(level, _)| *level), Some(normal), "the modal open: the palette is an ordinary window"); + let raises: Vec = frames.iter().enumerate().filter(|(_, (_, raise))| !raise.is_empty()).map(|(at, _)| at).collect(); + let lowered = frames.iter().position(|(level, _)| *level == normal); + assert_eq!(raises.len(), 1, "the main window is raised once: {frames:?}"); + assert!(lowered.is_some_and(|lowered| raises[0] > lowered), "the raise follows the frame that lowered the palette: {frames:?}"); + let level = |level| ViewportCommand::WindowLevel(level); + assert_eq!( + frames[raises[0]].1, + vec![level(egui::WindowLevel::AlwaysOnTop), level(egui::WindowLevel::Normal)], + "the raise stands the main window above every window and back, without focus" + ); + frame(false); + assert_eq!(frame(false), (on_top, vec![]), "the modal closed: the palette stands above again"); +} + +/// A palette's window is hidden while the main window is minimized and shown again at its place when the main window +/// is restored, on Windows and Linux; a document window stays. On macOS a minimized main window leaves the app active, +/// and its palettes stay. +#[trial] +fn palettes_hide_while_the_main_window_is_minimized() { + for os in [Os::Windows, Os::Linux, Os::Mac] { + let windows = Windows::with(InstallSpec::new(ShellInfo::default().os(os).caps(Caps::native(os)), Arc::new(FakeSystem::new()))); + let frame = |minimized: bool| { + windows.root_info(ViewportInfo { minimized: Some(minimized), ..ViewportInfo::default() }); + windows.frame(vec![], vec![], |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |_, _| {}); + Palette::new("doc", Some(WindowSpec::document())).show(ui, |_, _| {}); + }) + }; + let first = frame(false); + let (tool, doc) = (builder_titled(&first, "tool").0, builder_titled(&first, "doc").0); + frame(false); + let commands = |minimized: bool| -> Vec<(ViewportId, ViewportCommand)> { (0..3).flat_map(|_| frame(minimized).commands).collect() }; + let sent = |commands: &[(ViewportId, ViewportCommand)], to: ViewportId| -> Vec { + commands.iter().filter(|(id, _)| *id == to).map(|(_, command)| command.clone()).collect() + }; + let (minimized, restored) = (commands(true), commands(false)); + let hides = os != Os::Mac; + let visible = |on: bool| if hides { vec![ViewportCommand::Visible(on)] } else { vec![] }; + let (tool_minimized, doc_minimized) = (sent(&minimized, tool), sent(&minimized, doc)); + let (tool_restored, doc_restored) = (sent(&restored, tool), sent(&restored, doc)); + assert_eq!(tool_minimized, visible(false), "{os:?}: the main window minimized: the palette is hidden, and nothing else is sent"); + assert_eq!(tool_restored, visible(true), "{os:?}: the main window restored: the palette is shown where it was"); + assert_eq!((doc_minimized, doc_restored), (vec![], vec![]), "{os:?}: a document window is left as it is"); + } +} + /// A full-window container mounted in its own window opens a resizable OS window titled as the container where /// viewports are available, and covers the main window's content where they are not. #[trial] diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index d5011402b..6fccc6f25 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -22,7 +22,7 @@ use craft_ui::runtime::inspect; use craft_ui::runtime::layout_memory; use craft_ui::sections::{HeaderCommand, HeaderStrength, Panel}; use craft_ui::style::SurfaceKind; -use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration}; +use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration, least_stage_width}; /// A story's show function. type StoryFn = fn(&mut Ui, &mut StoryData) -> StoryOutput; @@ -57,6 +57,8 @@ pub struct Look { /// The control size. #[memo_props(hash = "a fieldless enum of the theme")] pub size: Option, + /// The component set. + pub set: Option, } /// One story a card shows. @@ -252,7 +254,7 @@ impl Card<'_> { let gap = Gap::Item.points(ui); // The narrowest a column of stories may be is the least story width, as the old gallery's grids kept // their cases. - let least = Env::of(ui).tokens.size.story.width_min; + let least = least_stage_width(&Env::of(ui).tokens); let fit = ((ui.available_width() + gap) / (least + gap)).floor() as usize; let columns = fit.clamp(1, usize::from(most).clamp(1, COLUMNS.len())); Grid::new(&COLUMNS[..columns]).gap(Gap::Item).fill_width().show(ui, |ui, _| { @@ -512,6 +514,9 @@ fn story_view(props: &mut StoryProps<'_>, ui: &mut Ui) -> Rect { env.direction = look.direction; env.size = look.size; env.wheel = host.gated.then_some(craft_ui::runtime::env::WheelScope::Gated); + if let Some(set) = look.set { + env.values.set(set); + } }, |ui| match region { Some(key) => inspect::record(ui, key, |ui| show(ui, data)).0, 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/options.rs b/crates/ui-gallery/src/chrome/options.rs index 5006b1a5a..1c75cfce6 100644 --- a/crates/ui-gallery/src/chrome/options.rs +++ b/crates/ui-gallery/src/chrome/options.rs @@ -2,7 +2,8 @@ //! layout and the workspace switch at the end. use crate::viewer::{ - CONTRASTS, DENSITIES, DIRECTIONS, GalleryCommands, MODES, MOTIONS, Preview, SCALES, TEXT_SIZES, VariantAxis, Viewer, Workspace, theme_entries, + CONTRASTS, DENSITIES, DIRECTIONS, GalleryCommands, MODES, MOTIONS, Preview, SCALES, SETS, TEXT_SIZES, VariantAxis, Viewer, Workspace, + theme_entries, }; use craft_behavior::{IconId, Value}; use craft_ui::bars::{Bar, BarKind}; @@ -40,15 +41,21 @@ fn line(ui: &mut Ui, mut add: impl FnMut(&mut Ui)) { fn more_form(ui: &mut Ui, viewer: &mut Viewer) { let env = &mut viewer.env; let (contrasts, densities, motions) = (CONTRASTS.entries(), DENSITIES.entries(), MOTIONS.entries()); - let (directions, text_sizes, scales) = (DIRECTIONS.entries(), TEXT_SIZES.entries(), SCALES.entries()); + let (directions, text_sizes, scales, sets) = (DIRECTIONS.entries(), TEXT_SIZES.entries(), SCALES.entries(), SETS.entries()); + // The set is a root app value, not a field of the root. + let mut set = env.component_set(); Stack::new().show(ui, |ui, _| { line(ui, |ui| choose(ui, "Contrast", &mut env.contrast, &contrasts)); line(ui, |ui| choose(ui, "Size", &mut env.density, &densities)); + line(ui, |ui| choose(ui, "Set", &mut set, &sets)); line(ui, |ui| choose(ui, "Reduced motion", &mut env.motion, &motions)); line(ui, |ui| choose(ui, "Direction", &mut env.direction, &directions)); line(ui, |ui| choose(ui, "Text", &mut env.text_size, &text_sizes)); line(ui, |ui| pick(ui, "Scale", &mut env.scale, &scales)); }); + if set != env.component_set() { + env.values.set(set); + } } /// The Variants toggle and its menu of axes: the toggle shows whether a Variants view is open, and a press opens the diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs index 4c8dea5ae..d58f8f5e0 100644 --- a/crates/ui-gallery/src/chrome/overview.rs +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -20,7 +20,7 @@ use craft_ui::pickers::Select; use craft_ui::runtime::env::{Env, WindowKey}; use craft_ui::shell::AppShell; use craft_ui::style::SurfaceKind; -use craft_ui::testing::StoryRegistration; +use craft_ui::testing::{StoryRegistration, least_stage_width}; use egui::Ui; /// A card's story row before it ran, in standard control heights (120 at a 24 control). @@ -28,7 +28,7 @@ const STORY_ROW_IN_CONTROLS: f32 = 5.0; /// The narrowest a card may be before the cards go to one column: a story at its least width inside the card's padding. fn card_min_width(tokens: &Tokens) -> f32 { - tokens.size.story.width_min + 2.0 * tokens.space.pad.regular + least_stage_width(tokens) + 2.0 * tokens.space.pad.regular } const ONE: &[ColumnWidth] = &[ColumnWidth::fill(1.0)]; diff --git a/crates/ui-gallery/src/chrome/shell.rs b/crates/ui-gallery/src/chrome/shell.rs index 42ae35c83..24bb721fc 100644 --- a/crates/ui-gallery/src/chrome/shell.rs +++ b/crates/ui-gallery/src/chrome/shell.rs @@ -25,6 +25,7 @@ use craft_ui::shell::app::ShellApp; use craft_ui::shell::embed::CloseDecision; use egui::Ui; use std::collections::HashSet; +use std::sync::Arc; use web_time::Instant; /// The viewer as the root window's app. @@ -84,7 +85,7 @@ fn read_dropped(file: &OsFile) -> Result { /// The registered name of the component whose tab is in front and selected in the shown workspace's dock. fn front_component(viewer: &Viewer) -> Option<&'static str> { let dock = if viewer.workspace == Workspace::Theme { &viewer.theme_dock } else { &viewer.dock }; - viewer.browser.selected_type().filter(|type_name| dock.layout.panel_state(&PanelId::component(type_name)) == PanelState::Front) + viewer.browser.selected_type().filter(|type_name| dock.layout().panel_state(&PanelId::component(type_name)) == PanelState::Front) } /// Gives an open Variants view its centre tab: the front centre tab of the components workspace when the view opens, @@ -92,12 +93,12 @@ fn front_component(viewer: &Viewer) -> Option<&'static str> { /// runs. fn place_variants(viewer: &mut Viewer) { let front = - |panel: &PanelId| matches!(panel, PanelId::Overview | PanelId::Component(_)) && viewer.dock.layout.panel_state(panel) == PanelState::Front; + |panel: &PanelId| matches!(panel, PanelId::Overview | PanelId::Component(_)) && viewer.dock.layout().panel_state(panel) == PanelState::Front; let owner = match (&viewer.variants, &viewer.variants_tab) { (None, _) => None, (Some(_), Some(tab)) if front(tab) => Some(tab.clone()), (Some(_), Some(_)) => None, - (Some(_), None) => viewer.dock.layout.panels().into_iter().find(|panel| front(panel)).cloned(), + (Some(_), None) => viewer.dock.layout().panels().into_iter().find(|panel| front(panel)).cloned(), }; if owner.is_none() { viewer.variants = None; @@ -109,17 +110,17 @@ 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(), }; - let window = Look { mode: Some(appearance.mode), direction: Some(env.direction), ..Look::default() }; + let window = Look { mode: Some(appearance.mode), direction: Some(env.direction), set: Some(env.component_set()), ..Look::default() }; let variants_in = (*variants).zip(variants_tab.clone()).map(|(axis, tab)| (tab, VariantsIn::new(axis, window))); let mut content = GalleryDock { browser, @@ -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 { @@ -147,11 +148,17 @@ fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) { if let Some(direction) = look.direction { env.direction = direction; } + if let Some(set) = look.set { + env.values.set(set); + } } *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/chrome/variants.rs b/crates/ui-gallery/src/chrome/variants.rs index 4d96c91d6..da2514a50 100644 --- a/crates/ui-gallery/src/chrome/variants.rs +++ b/crates/ui-gallery/src/chrome/variants.rs @@ -4,7 +4,7 @@ use super::card::Look; use super::overview::{Centre, Spec, SpecStory, apply, grid, on_background}; use super::panels::{selected_of, target_story}; -use crate::viewer::{DIRECTIONS, MODES, VariantAxis, entry_of}; +use crate::viewer::{DIRECTIONS, MODES, SETS, VariantAxis, entry_of}; use craft_i18n::Direction; use craft_theme::variant::Tone; use craft_theme::{ControlSize, Mode, ModeChoice}; @@ -22,7 +22,7 @@ use egui::Ui; pub struct VariantsIn { /// What the view repeats the story over. pub axis: VariantAxis, - /// The window's mode and direction. + /// The window's mode, direction and component set. pub shown: Look, } @@ -56,6 +56,7 @@ fn noun(axis: VariantAxis) -> &'static str { VariantAxis::Mode => "mode", VariantAxis::Contrast => "contrast", VariantAxis::Size => "size", + VariantAxis::Set => "set", VariantAxis::Direction => "direction", VariantAxis::ControlSize => "control size", VariantAxis::DirectionAndControlSize => "direction and control size", @@ -92,6 +93,9 @@ fn values(axis: VariantAxis) -> Option> { .map(|choice| Value { label: choice.label, look: Look { direction: direction(choice.value), ..Look::default() } }) .collect(), ), + VariantAxis::Set => { + Some(SETS.0.iter().map(|choice| Value { label: choice.label, look: Look { set: Some(choice.value), ..Look::default() } }).collect()) + } VariantAxis::ControlSize => { Some(sizes.iter().map(|(size, label)| Value { label, look: Look { size: Some(*size), ..Look::default() } }).collect()) } @@ -129,6 +133,7 @@ pub(super) fn show(ui: &mut Ui, c: &mut Centre<'_>) -> bool { let shown = |look: &Look| match axis { VariantAxis::Mode => look.mode == window.mode, VariantAxis::Direction => look.direction == window.direction, + VariantAxis::Set => look.set == window.set, _ => false, }; values diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index 5b17f1e8b..cb265feb5 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -14,7 +14,7 @@ use craft_ui::canvas::{PickStep, ViewCommands}; use craft_ui::contract::{Bind, BodyCx, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _}; use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; use craft_ui::display::{Divider, Text}; -use craft_ui::docking::{DockConfig, DockEvent, DockPanels as _}; +use craft_ui::docking::{DockConfig, DockEvent, PanelSpecs as _}; use craft_ui::menu::{Menu, MenuBar, MenuItem, MenuTitle}; use craft_ui::patterns::dock::DockArea; use craft_ui::patterns::form_dialogs::{ @@ -25,6 +25,7 @@ use craft_ui::runtime::env::{Env, Label, WindowKey}; use craft_ui::shell::{AppShell, AppShellOutput, CaptionFamily, Captions, Frame, ScreenMode, ShellDialogsCx as _, Title, TitleBar}; use craft_window::Layout; use egui::{Rect, Ui}; +use std::sync::Arc; /// The parameters of Gaussian Blur. const BLUR: &str = r#"{"radius":0.1..1000=1}"#; @@ -94,13 +95,19 @@ impl<'a> EditorMock<'a> { /// The dock, then the commands and dialog answers of this pass. fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { let mut tools = cx.keep::().clone(); - let ctx = ui.ctx().clone(); let (events, picked) = { - let mut panels = - Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, last_used: &mut state.last_used, picked: None, ctx: &ctx }; + let mut panels = Panels { + document: &mut state.document, + tool: state.tool, + tools: &mut tools, + slots: &state.slots, + last_used: &mut state.last_used, + picked: None, + }; // The mock app is a preview inside the gallery's page: its floats stay in it. - let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default().native_windows(false)) - .flyout(Bind::bound(&mut state.flyout)); + let mut area = + DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default().native_windows(false)) + .flyout(Bind::bound(&mut state.flyout)); if let Some(panel) = state.maximized { area = area.maximized(panel); } @@ -138,20 +145,13 @@ fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { for command in asked { if let Some(panel) = command.panel() { // A panel in a column collapsed to icons shows in its flyout: the command opens or closes that. - if state.workspace.layout.opens_in_flyout(&panel) { + if state.workspace.layout().opens_in_flyout(&panel) { state.flyout = if state.flyout == Some(panel) { None } else { Some(panel) }; continue; } - let shown = state.workspace.layout.panel_state(&panel) != PanelState::Hidden; - let panels = Panels { - document: &mut state.document, - tool: state.tool, - tools: &mut tools, - last_used: &mut state.last_used, - picked: None, - ctx: &ctx, - }; - let _ = state.workspace.set_visible(panel, !shown, None, false, |panel| panels.permissions(panel)); + let shown = state.workspace.layout().panel_state(&panel) != PanelState::Hidden; + let specs = &state.specs; + let _ = Arc::make_mut(&mut state.workspace).set_visible(panel, !shown, None, false, |panel| specs.permissions(panel)); continue; } match command { @@ -266,7 +266,7 @@ fn title_bar(ui: &mut Ui, state: &MockState) { }), MenuTitle::new("&Window", |ui| { for panel in Panel::ALL { - let layout = &state.workspace.layout; + let layout = state.workspace.layout(); let shown = if layout.opens_in_flyout(&panel) { state.flyout == Some(panel) } else { diff --git a/crates/ui-gallery/src/mock/model.rs b/crates/ui-gallery/src/mock/model.rs index b0d491640..b953bd304 100644 --- a/crates/ui-gallery/src/mock/model.rs +++ b/crates/ui-gallery/src/mock/model.rs @@ -12,6 +12,9 @@ use craft_ui::contract::{CommandSet, Tracked}; use craft_ui::rails::{LastUsed, RailTool, SlotId, ToolSlot}; use craft_ui::runtime::env::UnitKind; use egui::{Color32, Rect}; +use std::sync::Arc; + +use super::panels::MockSpecs; /// The width of the dock column at the end edge. const SIDE_WIDTH: f32 = 220.0; @@ -30,7 +33,7 @@ const TOOLS_DOCK_WIDTH: f32 = 120.0; /// The tools of the rail. Each is a command of the `tools` group; a tool alone in its slot carries its letter, and the /// letter of a slot with several is the pick command of [`ToolKey`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[command(prefix = "mockTool")] #[non_exhaustive] pub enum Tool { @@ -403,13 +406,17 @@ impl Document { #[non_exhaustive] pub struct MockState { /// The dock's panels and where they sit. - pub workspace: Workspace, + pub workspace: Arc>, + /// The dock's panel specs. + pub specs: Tracked, /// The open document. pub document: Document, /// The current tool. pub tool: Tool, /// The tool each rail slot showed last. - pub last_used: LastUsed, + pub last_used: Tracked>, + /// The rail's slots. + pub slots: Tracked>>, /// The status bar's item. pub status_item: StatusItem, /// The status bar's message: the newest thing the mock had to say. @@ -433,10 +440,12 @@ impl Default for MockState { Node::split(Axis::X, SplitSize::Ratio(CANVAS_SHARE), Node::tabs(vec![Panel::Canvas], 0), Node::dock(DockEdge::End, vec![side, icons])); let root = Node::split(Axis::X, SplitSize::FixedFirst(TOOLS_DOCK_WIDTH), Node::dock(DockEdge::Start, vec![tools]), canvas); MockState { - workspace: Workspace::new(Layout::new(Some(root), Vec::new())), + workspace: Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))), + specs: Tracked::new(MockSpecs), document: Document::default(), tool: Tool::Move, - last_used: LastUsed::default(), + last_used: Tracked::new(LastUsed::default()), + slots: Tracked::new(Tool::slots()), status_item: StatusItem::DocumentDimensions, status: None, colors: ColorPair::default(), diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index 11f5b9cdd..dde2721b2 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -13,16 +13,16 @@ use craft_ui::canvas::{ tool_pass, }; use craft_ui::canvas_controls::{Guides, Marquee}; -use craft_ui::contract::SizeLimits; use craft_ui::contract::{ Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, MemoProps, MemoView, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SweepApply, SweepStep, ToggleColumn, WordSetCx as _, }; -use craft_ui::docking::{DockPanels, GroupAt, PanelSpec}; +use craft_ui::contract::{SizeLimits, Tracked}; +use craft_ui::docking::{DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs}; use craft_ui::list::{ListRow, ToggleCell}; use craft_ui::patterns::canvas::NavigatorPanel; use craft_ui::primitives::textures::Revision; -use craft_ui::rails::{LastUsed, ToolRail}; +use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::env::UnitKind; use craft_ui::shell::CanvasPanel; use craft_ui::table::Table; @@ -45,20 +45,23 @@ pub(super) struct Panels<'a> { pub(super) tool: Tool, pub(super) tools: &'a mut Tools, /// The tool each toolbar slot showed last; the toolbar writes it. - pub(super) last_used: &'a mut LastUsed, + pub(super) last_used: &'a mut Tracked>, + /// The toolbar's slots. + pub(super) slots: &'a Tracked>>, /// The tool the toolbar picked in this pass. pub(super) picked: Option, - /// The context the toolbar's grid is measured in. - pub(super) ctx: &'a egui::Context, } +/// The dock's panel specs: fixed for the mock's four panels. +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::PlainData)] +pub struct MockSpecs; + impl Panels<'_> { /// The toolbar's rail in the rect the dock gives it, or its height at a width: as many tool columns as the width /// holds. The rail's own padding surrounds the buttons, so no group padding applies. fn toolbar(&mut self, ui: &mut Ui, at: GroupAt) -> f32 { - let slots = Tool::slots(); - let (current, last_used) = (self.tool, self.last_used.clone()); - let rail = ToolRail::new("Tools", &slots, ¤t, &last_used); + let current = self.tool; + let rail = ToolRail::new("Tools", self.slots, ¤t, self.last_used); match at { GroupAt::Measure(width) => rail.measure_rail(ui, width, |_, _| {}).y, GroupAt::Show(rect) => { @@ -67,7 +70,7 @@ impl Panels<'_> { self.picked = output.select; } if let Some(next) = output.last_used { - *self.last_used = next; + **self.last_used = next; } rect.height() } @@ -92,13 +95,13 @@ fn name(panel: Panel) -> &'static str { } } -impl DockPanels for Panels<'_> { +impl PanelSpecs for MockSpecs { fn spec(&self, panel: &Panel) -> PanelSpec { let spec = PanelSpec::new(name(*panel)).limits(SizeLimits::default()); match panel { Panel::Canvas => spec.canvas(), // The toolbar's column is whole tool columns wide. - Panel::Tools => spec.grid(ToolRail::::dock_grid(self.ctx, Tool::slots().len())), + Panel::Tools => spec.grid(DockGrid::rail(Tool::slots().len())), _ => spec, } } @@ -111,7 +114,9 @@ impl DockPanels for Panels<'_> { _ => Permissions::ALL, } } +} +impl DockPanels for Panels<'_> { fn body(&mut self, panel: &Panel, ui: &mut Ui, cx: &mut BodyCx<'_>) { match panel { Panel::Navigator => { diff --git a/crates/ui-gallery/src/viewer/appearance.rs b/crates/ui-gallery/src/viewer/appearance.rs index 6de1556ce..6dc56fa8e 100644 --- a/crates/ui-gallery/src/viewer/appearance.rs +++ b/crates/ui-gallery/src/viewer/appearance.rs @@ -1,7 +1,7 @@ //! The choices of the options bar: the named options of each root value, the theme list and the Variants axes. use craft_i18n::Direction; -use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, ThemeDef, ThemeId, builtins}; +use craft_theme::{ComponentSet, ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, ThemeDef, ThemeId, builtins}; use craft_ui::contract::Entry; use craft_ui::runtime::env::Scale; @@ -66,6 +66,7 @@ choices!(TEXT_SIZES: TextSize = [ (TextSize::Large, "large", "Large"), ]); choices!(DENSITIES: Size = [(Size::Compact, "compact", "Compact"), (Size::Comfortable, "comfortable", "Comfortable")]); +choices!(SETS: ComponentSet = [(ComponentSet::Creative, "creative", "Creative"), (ComponentSet::Productivity, "productivity", "Productivity")]); choices!(MOTIONS: MotionChoice = [ (MotionChoice::Full, "full", "Off"), (MotionChoice::Reduced, "reduced", "On"), @@ -91,6 +92,8 @@ pub enum VariantAxis { Contrast, /// Compact and comfortable density. Size, + /// The creative and the productivity component set. + Set, /// Left to right and right to left. Direction, /// Small and medium controls. @@ -101,11 +104,12 @@ pub enum VariantAxis { impl VariantAxis { /// Every axis, in menu order. - pub const ALL: [VariantAxis; 7] = [ + pub const ALL: [VariantAxis; 8] = [ VariantAxis::Theme, VariantAxis::Mode, VariantAxis::Contrast, VariantAxis::Size, + VariantAxis::Set, VariantAxis::Direction, VariantAxis::ControlSize, VariantAxis::DirectionAndControlSize, @@ -118,6 +122,7 @@ impl VariantAxis { VariantAxis::Mode => "Every mode (light, dark)", VariantAxis::Contrast => "Every contrast (standard, high)", VariantAxis::Size => "Every size (compact, comfortable)", + VariantAxis::Set => "Every set (creative, productivity)", VariantAxis::Direction => "Every direction (LTR, RTL)", VariantAxis::ControlSize => "Every control size (Sm, Md)", VariantAxis::DirectionAndControlSize => "Every direction and control size", diff --git a/crates/ui-gallery/src/viewer/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/mod.rs b/crates/ui-gallery/src/viewer/mod.rs index 3f85b7a28..4c82ea4a7 100644 --- a/crates/ui-gallery/src/viewer/mod.rs +++ b/crates/ui-gallery/src/viewer/mod.rs @@ -10,7 +10,7 @@ mod state; mod tree; pub use appearance::{ - CONTRASTS, Choice, Choices, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, TEXT_SIZES, VariantAxis, theme_entries, theme_named, theme_of, + CONTRASTS, Choice, Choices, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, SETS, TEXT_SIZES, VariantAxis, theme_entries, theme_named, theme_of, }; pub use catalog::{Catalog, ComponentInfo, Declared, Entry, StoryGroup, display_name}; pub use commands::GalleryCommands; diff --git a/crates/ui-gallery/src/viewer/settings.rs b/crates/ui-gallery/src/viewer/settings.rs index fbeea01fb..4ac05a348 100644 --- a/crates/ui-gallery/src/viewer/settings.rs +++ b/crates/ui-gallery/src/viewer/settings.rs @@ -1,6 +1,6 @@ //! What the viewer keeps between runs, in the gallery's own `config.toml`. -use super::appearance::{CONTRASTS, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, TEXT_SIZES, theme_named}; +use super::appearance::{CONTRASTS, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, SETS, TEXT_SIZES, theme_named}; use super::catalog::Catalog; use super::layout; use super::state::{Preview, Viewer, Workspace}; @@ -25,6 +25,8 @@ pub struct GallerySettings { pub text_size: String, /// The density preset. pub density: String, + /// The component set. + pub set: String, /// The motion mode. pub motion: String, /// The interface scale in percent. @@ -68,6 +70,7 @@ impl GallerySettings { contrast: CONTRASTS.name(env.contrast).to_owned(), text_size: TEXT_SIZES.name(env.text_size).to_owned(), density: DENSITIES.name(env.density).to_owned(), + set: SETS.name(env.component_set()).to_owned(), motion: MOTIONS.name(env.motion).to_owned(), scale: SCALES.name(env.scale).to_owned(), direction: DIRECTIONS.name(env.direction).to_owned(), @@ -91,6 +94,7 @@ impl GallerySettings { env.contrast = CONTRASTS.parse(&self.contrast).unwrap_or(default.contrast); env.text_size = TEXT_SIZES.parse(&self.text_size).unwrap_or(default.text_size); env.density = DENSITIES.parse(&self.density).unwrap_or(default.density); + env.values.set(SETS.parse(&self.set).unwrap_or(default.component_set())); env.motion = MOTIONS.parse(&self.motion).unwrap_or(default.motion); env.scale = SCALES.parse(&self.scale).unwrap_or(default.scale); env.direction = DIRECTIONS.parse(&self.direction).unwrap_or(default.direction); 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-macros/src/props.rs b/crates/ui-macros/src/props.rs index 158382be1..e334f26f8 100644 --- a/crates/ui-macros/src/props.rs +++ b/crates/ui-macros/src/props.rs @@ -175,7 +175,7 @@ const COLLECTION: &[Forwarded] = &[ ("striped", "bool", "Odd rows are tinted: the item reads `ItemCx::row.striped`."), ("allow_empty", "bool", "A press on the empty space below the rows empties the selection."), ("lead_on_open", "$ui::contract::LeadOnOpen", "Where the lead lands when rows first show."), - ("lead_follows_hover", "bool", "The lead, and the selection with it, moves to the row under the pointer when the pointer moves."), + ("hover_lead", "$ui::contract::HoverLead", "What the pointer moving over the rows changes: nothing, the lead, or the lead and the selection."), ("arrows_select", "bool", "The arrow keys select the row they move the lead to; off, they move the lead only."), ("arrows_wrap", "bool", "The arrow keys wrap from the last item to the first and back."), ("type_ahead", "bool", "Typed letters move the lead to the next item whose text starts with them; off, they stay shortcut candidates."), diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index d01fa012f..4e487eefd 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -32,7 +32,7 @@ use bar::panel_names; pub(super) use bar::{BarRecord, CHEVRON, ColumnGrip, bar_band, bar_name, bar_slots, describe_chevron, paint_chevron, show_bar}; use sizing::group_sizes; -pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, stepped, width_bounds}; +pub use sizing::{GroupSize, column_cells, fit_widths, group_heights, scale_widths, stacked, width_bounds}; const DIVIDER: PartKey = PartKey::new("divider"); const EDGE: PartKey = PartKey::new("edge"); @@ -68,7 +68,7 @@ pub enum ColumnArrow { /// Collapses the column to icons, or expands it. #[default] Collapse, - /// Switches a stepped column ([`stepped`]) between one and two steps. Holds the steps it shows. + /// Switches a stepped column ([`DockSizes::stepped`](super::DockSizes::stepped)) between one and two steps. Holds the steps it shows. Steps(u16), /// Nothing: the column neither collapses nor has steps. It shows no double arrow, and its menu offers no /// collapse. @@ -78,11 +78,11 @@ pub enum ColumnArrow { impl ColumnArrow { /// The arrow of `column`: an expanded column whose panels do not collapse (`collapses` false) switches steps /// when it is stepped and has none otherwise; any other column collapses or expands. - pub fn of

(column: &Column

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

(column: &Column

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

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

(column: &Column

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

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> Option<(DockGrid, u16)> { + let steps = column.steps?; + let grid = column.panels().find_map(|panel| spec(panel).grid.map(|grid| grid.resolved(self)).filter(|grid| grid.valid()))?; + Some((grid, grid.clamp(steps))) + } } /// Column widths that add up to `total` as far as their bounds allow. Each entry is `(width, (lo, hi))`. The diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 4a94c1131..b08d63c16 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -409,12 +409,12 @@ impl DropTarget> for DockDro } } -/// The arrangement a dock drag started on: the dock area and the revision of the workspace it showed. +/// The arrangement a dock drag started on: the dock area and the generation of the workspace it showed. #[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct Arrangement { pub dock: Id, - pub revision: u64, + pub generation: u64, } /// The env value a dock area puts into its body: the arrangement it shows. `None` outside a dock area. @@ -463,9 +463,9 @@ where cx.start_drag(GroupDrag { unit, active, source: None, strip: Some(strip), started }, DragPreview::Named(label)); } -/// Ends a running tab or group drag that started on `shown`'s dock under another revision: another arrangement +/// Ends a running tab or group drag that started on `shown`'s dock under another generation: another arrangement /// replaced the workspace, and the panel or group the drag names may be gone or elsewhere. The dock's own edits keep -/// the revision, and so the drag. +/// the generation, and so the drag. #[doc(hidden)] pub fn end_replaced_drags(ctx: &Context, shown: Arrangement) { let replaced = |started: Option| started.is_some_and(|started| started.dock == shown.dock && started != shown); diff --git a/crates/ui-panels/src/docking/event.rs b/crates/ui-panels/src/docking/event.rs index 5fdfe8bcc..d0adf5976 100644 --- a/crates/ui-panels/src/docking/event.rs +++ b/crates/ui-panels/src/docking/event.rs @@ -1,7 +1,9 @@ //! `DockEvent`, `FloatSpace` and `HidePanels`: what a dock reports to the host and the host tells a dock. -use super::{DockCommands, DockSizes, DragUnit}; +use super::{DockCommands, DockSizes, DragUnit, PanelKey}; +use crate::contract::{MemoProps, Tracked}; use egui::{Rect, Vec2}; +use std::collections::BTreeSet; /// A request for host state outside the layout, or a report of where something ended up. #[derive(Clone, Debug, PartialEq, Eq)] @@ -42,24 +44,20 @@ pub enum DockEvent

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

Clone for HidePanels<'_, P> { - fn clone(&self) -> Self { - *self - } -} - -impl

Copy for HidePanels<'_, P> {} - /// Where a docking command floats a panel, group or column when it gives no rect. A dock records one each pass; /// the host reads it to turn a command into placements. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 1980e15bd..ba0c58ef9 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -9,7 +9,7 @@ use super::dock_column::{CHEVRON, ColumnArrow, describe_chevron, paint_chevron}; use super::drop::{DragUnit, start_group_drag}; -use super::{DockDropTarget, DockDropped, DockWords, GroupDrag, PanelDrag, PanelKey, native}; +use super::{DockDropTarget, DockDropped, DockSizes, DockWords, GroupDrag, PanelDrag, PanelKey, native}; use crate::contract::BodyCx; use crate::contract::SizeLimits; use crate::contract::overlay::{PlacementChange, PlacementKind, Popup, ResizeEdges}; @@ -53,14 +53,21 @@ pub struct FloatingGroupStyle { /// The column a dock's floating window holds. The window's title row is the column's bar: it shows the column's /// double arrow at the end on `edge`, and a collapsed column shows against that edge of the window's rect. +/// +/// A column whose content fixes its height ([`held`](Self::held)) shows at that height whatever the rect's, and the +/// rect keeps its own height for when the content no longer fixes it: a column collapsed to icons, and one whose +/// every group is minimized. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct WindowColumn { /// The edge of the float area, in reading order, that the window keeps to: the dock model's `Floating::edge`, /// else the one nearer the window. pub edge: DockEdge, - /// The size of the collapsed column under the title row; `None` while the column is expanded. - pub collapsed: Option, + /// The height of the column under the title row when its content fixes it: a collapsed column's icons, or the + /// tab strips of a column whose every group is minimized. `None` while the rect gives the height. + pub held: Option, + /// The width of the collapsed column; `None` while the column is expanded, and the rect gives the width. + pub collapsed: Option, /// The least and most width the sides of a collapsed column's window resize it to /// ([`DockSizes::iconic_bounds`](super::DockSizes::iconic_bounds)); unbounded while the column is expanded. pub widths: (f32, f32), @@ -74,20 +81,27 @@ pub struct WindowColumn { impl WindowColumn { /// An expanded column that keeps to `edge`. pub fn expanded(edge: DockEdge) -> Self { - WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } /// A column collapsed to icons, `size` under the title row, that keeps to `edge`. The window's sides resize its /// width within `widths`, as a docked collapsed column's inner edge does; its height stays `size`'s. pub fn collapsed(edge: DockEdge, size: Vec2, widths: (f32, f32)) -> Self { - WindowColumn { edge, collapsed: Some(size), widths, fitted: None, arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: Some(size.y), collapsed: Some(size.x), widths, fitted: None, arrow: ColumnArrow::Collapse } + } + + /// An expanded column whose every group is minimized, their strips `height` under the title row, that keeps to + /// `edge`. The window shows at its rect's place and width and that height; its sides resize the width, and the + /// rect keeps its height, which the window takes back once a group is restored. + pub fn minimized(edge: DockEdge, height: f32) -> Self { + WindowColumn { edge, held: Some(height), collapsed: None, widths: UNBOUNDED, fitted: None, arrow: ColumnArrow::Collapse } } /// An expanded column whose content is `size` under the title row, that keeps to `edge`. The window shows at /// that size at its rect's place; a resize the user makes is reported for the host to turn into the column's /// steps, and a move keeps the rect's size. pub fn fitted(edge: DockEdge, size: Vec2) -> Self { - WindowColumn { edge, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } + WindowColumn { edge, held: None, collapsed: None, widths: UNBOUNDED, fitted: Some(size), arrow: ColumnArrow::Collapse } } /// The column with the double arrow `arrow` ([`ColumnArrow::of`]). @@ -96,20 +110,25 @@ impl WindowColumn { self } - /// Where a window that keeps `rect` shows while its column is collapsed: the collapsed column under the window's - /// chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect` and against the edge the window keeps - /// to. `None` while the column is expanded. + /// Where a window that keeps `rect` shows while its content fixes its height ([`Self::held`]): the column under + /// the window's chrome, `chrome` tall (`DockSizes::window_chrome`), at the top of `rect`, as wide as a collapsed + /// column or else as `rect`, and against the edge the window keeps to. `None` while the rect gives the height. pub fn shown(self, rect: Rect, chrome: f32, rtl: bool) -> Option { - let size = self.collapsed? + Vec2::new(0.0, chrome); + let size = Vec2::new(self.collapsed.unwrap_or(rect.width()), self.held? + chrome); let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; Some(Rect::from_min_size(Pos2::new(left, rect.top()), size)) } - /// The rect a window that keeps `rect` keeps when it shows at `shown`: while collapsed, `rect` moved with the - /// collapsed column ([`Self::shown`]) so that the column's side on the edge the window keeps to stays on that side - /// of `rect`, whatever width the column shows at; `rect` keeps its expanded size. While expanded, `shown`. + /// The rect a window that keeps `rect` keeps when it shows at `shown`, so that it keeps its height while its + /// content fixes the shown one ([`Self::shown`]). While collapsed, `rect` moved with the collapsed column so that + /// the column's side on the edge the window keeps to stays on that side of `rect`, whatever width the column shows + /// at; `rect` keeps its expanded size. While every group is minimized, `shown`'s place and width with `rect`'s + /// height. Otherwise `shown`. pub fn kept(self, shown: Rect, rect: Rect, chrome: f32, rtl: bool) -> Rect { let Some(at) = self.shown(rect, chrome, rtl) else { return shown }; + if self.collapsed.is_none() { + return Rect::from_min_size(shown.min, Vec2::new(shown.width(), rect.height())); + } let dx = if at_left(self.edge, rtl) { shown.left() - at.left() } else { shown.right() - at.right() }; rect.translate(Vec2::new(dx, shown.top() - at.top())) } @@ -126,7 +145,8 @@ impl WindowColumn { /// at the same place against that edge ([`Self::around_strip`]); an expanded window keeps `rect`, and the edge /// nearer it (`None`). pub fn dropped(self, rect: Rect, bounds: Rect, rtl: bool) -> (Rect, Option) { - let Some(size) = self.collapsed else { return (rect, None) }; + let (Some(width), Some(height)) = (self.collapsed, self.held) else { return (rect, None) }; + let size = Vec2::new(width, height); let left = if at_left(self.edge, rtl) { rect.left() } else { rect.right() - size.x }; let (rect, edge) = Self::around_strip(Rect::from_min_size(Pos2::new(left, rect.top()), size), rect.size(), bounds, rtl); (rect, Some(edge)) @@ -199,7 +219,8 @@ impl Outcome for FloatingGroupOutput { /// in [`FloatingGroupOutput::collapsed_width`]) while its height stays the icons', and the rect keeps its size. A /// column its content sizes ([`WindowColumn::fitted`]) shows at that size at the rect's place; its resizes are /// reported as the user makes them, and in an OS window the app runs them, so the window takes only the size the -/// host gives it. +/// host gives it. A column whose every group is minimized ([`WindowColumn::minimized`]) shows at the rect's place +/// and width and its strips' height; its sides resize the width, and the rect keeps its height. /// - Docking: with [`window_of`](FloatingGroup::window_of) set, a move by the title starts a window-unit drag /// (`GroupDrag`) for the dock's `DockDropTarget`, which shows the drop mark and docks the window on release. /// - Window: with `native` set the group opens in an OS window of that kind, with the layer as the fallback where @@ -256,6 +277,10 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome, the rule under its title row included, is sized at that scale. + #[prop(quantity = "display scale, pixels per point")] + scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, /// Takes the drops released on the group, on the group's own layer. @@ -302,6 +327,7 @@ impl<'a> FloatingGroup<'a> { rtl: false, placed: None, collapsed_width: None, + scale: None, start_drag: None, take_drop: None, moving: false, @@ -348,11 +374,11 @@ impl<'a> FloatingGroup<'a> { /// Shows the group; `body` fills the area under the title row unless the group is minimized. pub fn show_group(mut self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { let env = Env::of(ui); - let header = title_row(&env.tokens); // A window in the app window keeps the band over its title row that a layer the user moves keeps for its top - // grip; an OS window's grips lie over its title row. - let band = if self.native.is_none() { crate::contract::grip_band(&env.tokens) } else { 0.0 }; - (self.header, self.chrome, self.rtl) = (header, header + band, env.direction.is_rtl()); + // grip; an OS window's grips lie over its title row. The rule under the title row takes a band of its own. + let sizes = DockSizes::style(&StyleCx::of_env(ui.ctx(), &env)); + let sizes = self.scale.map_or(sizes, |scale| sizes.at_scale(scale)); + (self.header, self.chrome, self.rtl) = (sizes.title_row, sizes.window_chrome(self.native.is_none()), env.direction.is_rtl()); let mount = self.mount(); self.props = self.props.mount(mount); let minimized = self.minimized; @@ -367,10 +393,15 @@ impl<'a> FloatingGroup<'a> { fn mount(&self) -> Mount { // The frame's limits are the body's with the chrome on top. let frame = self.limits.around(Vec2::new(0.0, self.chrome)); - let collapsed = self.collapsed_rect().zip(self.column.map(|column| column.widths)); + // A collapsed column's width stays within its own bounds, a minimized one's within the panels' limits. + let widths = self.column.map(|column| match column.collapsed { + Some(_) => column.widths, + None => (frame.min.x, frame.max.map_or(f32::INFINITY, |max| max.x)), + }); + let held = self.held_rect().zip(widths); let mut overlay = Overlay::floating().movable(true).resizable(!self.minimized).opacity(self.opacity).body_scroll(false); - overlay = if let Some((shown, (least, most))) = collapsed { - // The sides resize a collapsed column's width; its height is its icons'. + overlay = if let Some((shown, (least, most))) = held { + // The sides resize the column's width; its content fixes its height. let height = shown.height(); let edges = if self.minimized { ResizeEdges::NONE } else { ResizeEdges::LEFT.union(ResizeEdges::RIGHT) }; overlay.placed(shown).resize_edges(edges).size_limits(SizeLimits::new(Vec2::new(least, height), Vec2::new(most.max(least), height))) @@ -399,9 +430,9 @@ impl<'a> FloatingGroup<'a> { } } - /// Where the group shows while its column is collapsed: the collapsed column under the chrome, at the top of the - /// rect and against its edge the window keeps to. `None` while the column is expanded. - fn collapsed_rect(&self) -> Option { + /// Where the group shows while its column's content fixes its height ([`WindowColumn::shown`]). `None` while the + /// rect gives the height. + fn held_rect(&self) -> Option { self.column?.shown(self.rect, self.chrome, self.rtl) } @@ -524,14 +555,15 @@ impl Container for FloatingGroup<'_> { fn placement_changed(&mut self, change: &PlacementChange) { let mut change = *change; let fitted = self.column.is_some_and(|column| column.fitted.is_some()); - if let Some(column) = self.column.filter(|column| column.collapsed.is_some()) { - // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. + if let Some(column) = self.column.filter(|column| column.held.is_some()) { + // A resize of the collapsed window sets the column's width; the rect keeps its expanded size. A minimized + // window's rect takes the width and keeps its height. let resized = match change.kind { PlacementKind::Size(_) => true, - PlacementKind::Keyboard => self.collapsed_rect().is_some_and(|shown| change.rect.width() != shown.width()), + PlacementKind::Keyboard => self.held_rect().is_some_and(|shown| change.rect.width() != shown.width()), _ => false, }; - if resized { + if resized && column.collapsed.is_some() { self.collapsed_width = Some(change.rect.width()); } change.rect = column.kept(change.rect, self.rect, self.chrome, self.rtl); diff --git a/crates/ui-panels/src/docking/frame.rs b/crates/ui-panels/src/docking/frame.rs index e57718e4c..8201517d8 100644 --- a/crates/ui-panels/src/docking/frame.rs +++ b/crates/ui-panels/src/docking/frame.rs @@ -1,5 +1,6 @@ //! What the tree adds around the groups: Maximize Frame, the hidden-panel prune and the outer edge bands. +use super::PanelKey; use super::config::DockConfig; use super::event::HidePanels; use super::targets::{DockSizes, DockSpot, DockTargets}; @@ -27,6 +28,11 @@ pub struct FrameView<'a, P: Clone> { } impl FrameView<'_, P> { + /// The view with its layout owned, to keep it past the layout it was made from. + pub fn into_owned(self) -> FrameView<'static, P> { + FrameView { layout: Cow::Owned(self.layout.into_owned()), maximized: self.maximized, hidden: self.hidden, paths: self.paths } + } + /// Writes the split sizes of `edited`, an edit of the view's layout, into `layout`, the layout the view was made /// from. Panels the view left out keep their place; only the docked tree's split sizes change: floating windows /// have no splits. @@ -64,13 +70,13 @@ fn split_sizes

(node: &Node

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

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

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

::register(&cx.core.ctx, dock, DockSpot::tab(self.anchor.clone(), self.panels.as_slice().len()), strip); if self.minimized { return; } @@ -518,7 +518,7 @@ impl Container for } let row = TabRow { anchor: self.anchor.clone(), - panels: self.panels, + panels: self.panels.clone(), active: self.active, closable: self.closable, wheel_selects: self.wheel_selects_tabs, @@ -585,7 +585,8 @@ struct TabRow<'a, P> { /// The group's anchor panel, which names its drop spots. #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] anchor: P, - panels: &'a [PanelTitle], + #[memo_props(hash = "its Hash is the content key taken when the titles were made")] + panels: Titles, active: PanelKey, closable: bool, wheel_selects: bool, @@ -598,7 +599,7 @@ fn tab_row(row: &mu let env = crate::runtime::env::Env::of(ui); let name = Label::from(env.words::().panels.as_str().to_owned()); let rtl = env.direction.is_rtl(); - let (panels, active, closable) = (row.panels, row.active, row.closable); + let (panels, active, closable) = (row.panels.as_slice(), row.active, row.closable); let from = PanelKey::of(&row.anchor); let drags = crate::runtime::drag::started(ui.ctx()); let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str())); diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 4971991ec..6ab02daf3 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -205,7 +205,9 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// Whether Auto-Collapse Iconic Panels is on. #[prop] auto_collapse: bool, - /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. + /// The rect the dock may grow within, which bounds how wide its inner edge can make the column, and the rect its + /// flyouts open in. Unset, the flyouts take the room layers opened there have (`overlay::layer_room`): around a + /// palette window, the work area. #[prop] within: Rect, open: Bind<'a, Option

>, @@ -617,7 +619,7 @@ impl Component for IconicColumn<'_, P> { let (opens, auto_collapse, column) = (self.opens, self.auto_collapse, cx.rect); // The screen side the flyouts open on, mirrored in a right-to-left layout. let right = (opens == Side::End) != cx.flow.is_rtl(); - let within = if self.within.is_positive() { self.within } else { cx.core.ctx.content_rect() }; + let within = if self.within.is_positive() { self.within } else { crate::contract::overlay::layer_room(&cx.core.ctx) }; // The column side of the bounds stops at the column, so a saved width wider than the room keeps that side. let bounds = if right { within.with_min_x(within.min.x.max(column.right())) } else { within.with_max_x(within.max.x.min(column.left())) }; if !bounds.is_positive() { diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index ee98e4d2d..e3794a20f 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -38,7 +38,7 @@ pub use event::{DockEvent, FloatSpace, HidePanels}; pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook, MenuRows}; pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, WindowColumn}; -pub use panels::{DockPanels, request_actions}; +pub use panels::{DockPanels, PanelSpecs, SpecSource, request_actions}; #[doc(hidden)] pub use panels::{close_requests, open_requests}; pub use placed::{Placing, placed_rect, with_area_rules}; @@ -59,7 +59,7 @@ pub(crate) mod iconic; pub use dock_column::{ ColumnArrow, ColumnBar, DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, column_cells, fit_widths, group_heights, - group_rects, scale_widths, stacked, stepped, width_bounds, + group_rects, scale_widths, stacked, width_bounds, }; pub use flyout::{Flyout, FlyoutOutput, FlyoutShown, FlyoutStyle, GroupAt}; pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes}; @@ -79,12 +79,13 @@ use divider::{Divider, Drag}; use egui::{Rect, Response, Vec2}; use std::fmt::Debug; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; use tree::{FrameRules, SplitHandle}; const HANDLE: PartKey = PartKey::new("handle"); /// The stable key of a panel. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, crate::contract::MemoProps)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, crate::contract::MemoProps, crate::contract::PlainData)] #[non_exhaustive] pub struct PanelKey(pub u64); @@ -114,6 +115,34 @@ pub struct PanelTitle { pub closable: bool, } +/// The tab titles of one group with their content key, taken once when they are made: a memoized view that holds them +/// feeds that key, not the titles. A host keeps a group's titles in a derived value so the key is taken only when they +/// are rebuilt. +#[derive(Clone, Debug)] +pub struct Titles { + list: Arc>, + key: u128, +} + +impl Titles { + /// The titles `list`, keyed by their content: this call walks them. + pub fn from_content(list: Vec) -> Self { + Titles { key: crate::contract::MemoKey::of(&list), list: Arc::new(list) } + } + + /// The titles in tab order. + pub fn as_slice(&self) -> &[PanelTitle] { + &self.list + } +} + +/// Feeds the content key taken when the titles were made, not the titles. +impl Hash for Titles { + fn hash(&self, state: &mut H) { + self.key.hash(state); + } +} + impl PanelTitle { /// A panel `key` titled `title`, not closable from its tab. pub fn new(key: PanelKey, title: impl Into

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

`. +pub trait SpecSource

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

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

{ - /// What the dock reads of `panel`. - fn spec(&self, panel: &P) -> PanelSpec; - - /// What may happen to `panel`: whether it moves, floats, closes and takes tabs and splits (the default allows - /// everything). A canvas is `Permissions::PROTECTED`. A locked workspace narrows these itself. - fn permissions(&self, _panel: &P) -> Permissions { - Permissions::ALL - } - /// Shows `panel`'s body in `ui`: the group's body, inset from its edges by the panel padding. The group is the /// body's panel and its tab the body's title, so the body shows no framework `Panel` or padding of its own; content /// taller than the group scrolls in the body's own scrolling container. A document panel's body diff --git a/crates/ui-panels/src/docking/placed.rs b/crates/ui-panels/src/docking/placed.rs index c276de59b..c6f496872 100644 --- a/crates/ui-panels/src/docking/placed.rs +++ b/crates/ui-panels/src/docking/placed.rs @@ -3,7 +3,7 @@ use super::frame::maximize; use super::tree::{self, FrameRules}; -use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects, stepped}; +use super::{ColumnBar, DockSizes, HidePanels, PanelSpec, column_cells, group_rects}; use craft_behavior::Flow; use craft_behavior::dock::{Column, Layout, Node}; use egui::Rect; @@ -20,7 +20,7 @@ pub struct Placing<'a, P> { /// The panels that always show, such as a canvas. pub protected: &'a dyn Fn(&P) -> bool, /// The panels the area hides, as the shell's visibility leaves them. - pub hide: HidePanels<'a, P>, + pub hide: HidePanels<'a>, /// The panel whose frame the area shows maximized. pub maximized: Option<&'a P>, /// The floating window whose column the dock lays out, by its id; `None` for a dock area's docked tree. @@ -35,7 +35,7 @@ impl<'a, P> Placing<'a, P> { /// The area hides `hide` and shows the frame of `maximized` alone. #[must_use] - pub fn shown(mut self, hide: HidePanels<'a, P>, maximized: Option<&'a P>) -> Self { + pub fn shown(mut self, hide: HidePanels<'a>, maximized: Option<&'a P>) -> Self { self.hide = hide; self.maximized = maximized; self @@ -109,7 +109,7 @@ fn column_rects( if !column.panels().any(moves) { return Some(()); } - if column.iconic || stepped(column, placing.spec).is_some() { + if column.iconic || placing.sizes.stepped(column, placing.spec).is_some() { return None; } if column.panels().all(moves) { diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index b395cd6f0..2758a1cd1 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -1,5 +1,6 @@ //! `PanelSpec`: what the dock asks of a panel before it shows its body. +use super::DockSizes; use crate::contract::SizeLimits; use crate::primitives::IconSpec; use crate::runtime::env::Label; @@ -52,26 +53,61 @@ impl DockHeights { /// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as /// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag /// of the column's edge sets whole steps; the content lays out as many columns as fit the width it gets. +/// +/// A tool rail's grid is [`DockGrid::rail`]: the dock computes its widths from its own style +/// ([`resolved`](Self::resolved)), so the grid follows the theme and density without the panel's spec reading them. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct DockGrid { - /// The content's width at one column: a cell and the content's own padding on both sides. - pub first: f32, - /// The width each further column adds: a cell and the gap before it. - pub step: f32, + widths: GridWidths, /// The most columns the content fills, its cell count: more steps show it no wider. pub most: u16, } +/// The widths of a [`DockGrid`]'s columns. +#[derive(Clone, Copy, Debug, PartialEq)] +enum GridWidths { + /// `first`: the content's width at one column, a cell and the content's own padding on both sides; `step`: the + /// width each further column adds, a cell and the gap before it. + Content { first: f32, step: f32 }, + /// A tool rail's cells, sized by the dock's style. + Rail, +} + impl DockGrid { /// A grid `first` wide at one column, `step` wider for each further column, up to `most` columns. pub const fn new(first: f32, step: f32, most: u16) -> Self { - DockGrid { first, step, most } + DockGrid { widths: GridWidths::Content { first, step }, most } } - /// Whether the widths are finite and positive and the grid has a column. + /// The grid of a tool rail of `cells` cells: a rail button and the control padding on both sides at one column, + /// a button and the tight gap for each further column, in the style the dock shows it in. + pub fn rail(cells: usize) -> Self { + DockGrid { widths: GridWidths::Rail, most: u16::try_from(cells).unwrap_or(u16::MAX).max(1) } + } + + /// The grid with its widths in points: a [`rail`](Self::rail) grid takes the rail widths of `sizes`. + pub fn resolved(self, sizes: &DockSizes) -> Self { + match self.widths { + GridWidths::Content { .. } => self, + GridWidths::Rail => DockGrid::new(sizes.rail_first, sizes.rail_step, self.most), + } + } + + /// The content's width at one column and the width each further column adds; zero for a rail grid not yet + /// [`resolved`](Self::resolved). + fn first_step(self) -> (f32, f32) { + match self.widths { + GridWidths::Content { first, step } => (first, step), + GridWidths::Rail => (0.0, 0.0), + } + } + + /// Whether the widths are finite and positive and the grid has a column. A rail grid not yet + /// [`resolved`](Self::resolved) is not. pub fn valid(self) -> bool { - self.first.is_finite() && self.first > 0.0 && self.step.is_finite() && self.step > 0.0 && self.most > 0 + let (first, step) = self.first_step(); + first.is_finite() && first > 0.0 && step.is_finite() && step > 0.0 && self.most > 0 } /// `steps` kept between one column and [`most`](Self::most). @@ -81,7 +117,8 @@ impl DockGrid { /// The content's width at `steps` columns, kept within the grid's columns. pub fn width(self, steps: u16) -> f32 { - self.first + f32::from(self.clamp(steps) - 1) * self.step + let (first, step) = self.first_step(); + first + f32::from(self.clamp(steps) - 1) * step } /// The most columns whose width fits `width`, at least one. diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 71b53c765..3149f9795 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -4,9 +4,11 @@ use super::SplitFramesCx as _; use super::group::MENU; use super::stack::{StackSection, StackSections}; use super::tree::FrameRules; -use super::{DockCommands, DockGroup, DockPanels, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelTitle, SplitArea, Splitter, WindowMenuRows}; +use super::{ + DockCommands, DockGroup, DragUnit, GroupGrip, HANDLE, PanelKey, PanelSpec, PanelSpecs, PanelTitle, SplitArea, Splitter, Titles, WindowMenuRows, +}; use crate::contract::SizeLimits; -use crate::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, Validity}; +use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Tracked, Validity}; use crate::menu::{Menu, PanelRow}; use crate::runtime::commands::CommandRef; use crate::runtime::env::Message; @@ -45,7 +47,7 @@ fn dock(ui: &mut Ui, bind: Bind<'_, Layout>, shown: &Layout) -> St let Some(Node::Tabs { panels, .. }) = shown.place(&anchor).and_then(|place| shown.node_of(&place)) else { continue }; let panels = titles(panels); let active = panels.first().map_or(PanelKey::new(0), |panel| panel.key); - DockGroup::new(anchor, &panels, active).show_at(ui, rect, |_, _| ()); + DockGroup::new(anchor, Titles::from_content(panels.clone()), active).show_at(ui, rect, |_, _| ()); } }); area.output.edit.into() @@ -84,14 +86,14 @@ fn a_dock_of_one_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(DockGroup<'static, usize>, covers = [Default])] fn two_panels(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); - DockGroup::new(LAYERS, &panels, panels[0].key).show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).show(ui, |_, _| ()).output.into() } /// A group in a floating window: nothing goes beside it, so a drop on its body joins it or stacks above or below. #[story(DockGroup<'static, usize>, covers = [Default])] fn a_group_in_a_window(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); - DockGroup::new(LAYERS, &panels, panels[0].key).in_window().show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).in_window().show(ui, |_, _| ()).output.into() } /// A click on the panel menu button opens the group's panel menu. @@ -106,7 +108,7 @@ fn open_panel_menu(fixture: &mut Fixture) { fn panel_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); let rows = [DockCommands::FloatPanel, DockCommands::FloatGroup].map(|command| PanelRow::Command(CommandRef::from(command))).to_vec(); - DockGroup::new(LAYERS, &panels, panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, Titles::from_content(panels.clone()), panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() } #[story(GroupGrip, covers = [Default])] @@ -130,21 +132,20 @@ fn between_sections(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } /// The panels of the Window menu story: each labelled by its number. +#[derive(crate::contract::PlainData)] struct NumberedPanels; -impl DockPanels for NumberedPanels { +impl PanelSpecs for NumberedPanels { fn spec(&self, panel: &u32) -> PanelSpec { PanelSpec::new(format!("Panel {panel}")) } - - fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} } #[story(WindowMenuRows<'static, u32>, covers = [Default], drive = Drive::Never)] fn window_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let layout = Layout::new(Some(Node::tabs(vec![1], 0)), Vec::new()); let menu = Menu::new("Window").open(data.bind("open", true)).show(ui, |ui, _| { - WindowMenuRows::new(&layout, &NumberedPanels, &[1, 2]).show(ui); + WindowMenuRows::new(&layout, &Tracked::new(NumberedPanels), &[1, 2]).show(ui); }); StoryOutput::from(menu.output) } diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 7ab6ef704..ab44830f8 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -4,10 +4,10 @@ //! previous pass's registry, because a drop is decided against what was on screen when the pointer moved. Every //! zone is a rect. A spot names a group by an anchor panel, as the dock model does. -use super::{DragUnit, PanelKey, PanelSpec, scale_widths, stepped, width_bounds}; +use super::{DragUnit, PanelKey, PanelSpec, scale_widths, width_bounds}; use crate::contract::DropMark; use crate::runtime::frame::{self, PassStep, PerViewport, Stamped, Stored}; -use crate::style::StyleCx; +use crate::style::{RuleKind, RuleWidth, StyleCx}; use craft_behavior::DockSide; use craft_behavior::dock::{Action, Column, DockEdge, Layout, Node, ZoneSize, node_at, zones}; use egui::{Context, Id, Pos2, Rect, Vec2}; @@ -53,6 +53,12 @@ pub struct DockSizes { pub bar: f32, /// The height of a floating window's title row, which is the bar of the column the window holds. pub title_row: f32, + /// The divider rule a floating window draws under its title row, which the container lays out in a band of its + /// own: the rule's width in whole physical pixels on the window's display ([`Self::pixels_per_point`]). + pub title_rule: RuleWidth, + /// The display scale the sizes that depend on it are for: the running window's, or with [`Self::at_scale`] an OS + /// window's own. + pub pixels_per_point: f32, /// The band a floating window in the app window keeps clear over its title row for its top grip /// (`contract::grip_band`); an OS window keeps none. Every height of a window's body or content is the window's /// height less its chrome ([`Self::window_chrome`]). @@ -69,6 +75,11 @@ pub struct DockSizes { pub iconic_least: f32, /// The width of an expanded column the user has not resized (the dock column width). pub column: f32, + /// A tool rail's width at one column: a rail button and the control padding on both sides + /// ([`DockGrid::rail`](super::DockGrid::rail)). + pub rail_first: f32, + /// The width each further column of a tool rail adds: a rail button and the tight gap before it. + pub rail_step: f32, } impl DockSizes { @@ -78,6 +89,12 @@ impl DockSizes { StyleCx::with_root(ctx, DockSizes::style) } + /// The sizes in the style of the scope `ui` is in: what a dock shown in `ui` sizes with. + pub fn of_scope(ui: &egui::Ui) -> Self { + let env = crate::runtime::env::Env::of(ui); + Self::style(&StyleCx::of_env(ui.ctx(), &env)) + } + /// The sizes of the style context `cx`. pub fn style(cx: &StyleCx<'_>) -> Self { let size = &cx.tokens.size; @@ -96,6 +113,8 @@ impl DockSizes { strip: size.panel_header, bar: size.control.sm, title_row: super::floating::title_row(cx.tokens), + title_rule: cx.rule(RuleKind::Divider).width, + pixels_per_point: cx.frame_ctx().pixels_per_point(), top_band: crate::contract::grip_band(cx.tokens), least: size.panel_header, reach: size.hit.target, @@ -103,13 +122,28 @@ 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, } } - /// The height above a floating window's body: its title row and, for a window in the app window (`in_app`), the - /// band over it. + /// The height above a floating window's body: its title row, the rule under it and, for a window in the app + /// window (`in_app`), the band over it. pub fn window_chrome(&self, in_app: bool) -> f32 { - self.title_row + if in_app { self.top_band } else { 0.0 } + self.title_row + self.title_rule.points(self.pixels_per_point) + if in_app { self.top_band } else { 0.0 } + } + + /// The sizes for a window on a display of `pixels_per_point`: an OS window lays out at its own monitor's scale. + #[must_use] + pub fn at_scale(mut self, pixels_per_point: f32) -> Self { + self.pixels_per_point = pixels_per_point; + self + } + + /// The height of a column whose every group is minimized: their tab strips, as the column stacks them. `None` + /// while a group is open. + pub fn minimized_height

(&self, column: &Column

) -> Option { + column.groups.iter().all(|group| group.minimized).then_some(self.strip * column.groups.len() as f32) } /// The width bounds of an expanded column from the limits of its panels. @@ -120,9 +154,9 @@ impl DockSizes { /// The width an expanded column's panels draw at, whether the column is expanded or iconic (its flyout and a /// floated iconic column use it): the stored width kept within the panels' limits, or a stepped column's width - /// at its steps ([`stepped`]). + /// at its steps ([`DockSizes::stepped`](super::DockSizes::stepped)). pub fn expanded_width

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> f32 { - if let Some((grid, steps)) = stepped(column, spec) { + if let Some((grid, steps)) = self.stepped(column, spec) { return grid.width(steps); } let (lo, hi) = self.width_bounds(column, spec); @@ -141,7 +175,7 @@ impl DockSizes { pub fn shown_bounds

(&self, column: &Column

, spec: &dyn Fn(&P) -> PanelSpec) -> (f32, f32) { if column.iconic { self.iconic_bounds(column, spec) - } else if let Some((grid, _)) = stepped(column, spec) { + } else if let Some((grid, _)) = self.stepped(column, spec) { (grid.width(1), grid.width(grid.most)) } else { self.width_bounds(column, spec) @@ -175,7 +209,7 @@ impl DockSizes { Some(Node::Dock { columns, .. }) => columns, _ => return Vec::new(), }; - let fixed = |column: &Column

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

| !column.iconic && self.stepped(column, spec).is_some(); let current: Vec<(f32, (f32, f32))> = columns .iter() .map(|column| { @@ -201,7 +235,7 @@ impl DockSizes { columns .iter() .map(|column| { - let keeps = column.iconic || stepped(column, spec).is_some(); + let keeps = column.iconic || self.stepped(column, spec).is_some(); (self.width(column, spec), (!keeps).then(|| self.width_bounds(column, spec).0.max(1.0))) }) .collect() diff --git a/crates/ui-panels/src/docking/window_menu.rs b/crates/ui-panels/src/docking/window_menu.rs index 054037daa..8a0d29a51 100644 --- a/crates/ui-panels/src/docking/window_menu.rs +++ b/crates/ui-panels/src/docking/window_menu.rs @@ -1,6 +1,6 @@ //! `WindowMenuRows`: the Window menu's check row for every panel of an app. -use super::DockPanels; +use super::SpecSource; use crate::contract::Show as _; use crate::menu::MenuItem; use craft_behavior::dock::{Action, Layout, PanelState}; @@ -8,7 +8,7 @@ use egui::Ui; use std::hash::Hash; /// One check row per panel in the order the app gives, for a Window menu. A row is checked while its panel is in the -/// layout (closed panels are not), and its label and icon come from [`DockPanels::spec`]. A pick returns the action +/// layout (closed panels are not), and its label and icon come from the panels' specs ([`PanelSpecs::spec`](super::PanelSpecs::spec)). A pick returns the action /// that shows the panel (open a closed one, bring a panel behind another tab to the front) or closes it (a panel /// showing); the app applies it through the same path as the actions of a `DockArea`. A Hidden pick's `Action::open` /// restores the panel's last place through `Workspace::apply_all`. @@ -20,7 +20,7 @@ use std::hash::Hash; #[pattern(probe(WindowMenuRows<'static, u32>))] pub struct WindowMenuRows<'a, P> { layout: &'a Layout

, - panels: &'a dyn DockPanels

, + specs: &'a dyn SpecSource

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

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

, panels: &'a dyn DockPanels

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

, specs: &'a dyn SpecSource

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

{ let (mut action, mut flyout) = (None, None); for panel in self.order { - let spec = self.panels.spec(panel); + let spec = self.specs.spec(panel); let state = self.layout.panel_state(panel); let in_flyout = self.layout.opens_in_flyout(panel); let open = self.flyout == Some(panel); diff --git a/crates/ui-panels/src/rails/drawer/stories.rs b/crates/ui-panels/src/rails/drawer/stories.rs index eb22e6385..1218fe7c8 100644 --- a/crates/ui-panels/src/rails/drawer/stories.rs +++ b/crates/ui-panels/src/rails/drawer/stories.rs @@ -1,6 +1,7 @@ //! Stories of `ToolbarDrawer`. use super::{DrawerGroup, ToolbarDrawer}; +use crate::contract::Tracked; use crate::rails::tool::stories::{BRUSH, tools}; use crate::rails::tool::{LastUsed, ToolRail, ToolSlot}; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -11,8 +12,8 @@ use egui::Ui; #[story(ToolbarDrawer<'static, u8>, covers = [], drive = Drive::Never)] fn toolbar_drawer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let groups = [DrawerGroup::new("Drawing", tools(&[0, 1, 2])), DrawerGroup::new("Retouching", tools(&[3, 4]))]; - let slots = [ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))]; - let last = LastUsed::default(); + let slots = Tracked::new(vec![ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))]); + let last = Tracked::new(LastUsed::default()); let rail = ToolRail::new("Tools", &slots, &BRUSH, &last).edit_toolbar("Edit Toolbar").show_rail(ui, |_, _| {}); let open = data.value("open", false); let Some(opener) = rail.edit_toolbar.as_ref() else { return rail.into() }; diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index b59097803..900210f47 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -8,8 +8,8 @@ use crate::contract::{ Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, NoValue, Outcome, Pad, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, WordSetCx as _, }; -use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox}; -use crate::docking::DockGrid; +use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox, PlainData, Tracked}; +use crate::docking::{DockGrid, DockSizes}; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; use crate::runtime::access::Name; @@ -92,7 +92,7 @@ type FooterFn<'a> = Box; /// The rail of tool slots, laid out in a grid of columns: one `FlyoutButton` per visible slot showing the slot's shown /// tool, the slot with the current tool toggled on. A click selects the shown tool, a row of the flyout selects that /// tool. The rail takes as many columns as the width it gets holds, the most whole columns that fit -/// ([`dock_grid`](ToolRail::dock_grid)): it is `first` wide at one column and `step` wider for each further column, +/// ([`DockGrid::rail`] in the scope's style): it is a button and the control padding wide at one column and a button and the tight gap wider for each further column, /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button /// follows the last slot; the host's footer stays in view under the slots, which scroll when the room is short under @@ -102,14 +102,14 @@ type FooterFn<'a> = Box; /// grid. While the toolbar is edited the buttons are dragged and take drops, and report the drop in the output. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, probe(ToolRail<'static, u8>))] -pub struct ToolRail<'a, T: Value + MemoProps + 'static> { +pub struct ToolRail<'a, T: Value + MemoProps + PlainData + 'static> { #[common] common: Common, #[container] props: ContainerProps, - slots: &'a [ToolSlot], + slots: &'a Tracked>>, current: &'a T, - last_used: &'a LastUsed, + last_used: &'a Tracked>, /// The side of the rail its flyouts and drawer open on: the side of the canvas. #[prop] opens: Side, @@ -120,17 +120,17 @@ pub struct ToolRail<'a, T: Value + MemoProps + 'static> { #[prop(flag)] editing: bool, /// The tools the user's toolbar settings hide. - #[prop] - hidden: &'a [T], + #[prop(into)] + hidden: Option<&'a Tracked>>, footer: Option>, /// The columns the rail lays out in this pass. columns: usize, } -impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { +impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { /// A one-column rail named `label` over `slots`, with `current` the host's tool and `last_used` what the slots /// showed last. - pub fn new(label: impl Into

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

Outcome for DockAreaOutput

{ /// flyouts; a group is a `DockGroup`; a floating window is a `FloatingGroup` holding one column, shown as a dock's /// column is, whose bar is the window's title row. The host's `DockPanels` supplies the panels. /// - Edits: a divider drag and every [`Action`] of the pass (menu rows, drags, drops) are written to the workspace -/// through its binding, with the panels' [`DockPanels::permissions`] (narrowed when `locked`). The output lists the +/// through its binding, with the panels' [`SpecSource::permissions`](crate::docking::SpecSource::permissions) (narrowed when `locked`). The output lists the /// actions the workspace took, divider sizes and window moves included. A given workspace is not written. /// - Requests: while the pass runs, a body changes the workspace through /// [`request_actions`](crate::docking::request_actions); the output returns those actions unapplied in `requested`. @@ -108,18 +110,22 @@ impl

Outcome for DockAreaOutput

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

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

, panels: &'a mut dyn DockPanels

, config: DockConfig, /// Which panels the host hides. #[prop] - hide: HidePanels<'a, P>, + hide: HidePanels<'a>, /// The panel whose frame shows alone. #[prop] maximized: Option

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

>, panels: &'a mut dyn DockPanels

, config: DockConfig) -> Self { + /// A dock area named `label` over `workspace`, with its panels' specs from `specs`, their views from `panels` and + /// its behaviour from `config`. The root's id comes from the label under the parent's id, and inside an `AppShell` + /// from the window too, so two windows' docks never share state. Keep one `Arc` across frames and clone the `Arc`, + /// not the workspace: a new workspace value each frame is a new revision, which reads every spec each frame. + pub fn new + 'a>( + label: impl Into

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

, panels: &'a mut dyn DockPanels

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

, + config: DockConfig, + ) -> Self { + DockArea { locked: true, ..Self::new(label, Bind::given(Arc::clone(workspace)), specs, panels, config) } } } @@ -167,20 +187,23 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { struct AreaMemory

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

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

{ id: GestureId, - before: Workspace

, + before: Arc>, } impl

Default for AreaMemory

{ fn default() -> Self { - AreaMemory { open: None, moving: None } + AreaMemory { open: None, moving: None, window_floor: 0 } } } @@ -192,7 +215,7 @@ struct Drops<'a, P> { permissions: &'a dyn Fn(&P) -> Permissions, config: &'a DockConfig, specs: &'a HashMap, - hide: HidePanels<'a, P>, + hide: HidePanels<'a>, maximized: Option<&'a P>, rtl: bool, } @@ -232,9 +255,19 @@ struct Report

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

, @@ -254,6 +287,36 @@ fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) } +/// What an area derives from its workspace, its panels' specs and its lock, kept while none of them changes: whether +/// the workspace is valid, and for each panel in its layout the spec, the permissions (narrowed when locked) and the +/// key. +struct DockModel

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

{ + fn of(workspace: &Workspace

, specs: &dyn SpecSource

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

{ events: Vec>, focused: Option

, picked: Option

, - edit: EditEvents>, + edit: EditEvents>>, space: Option>, columns: Vec<(P, Rect)>, windows: Vec<(P, ViewportId)>, @@ -296,7 +359,7 @@ struct Look { /// What a group's header shows besides its panels' bodies: the tab titles, the panel menu's rows and whether the host /// gave any, and the panel commands' states. struct GroupParts { - titles: Vec, + titles: Titles, hosted: bool, states: Vec<(DockCommands, CommandState)>, } @@ -346,7 +409,7 @@ struct Pass<'s, P> { impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { /// Shows the area across the room offered. pub fn show(self, ui: &mut Ui) -> DockAreaOutput

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

(&ctx, shows); let dropped: RefCell>> = RefCell::new(None); let root = DockRoot::new(|cx| { @@ -397,26 +451,30 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { open_requests::

(&ctx); let shown = root.show(ui, |ui, body| { let Some(sizes) = body.style::>>().map(|style| *style.sizes()) else { return }; + let memory = body.memory::>(); + memory.window_floor = memory.window_floor.max(current.layout().window_floor()); let input = Input { id, ctx: &ctx, current: ¤t, config: &config, - specs: &specs, + specs: &model.specs, + keys: &model.keys, hide, + model: key, maximized: maximized.as_ref(), auto_collapse, sizes, rtl, }; - let mut result = show_area(ui, body, &input, &rights, &mut *panels, flyout.as_mut()); + let mut result = show_area(ui, body, &input, rights, &mut *panels, flyout.as_mut()); for edit in &result.edit { workspace.reborrow().write(body, edit); } result.actions.extend(dropped.take()); if !result.actions.is_empty() { let proposed = std::mem::take(&mut result.actions); - let applied = apply_actions(body, workspace.reborrow(), ¤t, &*panels, locked, &label, proposed); + let applied = apply_actions(body, workspace.reborrow(), ¤t, specs, locked, &label, proposed); result.actions = applied.actions; result.edit.extend(applied.edit); } @@ -459,27 +517,29 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { /// What the workspace took of a pass's actions. struct Applied

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

>, - current: &Workspace

, - panels: &dyn DockPanels

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

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

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

, + current: &'i Arc>, config: &'i DockConfig, specs: &'i HashMap, - hide: HidePanels<'i, P>, + keys: &'i HashMap, + hide: HidePanels<'i>, + model: ModelKey, maximized: Option<&'i P>, auto_collapse: bool, sizes: DockSizes, @@ -530,28 +592,30 @@ fn show_area( panels: &mut dyn DockPanels

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

>>, ) -> Passed

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

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

| layout.floating.iter().find(|window| window.contains(&anchor)).map(|window| (window.rect, window.edge)); if let Some((rect, edge)) = - event.landed().and_then(|landed| place_in(&landed.layout)).filter(|place| Some(*place) != place_in(¤t.layout)) + event.landed().and_then(|landed| place_in(landed.layout())).filter(|place| Some(*place) != place_in(current.layout())) { geometry.push(Action::move_floating_with_edge(anchor.clone(), rect, edge)); } @@ -857,6 +928,7 @@ impl Pass<'_, P> { } let shown = &members[active]; let words = body.words::(); + let ctx = ui.ctx().clone(); let panels = RefCell::new(&mut *self.panels); // The tab titles, the menu rows and the panel commands' states, built when the group runs. // The tab titles, whether the host gives menu rows and the panel commands' states, built once per pass; the @@ -864,10 +936,17 @@ impl Pass<'_, P> { let parts: OnceCell = OnceCell::new(); let parts_of = || { parts.get_or_init(|| { - let titles = members - .iter() - .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) - .collect(); + let key = (scene.view, PanelKey::of(anchor)); + // Keyed by their content once built, so a group's tab row replays unless its own titles changed. + let titles = derived(&ctx, scene.dock.with(("titles", key.1)), &key, || { + Titles::from_content( + members + .iter() + .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) + .collect(), + ) + }); + let titles = Titles::clone(&titles); let hosted = !panels.borrow_mut().panel_rows(shown).is_empty(); let permissions = |panel: &P| scene.permissions(panel); let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &permissions).floated(scene.floated), shown); @@ -879,7 +958,7 @@ impl Pass<'_, P> { let panels = &panels; let words = &words; let GroupParts { titles, hosted, states } = parts_of(); - let mut group = DockGroup::new(anchor.clone(), titles, PanelKey::of(&members[at])) + let mut group = DockGroup::new(anchor.clone(), titles.clone(), PanelKey::of(&members[at])) .extra(move |ui, body| panels.borrow_mut().group_header(members, at, ui, body)) .dock(self.dock) .zones(scene.config.zone_rule()) @@ -1029,7 +1108,7 @@ impl Pass<'_, P> { ) -> Option { let scene = self.scene; let spec_of = |panel: &P| scene.spec(panel); - let (grid, steps) = stepped(column, &spec_of)?; + let (grid, steps) = scene.sizes.stepped(column, &spec_of)?; let by_height = match change.kind { PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), _ => (change.rect.width() - fitted.x).abs() <= 0.5, @@ -1060,7 +1139,7 @@ impl Pass<'_, P> { fn stepped_height(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

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

) -> ColumnArrow { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); - ColumnArrow::of(column, &spec, column.panels().all(|panel| scene.permissions(panel).collapses)) + ColumnArrow::of(column, &scene.sizes, &spec, column.panels().all(|panel| scene.permissions(panel).collapses)) } /// What a click on the double arrow of `column`, whose first panel is `first`, asks for when it reports @@ -1145,7 +1224,7 @@ impl Pass<'_, P> { let scene = self.scene; let spec = |panel: &P| scene.spec(panel); if let Some(width) = work.width { - match stepped(column, &spec) { + match scene.sizes.stepped(column, &spec) { // The edge of a stepped column moves in whole steps: the most that fit where it is dragged. Some((grid, steps)) if !column.iconic => { let to = grid.steps_within(width); @@ -1191,6 +1270,10 @@ impl Pass<'_, P> { /// where it would sit in the app window ([`native::in_app`]), and the end of each of its moves and resizes records /// that rect and edge; its placement keeps its expanded rect while its column is collapsed ([`WindowColumn::kept`]). /// + /// A window whose every group is minimized shows its title row and their strips at its rect's place and width + /// ([`WindowColumn::minimized`]): its sides resize its width, and its placement keeps its expanded height, so a + /// restore shows it at that height again. + /// /// A window whose column has steps ([`stepped`]) is as wide as its steps and as tall as its content at that /// width, at its rect's place: a drag of its side sets the most steps that fit the width, one of its top or /// bottom the fewest whose content fits the height, and the window keeps its place; a drag of its left side keeps @@ -1218,6 +1301,14 @@ impl Pass<'_, P> { let dock = scene.dock.with(("floating", window.id)); let group_id = dock.with("window"); let opening = native::opening(&ctx, scene.config, window, &specs, group_id); + // An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the + // main window's. + let scale = opening + .spec + .as_ref() + .and_then(|_| WindowHost::of(&ctx).viewport_of(group_id)) + .and_then(|viewport| native::pixels_per_point(&ctx, viewport)); + let window_sizes = scale.map_or(scene.sizes, |scale| scene.sizes.at_scale(scale)); let movable = rights.iter().all(|rights| rights.movable); // The title row is the column's bar: its double arrow and Close; the menu opens from a context request on // its band. @@ -1251,6 +1342,8 @@ impl Pass<'_, P> { WindowColumn::collapsed(edge, size, scene.sizes.iconic_bounds(&window.column, &spec_of)) } else if let Some(content) = self.stepped_height(ui, body, &window.column, width, true) { WindowColumn::fitted(edge, Vec2::new(width, content)) + } else if let Some(strips) = scene.sizes.minimized_height(&window.column) { + WindowColumn::minimized(edge, strips) } else { WindowColumn::expanded(edge) } @@ -1264,6 +1357,9 @@ impl Pass<'_, P> { .takes_drops(target, &dropped) .command_scope(DockCommands::SCOPE) .id(group_id); + if let Some(scale) = scale { + group = group.scale(scale); + } group = match opening.spec.clone() { Some(window_spec) => group.native(window_spec), None => group.bounds(scene.bounds), @@ -1284,7 +1380,10 @@ impl Pass<'_, P> { while let Some((command, _)) = body.take_command::() { commands.push(command); } - let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within: scene.bounds, open: open.clone() }; + // An OS window's flyouts and other layers take the room around the window (`overlay::layer_room`); an + // in-app window's stay in the float area. + let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds }; + let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone() }; self.column(ui, body, &window.column, at); }); self.dock = area_dock; @@ -1294,8 +1393,9 @@ impl Pass<'_, P> { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); } - // The height above the window's body: the title row, and in the app window the band over it. - let chrome = scene.sizes.window_chrome(opening.spec.is_none()); + // The height above the window's body at its scale: the title row, the rule under it, and in the app window + // the band over it. + let chrome = window_sizes.window_chrome(opening.spec.is_none()); // A resize of a window whose column has steps: the steps it sets, and the window's rect at them. let resized = output .placed @@ -1327,8 +1427,11 @@ impl Pass<'_, P> { let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl)); self.report.actions.extend(reported); } - } else if let Some(mut change) = output.placed { - // A collapsed window keeps the edge its move began with until the move ends where its strip was dropped. + } else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit) + { + // The layer host shows a window its title row moves under the pointer, so the move reaches the workspace + // once, when it ends: one edit. A collapsed window keeps its edge until then, and the move ends where its + // strip was dropped. let mut keeps = shape.collapsed.map(|_| edge); if change.phase == GesturePhase::Commit && output.collapsed_width.is_none() { (change.rect, keeps) = shape.dropped(change.rect, scene.bounds, scene.rtl); @@ -1391,26 +1494,27 @@ fn split_changes

(from: &Node

, to: &Node

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

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

, label: Arc, -) -> Option>> { +) -> Option>>> { let moved = || { - let mut next = current.clone(); + let mut next = Workspace::clone(current); let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL); - next.apply(action.clone(), false, policy).ok().map(|_| next) + next.apply(action.clone(), false, policy).ok().map(|_| Arc::new(next)) }; let begin = |moving: &mut Option>| { let id = crate::runtime::edit::next_gesture_id(ctx); - *moving = Some(Moving { id, before: current.clone() }); - EditEvent::begin(id, Mixed::Same(current.clone()), Arc::clone(&label), None) + *moving = Some(Moving { id, before: Arc::clone(current) }); + EditEvent::begin(id, Mixed::Same(Arc::clone(current)), Arc::clone(&label), None) }; match phase { GesturePhase::Begin => Some(begin(moving)), @@ -1420,7 +1524,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..0c2a31a27 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); } @@ -89,36 +96,45 @@ impl DockPanels for Demo { } /// A canvas between a start dock, a toolbar column one step wide and a column of panels, and an iconic column at the -/// end, with one floating group and one floating window collapsed to icons. -fn workspace() -> Workspace { +/// end, with one floating group, `minimized` or not, and one floating window collapsed to icons. +fn workspace(minimized: bool) -> 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 mut window = Floating::single(1, vec![HISTORY], 0, WINDOW); + window.column.groups[0].minimized = minimized; + 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 { - let (workspace, workspace_at) = data.value_at("workspace", workspace()); - DockArea::new("Dock", workspace_at.bind(&mut *workspace), demo, DockConfig::default()).show(ui).into() +fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo, minimized: bool) -> 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(minimized)); + DockArea::new("Dock", workspace_at.bind(&mut *workspace), &*SPECS, demo, DockConfig::default()).show(ui).into() } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn docked_columns_a_floating_group_and_a_flyout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn a_canvas_group_the_host_draws(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }) + dock(ui, data, &mut Demo { canvas_view: true, host_rows: false }, false) } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] fn host_rows_above_the_dock_rows_in_a_panel_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }) + dock(ui, data, &mut Demo { canvas_view: false, host_rows: true }, false) +} + +/// The floating group minimized: its window shows the title row and the tab strip at its width. +#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] +fn a_minimized_floating_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + dock(ui, data, &mut Demo { canvas_view: false, host_rows: false }, true) } diff --git a/crates/ui-patterns/src/patterns/dock/hide.rs b/crates/ui-patterns/src/patterns/dock/hide.rs index 7ea931261..944613d3b 100644 --- a/crates/ui-patterns/src/patterns/dock/hide.rs +++ b/crates/ui-patterns/src/patterns/dock/hide.rs @@ -1,39 +1,27 @@ //! The hidden-panel prune of a dock area: what the host hides, the shell's panel visibility and Maximize Frame -//! decide which panels the area shows. +//! decide which panels the area shows. The area derives the pruned layout under a [`PruneKey`] and keeps it while the +//! key holds. -use crate::docking::HidePanels; -use crate::docking::frame::{FrameView, maximize}; +use super::area::ModelKey; +use crate::docking::{HidePanels, PanelKey}; use crate::runtime::env::ShellCx; -use craft_behavior::dock::Layout; -use std::hash::Hash; -/// The layout as the area shows it, and whether its floating windows show. -pub(super) struct Shown<'a, P: Clone> { - /// The pruned layout with its write-back map. - pub(super) view: FrameView<'a, P>, - /// Floating windows show: the shell shows them, or it hides the panels and the view keeps what the host names. +/// What the pruned layout is a function of: the workspace, the specs and the lock (the protected panels), what is +/// hidden after the shell's visibility, whether floating windows show and the maximized panel. +#[derive(crate::contract::MemoProps)] +pub(super) struct PruneKey<'h> { + pub(super) model: ModelKey, + pub(super) hide: HidePanels<'h>, pub(super) floating: bool, -} - -/// `layout` with the host's `hide`, the shell's panel visibility and the frame of `maximized` applied. Protected -/// panels always stay, so a canvas shows while the dock is hidden. While the shell hides the panels and keeps the -/// tools (Shift+Tab), the panels the host's `HidePanels::Except` names stay, docked or floating, and every other panel -/// hides; while the shell hides the dock (Tab, body-only mode), every panel hides. Size edits made on the view go back -/// through `FrameView::write_back`. -pub(super) fn shown<'a, P: Clone + Eq + Hash>( - layout: &'a Layout

, - maximized: Option<&P>, - hide: HidePanels<'_, P>, - shell: Option<&ShellCx>, - protected: &dyn Fn(&P) -> bool, -) -> Shown<'a, P> { - let (hide, floating) = resolved(hide, shell); - Shown { view: maximize(layout, maximized, hide, protected), floating } + pub(super) maximized: Option, } /// The panels the area hides, the host's `hide` with the shell's panel visibility applied, and whether floating windows -/// show (see [`shown`]). -pub(super) fn resolved<'h, P>(hide: HidePanels<'h, P>, shell: Option<&ShellCx>) -> (HidePanels<'h, P>, bool) { +/// show. Protected panels always stay, so a canvas shows while the dock is hidden. While the shell hides the panels and +/// keeps the tools (Shift+Tab), the panels the host's `HidePanels::Except` names stay, docked or floating, and every +/// other panel hides; while the shell hides the dock (Tab, body-only mode), every panel hides. Size edits made on the +/// pruned view go back through `FrameView::write_back`. +pub(super) fn resolved<'h>(hide: HidePanels<'h>, shell: Option<&ShellCx>) -> (HidePanels<'h>, bool) { match shell { None => (hide, true), Some(shell) if shell.panels_hidden() => (if let HidePanels::Except(keep) = hide { HidePanels::Except(keep) } else { HidePanels::All }, true), diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 92f838b93..1a0caefeb 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -2,7 +2,7 @@ //! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview. use super::fields::{DialogFields, FieldValue}; -use crate::patterns::presets::{PresetKind, PresetRow}; +use crate::patterns::presets::{PresetKind, PresetRow, PresetSource}; use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest}; use super::form::{FormDialog, FormDialogWords}; @@ -243,9 +243,10 @@ pub struct ParamDialog<'a> { /// dialog open; a press comes back as `ParamDialogOutput::footer_action`. #[prop] extra_buttons: Vec<(String, Label)>, - /// The patterns the dialog's [`ParamKind::Pattern`] rows offer. + /// The patterns the dialog's [`ParamKind::Pattern`] rows offer. A hosted dialog's build gives a source over + /// owned inputs. #[prop] - patterns: Cow<'a, [PresetRow]>, + patterns: Option>, /// A muted line at the footer's start edge, left of the buttons (a file size estimate, say). #[prop(into)] footer_note: Option

for Numbered { + fn spec(&self, panel: &P) -> craft_ui::docking::PanelSpec { + craft_ui::docking::PanelSpec::new(format!("Panel {panel}")) + } +} diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 681d42e1e..2cc0dd9c8 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -4,18 +4,20 @@ 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::Role; +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; use craft_ui::runtime::drag; +use craft_ui::testing::access::AccessTree; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; -use craft_ui_test_kit::windows::Windows; +use craft_ui_test_kit::windows::{Out, Windows}; use egui::{Event, HoveredFile, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo}; use std::sync::Arc; @@ -24,18 +26,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 +69,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 +86,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 +101,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 +136,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 +162,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 +180,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 +200,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 +242,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,23 +253,28 @@ 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, + /// The palette's window: the first child window the dock opened. + palette: Option, + /// The tree the palette window's pass produced in the last frame. + palette_tree: Option, } impl NativeDock { 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 +282,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, palette: None, palette_tree: None }; for _ in 0..3 { dock.frame(vec![]); } @@ -282,12 +300,18 @@ 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) { + if self.palette.is_none() { + self.palette = out.builders.iter().map(|(viewport, _)| *viewport).find(|viewport| *viewport != ViewportId::ROOT); + } + let palette = self.palette; + self.palette_tree = out.trees.into_iter().find(|(viewport, _)| Some(*viewport) == palette).map(|(_, tree)| tree); + for (_, builder) in out.builders.into_iter().filter(|(viewport, _)| Some(*viewport) == palette) { match self.builder.as_mut() { Some(kept) => { let _ = kept.patch(builder); @@ -295,7 +319,7 @@ impl NativeDock { None => self.builder = Some(builder), } } - let commands = out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect(); + let commands = out.commands.into_iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command).collect(); (actions, commands) } } @@ -479,7 +503,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 +539,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 +552,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 +590,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 +601,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 +651,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 +665,10 @@ fn a_native_palette_collapsed_moved_and_expanded_comes_back_at_its_size() { let sent = follow(&mut dock, &mut at, 4); assert!(placing(&sent).is_empty(), "the strip stays where it was dropped: {:?}", placing(&sent)); assert_eq!(at, dropped); - assert_eq!(dock.workspace.layout.floating[0].edge, Some(DockEdge::Start), "it keeps to the edge nearer the strip"); + assert_eq!(dock.workspace.layout().floating[0].edge, Some(DockEdge::Start), "it keeps to the edge nearer the strip"); assert_eq!(Vec2::from(recorded(&dock).normal.size), expanded, "moved, the model keeps the expanded size"); - dock.workspace.apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, false), false, |_| Permissions::ALL).expect("the column expands"); let sent = follow(&mut dock, &mut at, 3); assert!(sent.contains(&ViewportCommand::InnerSize(expanded)), "the window takes its expanded size back: {:?}", placing(&sent)); assert_eq!(at.min, dropped.min, "it opens from the strip's place, against the start edge"); @@ -667,7 +691,7 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() dock.windows.child_info(info(true, *at)); commands }; - dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); for _ in 0..3 { follow(&mut dock, &mut at, vec![]); } @@ -696,7 +720,7 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() for _ in 0..3 { sent.extend(follow(&mut dock, &mut at, vec![])); } - let palette = &dock.workspace.layout.floating[0]; + let palette = &dock.workspace.layout().floating[0]; assert!(palette.column.iconic_width.is_some_and(|kept| (kept - width).abs() <= 0.5), "the column keeps the width: {:?}", palette.column); let recorded = palette.native.clone().expect("the model records the window"); assert_eq!(Vec2::from(recorded.normal.size), FLOAT_AT.size(), "the model keeps the expanded size"); @@ -704,6 +728,68 @@ fn a_collapsed_native_palette_on_macos_is_resized_by_appkit_in_its_width_only() assert_eq!(at.width(), width, "the window keeps the width the OS gave it"); } +/// A native palette whose every group is minimized shrinks to its title row and tab strip at its place and width. +/// The OS resizes its width and never its height: AppKit takes the height as fixed, and the app sends no size back +/// for the width the OS gave it. The model keeps the expanded height throughout, and restored, the window takes that +/// height back at the width it was given. +#[trial] +fn a_minimized_native_palette_keeps_its_width_resizable_and_comes_back_at_its_height() { + for os in [Os::Mac, Os::Windows] { + let mut dock = NativeDock::on(os, Arc::new(FakeSystem::new())); + let expanded = FLOAT_AT.size(); + let mut at = FLOAT_AT; + // The OS follows the window commands of each frame, within the limits in force, and the window reports where it is. + let follow = |dock: &mut NativeDock, at: &mut Rect, frames: usize| { + let mut sent = Vec::new(); + for _ in 0..frames { + let mut max = dock.builder.as_ref().and_then(|builder| builder.max_inner_size); + let commands = dock.frame(vec![]).1; + for command in &commands { + match command { + ViewportCommand::MaxInnerSize(limit) => max = Some(*limit), + ViewportCommand::InnerSize(size) => *at = Rect::from_min_size(at.min, max.map_or(*size, |max| size.min(max))), + ViewportCommand::OuterPosition(to) => *at = Rect::from_min_size(*to, at.size()), + _ => {} + } + } + dock.windows.child_info(info(true, *at)); + sent.extend(commands); + } + sent + }; + let recorded = + |dock: &NativeDock| Vec2::from(dock.workspace.layout().floating[0].native.clone().expect("the model records the window").normal.size); + Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, true), false, |_| Permissions::ALL).expect("the group minimizes"); + follow(&mut dock, &mut at, 3); + let strips = at; + assert!(strips.height() < expanded.y / 4.0, "{os:?}: the window shrinks to its title row and strip: {strips:?}"); + if let Err(fit) = fits_exactly(dock.palette_tree.as_ref().expect("the palette ran a pass"), strips.size(), Role::TAB_LIST) { + panic!("{os:?}: the minimized window fits its title row and strip: {fit}"); + } + assert_eq!((strips.min, strips.width()), (FLOAT_AT.min, expanded.x), "{os:?}: at its place and width"); + assert_eq!(recorded(&dock), expanded, "{os:?}: minimized, the model keeps the expanded size"); + let builder = dock.builder.clone().expect("the palette's window opened"); + let (least, most) = (builder.min_inner_size.expect("a least size"), builder.max_inner_size.expect("a most size")); + assert!(least.y == most.y && (least.y - strips.height()).abs() <= 0.5, "{os:?}: the height is fixed: {least:?}..{most:?}, {strips:?}"); + assert!(least.x < most.x, "{os:?}: the width resizes: {least:?}..{most:?}"); + if os == Os::Mac { + assert_eq!(builder.resizable, Some(true), "AppKit resizes the minimized window"); + } + + // The OS widens the window. + let width = expanded.x + 60.0; + at = Rect::from_min_size(at.min, Vec2::new(width, at.height())); + dock.windows.child_info(info(true, at)); + let sent = follow(&mut dock, &mut at, 3); + assert!(!sent.iter().any(|command| matches!(command, ViewportCommand::InnerSize(_))), "{os:?}: no size goes back: {sent:?}"); + assert_eq!(recorded(&dock), Vec2::new(width, expanded.y), "{os:?}: the model takes the width and keeps the expanded height"); + + Arc::make_mut(&mut dock.workspace).apply(Action::set_minimized(1, false), false, |_| Permissions::ALL).expect("the group restores"); + follow(&mut dock, &mut at, 3); + assert_eq!(at, Rect::from_min_size(FLOAT_AT.min, Vec2::new(width, expanded.y)), "{os:?}: restored, the window takes its height back"); + } +} + /// On a display at 125 % (Windows), a click on the double arrow of a native palette collapsed to icons expands its /// column, and the OS window takes its expanded size. #[trial] @@ -720,11 +806,11 @@ fn a_click_on_the_double_arrow_of_a_collapsed_native_palette_expands_it() { actions }; frame(&mut dock, &mut at, vec![]); - dock.workspace.apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); for _ in 0..3 { frame(&mut dock, &mut at, vec![]); } - assert!(dock.workspace.layout.floating[0].column.iconic, "the column is collapsed"); + assert!(dock.workspace.layout().floating[0].column.iconic, "the column is collapsed"); assert!(at.width() < FLOAT_AT.width(), "the OS window shows the strip: {at:?}"); // The double arrow is the title row's square at the end the strip keeps to: a point just inside its outer corner. @@ -734,20 +820,256 @@ 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"); } +/// Panels whose palette panel's body records, in each of its real runs, the viewport it runs in. +#[derive(Default)] +struct BodyProbe(Vec); + +impl DockPanels for BodyProbe { + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + let ctx = ui.ctx(); + if *panel == 1 && !craft_ui::testing::is_measuring(ctx) { + self.0.push(ctx.viewport_id()); + } + } +} + +/// The scale of the display the collapsed palette trials run on: Windows at 125 %, where the issue was reported. +const COLLAPSED_SCALE: f32 = 1.25; + +/// A native palette collapsed to icons on Windows at 125 %, and the rect its OS window shows the strip at. +fn collapsed_palette() -> (NativeDock, Rect) { + let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + // Both windows report the display at 125 % before the column collapses. + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE)); + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..4 { + collapsed_frame(&mut dock, &mut BodyProbe::default(), &mut at, vec![], vec![]); + } + (dock, at) +} + +/// One frame of `dock` with `panels`, `root` events for the main window and `child` events for the palette's window, +/// whose OS window follows its commands at `at`: the frame's output. +fn collapsed_frame(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect, root: Vec, child: Vec) -> Out { + let workspace = &mut dock.workspace; + let specs = &dock.specs; + let out = dock.windows.frame(root, child, |ui| { + let _ = DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui); + }); + let palette = dock.palette; + let commands: Vec = + out.commands.iter().filter(|(viewport, _)| Some(*viewport) == palette).map(|(_, command)| command.clone()).collect(); + *at = placed_by(&commands, *at); + dock.windows.child_info(scaled(true, *at, COLLAPSED_SCALE)); + out +} + +/// The windows the frame showed other than the main window and the palette's: its popup windows. +fn popups(dock: &NativeDock, out: &Out) -> Vec { + out.builders.iter().map(|(viewport, _)| *viewport).filter(|viewport| *viewport != ViewportId::ROOT && Some(*viewport) != dock.palette).collect() +} + +/// The rect of `viewport`'s window in desktop points, as the window system reports it. +fn window_rect(dock: &NativeDock, viewport: ViewportId) -> Rect { + dock.windows.facts(viewport).inner_rect.expect("the window reports its rect") +} + +/// The rect, in its window's points, of the node of `tree` named `name` whose role is `role`. +fn node_rect(tree: &AccessTree, name: &str, role: Role) -> Option { + tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) == Some(role)).and_then(|key| tree.bounds_of(key)) +} + +/// How far a node's edge may stray from the window's for float rounding: far under a pixel at any scale. +const FIT_ROUNDING: f32 = 0.05; + +/// Whether a window `size` big fits what its pass shows in `tree` exactly: every node lies inside it, and the lowest +/// node of `role` ends at its bottom, within float rounding. +fn fits_exactly(tree: &AccessTree, size: Vec2, role: Role) -> Result<(), String> { + let window = Rect::from_min_size(Pos2::ZERO, size); + let outside: Vec = + tree.keys().into_iter().filter_map(|key| tree.bounds_of(key)).filter(|rect| !window.expand(FIT_ROUNDING).contains_rect(*rect)).collect(); + let bottom = tree.with_role(role).into_iter().filter_map(|key| tree.bounds_of(key)).map(|rect| rect.max.y).fold(f32::MIN, f32::max); + if !outside.is_empty() { + return Err(format!("nodes past the {size:?} window: {outside:?}")); + } + if (bottom - size.y).abs() > FIT_ROUNDING { + return Err(format!("the content ends at {bottom}, the {size:?} window at {}", size.y)); + } + Ok(()) +} + +/// The role and name of each named node of `tree`. +fn nodes(tree: &AccessTree) -> Vec<(Option, String)> { + let mut nodes: Vec<(Option, String)> = + tree.keys().into_iter().filter_map(|key| tree.name_of(key).map(|name| (tree.role_of(key), name.to_owned()))).collect(); + nodes.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + nodes +} + +/// The tree the frame's pass of `viewport` produced. +fn tree_of_viewport(out: &Out, viewport: ViewportId) -> &AccessTree { + &out.trees.iter().find(|(shown, _)| *shown == viewport).expect("the viewport ran a pass").1 +} + +/// Opens the flyout of the collapsed palette's panel by a click on its icon; returns the flyout's popup window. +fn open_flyout(dock: &mut NativeDock, panels: &mut dyn DockPanels, at: &mut Rect) -> ViewportId { + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let icon = node_rect(tree_of_viewport(&out, palette), PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon").center(); + for events in [vec![moved(icon)], vec![press(icon)], vec![release(icon)]] { + collapsed_frame(dock, panels, at, vec![], events); + } + let out = collapsed_frame(dock, panels, at, vec![], vec![]); + let opened = popups(dock, &out); + assert_eq!(opened.len(), 1, "the click opens one popup window: {opened:?}"); + opened[0] +} + +/// A click on the icon of a native palette collapsed to icons opens the panel's flyout in a popup OS window of its +/// own, beside the strip against its side away from the edge it keeps to, in desktop points: a palette-level window +/// with no taskbar entry that takes the focus. The flyout's body runs in the popup's pass only, as often in each +/// frame, never in the palette's. +#[trial] +fn a_click_on_an_icon_of_a_collapsed_native_palette_opens_its_flyout_in_an_os_window_beside_it() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let palette = dock.palette.expect("the palette's window opened"); + let strip = nodes(tree_of_viewport(&collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]), palette)); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let flyout = window_rect(&dock, popup); + let end = at.max.x >= FLOAT_AT.max.x - 1.0; + let outer = if end { (flyout.max.x - at.min.x).abs() } else { (flyout.min.x - at.max.x).abs() }; + assert!(outer <= 0.5, "the flyout stands against the strip's side away from its edge: {flyout:?} beside {at:?}"); + assert!(flyout.min.y >= at.min.y - 0.5 && flyout.min.y < at.max.y, "the flyout's top is level with the strip: {flyout:?}, {at:?}"); + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == popup).expect("the popup shows").1; + assert_eq!(builder.window_level, Some(egui::WindowLevel::AlwaysOnTop), "the popup stands as a palette of the active app"); + assert_eq!(builder.taskbar, Some(false), "the popup has no taskbar entry"); + assert_ne!(builder.active, Some(false), "the flyout takes the focus"); + assert_eq!(nodes(tree_of_viewport(&out, palette)), strip, "the palette's window shows none of the flyout"); + assert!(!tree_of_viewport(&out, popup).keys().is_empty(), "the popup window shows the flyout"); + let runs = |probe: &mut BodyProbe, dock: &mut NativeDock, at: &mut Rect| { + probe.0.clear(); + collapsed_frame(dock, probe, at, vec![], vec![]); + std::mem::take(&mut probe.0) + }; + let (first, second) = (runs(&mut probe, &mut dock, &mut at), runs(&mut probe, &mut dock, &mut at)); + assert!(!first.is_empty() && first.iter().all(|viewport| *viewport == popup), "the body runs in the popup's pass: {first:?}"); + assert_eq!(first.len(), second.len(), "the body runs as often in each frame"); +} + +/// The pointer rests on the double arrow of a collapsed native palette past the tooltip delay: the frame that follows. +fn hovered_arrow(dock: &mut NativeDock, at: &mut Rect) -> (Out, Rect) { + let end = at.max.x >= FLOAT_AT.max.x - 1.0 && at.min.x > FLOAT_AT.min.x + 1.0; + let arrow = Pos2::new(if end { at.width() - 4.0 } else { 4.0 }, 4.0); + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![moved(arrow)]); + // The tooltip shows after its delay, at 60 frames a second. + let frames = (craft_ui::contract::tooltip::DELAY * 60.0).ceil() as usize + 2; + for _ in 0..frames { + collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + } + let out = collapsed_frame(dock, &mut BodyProbe::default(), at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let name = tree_of_viewport(&out, palette).keys().into_iter().find_map(|key| { + let tree = tree_of_viewport(&out, palette); + tree.name_of(key) + .filter(|name| name.starts_with("Expand")) + .filter(|_| tree.role_of(key) == Some(Role::BUTTON)) + .and_then(|_| tree.bounds_of(key)) + }); + let arrow_rect = name.expect("the title row shows the double arrow"); + (out, arrow_rect) +} + +/// A native palette collapsed to icons paints the icons of its panels and no text cut by its window, also while the +/// pointer rests on its double arrow: the arrow's tooltip shows outside the strip, not wrapped inside it, and the +/// window fits the title row, its rule and the icons exactly. +#[trial] +fn a_collapsed_native_palette_paints_its_icons_and_no_clipped_text() { + let (mut dock, mut at) = collapsed_palette(); + let (out, _) = hovered_arrow(&mut dock, &mut at); + let palette = dock.palette.expect("the palette's window opened"); + let tree = tree_of_viewport(&out, palette); + let window = Rect::from_min_size(Pos2::ZERO, at.size()); + let icon = node_rect(tree, PALETTE_TITLE, Role::BUTTON).expect("the strip shows the panel's icon"); + assert!(window.contains(icon.center()), "the icon shows in the strip: {icon:?} in {window:?}"); + assert!(tree.with_role(Role::TOOLTIP).is_empty(), "no tooltip shows inside the strip"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons: {fit}"); + } +} + +/// A native palette on a monitor at 1x while the main window is on one at 2x (a laptop with an external display): +/// collapsed to icons, its window fits the title row, the rule under it and the icons exactly at its own scale. +#[trial] +fn a_collapsed_native_palette_on_a_1x_monitor_beside_a_2x_main_window_fits_its_icons_exactly() { + let mut dock = NativeDock::on(Os::Mac, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, 2.0)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, 1.0)); + Arc::make_mut(&mut dock.workspace).apply(Action::set_iconic(1, true), false, |_| Permissions::ALL).expect("the column collapses"); + for _ in 0..4 { + let commands = dock.frame(vec![]).1; + at = placed_by(&commands, at); + dock.windows.child_info(scaled(true, at, 1.0)); + } + let tree = dock.palette_tree.as_ref().expect("the palette ran a pass"); + if let Err(fit) = fits_exactly(tree, at.size(), Role::BUTTON) { + panic!("the strip's window fits its icons at its own scale: {fit}"); + } +} + +/// The tooltip of a collapsed native palette's double arrow opens in a popup OS window below the arrow, in desktop +/// points, on one line: the window takes no focus and lets the pointer through to the palette. +#[trial] +fn a_tooltip_from_a_native_palette_opens_in_a_popup_os_window() { + let (mut dock, mut at) = collapsed_palette(); + let (out, arrow) = hovered_arrow(&mut dock, &mut at); + let shown = popups(&dock, &out); + let tip = shown + .iter() + .copied() + .find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::TOOLTIP).is_empty()) + .expect("the tooltip shows in a popup window"); + let builder = &out.builders.iter().find(|(viewport, _)| *viewport == tip).expect("the popup shows").1; + assert_eq!(builder.active, Some(false), "the tooltip's window takes no focus"); + assert_eq!(builder.mouse_passthrough, Some(true), "the pointer passes through the tooltip's window"); + let rect = window_rect(&dock, tip); + assert!(rect.min.y >= at.min.y + arrow.max.y - 0.5, "the tooltip stands below the arrow: {rect:?}, arrow {arrow:?} in {at:?}"); + assert!(rect.width() > at.width() && rect.height() < rect.width(), "the tooltip's text runs on one line, wider than the strip: {rect:?}"); +} + +/// A press in the main window closes the flyout a collapsed native palette opened in a popup window. +#[trial] +fn a_press_in_the_main_window_closes_a_native_palettes_flyout() { + let (mut dock, mut at) = collapsed_palette(); + let mut probe = BodyProbe::default(); + let popup = open_flyout(&mut dock, &mut probe, &mut at); + let over = OVER_GROUP - MAIN_AT.min.to_vec2(); + for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] { + collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]); + } + // The flyout fades out, then its window closes. + let closed = (0..60).any(|_| { + let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]); + !popups(&dock, &out).contains(&popup) + }); + assert!(closed, "the flyout's window closed"); +} + /// Palettes no smaller than `PALETTE_LEAST`. struct Least; const PALETTE_LEAST: Vec2 = Vec2::new(240.0, 160.0); impl DockPanels for Least { - fn spec(&self, _: &u32) -> PanelSpec { - PanelSpec::new(PALETTE_TITLE).limits(SizeLimits::at_least(PALETTE_LEAST)) - } - fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {} } @@ -758,14 +1080,21 @@ fn a_native_palette_is_never_sized_below_its_limits() { let windows = Windows::new(); windows.root_info(info(true, MAIN_AT)); windows.child_info(info(true, FLOAT_AT)); - let mut window = Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); + let mut window = Floating::single(103, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), FLOAT_AT.size())); let mut saved = Placement::new(FLOAT_AT.size().into(), 1.0); saved.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]); window.native = Some(saved); - let mut workspace = Workspace::new(Layout::new(None, vec![window])); - let run = |workspace: &mut Workspace| { + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![window]))); + let run = |workspace: &mut Arc>| { let out = windows.frame(vec![], vec![], |ui| { - let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Least, DockConfig::default().native_windows(true)).show(ui); + let _ = DockArea::new( + "Native dock", + Bind::bound(workspace), + &Tracked::new(Specs { rights: Permissions::ALL, least: true, stepped: false }), + &mut Least, + DockConfig::default().native_windows(true), + ) + .show(ui); }); out.commands.into_iter().filter(|(viewport, _)| *viewport != ViewportId::ROOT).map(|(_, command)| command).collect::>() }; @@ -774,7 +1103,7 @@ fn a_native_palette_is_never_sized_below_its_limits() { } let mut small = Placement::new([80.0, 60.0], 1.0); small.position_px = Some([FLOAT_AT.min.x as i32, FLOAT_AT.min.y as i32]); - workspace.apply(Action::set_native(1, Some(small)), false, |_| Permissions::ALL).expect("the model takes the place"); + Arc::make_mut(&mut workspace).apply(Action::set_native(1, Some(small)), false, |_| Permissions::ALL).expect("the model takes the place"); let mut sent = Vec::new(); for _ in 0..3 { sent.extend(run(&mut workspace)); @@ -793,11 +1122,12 @@ fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_scree windows.root_info(ViewportInfo { fullscreen: Some(true), ..info(true, MAIN_AT) }); windows.child_info(info(true, FLOAT_AT)); let start = float().rect; - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let mut child = false; - let mut run = |workspace: &mut Workspace, events: Vec| { + let mut run = |workspace: &mut Arc>, events: Vec| { let out = windows.frame(events, vec![], |ui| { - let _ = DockArea::new("Native dock", Bind::bound(workspace), &mut Palettes(Permissions::ALL), DockConfig::default()).show(ui); + let _ = + DockArea::new("Native dock", Bind::bound(workspace), &Specs::with(Permissions::ALL), &mut Palettes, DockConfig::default()).show(ui); }); child |= out.builders.iter().any(|(viewport, _)| *viewport != ViewportId::ROOT); }; @@ -816,7 +1146,7 @@ fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_scree run(&mut workspace, vec![]); } assert!(!child, "no OS window opens over the full-screen window"); - let moved_to = workspace.layout.floating[0].rect.min; + let moved_to = workspace.layout().floating[0].rect.min; assert!( (moved_to - (start.min + by)).length() <= by.length() / 2.0, "the drag moved the float with the pointer: {moved_to:?} from {:?}", @@ -828,10 +1158,6 @@ fn a_float_shows_and_moves_in_the_app_window_while_the_main_window_is_full_scree struct Veiled; impl DockPanels for Veiled { - fn spec(&self, _: &u32) -> PanelSpec { - PanelSpec::new(PALETTE_TITLE) - } - fn body(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { let _ = DropVeil::new("Drop").show(ui, |_, _| {}); } @@ -845,15 +1171,15 @@ fn a_file_dropped_on_a_native_float_reaches_window_files_once() { let windows = Windows::new(); windows.root_info(info(true, ROOT_AT)); windows.child_info(info(true, PALETTE_AT)); - let mut workspace = Workspace::new(Layout::new(None, vec![float()])); + let mut workspace = Arc::new(Workspace::new(Layout::new(None, vec![float()]))); let mut frame = |hovered: Vec, dropped: Vec| { let mut files = 0; windows.frame_with_files(vec![], vec![], hovered, dropped, |ui| { let config = DockConfig::default(); let shown = if veiled { - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Veiled, config).show(ui) + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Veiled, config).show(ui) } else { - DockArea::new("Native dock", Bind::bound(&mut workspace), &mut Palettes(Permissions::ALL), config).show(ui) + DockArea::new("Native dock", Bind::bound(&mut workspace), &Specs::with(Permissions::ALL), &mut Palettes, config).show(ui) }; files += shown.window_files.len(); }); @@ -875,7 +1201,7 @@ fn a_file_dropped_on_a_native_float_reaches_window_files_once() { /// A palette float made in the app window. fn float() -> Floating { - Floating::single(vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))) + Floating::single(104, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0))) } fn info(focused: bool, rect: Rect) -> ViewportInfo { diff --git a/crates/ui-patterns/tests/it/docking/panel_menu.rs b/crates/ui-patterns/tests/it/docking/panel_menu.rs index db3227c09..b3b76895e 100644 --- a/crates/ui-patterns/tests/it/docking/panel_menu.rs +++ b/crates/ui-patterns/tests/it/docking/panel_menu.rs @@ -4,22 +4,29 @@ use craft_behavior::Axis; use craft_behavior::PartKey; use craft_behavior::dock::{Action, Column, DockEdge, Group, Layout, Node, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx, Role, ShowContainer as _}; -use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, WindowMenuRows}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Role, ShowContainer as _, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelSpec, PanelSpecs, WindowMenuRows}; use craft_ui::menu::{Menu, PanelRow}; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; + +/// Panels named by number. +#[derive(PlainData)] +struct Specs; + +impl PanelSpecs for Specs { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } +} struct Panels; impl DockPanels for Panels { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} /// A host row, so each group shows its panel menu button. @@ -32,11 +39,11 @@ impl DockPanels for Panels { #[trial] fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0, 1], 0), Node::tabs(vec![2, 3], 0)); - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new())))); - let held = Rc::clone(&workspace); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Specs)); let mut fixture = Fixture::new(move |ui| { let mut shown = held.borrow().clone(); - DockArea::new("Dock", Bind::bound(&mut shown), &mut Panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut shown), &specs, &mut Panels, DockConfig::default()).show(ui); *held.borrow_mut() = shown; }); fixture.room(Vec2::new(1200.0, 600.0)).settle(); @@ -48,7 +55,8 @@ fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { fixture.click(&buttons[1]).idle(2); let float = fixture.by_label("Float").expect("the menu's Float row"); fixture.click(&float).idle(2); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); let floated: Vec = layout.floating.iter().flat_map(|window| window.panels().copied().collect::>()).collect(); assert_eq!(floated, vec![2], "Float reaches the group whose menu ran it"); } @@ -57,9 +65,10 @@ fn a_panel_menu_command_reaches_the_group_whose_button_opened_it() { /// then the panel menu button. #[trial] fn tab_reaches_the_tabs_then_the_drag_band_then_the_panel_menu_button() { - let mut workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new())); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new()))); + let specs = Tracked::new(Specs); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut Panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(800.0, 600.0)).settle(); let tab = fixture.by_label("Panel 0").expect("the group's tab"); @@ -87,7 +96,7 @@ fn the_window_menu_opens_and_closes_the_flyout_of_a_panel_in_a_collapsed_column( let shown = *open.borrow(); let mut menu_open = true; Menu::new("Window").open(Bind::bound(&mut menu_open)).show(ui, |ui, _| { - let out = WindowMenuRows::new(&layout, &Panels, &[1, 2]).flyout(shown.as_ref()).show(ui); + let out = WindowMenuRows::new(&layout, &Tracked::new(Specs), &[1, 2]).flyout(shown.as_ref()).show(ui); if let Some(next) = out.flyout { *open.borrow_mut() = next; } @@ -106,3 +115,35 @@ fn the_window_menu_opens_and_closes_the_flyout_of_a_panel_in_a_collapsed_column( assert_eq!(*actions.borrow(), vec![Action::close(1)], "the row of a showing panel closes it"); assert_eq!(*flyout.borrow(), None, "and leaves the flyout alone"); } + +/// Floats panel 2 through the panel menu of the second group. +fn float_second_group(fixture: &mut Fixture) { + let buttons: Vec<_> = + fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Panel Menu")).collect(); + fixture.click(&buttons[1]).idle(2); + let float = fixture.by_label("Float").expect("the menu's Float row"); + fixture.click(&float).idle(2); +} + +/// An undo that brings back the workspace from before a float keeps the area's next window off the id the undone +/// window had: the area remembers the ids it has shown. +#[trial] +fn a_window_floated_after_an_undo_takes_a_new_id() { + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0, 1], 0), Node::tabs(vec![2, 3], 0)); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Specs)); + let mut fixture = Fixture::new(move |ui| { + DockArea::new("Dock", Bind::bound(&mut *held.borrow_mut()), &specs, &mut Panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + let older = Arc::clone(&workspace.borrow()); + float_second_group(&mut fixture); + let undone: Vec = workspace.borrow().layout().floating.iter().map(|window| window.id).collect(); + assert_eq!(undone.len(), 1, "Float made a window"); + *workspace.borrow_mut() = older; + fixture.settle(); + float_second_group(&mut fixture); + let ids: Vec = workspace.borrow().layout().floating.iter().map(|window| window.id).collect(); + assert_eq!(ids.len(), 1, "Float made a window again"); + assert_ne!(ids, undone, "the window after the undo does not take the undone window's id"); +} diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 60f7a82f0..ec73100e1 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -6,25 +6,35 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, SplitSize, Workspace}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, BodyCx, MemoProps, MemoView, Role, Show as _}; -use craft_ui::docking::{DockConfig, DockPanels, PanelDrag, PanelSpec}; +use craft_ui::contract::{Bind, BodyCx, MemoProps, MemoView, PlainData, Role, Show as _, Tracked}; +use craft_ui::docking::{DockConfig, DockPanels, PanelDrag, PanelSpec, PanelSpecs}; use craft_ui::menu::PanelRow; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; use craft_ui::testing::in_audit_run; use craft_ui::testing::pointer::{moved, press}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs, trial}; +use craft_ui::testing::{ + Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, trial, +}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; + +/// Panels named by their number, which count the specs the dock reads. +#[derive(PlainData)] +struct Named; + +impl PanelSpecs for Named { + fn spec(&self, panel: &usize) -> PanelSpec { + SPEC_READS.with(|reads| reads.set(reads.get() + 1)); + PanelSpec::new(format!("Panel {panel}")) + } +} struct Panels; impl DockPanels for Panels { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} /// A host row, so each group shows its panel menu button and its menu. @@ -37,9 +47,10 @@ impl DockPanels for Panels { fn settled_runs(groups: usize, tabs: usize) -> Vec<(&'static str, u32)> { let group = |at: usize| Node::tabs((tabs * at..tabs * (at + 1)).collect(), 0); let root = (1..groups).fold(group(0), |left, at| Node::split(Axis::X, SplitSize::Ratio(0.5), left, group(at))); - let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let specs = Tracked::new(Named); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut Panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); last_pass_runs(fixture.ctx()) @@ -82,6 +93,13 @@ fn a_settled_dock_group_runs_the_same_whatever_its_tab_count() { thread_local! { /// The panels whose memoized bodies ran on this trial's thread, in order. static BODY_RUNS: RefCell> = const { RefCell::new(Vec::new()) }; + /// The panel specs the docks read on this trial's thread. + static SPEC_READS: Cell = const { Cell::new(0) }; +} + +/// Takes the count of specs the docks read since the last call. +fn spec_reads() -> u32 { + SPEC_READS.with(|reads| reads.replace(0)) } /// Takes the panels whose bodies ran since the last call. @@ -103,19 +121,25 @@ fn panel_body(props: &mut BodyProps, ui: &mut Ui) { Button::new(format!("Body {}", props.panel)).show(ui); } -/// Panels whose bodies are memoized views, named by `labels`; `plain` is a panel whose body is not, which counts its -/// runs in `plain_runs`. +/// The panels' names, by panel; the specs count their reads. +#[derive(PlainData)] +struct Labels(Vec); + +impl PanelSpecs for Labels { + fn spec(&self, panel: &usize) -> PanelSpec { + SPEC_READS.with(|reads| reads.set(reads.get() + 1)); + PanelSpec::new(self.0[*panel].clone()) + } +} + +/// Panels whose bodies are memoized views; `plain` is a panel whose body is not, which counts its runs in +/// `plain_runs`. struct Memo { - labels: Rc>>, plain: Option, plain_runs: Rc>, } impl DockPanels for Memo { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(self.labels.borrow()[*panel].clone()) - } - fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { if self.plain == Some(*panel) { self.plain_runs.set(self.plain_runs.get() + 1); @@ -133,27 +157,29 @@ impl DockPanels for Memo { /// A settled dock whose panels are [`Memo`]. struct MemoDock { fixture: Fixture, - labels: Rc>>, + labels: Rc>>, plain_runs: Rc>, - workspace: Rc>>, + workspace: Rc>>>, /// The panel each pass of the dock reported picked. picked: Rc>>, } /// A settled dock over `layout` whose panels are [`Memo`], with `plain` a body that is not memoized. fn memo_dock(layout: Layout, plain: Option) -> MemoDock { - let labels = Rc::new(RefCell::new((0..32).map(|panel| format!("Panel {panel}")).collect::>())); + let labels = Rc::new(RefCell::new(Tracked::new(Labels((0..32).map(|panel| format!("Panel {panel}")).collect())))); let plain_runs = Rc::new(Cell::new(0)); - let workspace = Rc::new(RefCell::new(Workspace::new(layout))); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout)))); let picked = Rc::new(RefCell::new(Vec::new())); - let mut panels = Memo { labels: Rc::clone(&labels), plain, plain_runs: Rc::clone(&plain_runs) }; - let (shown, seen) = (Rc::clone(&workspace), Rc::clone(&picked)); + let mut panels = Memo { plain, plain_runs: Rc::clone(&plain_runs) }; + let (shown, seen, named) = (Rc::clone(&workspace), Rc::clone(&picked), Rc::clone(&labels)); let mut fixture = Fixture::new(move |ui| { - let output = DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &mut panels, DockConfig::default()).show(ui); + let specs = named.borrow(); + let output = DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &*specs, &mut panels, DockConfig::default()).show(ui); seen.borrow_mut().extend(output.picked); }); fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); body_runs(); + spec_reads(); picked.borrow_mut().clear(); MemoDock { fixture, labels, plain_runs, workspace, picked } } @@ -176,7 +202,7 @@ fn full(groups: usize) -> Layout { let columns = vec![Column::new(vec![Group::new(vec![20], 0)]).with_width(240.0), iconic]; let root = side_by_side(groups).root.expect("the groups"); let root = Node::split(Axis::X, SplitSize::Ratio(0.7), root, Node::dock(DockEdge::End, columns)); - let window = Floating::single(vec![22], 0, Rect::from_min_size(Pos2::new(200.0, 300.0), Vec2::new(300.0, 200.0))); + let window = Floating::single(100, vec![22], 0, Rect::from_min_size(Pos2::new(200.0, 300.0), Vec2::new(300.0, 200.0))); Layout::new(Some(root), vec![window]) } @@ -275,7 +301,7 @@ fn the_pointer_over_a_body_runs_only_that_body() { #[trial] fn a_tab_switch_runs_only_its_group() { let MemoDock { mut fixture, workspace, .. } = memo_dock(side_by_side(3), None); - workspace.borrow_mut().apply(Action::activate(3), false, |_| Permissions::ALL).expect("panel 3 is shown"); + Arc::make_mut(&mut workspace.borrow_mut()).apply(Action::activate(3), false, |_| Permissions::ALL).expect("panel 3 is shown"); fixture.frame(Vec::new()); let rows_ran = frame_ran_ids(&fixture, "TabRow"); // The changed row runs in the real run; the discard pass its new size asks for measures it once (no measure of the @@ -304,7 +330,7 @@ fn a_label_change_runs_only_its_groups_chrome() { const RENAMED: &str = "A renamed panel whose title is far too long to share its group's tab row with the other panel"; let MemoDock { mut fixture, labels, .. } = memo_dock(side_by_side(3), None); assert!(fixture.by_label("More tabs").is_none(), "every group's tabs fit before the change"); - labels.borrow_mut()[4] = RENAMED.to_owned(); + labels.borrow_mut().edit(|labels| labels.0[4] = RENAMED.to_owned()); fixture.frame(Vec::new()); let rows_ran = frame_ran_ids(&fixture, "TabRow"); assert_eq!( @@ -352,7 +378,8 @@ fn a_click_on_a_replayed_tab_row_is_picked_once() { assert_eq!(*picked.borrow(), vec![1], "the click picked panel 1 once"); fixture.frame(vec![egui::Event::PointerGone]).idle(SETTLE); assert_eq!(*picked.borrow(), vec![1], "no frame after the click picks again"); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); assert!(matches!(layout.root.as_ref(), Some(Node::Split { first, .. }) if matches!(&**first, Node::Tabs { active: 1, .. })), "panel 1 is shown"); } @@ -367,7 +394,8 @@ fn a_double_click_on_a_replayed_column_bar_collapses_its_column() { assert_eq!(memo_of(&fixture, "BarProps"), (0, 1), "the bar replays before the click"); let band = fixture.by_label("Move panel column").expect("the column's band").center(); fixture.click_at(band).click_at(band).settle(); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); let Some(Node::Split { second, .. }) = layout.root.as_ref() else { panic!("the split") }; assert!(matches!(&**second, Node::Dock { columns, .. } if columns[0].iconic), "the column collapsed to icons: {layout:?}"); } @@ -383,7 +411,8 @@ fn a_tab_dropped_on_a_settled_group_lands_there() { fixture.frame(vec![moved(to)]); assert!(drag::mark(fixture.ctx()).is_some(), "the settled group's strip takes the drop in the frame the pointer arrives"); fixture.release_at(to).idle(1); - let layout = &workspace.borrow().layout; + let shown = workspace.borrow(); + let layout = shown.layout(); let group = layout.place(&4).and_then(|place| layout.node_of(&place)); assert!(matches!(group, Some(Node::Tabs { panels, .. }) if panels.contains(&0)), "the tab joined the third group: {group:?}"); } @@ -400,7 +429,7 @@ fn close_in_a_settled_groups_panel_menu_closes_the_panel() { let close = fixture.by_label("Close").expect("the menu's Close row"); fixture.click(&close); fixture.frame(vec![egui::Event::PointerGone]); - assert!(workspace.borrow().layout.place(&2).is_none(), "Close closed the second group's panel"); + assert!(workspace.borrow().layout().place(&2).is_none(), "Close closed the second group's panel"); } /// Panels without versions whose bodies note the id of the `Ui` they run in. @@ -409,10 +438,6 @@ struct Noted { } impl DockPanels for Noted { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { self.ids.borrow_mut().push((*panel, ui.scope_id())); } @@ -423,16 +448,67 @@ impl DockPanels for Noted { #[trial] fn a_tab_moved_to_the_front_keeps_the_shown_bodys_ids() { let ids: Rc>> = Rc::default(); - let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new())))); - let (shown, mut panels) = (Rc::clone(&workspace), Noted { ids: Rc::clone(&ids) }); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![0, 1], 0)), Vec::new()))))); + let (shown, mut panels, specs) = (Rc::clone(&workspace), Noted { ids: Rc::clone(&ids) }, Tracked::new(Named)); let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &mut panels, DockConfig::default()).show(ui); + DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &specs, &mut panels, DockConfig::default()).show(ui); }); fixture.room(Vec2::new(800.0, 600.0)).settle(); let body_id = |ids: &RefCell>| ids.borrow().iter().rev().find(|(panel, _)| *panel == 0).map(|(_, id)| *id); let before = body_id(&ids).expect("panel 0's body ran"); - workspace.borrow_mut().layout.root = Some(Node::tabs(vec![1, 0], 1)); + *workspace.borrow_mut() = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![1, 0], 1)), Vec::new()))); ids.borrow_mut().clear(); fixture.frame(Vec::new()); assert_eq!(body_id(&ids), Some(before), "the shown body keeps its id when another tab moves to the front"); } + +/// An idle dock reads no panel spec and builds nothing it derives: its specs, permissions and keys are kept while the +/// workspace, the spec model and the lock are unchanged. That holds for a read-only dock too. +#[trial] +fn an_idle_dock_reads_no_spec_and_builds_nothing() { + let MemoDock { mut fixture, .. } = memo_dock(side_by_side(4), None); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an idle pass of a dock of 8 panels builds nothing"); + } + assert_eq!(spec_reads(), 0, "and reads no spec"); + + let shown = Arc::new(Workspace::new(side_by_side(4))); + let specs = Tracked::new(Named); + let mut fixture = Fixture::new(move |ui| { + DockArea::read_only("Shown", &shown, &specs, &mut Panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); + spec_reads(); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an idle pass of a read-only dock builds nothing"); + } + assert_eq!(spec_reads(), 0, "and reads no spec"); +} + +/// One workspace edit reads the specs once, in the frame of the edit, and none after. +#[trial] +fn one_workspace_edit_reads_the_specs_once() { + let MemoDock { mut fixture, workspace, .. } = memo_dock(side_by_side(4), None); + Arc::make_mut(&mut workspace.borrow_mut()).apply(Action::activate(3), false, |_| Permissions::ALL).expect("panel 3 is shown"); + fixture.frame(Vec::new()); + assert_eq!(spec_reads(), 8, "the edit reads each of the 8 panels' specs once: one build"); + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "the next pass builds nothing"); + assert_eq!(spec_reads(), 0, "and reads no spec"); +} + +/// The key bytes of an idle pass of a dock whose single group holds `tabs` panels. +fn idle_key_bytes(tabs: usize) -> usize { + let MemoDock { mut fixture, .. } = memo_dock(Layout::new(Some(Node::tabs((0..tabs).collect(), 0)), Vec::new()), None); + fixture.frame(Vec::new()); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an idle pass builds no derived value"); + last_pass_memo_key_bytes(fixture.ctx()) +} + +/// An idle dock feeds the same key bytes whatever the number of its panels. +#[trial] +fn a_docks_idle_key_bytes_do_not_grow_with_its_panels() { + assert_eq!(idle_key_bytes(4), idle_key_bytes(32), "the tab row's key follows the dock's revisions, not its titles"); +} diff --git a/crates/ui-patterns/tests/it/docking/split.rs b/crates/ui-patterns/tests/it/docking/split.rs index 89df28103..2d89727a4 100644 --- a/crates/ui-patterns/tests/it/docking/split.rs +++ b/crates/ui-patterns/tests/it/docking/split.rs @@ -2,15 +2,16 @@ use craft_behavior::Axis; use craft_behavior::dock::{Column, Group, Layout, Node, SplitSize}; -use craft_ui::contract::Role; +use craft_ui::contract::{Role, Tracked}; use craft_ui::docking::frame::maximize; use craft_ui::docking::tree; -use craft_ui::docking::{DockColumn, HidePanels, PanelSpec}; +use craft_ui::docking::{DockColumn, HidePanels, PanelKey, PanelSpec}; use craft_ui::testing::memory::global; use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, trial}; use egui::{Pos2, Rect}; use std::cell::RefCell; +use std::collections::BTreeSet; use std::rc::Rc; fn spec(panel: &u8) -> PanelSpec { @@ -64,7 +65,7 @@ fn a_column_divider_dragged_past_a_minimum_and_back_stays_under_the_pointer() { fn a_resize_under_a_pruned_view_keeps_the_hidden_panels() { let rest = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![1], 0), Node::tabs(vec![2], 0)); let mut layout = Layout::new(Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), rest)), Vec::new()); - let keep = |panel: &usize| *panel != 2; + let keep = Tracked::new(BTreeSet::from([PanelKey::of(&0_usize), PanelKey::of(&1_usize)])); let none_protected = |_: &usize| false; let original = layout.clone(); let view = maximize(&original, None, HidePanels::Except(&keep), &none_protected); diff --git a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs index f8a1a428d..cc78ff097 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs @@ -9,7 +9,7 @@ use craft_ui::dialog::{DialogHost, DialogResult, HeldAnswer, HeldOk, dialog_id}; use craft_ui::patterns::form_dialogs::{ DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult, }; -use craft_ui::patterns::presets::PresetRow; +use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource}; use craft_ui::runtime::env::Label; use craft_ui::runtime::overlay::CloseReason; use craft_ui::sections::{DialogRole, FooterButton}; @@ -18,7 +18,6 @@ use craft_ui::testing::{Fixture, trial}; use egui::load::SizedTexture; use egui::{Key, Modifiers, TextureId, Vec2, vec2}; use serde_json::json; -use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::path::PathBuf; use std::rc::Rc; @@ -477,12 +476,11 @@ fn filter_params(narrow: bool) -> Vec { /// A remembering filter dialog; `narrow` offers fewer patterns. fn filter(fields: &mut DialogFields, narrow: bool) -> ParamDialog<'_> { - let ids: &[&str] = if narrow { &["dots"] } else { &["dots", "stripes"] }; - let patterns: Vec> = ids.iter().map(|id| PresetRow::item((*id).to_owned(), *id, 0)).collect(); + let ids: &'static [&'static str] = if narrow { &["dots"] } else { &["dots", "stripes"] }; ParamDialog::new("filter", "Filter", filter_params(narrow)) .values(Bind::bound(fields)) .remember(SaveKey::new("trial.filter")) - .patterns(Cow::Owned(patterns)) + .patterns(PresetSource::new(ids, PresetFns::new(|ids, _| ids.iter().map(|id| PresetRow::item((*id).to_owned(), *id, 0)).collect()))) } fn wide_filter(fields: &mut DialogFields) -> ParamDialog<'_> { diff --git a/crates/ui-patterns/tests/it/form_dialogs/export.rs b/crates/ui-patterns/tests/it/form_dialogs/export.rs index 9e8c91f79..b27455b9f 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/export.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/export.rs @@ -8,6 +8,7 @@ use craft_ui::patterns::form_dialogs::{ HostedFormatOptions, JpegOptions, OutputPathRow, Resample, ScaleRow, ScaleSize, SizeEstimate, }; use craft_ui::runtime::requests::PathRequest; +use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; @@ -281,6 +282,36 @@ fn export_as_starts_from_its_remembered_options_and_stores_the_confirmed_ones() assert_eq!(again.scale_all, jpeg.scale_all, "and their Scale All rows"); } +/// Export As lists the app's resample methods in the order it gives, and an unlisted opening method opens as Automatic +/// when listed, else as the first listed one. +#[trial] +fn export_as_lists_resample_methods_in_the_hosts_order() { + let methods = vec![Resample::Bicubic, Resample::BicubicSmoother, Resample::NearestNeighbor, Resample::PreserveDetails]; + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(Vec2::new(1400.0, 1000.0)); + let mut start = ExportOptions::default(); + start.resample = Resample::Lanczos; + host.borrow_mut().open(HostedExportAs::new("Poster", document(), start).methods(methods.clone())); + fixture.idle(10); + let opened = host.borrow_mut().get_mut::().map(|dialog| dialog.options().resample).expect("the dialog is open"); + assert_eq!(opened, Resample::Bicubic, "without Automatic in the list, the first listed method opens"); + + let select = fixture.by_label("Resample").expect("the resample select"); + fixture.access(AccessActionKind::Focus, &select).idle(2); + fixture.key(Key::Space, Modifiers::NONE).idle(3); + let mut options = fixture.by_role(Role::LIST_BOX_OPTION); + options.sort_by(|a, b| a.center().y.total_cmp(&b.center().y)); + let names: Vec = options.iter().map(|option| fixture.tree().name_of(option.node).expect("the option has a name").to_owned()).collect(); + assert_eq!(names.len(), methods.len(), "the list offers the listed methods only"); + assert_eq!( + names, + ["Bicubic (smooth gradients)", "Bicubic Smoother (enlargement)", "Nearest Neighbor (hard edges)", "Preserve Details"], + "the list keeps the host's order" + ); +} + /// Export As with the app's resample methods offers no other: an unlisted opening method opens as the first listed /// one, and automation cannot set an unlisted one. #[trial] diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index 91004c210..74646a479 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -464,3 +464,120 @@ fn image_size_alt_digits_pick_resample_without_typing_into_a_field() { alt_digit(&mut fixture, Key::Num7, "7", alt); assert_eq!(resample(&host), Some(json!("nearestNeighbor")), "Alt+7 picks a listed method"); } + +/// Opens a dialog on a host. +type Opener = fn(&mut DialogHost); + +/// Image Size's and Canvas Size's Width and Height rows (a stack of fields beside the link) show as they measured, at +/// 1x and 1.25x (#15483, #15538): each label sits beside its field, each field and unit select is as tall as a direct +/// row's control (`reference`), and Height's label starts under Width's controls. +#[trial] +fn sizing_dialogs_show_width_and_height_beside_their_labels_at_full_height() { + for scale in [1.0, 1.25] { + let opens: [(Opener, &str); 2] = [ + ( + |host| { + host.open(image_size()); + }, + "Resolution", + ), + ( + |host| { + host.open(canvas_size()); + }, + "Canvas extension color", + ), + ]; + for (open, reference) in opens { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + fixture.pixels_per_point(scale); + open(&mut host.borrow_mut()); + fixture.settle(); + let rect = |name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let label_of = |name: &str| { + // The field's label names the unit select's group, the number field's parent. + let tree = fixture.tree(); + let mut node = fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).node; + let label = loop { + if let Some(label) = tree.labelled_by_key(node).into_iter().next() { + break label; + } + node = tree.parent_of_key(node).unwrap_or_else(|| panic!("{name} is labelled")); + }; + tree.bounds_of(label).unwrap_or_else(|| panic!("{name}'s label is shown")) + }; + let full = rect(reference).height(); + for name in ["Width", "Height"] { + let (label, field) = (label_of(name), rect(name)); + for part in [field, rect(&format!("{name} unit"))] { + assert!(part.height() >= full - 0.5, "{name}'s controls are a full row tall at {scale}x ({reference}): {part:?} {full}"); + } + assert!(label.max.x <= field.min.x + 0.5, "{name}'s label sits before its field at {scale}x ({reference}): {label:?} {field:?}"); + assert!( + label.min.y < field.max.y && label.max.y > field.min.y, + "{name}'s label is on its field's line at {scale}x: {label:?} {field:?}" + ); + } + let (width, height) = (rect("Width").union(rect("Width unit")), label_of("Height")); + assert!(height.min.y >= width.max.y - 0.5, "Height's row starts under Width's at {scale}x ({reference}): {height:?} {width:?}"); + } + } +} + +/// The horizontal line segments one frame of `fixture` paints, as (y, from x, to x). +fn horizontal_lines(fixture: &mut Fixture) -> Vec<(f32, f32, f32)> { + fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::LineSegment { points: [a, b], .. } if (a.y - b.y).abs() < 0.5 => Some((a.y, a.x.min(b.x), a.x.max(b.x))), + _ => None, + }) + .collect() +} + +/// Image Size as 0.23.1 lays it out: the chain sits halfway between Width's and Height's controls with the bracket +/// drawn from each control to it, and Resample starts in the control column with the method on its line. +#[trial] +fn image_size_brackets_width_and_height_and_starts_resample_in_the_control_column() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(image_size()); + fixture.settle(); + let rect = |fixture: &Fixture, name: &str| fixture.by_label(name).unwrap_or_else(|| panic!("{name} is shown")).rect; + let (width, height, link) = (rect(&fixture, "Width unit"), rect(&fixture, "Height unit"), rect(&fixture, "Maintain aspect ratio")); + let middle = (width.center().y + height.center().y) / 2.0; + assert!((link.center().y - middle).abs() <= 0.5, "the chain sits halfway between Width and Height: {link:?} {middle}"); + let lines = horizontal_lines(&mut fixture); + for (name, row) in [("Width", width), ("Height", height)] { + assert!( + lines.iter().any(|(y, from, to)| (y - row.center().y).abs() <= 1.0 && *from >= row.max.x && *to >= link.center().x - 1.0), + "a tick runs from {name}'s control to the chain: {lines:?}" + ); + } + let (number, check, method) = (rect(&fixture, "Width"), rect(&fixture, "Resample"), rect(&fixture, "Resample method")); + assert!((check.min.x - number.min.x).abs() <= 0.5, "Resample starts at the control column: {check:?} {number:?}"); + assert!( + method.min.x >= check.max.x - 0.5 && method.min.y < check.max.y && method.max.y > check.min.y, + "the method follows Resample on its line: {method:?} {check:?}" + ); +} + +/// Canvas Size draws one rule between its title and Current Size, the title's: the first section's rule above would +/// stand right under it. The rule between the two sections stays. +#[trial] +fn canvas_size_draws_one_rule_under_its_title() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(canvas_size()); + fixture.settle(); + let text = |fixture: &Fixture, text: &str| { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted")) + }; + let (title, current, new) = (text(&fixture, "Canvas Size"), text(&fixture, "Current Size"), text(&fixture, "New Size")); + let lines = horizontal_lines(&mut fixture); + let across = |top: f32, bottom: f32| lines.iter().filter(|(y, from, to)| *y > top && *y < bottom && to - from > current.width()).count(); + assert_eq!(across(title.max.y, current.min.y), 1, "one rule between the title and Current Size: {lines:?}"); + assert_eq!(across(current.max.y, new.min.y), 1, "a rule between Current Size and New Size: {lines:?}"); +} diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index 81066b702..760b341b0 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -10,7 +10,7 @@ use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; use std::rc::Rc; -/// Opens the Save Document Preset pane with the button below the fields, types `name` over the proposed one and saves. +/// Opens the Save Document Preset pane with the icon on the Name row, types `name` over the proposed one and saves. fn save_preset(fixture: &mut Fixture, name: &str) { let save = fixture.by_label("Save Document Preset").expect("the Save Document Preset button"); fixture.click(&save).idle(10); @@ -266,5 +266,38 @@ fn the_new_document_layout_places_presets_and_details_below_the_tabs() { assert!(recent.bottom() <= mode.top(), "tabs go above the details"); assert!((mode.top() - depth.top()).abs() < 1.0, "color mode and depth share a row"); assert!(mode.right() <= depth.left(), "depth follows color mode"); - assert!(mode.bottom() <= save.top() && save.bottom() <= create.top(), "Save Preset is between the fields and the footer"); + assert!(save.bottom() <= create.top(), "Save Preset is above the footer"); +} + +/// The fields run Name, size, Color Mode, Background Contents, then the advanced Color Profile and Pixel Aspect Ratio; the +/// save icon (no text) sits at the end of the Name row. +#[trial] +fn the_new_document_fields_run_background_before_the_advanced_ones_and_save_sits_on_the_name_row() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + let top = |fixture: &Fixture, label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the {label} field")).rect.top(); + let (mode, background) = (top(&fixture, "Color Mode"), top(&fixture, "Background Contents")); + let (profile, aspect) = (top(&fixture, "Color Profile"), top(&fixture, "Pixel Aspect Ratio")); + assert!(mode < background && background < profile && profile < aspect, "Background Contents comes before the advanced fields"); + + let name = fixture.by_label("Name").expect("the Name field").rect; + let save = fixture.by_label("Save Document Preset").expect("the save action").rect; + assert!(save.top() < name.bottom() && name.top() < save.bottom(), "the save icon shares the Name row"); + assert!(name.right() <= save.left(), "the save icon is at the end of the Name field"); + assert!(!fixture.texts().iter().any(|run| run.text.starts_with("Save ")), "the save control is an icon, with no text"); +} + +/// The caption role sets its text in capitals when it paints; the label stays as written. +#[trial] +fn section_captions_paint_in_capitals_and_keep_their_text() { + let mut options = DocumentOptions::default(); + let mut fixture = Fixture::new(move |ui| { + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + assert!(shows(&fixture, "PRESET DETAILS"), "the caption paints in capitals"); + assert!(fixture.by_label("Preset Details").is_some(), "the accessible name keeps the text as written"); } diff --git a/crates/ui-patterns/tests/it/form_dialogs/params.rs b/crates/ui-patterns/tests/it/form_dialogs/params.rs index a0b978421..90ec7fd5a 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/params.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/params.rs @@ -4,7 +4,7 @@ use craft_ui::contract::{Bind, Role}; use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut}; use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, NumberUnit, Param, ParamDialog, ParamKind, ParamRows, set_param_field}; -use craft_ui::patterns::presets::PresetRow; +use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource}; use craft_ui::runtime::env::{Label, Scale, UnitKind}; use craft_ui::testing::{Fixture, trial}; use craft_ui::value_drag::SliderScale; @@ -350,11 +350,16 @@ fn paired_parameter_fields_15539_leave_no_gap_when_both_are_hidden() { /// id, and a group header takes no pick. #[trial] fn a_pattern_row_picks_its_pattern() { - let rows = vec![ - PresetRow::group("nature".to_owned(), "Nature", 0), - PresetRow::item("grass".to_owned(), "Grass", 1), - PresetRow::item("sand".to_owned(), "Sand", 1), - ]; + let rows = PresetSource::new( + (), + PresetFns::new(|_, _| { + vec![ + PresetRow::group("nature".to_owned(), "Nature", 0), + PresetRow::item("grass".to_owned(), "Grass", 1), + PresetRow::item("sand".to_owned(), "Sand", 1), + ] + }), + ); let values = Rc::new(RefCell::new(DialogFields::from_pairs([("fill", "ghost")]))); let shown = values.clone(); let params = vec![Param::new("fill", "Fill", ParamKind::pattern(None))]; diff --git a/crates/ui-patterns/tests/it/presets/browser.rs b/crates/ui-patterns/tests/it/presets/browser.rs index f2ac771b1..e4500e9cc 100644 --- a/crates/ui-patterns/tests/it/presets/browser.rs +++ b/crates/ui-patterns/tests/it/presets/browser.rs @@ -1,7 +1,7 @@ //! `PresetBrowser::drop_zone`: a preset dragged from the browser and released over the zone reports `DropAt`. use craft_ui::contract::{Bind, DropZone}; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, PresetView}; +use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetView}; use craft_ui::runtime::drag; use craft_ui::testing::{Fixture, trial}; use egui::{Id, Key, Modifiers, Pos2, Rect, Sense, UiBuilder, pos2, vec2}; @@ -19,7 +19,10 @@ const COVER: Rect = Rect { min: Pos2::new(260.0, 200.0), max: Pos2::new(460.0, 2 fn rig() -> (Fixture, Rc>>>) { let events = Rc::new(RefCell::new(Vec::new())); let seen = events.clone(); - let rows = vec![PresetRow::group(GROUP, "Group", 0), PresetRow::item(ALPHA, "Alpha", 1), PresetRow::item(2, "Beta", 1)]; + let rows = PresetSource::new( + (), + PresetFns::new(|_, _| vec![PresetRow::group(GROUP, "Group", 0), PresetRow::item(ALPHA, "Alpha", 1), PresetRow::item(2, "Beta", 1)]), + ); let mut state = PresetState::::new(); let mut fixture = Fixture::new(move |ui| { let zone = DropZone::new(ui.layer_id(), ZONE); @@ -65,8 +68,14 @@ fn a_preset_released_over_the_zone_reports_drop_at_and_nothing_else_does() { /// `room_height` set when given, and where its New Group button and its last preset are. fn footer_rig(presets: u32, room_height: Option) -> (Rect, Option) { const ROOM: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(250.0, 300.0) }; - let mut rows = vec![PresetRow::group(GROUP, "Group", 0)]; - rows.extend((1..=presets).map(|key| PresetRow::item(key, format!("Preset {key}"), 1))); + let rows = PresetSource::new( + presets, + PresetFns::new(|presets: &u32, _| { + let mut rows = vec![PresetRow::group(GROUP, "Group", 0)]; + rows.extend((1..=*presets).map(|key| PresetRow::item(key, format!("Preset {key}"), 1))); + rows + }), + ); let mut state = PresetState::::new(); let mut fixture = Fixture::new(move |ui| { ui.scope_builder(UiBuilder::new().max_rect(ROOM), |ui| { @@ -105,7 +114,7 @@ fn delete_and_backspace_on_a_selected_preset_report_delete() { for key in [Key::Delete, Key::Backspace] { let events = Rc::new(RefCell::new(Vec::new())); let seen = events.clone(); - let rows = vec![PresetRow::item(ALPHA, "Alpha", 0), PresetRow::item(2, "Beta", 0)]; + let rows = PresetSource::new((), PresetFns::new(|_, _| vec![PresetRow::item(ALPHA, "Alpha", 0), PresetRow::item(2, "Beta", 0)])); let mut state = PresetState::::new(); let mut fixture = Fixture::new(move |ui| { ui.scope_builder(UiBuilder::new().max_rect(BROWSER), |ui| { diff --git a/crates/ui-patterns/tests/it/presets/named.rs b/crates/ui-patterns/tests/it/presets/named.rs index 03abb1d8e..ffa5329f9 100644 --- a/crates/ui-patterns/tests/it/presets/named.rs +++ b/crates/ui-patterns/tests/it/presets/named.rs @@ -1,7 +1,9 @@ //! `NamedPresetRow`: F2 on the picker renames a user preset and nothing else; New… opens the name prompt. use craft_ui::contract::{Bind, Role}; -use craft_ui::patterns::presets::{NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PresetPicker, PresetRow, PresetState}; +use craft_ui::patterns::presets::{ + NamedPresetEvent, NamedPresetRow, NamedPresetStyle, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, +}; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers}; use std::cell::RefCell; @@ -19,7 +21,7 @@ struct Rig { fn rig(style: NamedPresetStyle, current: u32) -> Rig { let events = Rc::new(RefCell::new(Vec::new())); let seen = events.clone(); - let rows = vec![PresetRow::item(LINEAR, "Linear", 0), PresetRow::item(MINE, "Mine", 0)]; + let rows = PresetSource::new((), PresetFns::new(|_, _| vec![PresetRow::item(LINEAR, "Linear", 0), PresetRow::item(MINE, "Mine", 0)])); let mut value = Some(current); let mut state = PresetState::::new(); let mut fixture = Fixture::new(move |ui| { diff --git a/crates/ui-patterns/tests/it/presets/picker.rs b/crates/ui-patterns/tests/it/presets/picker.rs index f5ec2cbdb..243819838 100644 --- a/crates/ui-patterns/tests/it/presets/picker.rs +++ b/crates/ui-patterns/tests/it/presets/picker.rs @@ -5,9 +5,9 @@ use craft_ui::bars::{Bar, BarKind}; use craft_ui::buttons::Button; use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _}; -use craft_ui::patterns::presets::{PickerField, PresetPicker, PresetRow, PresetState}; +use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, PresetView}; use craft_ui::popover::Popover; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, last_pass_runs, trial}; use egui::{Key, Modifiers, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -27,8 +27,14 @@ fn a_click_picks_and_closes_and_escape_closes_keeping_the_value() { let host = Rc::new(RefCell::new(Host { value: Some(CORAL), state: PresetState::new(), picked: Vec::new(), open: false })); let shown = Rc::clone(&host); // A library longer than a row of the grid, so the room would hold every tile on one line. - let mut rows = vec![PresetRow::item(CORAL, "Coral", 0), PresetRow::item(TEAL, "Teal", 0)]; - rows.extend((100..130).map(|key| PresetRow::item(key, format!("Preset {key}"), 0))); + let rows = PresetSource::new( + (), + PresetFns::new(|_, _| { + let mut rows = vec![PresetRow::item(CORAL, "Coral", 0), PresetRow::item(TEAL, "Teal", 0)]; + rows.extend((100..130).map(|key| PresetRow::item(key, format!("Preset {key}"), 0))); + rows + }), + ); let mut fixture = Fixture::new(move |ui| { let mut host = shown.borrow_mut(); let Host { value, state, picked, open } = &mut *host; @@ -70,7 +76,7 @@ fn a_click_picks_and_closes_and_escape_closes_keeping_the_value() { fn a_picker_in_a_popover_opens_and_picks_with_the_popover_kept_open() { let (parent, value) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(Some(1u32)))); let (parent_seen, value_seen) = (parent.clone(), value.clone()); - let rows = vec![PresetRow::item(1u32, "Alpha", 0), PresetRow::item(2, "Beta", 0)]; + let rows = PresetSource::new((), PresetFns::new(|_, _| vec![PresetRow::item(1u32, "Alpha", 0), PresetRow::item(2, "Beta", 0)])); let mut state = PresetState::::new(); let mut fixture = Fixture::new(move |ui| { let opener = Button::new("Fill").show(ui); @@ -101,7 +107,7 @@ fn a_picker_in_a_popover_opens_and_picks_with_the_popover_kept_open() { fn a_chip_with_a_caption_range_keeps_its_width_as_the_caption_grows() { let size = Rc::new(Cell::new(9u32)); let shown = Rc::clone(&size); - let rows = vec![PresetRow::item(CORAL, "Coral", 0), PresetRow::item(TEAL, "Teal", 0)]; + let rows = PresetSource::new((), PresetFns::new(|_, _| vec![PresetRow::item(CORAL, "Coral", 0), PresetRow::item(TEAL, "Teal", 0)])); let mut state = PresetState::::new(); let mut value = Some(CORAL); let mut fixture = Fixture::new(move |ui| { @@ -128,3 +134,32 @@ fn a_chip_with_a_caption_range_keeps_its_width_as_the_caption_grows() { assert_eq!(place(&fixture), first, "caption {next}: the chip and the button after it stay in place"); } } + +/// The views of `props` that ran in the last frame, and the list rows that ran in its last pass. +fn list_runs(fixture: &Fixture, props: &str) -> (usize, u32) { + let views = last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count(); + let rows = last_pass_runs(fixture.ctx()).into_iter().filter(|(name, _)| name.contains("ListRow")).map(|(_, runs)| runs).sum(); + (views, rows) +} + +/// While nothing changes an open picker's list replays: no list row runs. The search field takes the focus on open, as +/// in the Brush Preset picker: a list that holds the focus runs in every pass. +#[trial] +fn an_open_picker_with_nothing_changing_runs_no_list_row() { + let mut value = Some(CORAL); + let mut state = PresetState::::new(); + let rows = PresetSource::new((), PresetFns::new(|_, _| (0..12).map(|key| PresetRow::item(CORAL + key, format!("Preset {key}"), 0)).collect())); + let mut fixture = Fixture::new(move |ui| { + let _ = PresetPicker::new("Swatch", Bind::bound(&mut value), &rows, Bind::bound(&mut state)).view(PresetView::List).toolbar(true).show(ui); + }); + fixture.room(Vec2::new(800.0, 800.0)); + fixture.settle(); + let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the field shows"); + fixture.click(&field); + fixture.settle(); + fixture.frame(vec![]); + assert!(fixture.by_label("Preset 3").is_some(), "the open popover lists the presets"); + assert_eq!(list_runs(&fixture, "ListProps"), (0, 0), "an idle frame runs neither the list view nor a row"); + let replayed = last_frame_memo_runs(fixture.ctx()).into_iter().any(|(name, _, run)| name.contains("ListProps") && run == MemoRun::Replayed); + assert!(replayed, "the list view replays"); +} diff --git a/crates/ui-shell/src/shell/document_window.rs b/crates/ui-shell/src/shell/document_window.rs index 1bc55a73d..edab6e6fa 100644 --- a/crates/ui-shell/src/shell/document_window.rs +++ b/crates/ui-shell/src/shell/document_window.rs @@ -84,6 +84,8 @@ impl Outcome for DocumentWindowOutput { /// - **Title and focus.** The title is the label given to `new`; it follows the document while the app changes it. /// [`raise`](DocumentWindow::raise) brings the window forward in the pass it is set. With /// [`in_list`](DocumentWindow::in_list) the window makes itself the list's active window when it gains OS focus. +/// - **Body.** The body is laid out in the window's room and never scrolls, in the OS window and on the fallback +/// layer alike; an app that wants scrolling puts a scroll region in the body. /// - **Fallback.** Where OS windows are unavailable the document shows on a movable, resizable layer with a title row. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container)] @@ -138,7 +140,7 @@ impl<'a> DocumentWindow<'a> { /// A window titled `title`, resizable, with the installed decision's frame. pub fn new(title: impl Into

`: +The host holds the workspace as an `Arc>` (`state.workspace`): a pass shares it instead of cloning it, and an edit writes a new one (`Arc::make_mut`). Keep that one `Arc` across frames and clone the `Arc`, not the workspace: a new workspace value is a new revision, so a host that wraps a fresh copy each frame makes the area read every spec each frame. + +The host keeps its panels' specs in a plain-data model that implements `PanelSpecs

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

` for the views: + +| Method | Does | +| --- | --- | | `body` | Shows the panel's body in the group's body, which the group insets by the panel padding (`Pad::Regular`). The group is the body's panel, so the body adds no `Panel` or padding of its own. A document panel's body (`WindowKind::Document`) is shown edge to edge. | | `group_view` | Takes a whole group in place of its tab strip and body, in a `Ui` held to the group's rect; a canvas group draws its document here. Default `None`. | | `group_header` | The host's controls in a group header, before the tab strip. | | `panel_rows` | The host's rows of a panel's menu, before the dock's own. | -The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a layout locked. +The binding decides who applies the edits. With `Bind::bound` the area writes every action to the workspace itself. With `Bind::given` it writes nothing, and the host applies `DockAreaOutput::actions` (or `edit`, the same changes as edit events) to its own copy: the actions hold every change of the pass, divider sizes and window moves included. `DockArea::read_only` shows a workspace locked, keyed by its revision. A panel body, or code a body calls, changes the workspace during the pass with `docking::request_actions(ctx, actions)`, never by writing the workspace the area shows. The running area takes them unapplied and returns them in `DockAreaOutput::requested`, in order, for the host to apply after `actions` in the same frame. With no area over that panel type running, `request_actions` hands the actions back for the caller to apply. @@ -103,9 +112,11 @@ 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. +- A floating window whose every group is minimized shows its title row and their tab strips, at its rect's place and width (`WindowColumn::minimized`). Its sides resize its width, never its height, and its rect, in the app window and in an OS window's recorded placement, keeps the expanded height, which the window takes back when a group is restored. A window with some groups open keeps its size, and its open groups share the room the strips leave. - Ctrl or Cmd held at the release floats the drop. A release over the dragged unit's own group leaves it where it is. -- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's revision, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the revision, so they keep the drag. +- A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives. +- A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. - Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s. diff --git a/migration/api-map/canvas-core.toml b/migration/api-map/canvas-core.toml index 5529bc472..c885251da 100644 --- a/migration/api-map/canvas-core.toml +++ b/migration/api-map/canvas-core.toml @@ -152,7 +152,7 @@ name = "RulerTick" old = "craft_ui::canvas::rulers::RulerTick" new = "craft_ui::canvas::RulerTick" status = "moved" -note = "`RulerTick { value, rank: primitives::TickRank, step }`: the label text is written at paint time from `RulerText::tick_label`, and the rank is Major at a labelled step, Mid halfway between labels in an even subdivision, Minor otherwise (`primitives::ticks` draws the length by rank; the mid length is the token `size.ruler.tick.mid`)." +note = "`RulerTick { value, rank: primitives::TickRank, step }`: the label text is written at paint time from `RulerText::tick_label`, and the rank is Major at a labelled step, Mid halfway between labels in an even subdivision, Minor otherwise (`primitives::ticks` draws the length by rank; the minor and mid lengths are the constants `TICK_MINOR` and `TICK_MID` in `primitives/kit.rs`)." [[type]] name = "TickRule" diff --git a/migration/api-map/craft-menu.toml b/migration/api-map/craft-menu.toml index 3cb23d23a..056edf546 100644 --- a/migration/api-map/craft-menu.toml +++ b/migration/api-map/craft-menu.toml @@ -107,7 +107,12 @@ old = "id(Id)" new = "" note = "Use `Props::id_salt` on the bar's parent scope." +[[call]] +old = "MenuBarUi::english(hook)" +new = "" +note = "The English name is a field of the model (`Item::english`, `Node::english`, `Menu::english`), set where the app translates a label." + [[call]] old = "MenuBar::palette_entries(&keymap, target, &options, english, os)" -new = "MenuBar::help_entries(target, &options, english)" -note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go." +new = "MenuBar::help_entries(target, &options)" +note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go, and so does the English hook: set `Item::english` on the model."