From 587590fec792c826af7b8a24a43502563de04ce4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 11:00:57 +0000 Subject: [PATCH] craft-ui: dock chrome and shell slots as memoized views Each dock group's tab row, each column's bar and each iconic column's bar is a memoized view on the spec values, the arrangement and the look; what the user did on them leaves through an outbox. The containers (DockGroup, DockColumn, IconicColumn) and the host's body, group view and group header run every pass, and the host memoizes inside them; shell slots the same way. The group menu is one popup, opened by the panel menu button or by a context request on a tab, and its rows are built only while it is open. Removed: DockPanels::content and spec_version, the chrome key, DockColumn::content, IconicColumn::content, Slot::content, Slot::content_version, AppShell::content, Lazy::show_or and Run::unkept. The gallery's mock Navigator body is a memoized view. --- crates/ui-contract/src/contract/lazy.rs | 48 +-- crates/ui-contract/src/contract/memo.rs | 20 + crates/ui-contract/src/runtime/lazy.rs | 9 - crates/ui-gallery/src/mock/panels.rs | 23 +- crates/ui-panels/src/docking/dock_column.rs | 23 +- .../ui-panels/src/docking/dock_column/bar.rs | 123 +++--- crates/ui-panels/src/docking/drop.rs | 2 +- crates/ui-panels/src/docking/group.rs | 277 +++++++++---- crates/ui-panels/src/docking/iconic.rs | 14 +- crates/ui-panels/src/docking/mod.rs | 6 +- crates/ui-panels/src/docking/panels.rs | 42 +- crates/ui-panels/src/docking/stories.rs | 2 +- crates/ui-patterns/src/patterns/dock/area.rs | 162 ++------ crates/ui-patterns/tests/it/docking/runs.rs | 377 ++++++++++-------- crates/ui-shell/src/shell/app_shell.rs | 24 +- crates/ui-shell/src/shell/regions.rs | 21 +- crates/ui-shell/tests/it/shell/app_shell.rs | 69 +++- .../ui-shell/tests/it/shell/window_parts.rs | 28 +- 18 files changed, 645 insertions(+), 625 deletions(-) diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 47b72393d..e5c236f5b 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -3,7 +3,6 @@ use crate::layout::{flow_region, take_in_flow}; use crate::runtime::egui::alloc; -use crate::runtime::egui::areas::Layer; use crate::runtime::env::Env; use crate::runtime::focus; use crate::runtime::layout_memory; @@ -98,32 +97,6 @@ impl Lazy { self.run(ui, |ui, _| add(ui)) } - /// [`show`](Self::show) for a child that may leave its room to other content: `add` runs first and settles; when - /// it returns `None`, `otherwise` runs in the same child `Ui` and the run is not kept, so a settling child runs - /// again in the next pass rather than replay it. A dock group's host view is one: where the host leaves the group - /// to the dock, the dock's group shows in its place and settles by its own rules. `None` when the child did not - /// run: it replayed a run of `add`, or was out of view. - /// - /// `add` runs in a `Ui` that takes room in the child only when it returns `Some`: an `add` that leaves its room - /// leaves the child as it found it, so `otherwise` takes the same place whether it runs or replays, and the child's - /// extent does not change between them (a change would cost the frame a discard pass). - pub fn show_or(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> Option, otherwise: impl FnOnce(&mut Ui) -> U) -> Option> { - self.run(ui, |ui, run| { - let mut first = alloc::child(ui, UiBuilder::new().max_rect(flow_region(ui)).layout(*ui.layout())); - match add(&mut first) { - Some(shown) => { - alloc::advance_past(ui, first.min_rect()); - Ok(shown) - } - None => { - drop(first); - run.unkept(ui.ctx()); - Err(otherwise(ui)) - } - } - }) - } - fn run(self, ui: &mut Ui, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Option { let key = match self.content { Some(version) => Key::Version(version), @@ -208,7 +181,7 @@ impl Lazy { return Shown::Replayed(kept); } let mark = focus::mark(&ctx); - let mut run = Run { recording: self.settles && real, kept: true, layer: place.layer, output: None }; + let mut run = Run { recording: self.settles && real, output: None }; let edits = if run.recording { lazy::edits(&ctx) } else { 0 }; let seen = if run.recording && matches!(key, Key::Memo(_)) { crate::runtime::inputs::seen(&ctx) } else { Default::default() }; if run.recording { @@ -221,9 +194,6 @@ impl Lazy { // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); let record = run.recording.then(|| replay::close(&ctx, place.layer)); - if !run.kept { - lazy::forget(&ctx, id); - } if real { layout_memory::backstop(&ctx, id, rect.size()); } @@ -263,23 +233,9 @@ pub(super) enum Shown { OutOfView, } -/// The run of a child: whether it records what it adds for a replay, and whether it is kept. +/// The run of a child: whether it records what it adds for a replay. pub(super) struct Run { recording: bool, - kept: bool, - layer: Layer, /// What a memoized view's run returned, which its replays return. pub(super) output: Option, } - -impl Run { - /// Ends the run's record here and keeps it from settling: what the child adds from here on is not what it settles - /// on. - fn unkept(&mut self, ctx: &egui::Context) { - if self.recording { - replay::close(ctx, self.layer); - self.recording = false; - } - self.kept = false; - } -} diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index e917c3f4f..ff21b9c5a 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -870,6 +870,26 @@ impl MemoProps for craft_behavior::IconId { } /// Derived `Hash` (`#[non_exhaustive]`). +/// Every field (`#[non_exhaustive]`, so a field added later is listed here by hand): the screen rect, the document +/// point at its centre, the zoom, the turn, the mirror and the pixel aspect. +impl MemoProps for craft_behavior::canvas::CanvasView { + fn key(&self, key: &mut MemoKey) { + self.rect.key(key); + for value in [self.center.x, self.center.y, self.zoom, self.rotation, self.aspect] { + value.key(key); + } + self.flip_x.key(key); + } +} + +/// The width and the height. +impl MemoProps for craft_behavior::kurbo::Size { + fn key(&self, key: &mut MemoKey) { + self.width.key(key); + self.height.key(key); + } +} + impl MemoProps for craft_behavior::fit::FitKeep { fn key(&self, key: &mut MemoKey) { key.feed_hash(self); diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 852c97bef..6fec582ab 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -520,15 +520,6 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec }); } -/// Drops the kept run of the settling child `id`: its last run is not one it settles on, so it runs again. -pub(crate) fn forget(ctx: &Context, id: Id) { - with(ctx, |store, _, _| { - if let Some(entry) = store.entries.get_mut(&id) { - entry.settled = None; - } - }); -} - /// Whether the measure-only child `id` takes the size its last measuring run at `place` found, in place of measuring /// again, and that size. It does when that run was in this pass, or in an earlier frame and since then none of the /// settled rules a measure reads has broken (`settled`): nothing in it moves or asked to be shown again, no value it diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index 7fad69c94..8746ebcc6 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -3,9 +3,10 @@ use super::model::{Document, Layer, Panel, Tool}; use super::tools::{MarqueeTool, MoveTool, Tools}; use super::words::MockWords; +use craft_behavior::CanvasView; use craft_behavior::dock::Permissions; use craft_behavior::geometry::Directions; -use craft_behavior::kurbo::Rect as DocRect; +use craft_behavior::kurbo::{Rect as DocRect, Size}; use craft_behavior::{ColumnKey, ColumnWidth, PixelSize, RulerUnits, Ticks, keyed}; use craft_ui::canvas::{ Canvas, CanvasScrollbars, CanvasSpace, NoTool, PageFrame, Pasteboard, PixelRect, RasterDisplay, RasterSource, RulerText, Rulers, ToolHost, @@ -14,8 +15,8 @@ use craft_ui::canvas::{ use craft_ui::canvas_controls::{Guides, Marquee}; use craft_ui::contract::SizeLimits; use craft_ui::contract::{ - Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, - SweepApply, SweepStep, ToggleColumn, WordSetCx as _, + 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::list::{ListRow, ToggleCell}; @@ -114,8 +115,8 @@ impl DockPanels for Panels<'_> { fn body(&mut self, panel: &Panel, ui: &mut Ui, cx: &mut BodyCx<'_>) { match panel { Panel::Navigator => { - let size = self.document.size; - let _ = NavigatorPanel::new("Navigator", Bind::bound(&mut self.document.view), size).show(ui); + let props = NavigatorProps { view: Bind::bound(&mut self.document.view), size: self.document.size }; + let _ = MemoView::new("navigator", props, navigator).show(ui); } Panel::Layers => layers(ui, cx, self.document), Panel::Canvas | Panel::Tools => {} @@ -267,6 +268,18 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) { /// The layer table: an eye column and a name column over the layers, top first, with several layers selectable and /// the lead being the current layer. +/// What the Navigator shows: the document's view, which it pans and zooms, and the document's size. +#[derive(MemoProps)] +struct NavigatorProps<'a> { + view: Bind<'a, CanvasView>, + size: Size, +} + +/// The Navigator, a memoized view: it runs when the view or the document's size changes or the pointer is over it. +fn navigator(props: &mut NavigatorProps<'_>, ui: &mut Ui) { + let _ = NavigatorPanel::new("Navigator", props.view.reborrowed(), props.size).show(ui); +} + fn layers(ui: &mut Ui, cx: &mut BodyCx<'_>, document: &mut Document) { let columns = vec![ ColumnSpec::new(VISIBLE, "Visible", ColumnWidth::Controls(1.5)).kind(ColumnKind::Toggle(ToggleColumn::sweepable())), diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 36c90de32..8cabf2989 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -6,7 +6,6 @@ //! user did; the dock decides what a drop changes. use super::divider::{self, Divider, Drag}; -use super::group::GroupGrip; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, PanelKey, PanelSpec, Splitter}; use crate::contract::{ Access, BodyCx, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Pad, PaintUi, PartsCx, Props as _, Role, ShowContainer as _, @@ -31,7 +30,7 @@ mod sizing; use bar::panel_names; -pub(super) use bar::{BarRecord, CHEVRON, bar_band, bar_name, bar_slots, describe_chevron, paint_chevron, settled_bar, show_bar}; +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}; @@ -63,7 +62,7 @@ impl ColumnBar { } /// What a column's double arrow does, which names it and sets where it points. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub enum ColumnArrow { /// Collapses the column to icons, or expands it. @@ -196,10 +195,6 @@ pub struct DockColumn<'a, P: Value + Hash + 'static> { /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. #[prop] within: Rect, - /// The version of what the column's bar shows of the host's panels and the arrangement: with one, the bar settles - /// (`Lazy::content`). - #[prop] - content: Option, /// The plan `parts` laid out this pass, which update, paint and access read. laid: Option, resized: Vec<(P, f32)>, @@ -223,7 +218,6 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { bar: ColumnBar::Own, arrow: ColumnArrow::Collapse, within: Rect::NOTHING, - content: None, laid: None, resized: Vec::new(), width: None, @@ -250,8 +244,7 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { at: Option, mut view: impl FnMut(&Group

, Rect, &mut Ui, &mut BodyCx<'_>) + 'a, ) -> DockColumnOutput

{ - let (column, spec, auto_collapse, edge, own, arrow, content) = - (self.column, self.spec, self.auto_collapse, self.edge, self.bar, self.arrow, self.content); + let (column, spec, auto_collapse, edge, own, arrow) = (self.column, self.spec, self.auto_collapse, self.edge, self.bar, self.arrow); let mut bar = BarRecord::default(); let shown = &mut bar; let body = move |ui: &mut Ui, body: &mut BodyCx<'_>| { @@ -262,9 +255,7 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { let plan = column_plan(column, spec, body.rect, own, &sizes, drags); if own == ColumnBar::Own { let band = bar_band(ui, plan.bar, edge); - *shown = settled_bar(ui, band, content, |ui| { - column_grip(column, spec, body).map(|grip| show_bar(ui, body, band, true, auto_collapse, arrow, grip)).unwrap_or_default() - }); + *shown = show_bar(ui, band, true, auto_collapse, arrow, false, column_grip(column, spec, body)); } for (group, rect) in column.groups.iter().zip(&plan.groups) { view(group, *rect, ui, body); @@ -521,13 +512,13 @@ impl Component for DockColumn<'_, P> { } /// The grip of the column bar: a drag moves the whole column, its ghost the column's size and its panels' names. -pub(super) fn column_grip(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, body: &BodyCx<'_>) -> Option> { +pub(super) fn column_grip(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, body: &BodyCx<'_>) -> Option> { let first = column.groups.first()?; let anchor = first.panels.first()?; let active = PanelKey::of(first.active_panel().unwrap_or(anchor)); - let name = bar_name(column, spec, &body.words::().move_column); + let name = Label::from(bar_name(column, spec, &body.words::().move_column)); let ghost = (body.rect.size(), Label::from(panel_names(column, spec))); - Some(GroupGrip::new(DragUnit::Column(anchor.clone()), active).ghost(ghost).label(name)) + Some(ColumnGrip { unit: DragUnit::Column(anchor.clone()), active, ghost, name }) } /// Registers the drop bands of the two edges of the column in `rect` with the dock `dock`: a drop there makes a new diff --git a/crates/ui-panels/src/docking/dock_column/bar.rs b/crates/ui-panels/src/docking/dock_column/bar.rs index 10d8dac39..37a2e2bfc 100644 --- a/crates/ui-panels/src/docking/dock_column/bar.rs +++ b/crates/ui-panels/src/docking/dock_column/bar.rs @@ -4,21 +4,22 @@ use crate::buttons::IconButton; use crate::buttons::icon_button::IconButtonStyleKey; use crate::contract::overlay::Trigger; -use crate::contract::{Access, BodyCx, Lazy, Name, PaintUi, Props as _, Role, Show as _, ShowContainer as _, WordSetCx as _}; +use crate::contract::{Access, MemoProps, MemoView, Name, Outbox, PaintUi, Props as _, Role, Show as _, ShowContainer as _}; use crate::docking::group::GroupGrip; -use crate::docking::{ColumnArrow, DockWords, PanelSpec}; +use crate::docking::{ColumnArrow, DockWords, DragUnit, PanelKey, PanelSpec}; use crate::menu::{GroupItem, Menu, MenuWords, PanelMenu, PanelRow}; use crate::runtime::env::Label; use craft_behavior::PartKey; use craft_behavior::dock::{Column, DockEdge}; use craft_theme::variant::Tone; use craft_theme::{ControlSize, CustomVariant, Emphasis, States, Tokens, Variant, VariantLook}; -use egui::{Rect, Ui, UiBuilder}; +use egui::{Rect, Ui, UiBuilder, Vec2}; +use std::hash::Hash; /// The chevron of a column's bar: a click collapses an expanded column to icons and expands an iconic one. pub(in crate::docking) const CHEVRON: PartKey = PartKey::new("chevron"); -/// What the column bar recorded while the body ran, for the container to read when it finishes. +/// What the user did on a column bar this pass, for the container to read when it finishes. #[derive(Default)] pub(in crate::docking) struct BarRecord { /// The user asked to collapse (`true`) or expand (`false`) the column. @@ -27,6 +28,24 @@ pub(in crate::docking) struct BarRecord { pub(in crate::docking) picked: Option, } +/// What the user did on a column bar, as its view sends it. +enum BarEvent { + /// A double click on the band: collapse (`true`) or expand (`false`) the column. + Iconic(bool), + /// A dock row of the column menu. + Picked(GroupItem), +} + +/// The grip of a column bar's band: what a drag on it moves and shows. +pub(in crate::docking) struct ColumnGrip

{ + pub(in crate::docking) unit: DragUnit

, + pub(in crate::docking) active: PanelKey, + /// The column's extent where the drag starts and the name its drop region shows. + pub(in crate::docking) ghost: (Vec2, Label), + /// The band's name. + pub(in crate::docking) name: Label, +} + /// The look of the collapse control: ghost, with the muted text until the pointer is over it, and no fill under the /// pointer. fn collapse_look(tokens: &Tokens) -> VariantLook { @@ -75,66 +94,78 @@ pub(in crate::docking) fn bar_band(ui: &Ui, bar: Rect, edge: DockEdge) -> Rect { bar_slots(bar, edge, crate::runtime::env::Env::of(ui).direction.is_rtl()).1 } -/// Shows `band`, the band of a column bar ([`bar_band`]), and the column menu: a drag on `grip` moves the column, a double click -/// collapses or expands it, and a context request opens the column menu, which offers the collapse only where the -/// column's double arrow (`arrow`) collapses it. The chevron at the bar's outer end is the column's own part. Returns -/// what the user did. -pub(in crate::docking) fn show_bar( +/// Shows a column's bar in `band`: the band of a column bar ([`bar_band`]) and the column menu, as a memoized view +/// ([`column_bar`]) held to the band. A drag on the band moves the column, a double click collapses or expands it, and a +/// context request opens the column menu, which offers the collapse only where the column's double arrow (`arrow`) +/// collapses it. The chevron at the bar's outer end is the column's own part. `icons` is a collapsed column's bar. +/// Returns what the user did. +#[allow(clippy::too_many_arguments, reason = "one argument per input of the bar's view")] +pub(in crate::docking) fn show_bar( ui: &mut Ui, - body: &mut BodyCx<'_>, band: Rect, expanded: bool, auto_collapse: bool, arrow: ColumnArrow, - grip: GroupGrip

, + icons: bool, + grip: Option>, ) -> BarRecord { - let words = body.words::(); - let menu_words = body.words::(); - let toggle = ColumnArrow::Collapse.name(&words, expanded); let mut record = BarRecord::default(); - if band.width() <= 0.0 { - return record; + let Some(ColumnGrip { unit, active, ghost, name }) = grip.filter(|_| band.is_positive()) else { return record }; + let mut sent = Vec::new(); + ui.scope_builder(UiBuilder::new().max_rect(band), |ui| { + let props = BarProps { expanded, auto_collapse, arrow, icons, unit, active, ghost, name, sent: Outbox::new(&mut sent) }; + // Keyed by its column's scope id: unique among the bars of a scroll area's columns. + let _ = MemoView::new(ui.scope_id(), props, column_bar::

).show(ui); + }); + for event in sent { + match event { + BarEvent::Iconic(iconic) => record.iconic = Some(iconic), + BarEvent::Picked(item) => record.picked = Some(item), + } } + record +} + +/// The props of a column bar's view. +#[derive(MemoProps)] +struct BarProps<'a, P> { + expanded: bool, + auto_collapse: bool, + arrow: ColumnArrow, + icons: bool, + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + unit: DragUnit

, + active: PanelKey, + ghost: (Vec2, Label), + name: Label, + sent: Outbox<'a, BarEvent>, +} + +/// A column bar's band, held to the view's room, and the column menu. +fn column_bar(props: &mut BarProps<'_, P>, ui: &mut Ui) { + let band = ui.max_rect(); + let env = crate::runtime::env::Env::of(ui); + let (words, menu_words) = (env.words::(), env.words::()); + let toggle = ColumnArrow::Collapse.name(&words, props.expanded); + let grip = GroupGrip::new(props.unit.clone(), props.active).ghost(props.ghost.clone()).label(props.name.clone()).icons(props.icons); let held = grip.show_at(ui, band); if held.double_pressed { - record.iconic = Some(expanded); + props.sent.send(BarEvent::Iconic(props.expanded)); } - let collapse = (arrow == ColumnArrow::Collapse).then(|| PanelRow::Item(crate::contract::Entry::new(GroupItem::CollapseToIcons, toggle))); + let collapse = (props.arrow == ColumnArrow::Collapse).then(|| PanelRow::Item(crate::contract::Entry::new(GroupItem::CollapseToIcons, toggle))); let auto = PanelRow::Item( - crate::contract::Entry::new(GroupItem::AutoCollapse, Label::from(menu_words.panel_auto_collapse.as_str().to_owned())).checked(auto_collapse), + crate::contract::Entry::new(GroupItem::AutoCollapse, Label::from(menu_words.panel_auto_collapse.as_str().to_owned())) + .checked(props.auto_collapse), ); let rows: Vec<_> = collapse.into_iter().chain([auto]).collect(); let picked = Menu::new(Label::from(words.panels.as_str().to_owned())) .opened_by(&held.response, Trigger::Context) .show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked); - record.picked = picked.inner.flatten(); - record -} - -/// Shows a column's bar in `band` through `show`, in a child `Ui` held to the band. With a `content` version (the -/// dock's [`DockPanels::spec_version`](crate::docking::DockPanels::spec_version) joined with its arrangement) the bar -/// settles: it runs when that version, its band or something the framework tracks in it changed, or the pointer or -/// focus is on it, and otherwise repaints its last run, which reports nothing. -pub(in crate::docking) fn settled_bar(ui: &mut Ui, band: Rect, content: Option, show: impl FnOnce(&mut Ui) -> BarRecord) -> BarRecord { - if !band.is_positive() { - return BarRecord::default(); + if let Some(item) = picked.inner.flatten() { + props.sent.send(BarEvent::Picked(item)); } - ui.scope_builder(UiBuilder::new().max_rect(band), |ui| { - // Keyed by its column's scope id: unique among the bars of a scroll area's columns. - let lazy = Lazy::new(ui.scope_id(), 0.0).settles(content.is_some()); - let lazy = match content { - Some(version) => lazy.content(version), - None => lazy, - }; - lazy.show(ui, |ui| { - let record = show(ui); - // The grip takes no room in flow; the run covers the band, so the pointer over it runs it again. - ui.expand_to_include_rect(band); - record - }) - }) - .inner - .unwrap_or_default() + // The grip takes no room in flow; the run covers the band, so the pointer over it runs it again. + ui.expand_to_include_rect(band); } /// The name of a column's bar: the labels of its panels. diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index b3968564b..44fe2eb95 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -17,7 +17,7 @@ use egui::{Context, Id, Pos2, Rect, Vec2}; use std::hash::Hash; /// What a dock drag moves: one panel, or the whole group, floating window or column of a panel. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DragUnit

{ /// The panel alone. diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index fb1899f91..6450e1655 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -7,15 +7,17 @@ use super::targets::{DockSizes, DockSpot, DockTargets, ZoneRule}; use super::words::DockWords; use super::{PanelDrag, PanelKey, PanelTitle}; use crate::buttons::IconButton; +use crate::contract::overlay::Anchor; use crate::contract::{ Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, HeaderEdge, HeaderParts, HeaderRegion, - ListDrag, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, ShowCollection as _, - ShowContainer as _, Sizing, WordSetCx as _, + ListDrag, MeasureCx, MemoProps, MemoView, Name, Outbox, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, + Role, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusTarget}; +use crate::runtime::memory::sub; use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind}; use crate::tabs::{Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; @@ -131,8 +133,34 @@ fn grip_width(tokens: &Tokens) -> f32 { } /// The panel menu button at the header's end edge. pub(super) const MENU: PartKey = PartKey::new("panel_menu"); +/// Where the group menu hangs while a context request on a tab holds it open: the request's point. +const MENU_AT: &str = "menu_at"; +/// The point of a context request on a tab in the last pass, which opens the group menu. +const MENU_ASKED: &str = "menu_asked"; + +#[derive(Clone, Copy, Default)] +struct MenuAt(Option); + +#[derive(Clone, Copy, Default)] +struct MenuAsked(Option); type HeaderHookFn<'a> = Box) + 'a>; +type MenuRowsFn<'a> = Box Vec + 'a>; + +/// The rows of a group's menu, built while the menu is open: the panel menu button and a context request on a tab open +/// it. +pub struct MenuRows<'a>(MenuRowsFn<'a>); + +impl<'a> MenuRows<'a> { + /// Rows that `rows` builds each pass the menu shows. + pub fn new(rows: impl FnMut() -> Vec + 'a) -> Self { + MenuRows(Box::new(rows)) + } + + fn rows(&mut self) -> Vec { + (self.0)() + } +} /// A closure that adds the host's items to a group's header, before the tab strip. pub struct HeaderHook<'a>(HeaderHookFn<'a>); @@ -249,9 +277,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { /// sides take no drop, and its top, bottom and middle zones reach across them. #[prop(flag)] in_window: bool, - /// The rows of the group menu: the panel menu button and a context request on a tab open them. - #[prop] - menu: Vec, + /// The rows of the group menu, read while it is open: the panel menu button and a context request on a tab open + /// it. + #[prop(func = "FnMut() -> Vec")] + menu: Option>, /// Whether the panel menu button shows beside the tabs; a context request on a tab opens the menu either way. #[prop] panel_menu_shown: bool, @@ -287,7 +316,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< dock: None, zones: ZoneRule::Fraction, in_window: false, - menu: Vec::new(), + menu: None, panel_menu_shown: true, command_states: Vec::new(), extra: None, @@ -297,9 +326,9 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< .label(title) } - /// Whether the panel menu button shows: it is asked for and the menu has rows. + /// Whether the panel menu button shows: it is asked for and the group has a menu. fn shows_menu_button(&self) -> bool { - self.panel_menu_shown && !self.menu.is_empty() + self.panel_menu_shown && self.menu.is_some() } /// The panel menu button's face. @@ -367,15 +396,25 @@ impl Component for } } - /// The panel menu, opened by its button. + /// The group menu, opened by the panel menu button, under it, or by a context request on a tab, at the request's + /// point. Its rows are built only while it is open. fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { - if cx.part_if_declared(MENU).is_none() { + let Some(menu) = self.menu.as_mut() else { return }; + let popup = cx.popup("panel_menu"); + let at_id = sub(cx.core.id, MENU_AT); + if !popup.is_open(cx) { + cx.core.memory.shown::(at_id).0 = None; return; } - let popup = cx.popup("panel_menu"); + let at = cx.core.memory.shown::(at_id).0; + let anchor = match at { + Some(at) => Anchor::Point(at), + None if cx.part_if_declared(MENU).is_some() => ui.anchor_part(MENU), + None => Anchor::Pointer, + }; let name = cx.words::().panel_menu.clone(); - let rows = self.menu.clone(); - let layer = crate::menu::layer(false).anchor(ui.anchor_part(MENU)); + let rows = menu.rows(); + let layer = crate::menu::layer(false).anchor(anchor); if let Some(item) = ui.show(popup, layer, |ui, _| { Menu::inline(name.clone()).show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked).inner.flatten() }) { @@ -394,6 +433,15 @@ impl Component for fn update(&mut self, cx: &mut Cx<'_, Self>) { self.size = cx.rect.size(); + // A context request on a tab in the last pass opens the group menu at its point. + let asked = std::mem::take(&mut cx.core.memory.shown::(sub(cx.core.id, MENU_ASKED)).0); + if self.menu.is_some() { + let popup = cx.popup("panel_menu"); + if let Some(at) = asked { + cx.core.memory.shown::(sub(cx.core.id, MENU_AT)).0 = Some(at); + popup.open(cx); + } + } if let Some(grip) = cx.part_if_declared(GRIP).map(|grip| grip.press) { self.reported.toggle_minimized |= grip.double_pressed(); if self.movable && matches!(grip.phase, PressPhase::DragStart { .. }) { @@ -418,11 +466,15 @@ impl Component for } } - /// A drag that started on the strip's empty room in the header starts here: the header runs after `update`. + /// A drag that started on the strip's empty room in the header starts here, and a context request on a tab is kept + /// for the next pass's `update` to open the group menu: the header runs after `update`. fn finish(mut self, mut cx: Cx<'_, Self>) -> DockGroupOutput { if self.reported.empty_drag && self.movable { self.start_drag(&mut cx); } + if let Some(request) = &self.reported.menu { + cx.core.memory.shown::(sub(cx.core.id, MENU_ASKED)).0 = Some(request.at); + } let Reported { picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, .. } = self.reported; DockGroupOutput { response: cx.response.clone(), picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started } } @@ -446,7 +498,8 @@ impl Container for HeaderParts::NONE.end(band + button) } - /// The host's items and the tab strip, on one line. + /// The host's items, then the tab row, on one line. The tab row is a memoized view ([`tab_row`]): it runs when its + /// tabs, its room or the input on it change, else it replays, and what the user did on it comes out of its outbox. fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { for (command, state) in self.command_states.drain(..) { cx.publish(command, state); @@ -454,78 +507,152 @@ impl Container for while let Some((command, _)) = cx.take_command::() { self.reported.commands.push(command); } - let words = cx.words::(); - let from = PanelKey::of(&self.anchor); let started = drop::started(&cx.env); - let (panels, active, closable, wheel_selects) = (self.panels, self.active, self.closable, self.wheel_selects_tabs); - let menu_rows = self.menu.clone(); - let panel_menu = words.panel_menu.clone(); let mut extra = self.extra.take(); - let name = Label::from(words.panels.as_str().to_owned()); let env = crate::runtime::env::Env::of(ui); - let (dock, anchor, rtl) = (self.dock, self.anchor.clone(), env.direction.is_rtl()); + let rtl = env.direction.is_rtl(); let (line, gap) = (env.tokens.size.panel_header, env.tokens.space.gap.item); ui.set_min_height(line); let surface_pressed = cx.surface_pressed(); - let size = self.size; - let reported = &mut self.reported; - let drags = crate::runtime::drag::started(ui.ctx()); let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; - ui.with_layout(layout, |ui| { - ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) - if let Some(hook) = extra.as_mut() { - hook.run(ui, cx); - } - let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str())); - let closes = |panel: &PanelTitle| closable && panel.closable; - let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel }; - let mut strip = TabStrip::new(name.clone()) - .kind(kind) - .shown(active) - .tear_off() - .natural_height(true) - .drag_payload(move |drag: &ListDrag| Some(PanelDrag { panel: drag.grabbed, from, source: Some(size), started })); - if wheel_selects { - strip = strip.wheel_selects(); - } - let strip = strip.show_items(ui, &source, &mut |key, _| { - let panel = panels.iter().find(|panel| &panel.key == key); - let title = panel.map_or_else(Label::default, |panel| panel.title.clone()); - Tab::new(title).closable(panel.is_some_and(closes)) - }); - let strip_id = strip.response.response.id; - // A press on the group's empty body focuses its panel, as in Photoshop. - if surface_pressed { - focus::request(ui.ctx(), FocusTarget::Id(strip_id)); - } - for event in strip.response.events { - if let crate::contract::CollectionEvent::Selection(craft_behavior::SelectionChange::Set(keys)) = event { - reported.picked = keys.last().copied().or(reported.picked); + let mut sent = Vec::new(); + let strip = ui + .with_layout(layout, |ui| { + ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) + if let Some(hook) = extra.as_mut() { + hook.run(ui, cx); + } + let row = TabRow { + anchor: self.anchor.clone(), + panels: self.panels, + active: self.active, + closable: self.closable, + wheel_selects: self.wheel_selects_tabs, + dock: self.dock, + size: self.size, + sent: Outbox::new(&mut sent), + }; + MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui) + }) + .inner; + self.extra = extra; + // A press on the group's empty body focuses its panel, as in Photoshop. + if surface_pressed && let Some(strip) = strip { + focus::request(ui.ctx(), FocusTarget::Id(strip)); + } + let reported = &mut self.reported; + for event in sent { + match event { + TabEvent::Picked(key) => reported.picked = Some(key), + TabEvent::Closed(key) => reported.closed.push(key), + TabEvent::Menu(request) => reported.menu = Some(request), + TabEvent::TornOff(torn) => reported.torn_off = Some(torn), + // The strip's empty room is a handle the group is dragged by; a double click on it minimizes the group. + TabEvent::EmptyDrag => reported.empty_drag = true, + TabEvent::EmptyDouble => reported.toggle_minimized = true, + // The tab's drag records the arrangement it started on, which only the group reads. + TabEvent::DragStarted => { + reported.drag_started = true; + crate::runtime::drag::amend::(ui.ctx(), |drag| drag.started = started); } } - if let Some(dock) = dock { - register_insertions(ui.ctx(), dock, &anchor, panels, &strip.tab_rects, rtl); - } - reported.drag_started |= crate::runtime::drag::started(ui.ctx()) != drags - && crate::runtime::drag::active::(ui.ctx()).is_some_and(|drag| drag.from == from); - reported.picked = strip.picked.or(reported.picked); - reported.closed.extend(strip.closed); - reported.menu = strip.menu.or(reported.menu.take()); - reported.torn_off = strip.torn_off.or(reported.torn_off.take()); - // The strip's empty room is a handle the group is dragged by; a double click on it minimizes the group. - reported.empty_drag |= strip.empty_drag; - reported.toggle_minimized |= strip.empty_double; - if !menu_rows.is_empty() { - let rows = menu_rows.clone(); - let shown = Menu::context(panel_menu.clone(), &strip.response.response) - .show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked); - reported.item = shown.inner.flatten().or(reported.item); - } - }); - self.extra = extra; + } } } +/// What the user did on a group's tab row, in the order the row reported it. +enum TabEvent { + /// A tab was picked (a click, the wheel, the overflow menu); the last pick wins. + Picked(PanelKey), + /// A tab's close button or a middle click closed it. + Closed(PanelKey), + /// A context request on a tab: the group menu opens at its point. + Menu(ContextMenuRequest), + /// A tab was dragged out of the dock's windows. + TornOff(TornOff), + /// A drag started on the strip's empty room: the group's drag. + EmptyDrag, + /// A double click on the strip's empty room. + EmptyDouble, + /// A tab's drag started. + DragStarted, +} + +/// The props of a group's tab row: the tabs and how they show, the group's size where a tab's drag starts, and the +/// outbox for what the user did. +#[derive(MemoProps)] +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], + active: PanelKey, + closable: bool, + wheel_selects: bool, + dock: Option, + size: Vec2, + sent: Outbox<'a, TabEvent>, +} + +/// A group's tab strip with its tab insertion spots. Returns the strip's id. +fn tab_row(row: &mut TabRow<'_, P>, ui: &mut Ui) -> Id { + 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, size) = (row.panels, row.active, row.closable, row.size); + 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())); + let closes = |panel: &PanelTitle| closable && panel.closable; + let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel }; + let mut strip = TabStrip::new(name) + .kind(kind) + .shown(active) + .tear_off() + .natural_height(true) + .drag_payload(move |drag: &ListDrag| Some(PanelDrag { panel: drag.grabbed, from, source: Some(size), started: None })); + if row.wheel_selects { + strip = strip.wheel_selects(); + } + let strip = strip.show_items(ui, &source, &mut |key, _| { + let panel = panels.iter().find(|panel| &panel.key == key); + let title = panel.map_or_else(Label::default, |panel| panel.title.clone()); + Tab::new(title).closable(panel.is_some_and(closes)) + }); + for event in strip.response.events { + if let crate::contract::CollectionEvent::Selection(craft_behavior::SelectionChange::Set(keys)) = event + && let Some(key) = keys.last() + { + row.sent.send(TabEvent::Picked(*key)); + } + } + if let Some(dock) = row.dock { + register_insertions(ui.ctx(), dock, &row.anchor, panels, &strip.tab_rects, rtl); + } + if crate::runtime::drag::started(ui.ctx()) != drags && crate::runtime::drag::active::(ui.ctx()).is_some_and(|drag| drag.from == from) { + row.sent.send(TabEvent::DragStarted); + } + if let Some(key) = strip.picked { + row.sent.send(TabEvent::Picked(key)); + } + for key in strip.closed { + row.sent.send(TabEvent::Closed(key)); + } + if let Some(request) = strip.menu { + row.sent.send(TabEvent::Menu(request)); + } + if let Some(torn) = strip.torn_off { + row.sent.send(TabEvent::TornOff(torn)); + } + if strip.empty_drag { + row.sent.send(TabEvent::EmptyDrag); + } + if strip.empty_double { + row.sent.send(TabEvent::EmptyDouble); + } + strip.response.response.id +} + /// Registers the tab insertion spots of a group: the half of each shown tab nearer the start edge inserts before /// it, the other half after it, and each spot's mark is the line at the boundary it inserts at. fn register_insertions( diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 3ece3c89a..cc8f6cc19 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -2,8 +2,7 @@ use super::divider::{self, Divider, Drag}; use super::dock_column::{ - BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, settled_bar, - show_bar, + BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, }; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; use crate::buttons::IconButton; @@ -192,10 +191,6 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. #[prop] within: Rect, - /// The version of what the column's bar shows of the host's panels and the arrangement: with one, the bar settles - /// (`Lazy::content`). - #[prop] - content: Option, open: Bind<'a, Option

>, view: Option>, /// The bar's rect this pass. @@ -252,7 +247,6 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { bar: ColumnBar::Own, auto_collapse: false, within: Rect::NOTHING, - content: None, open, view: None, bar_rect: Rect::NOTHING, @@ -710,10 +704,6 @@ impl Container for IconicColumn<'_, P> { } let (column, spec, auto_collapse) = (self.column, self.spec, self.auto_collapse); let band = bar_band(ui, self.bar_rect, self.edge); - self.record = settled_bar(ui, band, self.content, |ui| { - column_grip(column, spec, cx) - .map(|grip| show_bar(ui, cx, band, false, auto_collapse, ColumnArrow::Collapse, grip.icons(true))) - .unwrap_or_default() - }); + self.record = show_bar(ui, band, false, auto_collapse, ColumnArrow::Collapse, true, column_grip(column, spec, cx)); } } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index dc680bb41..6f5c0a214 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -35,7 +35,7 @@ pub use config::{DockConfig, DockSides}; pub use drop::{Arrangement, end_replaced_drags}; pub use drop::{DockDrag, DockDropTarget, DockDropped, DragUnit, float_drop, resolve_drop, start_group_drag, start_icon_drag}; pub use event::{DockEvent, FloatSpace, HidePanels}; -pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook}; +pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook, MenuRows}; pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, WindowColumn}; pub use panels::{DockPanels, request_actions}; @@ -84,7 +84,7 @@ use tree::{FrameRules, SplitHandle}; const HANDLE: PartKey = PartKey::new("handle"); /// The stable key of a panel. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub struct PanelKey(pub u64); @@ -103,7 +103,7 @@ impl PanelKey { } /// A panel as its group's strip shows it. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub struct PanelTitle { /// The panel. diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index a988978d6..bdcd51b00 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -13,13 +13,16 @@ use egui::{Context, Id, Ui}; /// 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` /// for it. A flyout measures its group before it shows it, so a host view runs at `GroupAt::Measure` too. -/// 2. Otherwise, when the group runs (every pass, or only when something it shows changed while its chrome settles; -/// see `spec_version`): `panel_rows` for its shown panel, `group_header` once, inside the group's header region -/// before its tab strip, then `body` for the panels whose bodies are shown. A floating window's menu reads -/// `panel_rows` every pass. +/// 2. Otherwise `group_header` once, inside the group's header before its tab strip, then `body` for the panels whose +/// bodies are shown. /// -/// A panel's `spec` is read every pass, so a host may change a label or a limit between passes; a host whose chrome -/// settles (`spec_version`) changes that version with it. The dock's actions name a group by one of its panels. +/// 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. +/// +/// 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; @@ -36,33 +39,11 @@ pub trait DockPanels

{ /// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge. fn body(&mut self, panel: &P, ui: &mut Ui, cx: &mut BodyCx<'_>); - /// The version of the app data `panel`'s body shows that the framework does not track (a document's revision, a - /// job's progress). With one, the body settles (`Lazy::settles` with `Lazy::content`): it runs only when its - /// version, its room or something the framework tracks in it changed, the pointer is over it or focus is in it, and - /// otherwise repaints its last run. A [`group_view`](Self::group_view) settles the same way under the version of - /// the group's shown panel, its panels and its shown tab: the version covers what the view shows, and whether the - /// host takes the group depends only on its panels. `None` (the default) runs the body, and the view, every pass. - fn content(&self, _panel: &P) -> Option { - None - } - - /// The version of what the dock's chrome shows of the host's panels: every panel's `spec` (its name, icon and - /// limits), its `permissions`, what `group_header` shows, and whether `panel_rows` gives any rows (the group - /// shows its panel menu button only then; the rows themselves are read when the group runs). With one, each group's header and tab strip and each - /// column's bar settle (`Lazy::settles` with `Lazy::content`): they run only when this version, the arrangement, - /// their room or something the framework tracks in them changed, the pointer is over them or focus is in them, and - /// otherwise repaint their last run. A group settles only when its shown panel's body has a [`content`](Self::content) - /// version too. `None` (the default) runs the chrome every pass. - fn spec_version(&self) -> Option { - None - } - /// Takes the group holding `panels`, whose tab `active` is selected, in place of its tab strip and body: at /// `GroupAt::Show(rect)` it shows its view in `ui`, which the dock holds to `rect` and clips to it; at /// `GroupAt::Measure(width)` it measures that view at `width` the way it shows it. It returns the height the view /// takes (at `Show`, the rect's). `None` (the default) leaves the group to the dock, at both. A canvas group uses - /// the panels to tell which document it holds and draws it in the room `ui` has. At `Show` the view settles when - /// the shown panel has a [`content`](Self::content) version: a settled view repaints its last run instead of running. + /// the panels to tell which document it holds and draws it in the room `ui` has. fn group_view(&mut self, _panels: &[P], _active: usize, _ui: &mut Ui, _at: GroupAt, _cx: &mut BodyCx<'_>) -> Option { None } @@ -72,7 +53,8 @@ pub trait DockPanels

{ fn group_header(&mut self, _panels: &[P], _active: usize, _ui: &mut Ui, _cx: &mut BodyCx<'_>) {} /// The host's rows of `panel`'s menu, shown before the dock's own rows (the default has none): command rows, - /// which run by themselves. + /// which run by themselves. Read while the menu of `panel`'s group is open, and once per pass for whether the + /// group shows its panel menu button. fn panel_rows(&mut self, _panel: &P) -> Vec { Vec::new() } diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 9e08e6d01..8031951c8 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -106,7 +106,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(rows).show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, &panels, panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() } #[story(GroupGrip, covers = [Default])] diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 8c84717f3..4af84f572 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -4,7 +4,7 @@ use super::hide::{self, Shown}; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, Lazy, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; @@ -247,9 +247,6 @@ struct Scene<'s, P> { rtl: bool, /// The docked places floating panels left, for Dock Panel. floated: &'s [(P, Location

)], - /// The key of what every region of the chrome shows of the pass beyond its own room ([`chrome_key`]); `None` when - /// the host gives no [`DockPanels::spec_version`], and the chrome runs every pass. - chrome: Option, } /// The spec of `panel` in `specs`, or an unnamed one. @@ -300,7 +297,6 @@ struct Look { /// gave any, and the panel commands' states. struct GroupParts { titles: Vec, - menu: Vec, hosted: bool, states: Vec<(DockCommands, CommandState)>, } @@ -410,7 +406,6 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { hide, maximized: maximized.as_ref(), auto_collapse, - locked, sizes, rtl, }; @@ -509,7 +504,6 @@ struct Input<'i, P> { hide: HidePanels<'i, P>, maximized: Option<&'i P>, auto_collapse: bool, - locked: bool, sizes: DockSizes, rtl: bool, } @@ -536,7 +530,7 @@ 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, locked, sizes, rtl } = *input; + let Input { id, ctx, current, config, specs, hide, maximized, auto_collapse, sizes, rtl } = *input; let shell = body.shell(); let mut memory = body.memory::>().clone(); let keys: HashMap = current.layout.panels().into_iter().map(|panel| (PanelKey::of(panel), panel.clone())).collect(); @@ -545,7 +539,6 @@ fn show_area( let layout: &Layout

= &view.layout; let bounds = shell.as_ref().map_or(body.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, config, specs); - let chrome = panels.spec_version().map(|version| chrome_key(layout, version, config, locked, auto_collapse)); let scene = Scene { dock: id, sizes, @@ -559,7 +552,6 @@ fn show_area( auto_collapse, rtl, floated: ¤t.floated, - chrome, }; let open = open_of(&mut flyout, body, &memory); let mut pass = Pass { @@ -757,51 +749,6 @@ fn panel_menu_rows( (rows, hosted) } -/// The key of what the chrome's regions show beyond their own room: the host's panel specs (`version`), the config, -/// whether the workspace is locked, Auto-Collapse, and the shown arrangement: which panels each group, column and -/// floating window holds, the shown tab, and the minimized, open, iconic and stepped states, which the panel menus' -/// command states and move targets read across groups. Sizes are left out: a size reaches a region as its room. -fn chrome_key(layout: &Layout

, version: u64, config: &DockConfig, locked: bool, auto_collapse: bool) -> u64 { - use std::hash::Hasher; - fn column(shown: &Column

, hasher: &mut impl Hasher) { - (shown.iconic, shown.steps, shown.groups.len()).hash(hasher); - for group in &shown.groups { - (&group.panels, group.active, group.minimized).hash(hasher); - } - } - fn node(shown: &Node

, hasher: &mut impl Hasher) { - std::mem::discriminant(shown).hash(hasher); - match shown { - Node::Split { first, second, .. } => { - node(first, hasher); - node(second, hasher); - } - Node::Tabs { panels, active, .. } => (panels, active).hash(hasher), - Node::Stack { entries, .. } => { - for entry in entries { - (&entry.panel, entry.open).hash(hasher); - } - } - Node::Dock { side, columns, .. } => { - side.hash(hasher); - columns.iter().for_each(|one| column(one, hasher)); - } - // `Node` is non_exhaustive: a variant added later hashes only its discriminant until it is listed here. - _ => {} - } - } - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (version, config, locked, auto_collapse).hash(&mut hasher); - if let Some(root) = &layout.root { - node(root, &mut hasher); - } - for window in &layout.floating { - (window.id, window.edge).hash(&mut hasher); - column(&window.column, &mut hasher); - } - hasher.finish() -} - /// Whether `spec` is a document's: its group shows its body edge to edge. Every other docked body fills its 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 a /// docked body pads and frames nothing itself. @@ -902,26 +849,11 @@ impl Pass<'_, P> { return Some(height); } let shown = &members[active]; - let content = self.panels.content(shown); - // A host view settles as a panel body does, under the shown panel's content version (`DockPanels::content`): - // it runs again when that version, the group's panels or the shown tab change. - let view_version = content.map(|content| { - use std::hash::Hasher; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (content, members, active).hash(&mut hasher); - hasher.finish() - }); - // The group settles when the host versions its specs and the shown body: it runs again when the pass's chrome - // key, the body's version or how the group shows changes. - let version = scene.chrome.zip(content).map(|(chrome, content)| { - use std::hash::Hasher; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (chrome, content, members, active, look.minimized, look.section, look.in_window).hash(&mut hasher); - hasher.finish() - }); let words = body.words::(); 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 + // menu's rows are built only while it is open. let parts: OnceCell = OnceCell::new(); let parts_of = || { parts.get_or_init(|| { @@ -929,22 +861,23 @@ impl Pass<'_, P> { .iter() .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) .collect(); - let (menu, hosted) = panel_menu_rows(scene, &mut **panels.borrow_mut(), &words, shown); + 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); - GroupParts { titles, menu, hosted, states } + GroupParts { titles, hosted, states } }) }; // The group with `members[at]` shown: as it shows, or as it is measured. let make = |at: usize, minimized: bool| { let panels = &panels; - let GroupParts { titles, menu, hosted, states } = parts_of(); + let words = &words; + let GroupParts { titles, hosted, states } = parts_of(); let mut group = DockGroup::new(anchor.clone(), titles, 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()) .movable(scene.permissions(shown).movable) - .menu(menu.clone()) + .menu(move || panel_menu_rows(scene, &mut **panels.borrow_mut(), words, shown).0) .panel_menu_shown(*hosted) .command_states(states.clone()); if look.in_window { @@ -970,50 +903,27 @@ impl Pass<'_, P> { } GroupAt::Show(rect) => rect, }; - // One child `Ui` held to the group's rect, whether the group settles or not. It takes the parent's next id, as - // the group did before it settled, so a change of the group's first tab keeps every id inside; each Lazy is - // keyed by its `Ui`'s id, unique among the groups of a dock in a scroll area too. The host view runs first and - // settles; where the host leaves the group to the dock, the group shows in its place and settles under its own - // version. + // One child `Ui` held to the group's rect. It takes the parent's next id, so a change of the group's first tab + // keeps every id inside. The host's view runs first, held to the group's rect and clipped to it: it lays out in + // the group's room, never in the room the area has left. Where the host leaves the group to the dock, the + // group shows in its place. Both run every pass; the host memoizes inside its view, the group inside its + // header and its bodies. let output = ui .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - let view = Lazy::new(ui.unique_id(), 0.0).settles(view_version.is_some()); - let view = match view_version { - Some(version) => view.content(version), - None => view, - }; - view.show_or( - ui, - |ui| { - // The view draws held to the group's rect and clipped to it: it lays out in the group's room, - // never in the room the area has left. - let taken = ui - .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - ui.shrink_clip_rect(rect); - panels.borrow_mut().group_view(members, active, ui, at, body) - }) - .inner; - // The run covers the group, so the pointer over it runs the view again. - taken.map(|_| ui.expand_to_include_rect(rect)) - }, - |ui| { - let lazy = Lazy::new(ui.unique_id(), 0.0).settles(version.is_some()); - let lazy = match version { - Some(version) => lazy.content(version), - None => lazy, - }; - lazy.show(ui, |ui| { - let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output; - // `show_at` takes no room in flow; the run covers the group, so the pointer over it runs it again. - ui.expand_to_include_rect(rect); - output - }) - }, - ) + let taken = ui + .scope_builder(UiBuilder::new().max_rect(rect), |ui| { + ui.shrink_clip_rect(rect); + panels.borrow_mut().group_view(members, active, ui, at, body) + }) + .inner; + match taken { + Some(_) => None, + None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output), + } }) .inner; - // A host view took the group, or a settled view or group replayed its last run: nothing reached it. - let output = output.and_then(Result::err).flatten()?; + // A host view took the group. + let output = output?; // The size `panel` floats at out of this group: the group's width, and the height the group measures at with // `panel` shown in a floating window's room, so content that fills the body takes that room. let fitted = |ui: &Ui, panel: &P| { @@ -1187,28 +1097,22 @@ impl Pass<'_, P> { } let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; let work = if column.iconic { - let mut shown = IconicColumn::new(name, dock, column, Bind::given(open), &spec) + let shown = IconicColumn::new(name, dock, column, Bind::given(open), &spec) .edge(edge) .opens(opens) .bar(bar) .within(within) .auto_collapse(scene.auto_collapse); - if let Some(chrome) = scene.chrome { - shown = shown.content(chrome); - } let output = shown.show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at, in_window)); self.report.flyout.extend(output.edit.events); ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout } } else { - let mut shown = DockColumn::new(name, dock, column, &spec) + let shown = DockColumn::new(name, dock, column, &spec) .edge(edge) .bar(bar) .arrow(self.arrow_of(column)) .within(within) .auto_collapse(scene.auto_collapse); - if let Some(chrome) = scene.chrome { - shown = shown.content(chrome); - } let output = shown.show_groups_at(ui, cell, |group, rect, ui, body| { self.group_of(ui, body, group, GroupAt::Show(rect), in_window); }); @@ -1504,13 +1408,7 @@ fn window_edit( } } -/// Shows `panel`'s body in a group's body; a panel with a content version settles (`DockPanels::content`). +/// Shows `panel`'s body in a group's body. It runs every pass the group shows; the host memoizes inside it. fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) { - let content = panels.borrow().content(panel); - match content { - Some(version) => { - Lazy::new(("panel", PanelKey::of(panel).0), 0.0).settles(true).content(version).show(ui, |ui| panels.borrow_mut().body(panel, ui, body)); - } - None => panels.borrow_mut().body(panel, ui, body), - } + panels.borrow_mut().body(panel, ui, body); } diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 158de715b..7f5eaa5fb 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -1,17 +1,18 @@ -//! The runs of a settled docked layout: each group adds the same runs whatever its tab count, a closed menu, the -//! group's header controls and its tabs add none, and a panel body with a content version runs only when it changes. -//! With a host spec version the groups' chrome settles too: it runs only for the pointer, an arrangement or spec -//! change, or a body without a version. +//! The runs of a settled docked layout. Each group adds the same runs whatever its tab count, and a closed menu, the +//! group's header controls and its tabs add none. The dock's chrome (each group's tab row, each column's bar) and the +//! host's memoized bodies are memoized views: at rest they replay, and a change runs only the views it reaches. use craft_behavior::Axis; use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, SplitSize, Workspace}; -use craft_ui::contract::{Bind, BodyCx, Role}; -use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelDrag, PanelSpec}; +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::menu::PanelRow; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; use craft_ui::testing::pointer::{moved, press}; -use craft_ui::testing::{Fixture, last_pass_runs, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_pass_memo_runs, last_pass_runs, trial}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -77,133 +78,47 @@ fn a_settled_dock_group_runs_the_same_whatever_its_tab_count() { assert!(parts.is_empty(), "a settled dock ran header parts as runs: {parts:?}"); } -/// Two panels in two groups: panel 0 gives the content version `version`, panel 1 none. Each body counts its runs. -struct Versioned { - runs: Rc<[Cell; 2]>, - version: Rc>, +thread_local! { + /// The panels whose memoized bodies ran on this trial's thread, in order. + static BODY_RUNS: RefCell> = const { RefCell::new(Vec::new()) }; } -impl DockPanels for Versioned { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - - fn body(&mut self, panel: &usize, _: &mut Ui, _: &mut BodyCx<'_>) { - self.runs[*panel].set(self.runs[*panel].get() + 1); - } - - fn content(&self, panel: &usize) -> Option { - (*panel == 0).then(|| self.version.get()) - } +/// Takes the panels whose bodies ran since the last call. +fn body_runs() -> Vec { + BODY_RUNS.with(|runs| std::mem::take(&mut *runs.borrow_mut())) } -/// A panel body with a content version runs in the frame its version changes and settles otherwise; a body without one -/// runs every frame. -#[trial] -fn a_panel_body_with_a_content_version_runs_only_when_its_version_changes() { - let (runs, version): (Rc<[Cell; 2]>, _) = (Rc::default(), Rc::new(Cell::new(1))); - let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0)); - let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); - let mut panels = Versioned { runs: Rc::clone(&runs), version: Rc::clone(&version) }; - let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); - }); - fixture.room(Vec2::new(1200.0, 600.0)).settle(); - let mut frame = || { - runs.iter().for_each(|runs| runs.set(0)); - fixture.frame(Vec::new()); - [runs[0].get(), runs[1].get()] - }; - let [versioned, plain] = frame(); - assert!(versioned == 0 && plain > 0, "the versioned body settles, the other runs: {versioned}, {plain}"); - version.set(2); - assert!(frame()[0] > 0, "a new version runs the versioned body"); - assert_eq!(frame()[0], 0, "and it settles at it"); +/// What a panel's memoized body shows. +#[derive(MemoProps)] +struct BodyProps { + panel: usize, } -/// Panel 0's group is the host's view and panel 1's the dock's; both panels give the content version `version`. The -/// view counts its runs where it shows, the bodies theirs. -struct Hosted { - views: Rc>, - bodies: Rc>, - version: Rc>, +fn panel_body(props: &mut BodyProps, ui: &mut Ui) { + BODY_RUNS.with(|runs| runs.borrow_mut().push(props.panel)); + Button::new(format!("Body {}", props.panel)).show(ui); } -impl DockPanels for Hosted { - fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) - } - - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) { - self.bodies.set(self.bodies.get() + 1); - } - - fn content(&self, _: &usize) -> Option { - Some(self.version.get()) - } - - fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { - if !panels.contains(&0) { - return None; - } - match at { - GroupAt::Measure(_) => Some(0.0), - GroupAt::Show(rect) => { - self.views.set(self.views.get() + 1); - Some(rect.height()) - } - } - } -} - -/// A host view settles as a panel body does: it runs in the frame its panel's version changes or the pointer comes -/// over it, and not in a settled frame. The group the host leaves to the dock keeps showing beside it. -#[trial] -fn a_host_view_with_a_content_version_runs_only_when_its_version_changes() { - let (views, bodies, version) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)), Rc::new(Cell::new(1))); - let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0)); - let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); - let mut panels = Hosted { views: Rc::clone(&views), bodies: Rc::clone(&bodies), version: Rc::clone(&version) }; - let mut fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); - }); - fixture.room(Vec2::new(1200.0, 600.0)).settle(); - let mut frame = |events: Vec| { - views.set(0); - bodies.set(0); - fixture.frame(events); - (views.get(), bodies.get()) - }; - assert_eq!(frame(Vec::new()), (0, 0), "a settled frame runs neither the view nor the versioned body"); - assert_eq!(frame(Vec::new()), (0, 0), "nor the next one"); - version.set(2); - let (viewed, bodied) = frame(Vec::new()); - assert!(viewed > 0 && bodied > 0, "a new version runs the view and the body: {viewed}, {bodied}"); - assert_eq!(frame(Vec::new()), (0, 0), "both settle at it"); - assert!(frame(vec![moved(Pos2::new(300.0, 300.0))]).0 > 0, "the pointer over the view runs it"); - assert!(fixture.by_label("Panel 1").is_some(), "the dock's group shows beside the view"); -} - -/// Panels whose specs and bodies all have versions, so the dock's chrome settles; `plain` is a panel whose body has -/// none. -struct Settling { - spec: Rc>, +/// Panels whose bodies are memoized views, named by `labels`; `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 Settling { +impl DockPanels for Memo { fn spec(&self, panel: &usize) -> PanelSpec { - PanelSpec::new(format!("Panel {panel}")) + PanelSpec::new(self.labels.borrow()[*panel].clone()) } - fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} - - fn content(&self, panel: &usize) -> Option { - (self.plain != Some(*panel)).then_some(1) - } - - fn spec_version(&self) -> Option { - Some(self.spec.get()) + 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); + Button::new("Plain").show(ui); + return; + } + let _ = MemoView::new(("body", *panel), BodyProps { panel: *panel }, panel_body).show(ui); } fn panel_rows(&mut self, _: &usize) -> Vec { @@ -211,28 +126,37 @@ impl DockPanels for Settling { } } -/// A settled dock whose panels are [`Settling`]. -struct SettledDock { +/// A settled dock whose panels are [`Memo`]. +struct MemoDock { fixture: Fixture, - /// The spec version the panels report. - spec: Rc>, - /// The workspace the dock shows. + labels: Rc>>, + plain_runs: Rc>, workspace: Rc>>, + /// The panel each pass of the dock reported picked. + picked: Rc>>, } -/// A settled dock over `layout` whose panels are [`Settling`]. -fn settling(layout: Layout, plain: Option) -> SettledDock { - let spec = Rc::new(Cell::new(1)); +/// 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 plain_runs = Rc::new(Cell::new(0)); let workspace = Rc::new(RefCell::new(Workspace::new(layout))); - let mut panels = Settling { spec: Rc::clone(&spec), plain }; - let shown = Rc::clone(&workspace); + 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 fixture = Fixture::new(move |ui| { - DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &mut panels, DockConfig::default()).show(ui); + let output = DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &mut panels, DockConfig::default()).show(ui); + seen.borrow_mut().extend(output.picked); }); fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(1); - SettledDock { fixture, spec, workspace } + body_runs(); + picked.borrow_mut().clear(); + MemoDock { fixture, labels, plain_runs, workspace, picked } } +/// Idle frames that settle a view after a change: its animations have ended. +const SETTLE: usize = 30; + /// `groups` groups side by side, two tabs each. fn side_by_side(groups: usize) -> Layout { let group = |at: usize| Node::tabs(vec![2 * at, 2 * at + 1], 0); @@ -240,74 +164,173 @@ fn side_by_side(groups: usize) -> Layout { Layout::new(Some(root), Vec::new()) } +/// `groups` groups side by side, then a dock at the end edge with a column of panel 20 and an iconic column of panel +/// 21, and a floating window of panel 22. +fn full(groups: usize) -> Layout { + let mut iconic = Column::new(vec![Group::new(vec![21], 0)]).with_width(240.0); + iconic.iconic = true; + 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))); + Layout::new(Some(root), vec![window]) +} + +/// How the last pass's memoized views took part, by the short name of their props type: `(name, ran, replayed)`. +fn memo_runs(fixture: &Fixture) -> Vec<(&'static str, u32, u32)> { + let mut by_name: Vec<(&'static str, u32, u32)> = Vec::new(); + for (name, _, run) in last_pass_memo_runs(fixture.ctx()) { + let name = short(name); + let at = match by_name.iter().position(|(seen, _, _)| *seen == name) { + Some(at) => at, + None => { + by_name.push((name, 0, 0)); + by_name.len() - 1 + } + }; + match run { + MemoRun::Ran => by_name[at].1 += 1, + MemoRun::Replayed => by_name[at].2 += 1, + _ => {} + } + } + by_name +} + +/// The memoized views of `name` that ran and replayed in the last pass. +fn memo_of(fixture: &Fixture, name: &str) -> (u32, u32) { + memo_runs(fixture).iter().find(|(seen, _, _)| *seen == name).map_or((0, 0), |(_, ran, replayed)| (*ran, *replayed)) +} + +/// The memoized views that ran in the last pass. +fn ran(fixture: &Fixture) -> u32 { + memo_runs(fixture).iter().map(|(_, ran, _)| ran).sum() +} + /// How many runs of the types named `names` the last pass made. fn runs_of(fixture: &Fixture, names: &[&str]) -> u32 { last_pass_runs(fixture.ctx()).iter().filter(|(ty, _)| names.contains(&short(ty))).map(|(_, runs)| runs).sum() } -const CHROME: &[&str] = &["DockGroup", "TabStrip", "Tab", "GroupGrip"]; - -/// At rest a dock whose host versions its specs and bodies runs none of its groups' chrome, however many groups it -/// shows, and still paints their tabs. +/// At rest a dock with groups, a column, an iconic column and a floating window runs none of its memoized views: every +/// tab row, bar and body replays, the replays grow by the same count per group, and each group runs its container +/// once, whatever its panel count. The replayed tabs still paint their titles. #[trial] -fn a_settled_dock_runs_no_group_chrome_at_rest() { +fn an_idle_dock_runs_no_memo_view() { + let mut replays = Vec::new(); for groups in 1..=3 { - let SettledDock { mut fixture, .. } = settling(side_by_side(groups), None); + let MemoDock { mut fixture, .. } = memo_dock(full(groups), None); fixture.frame(Vec::new()); - assert_eq!(runs_of(&fixture, CHROME), 0, "{groups} settled groups ran chrome: {:?}", last_pass_runs(fixture.ctx())); + assert_eq!(ran(&fixture), 0, "{groups} groups ran memoized views: {:?}", memo_runs(&fixture)); + assert_eq!(body_runs(), Vec::::new(), "no body ran"); + // The side-by-side groups, the column's, the iconic column's flyout is closed, the window's. + assert_eq!(memo_of(&fixture, "TabRow").1 as usize, groups + 2, "every shown group's tab row replays"); + assert_eq!(memo_of(&fixture, "BarProps").1, 2, "the column's bar and the iconic column's bar replay"); + assert_eq!(runs_of(&fixture, &["DockGroup"]) as usize, groups + 2, "each shown group runs its container once"); + assert_eq!(runs_of(&fixture, &["TabStrip", "Tab", "GroupGrip", "Menu"]), 0, "{:?}", last_pass_runs(fixture.ctx())); let painted = |title: &str| fixture.texts().iter().any(|text| text.text == title); assert!((0..2 * groups).all(|panel| painted(&format!("Panel {panel}"))), "the replayed tabs paint their titles"); + replays.push(memo_runs(&fixture).iter().map(|(_, _, replayed)| replayed).sum::()); + } + assert_eq!(replays[2] - replays[1], replays[1] - replays[0], "the replays per group grow: {replays:?}"); + // A group's container runs once whatever its panel count. + let three_tabs = Layout::new(Some(Node::tabs(vec![0, 1, 2], 0)), Vec::new()); + let MemoDock { mut fixture, .. } = memo_dock(three_tabs, None); + fixture.frame(Vec::new()); + assert_eq!(runs_of(&fixture, &["DockGroup"]), 1, "a group of three panels runs its container once"); +} + +/// The pointer over one panel's body runs that body alone; the tab rows and the other bodies replay. +#[trial] +fn the_pointer_over_a_body_runs_only_that_body() { + let MemoDock { mut fixture, .. } = memo_dock(side_by_side(3), None); + let body = fixture.by_label("Body 2").expect("the second group's body").center(); + fixture.frame(vec![moved(body)]); + assert_eq!(body_runs(), vec![2], "only panel 2's body ran"); + assert_eq!(memo_of(&fixture, "TabRow").0, 0, "no tab row ran: {:?}", memo_runs(&fixture)); +} + +/// Picking a tab from outside the dock runs that group's tab row and the body it now shows; every other view replays, +/// and the frame after settles. +#[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"); + fixture.frame(Vec::new()); + assert_eq!(memo_of(&fixture, "TabRow"), (1, 2), "only the second group's tab row ran: {:?}", memo_runs(&fixture)); + assert_eq!(body_runs(), vec![3], "only the newly shown body ran"); + // The tab strip's indicator moves to the new tab, which runs the row while it animates. + fixture.idle(SETTLE).frame(Vec::new()); + assert_eq!(ran(&fixture), 0, "and they settle at it: {:?}", memo_runs(&fixture)); +} + +/// A new label for one panel runs only its group's tab row: the other groups' menus, which name it, are built only +/// while open. +#[trial] +fn a_label_change_runs_only_its_groups_chrome() { + let MemoDock { mut fixture, labels, .. } = memo_dock(side_by_side(3), None); + labels.borrow_mut()[4] = "Renamed".to_owned(); + fixture.frame(Vec::new()); + assert_eq!(memo_of(&fixture, "TabRow"), (1, 2), "only the third group's tab row ran: {:?}", memo_runs(&fixture)); + assert_eq!(body_runs(), Vec::::new(), "no body ran"); + assert!(fixture.texts().iter().any(|text| text.text == "Renamed"), "the tab shows the new label"); + fixture.idle(SETTLE).frame(Vec::new()); + assert_eq!(ran(&fixture), 0, "and it settles at it: {:?}", memo_runs(&fixture)); +} + +/// A body the host does not memoize runs every pass while the memoized views replay. +#[trial] +fn an_unconverted_body_runs_every_pass_while_the_others_replay() { + let MemoDock { mut fixture, plain_runs, .. } = memo_dock(side_by_side(2), Some(0)); + for _ in 0..3 { + plain_runs.set(0); + fixture.frame(Vec::new()); + assert_eq!(plain_runs.get(), 1, "the plain body runs once per pass"); + assert_eq!(ran(&fixture), 0, "the memoized views replay: {:?}", memo_runs(&fixture)); } } -/// The pointer over one group's tab runs that group alone; the others replay. +/// A click on a tab of a tab row that replayed reaches the dock once, through the row's outbox: idle frames that replay +/// the rows report no pick, the click reports one, and the frames after it (the focus stays on the strip, which runs +/// the row) report no other. #[trial] -fn hovering_a_tab_runs_only_its_group() { - let SettledDock { mut fixture, .. } = settling(side_by_side(3), None); - let tab = fixture.by_label("Panel 4").expect("the third group's tab"); - fixture.frame(vec![egui::Event::PointerMoved(tab.center())]); - assert_eq!(runs_of(&fixture, &["DockGroup"]), 1, "{:?}", last_pass_runs(fixture.ctx())); +fn a_click_on_a_replayed_tab_row_is_picked_once() { + let MemoDock { mut fixture, picked, workspace, .. } = memo_dock(side_by_side(2), None); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(memo_of(&fixture, "TabRow"), (0, 2), "both tab rows replay before the click"); + } + assert_eq!(*picked.borrow(), Vec::::new(), "an idle replay picks nothing"); + let tab = fixture.by_label("Panel 1").expect("the first group's second tab"); + fixture.click(&tab).idle(3); + 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; + assert!(matches!(layout.root.as_ref(), Some(Node::Split { first, .. }) if matches!(&**first, Node::Tabs { active: 1, .. })), "panel 1 is shown"); } -/// An edit of the arrangement (a tab picked from outside the dock) runs every group (its measuring runs included), and -/// a change of the host's spec version does too; the frame after settles again. +/// A double click on a replayed column bar collapses the column: the bar's view sends it through its outbox. #[trial] -fn an_arrangement_or_spec_change_runs_every_group() { - let SettledDock { mut fixture, spec, workspace } = settling(side_by_side(3), None); - workspace.borrow_mut().apply(Action::activate(1), false, |_| Permissions::ALL).expect("panel 1 is shown"); +fn a_double_click_on_a_replayed_column_bar_collapses_its_column() { + let columns = vec![Column::new(vec![Group::new(vec![20], 0)]).with_width(240.0)]; + let layout = + Layout::new(Some(Node::split(Axis::X, SplitSize::Ratio(0.7), Node::tabs(vec![0], 0), Node::dock(DockEdge::End, columns))), Vec::new()); + let MemoDock { mut fixture, workspace, .. } = memo_dock(layout, None); fixture.frame(Vec::new()); - assert!(runs_of(&fixture, &["DockGroup"]) >= 3, "the edit runs every group: {:?}", last_pass_runs(fixture.ctx())); - fixture.frame(Vec::new()); - assert_eq!(runs_of(&fixture, &["DockGroup"]), 0, "and they settle at it"); - spec.set(2); - fixture.frame(Vec::new()); - assert!(runs_of(&fixture, &["DockGroup"]) >= 3, "a new spec version runs every group: {:?}", last_pass_runs(fixture.ctx())); - fixture.frame(Vec::new()); - assert_eq!(runs_of(&fixture, &["DockGroup"]), 0, "and they settle at it"); -} - -/// A group whose shown body has no content version runs every pass, as its body does; the others settle. -#[trial] -fn a_group_whose_body_has_no_version_keeps_running() { - let SettledDock { mut fixture, .. } = settling(side_by_side(2), Some(0)); - fixture.frame(Vec::new()); - assert_eq!(runs_of(&fixture, &["DockGroup"]), 1, "{:?}", last_pass_runs(fixture.ctx())); -} - -/// A floating window's groups settle as the docked ones do. -#[trial] -fn a_settled_floating_window_runs_no_group_chrome() { - let window = Floating::single(vec![9], 0, Rect::from_min_size(Pos2::new(600.0, 100.0), Vec2::new(300.0, 300.0))); - let SettledDock { mut fixture, .. } = settling(Layout::new(Some(Node::tabs(vec![0], 0)), vec![window]), None); - fixture.frame(Vec::new()); - assert_eq!(runs_of(&fixture, CHROME), 0, "{:?}", last_pass_runs(fixture.ctx())); + 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 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:?}"); } /// A tab dragged straight onto the strip of a group that replayed its last run finds the group's drop spot in the /// frame it arrives: the replay registered the spots again. #[trial] fn a_tab_dropped_on_a_settled_group_lands_there() { - let SettledDock { mut fixture, workspace, .. } = settling(side_by_side(3), None); + let MemoDock { mut fixture, workspace, .. } = memo_dock(side_by_side(3), None); let (from, to) = (fixture.by_label("Panel 0").expect("a tab").center(), fixture.by_label("Panel 4").expect("a tab").center()); fixture.frame(vec![moved(from)]).frame(vec![press(from)]).frame(vec![moved(from + Vec2::new(0.0, 12.0))]); assert!(drag::active::(fixture.ctx()).is_some(), "the tab drag started"); @@ -323,7 +346,7 @@ fn a_tab_dropped_on_a_settled_group_lands_there() { /// group: the command the menu queued for the group reaches it. #[trial] fn close_in_a_settled_groups_panel_menu_closes_the_panel() { - let SettledDock { mut fixture, workspace, .. } = settling(side_by_side(2), None); + let MemoDock { mut fixture, workspace, .. } = memo_dock(side_by_side(2), None); let buttons: Vec<_> = fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Panel Menu")).collect(); assert_eq!(buttons.len(), 2, "each group shows its panel menu button"); diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index ef3c9bd83..16d64c203 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -14,13 +14,13 @@ use super::screen_mode::{ScreenMode, ScreenModeCommands, ScreenModeFollow}; use super::words::ShellWords; use crate::contract::overlay::Resize; use crate::contract::{ - Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, Lazy, Mount, NoValue, Outcome, PaneEdge, Props as _, Remember as _, - Role, ShellPane, ShowContainer as _, Sizing, + Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, PaneEdge, Props as _, Remember as _, Role, + ShellPane, ShowContainer as _, Sizing, }; use crate::notices::ToastStack; use crate::runtime::commands::{CommandAccess as _, CommandSet as _}; use crate::runtime::egui::pass; -use crate::runtime::env::{AppValues, BodyMode, Env, Label, RevealEdge, ShellCx, ShellEntry, ShellRegions, SlotKey, WindowKey}; +use crate::runtime::env::{AppValues, BodyMode, Env, Label, RevealEdge, ShellCx, ShellEntry, ShellRegions, WindowKey}; use crate::runtime::focus::FocusPolicy; use crate::runtime::frame::{note_shell, take_chrome_toggles}; use crate::runtime::overlay::{OpenFilter, any_open}; @@ -401,15 +401,6 @@ impl<'a, S> AppShell<'a, S> { self } - /// Gives the slot keyed `key`, added before, the version of the app data it shows ([`Slot::content`]), for the - /// slots the `options_bar` and `status` builders make. - pub fn content(mut self, key: SlotKey, version: u64) -> Self { - for placed in self.title.iter_mut().chain(self.slots.iter_mut()).filter(|placed| placed.slot.key() == key) { - placed.slot = placed.slot.clone().content(version); - } - self - } - /// Lays out the slots, then the body in what is left, runs the window's dialogs over them and shows the toasts of /// the window. Each slot and the body get `app`, one after the other: the slots that do not cover the body, then the /// body, then the slots a reveal lays over it. @@ -541,13 +532,8 @@ impl<'a, S> AppShell<'a, S> { if let Some(label) = slot.name().cloned().or_else(|| named.map(|name| name(&words))) { region = region.label(label); } - let content = slot.content_version(); - region.show(ui, |ui, bcx| match content { - Some(version) => { - Lazy::new(("slot", slot.key()), 0.0).settles(true).content(version).show(ui, |ui| add(ui, bcx, app)); - } - None => add(ui, bcx, app), - }); + // The slot runs every pass; the app memoizes inside it. + region.show(ui, |ui, bcx| add(ui, bcx, app)); } }; show_slots(ui, false, app); diff --git a/crates/ui-shell/src/shell/regions.rs b/crates/ui-shell/src/shell/regions.rs index 118a12dd0..2579323ff 100644 --- a/crates/ui-shell/src/shell/regions.rs +++ b/crates/ui-shell/src/shell/regions.rs @@ -44,8 +44,8 @@ impl SlotSize { } } -/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size, its AccessKit -/// name and the version of the app data it shows. The shell paints the chrome surface over the whole slot and a divider +/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size and its AccessKit +/// name. The shell paints the chrome surface over the whole slot and a divider /// along its edge toward the body; the title slot's bar paints its own. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -55,14 +55,13 @@ pub struct Slot { visible: bool, reveal: bool, label: Option