diff --git a/crates/layers/src/ui/filter/mod.rs b/crates/layers/src/ui/filter/mod.rs index 09566dff0..d37261ae1 100644 --- a/crates/layers/src/ui/filter/mod.rs +++ b/crates/layers/src/ui/filter/mod.rs @@ -11,7 +11,7 @@ mod stories; use craft_behavior::{EditEvent, IconId, Mixed, SelectionChange}; use craft_theme::{ControlSize, LabelColor}; use craft_ui::buttons::ToggleButton; -use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, Entry, MemoProps, NoValue, Outcome, PlainData, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::layout_components::Row; use craft_ui::list::{ListWords, label_color_label}; use craft_ui::pickers::Select; @@ -26,7 +26,7 @@ use super::tree::{LayerInfo, LayerKind, LayerPart, LayerTree}; /// What the Layers panel filters by: the filter bar's type select, Photoshop's types in its order /// (Selected waits for the feature that needs it). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum FilterBy { @@ -73,7 +73,7 @@ impl FilterBy { } /// A layer kind the Kind filter toggles. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum FilterKind { @@ -125,7 +125,7 @@ impl LayerKind { /// A layer effect kind, as the Effect filter picks it and [`LayerInfo::effect_kinds`] reports it, /// in Photoshop's order. `Overlay` stands for Color, Gradient and Pattern Overlay. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, PlainData, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum EffectKind { @@ -177,7 +177,7 @@ impl EffectKind { /// A layer attribute the Attribute filter picks, or its opposite: Photoshop's nine attributes, /// then their opposites. Each opposite lists the layers (and groups) its attribute doesn't. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum LayerAttribute { @@ -303,7 +303,7 @@ impl LayerAttribute { } /// Where a smart object's contents come from, as [`LayerInfo::smart`] reports it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum SmartSource { /// A file outside the document. @@ -313,7 +313,7 @@ pub enum SmartSource { } /// A kind of smart object the Smart Object filter toggles. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SmartKind { @@ -335,7 +335,7 @@ impl SmartKind { /// document) and passes it to [`LayersPanel::filter`](super::panel::LayersPanel::filter); every /// field has a serde default. Each type reads its own field; the others keep their values while /// another type is picked. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, MemoProps)] #[serde(default)] #[non_exhaustive] pub struct LayerFilter { @@ -354,6 +354,7 @@ pub struct LayerFilter { /// Color: the label colour; `None` (no label) at first. Serialized by name (`"none"`, `"red"`, /// … `"gray"`). #[serde(with = "label_name")] + #[memo_props(hash = "a plain enum with a derived Hash")] pub color: Option, /// Smart Object: the kinds toggled on, in the order they were toggled. pub smart: Vec, diff --git a/crates/layers/src/ui/mock.rs b/crates/layers/src/ui/mock.rs index f064b7f5e..2747a003d 100644 --- a/crates/layers/src/ui/mock.rs +++ b/crates/layers/src/ui/mock.rs @@ -1,9 +1,7 @@ //! `FakeLayers`: a `LayerTree` for stories and tests. -use std::cell::Cell; - use craft_theme::LabelColor; -use craft_ui::contract::Entry; +use craft_ui::contract::{Entry, PlainData}; use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut as S, blend_entries}; use craft_ui::runtime::env::Label; @@ -15,7 +13,7 @@ use super::tree::{ }; /// One layer of a [`FakeLayers`] tree. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PlainData)] #[non_exhaustive] pub struct FakeLayer { /// The layer's id. @@ -36,7 +34,7 @@ pub struct FakeLayer { /// A fake document's layers, kept in plain vectors: the tests' and stories' `LayerTree`. Ids are /// `u32`; the app's state (open groups, selection, effects open) is a field the test sets. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PlainData)] #[non_exhaustive] pub struct FakeLayers { /// Every layer, each group before its children, topmost first among siblings. @@ -45,15 +43,11 @@ pub struct FakeLayers { pub selection: LayerSelection, /// The layer under the pointer on the canvas. pub hovered: Option, - /// The revision the tree reports; `None` walks every pass. - pub revision: Option, /// The layers with no visible pixels, which only the app knows: the Attribute filter's Empty. pub empty: Vec, /// The linked smart objects whose file is not there, which only the app knows: the Smart Object /// filter's Missing. pub missing: Vec, - info_calls: Cell, - sub_rows_calls: Cell, } impl FakeLayers { @@ -301,16 +295,6 @@ impl FakeLayers { tree.selection.sub_row = Some(LayerRowKey::Filters(smart, Some(0))); tree } - - /// How many times `info` was called since the last [`take_info_calls`](Self::take_info_calls). - pub fn take_info_calls(&self) -> usize { - self.info_calls.replace(0) - } - - /// How many times `sub_rows` was called since the last [`take_sub_rows_calls`](Self::take_sub_rows_calls). - pub fn take_sub_rows_calls(&self) -> usize { - self.sub_rows_calls.replace(0) - } } impl FakeLayers { @@ -380,7 +364,6 @@ impl LayerTree for FakeLayers { } fn info(&self, id: &u32) -> LayerInfo { - self.info_calls.set(self.info_calls.get() + 1); self.layer(id).map(|layer| layer.info.clone()).unwrap_or_else(|| LayerInfo::new(String::new(), LayerKind::Pixel)) } @@ -400,7 +383,6 @@ impl LayerTree for FakeLayers { } fn sub_rows(&self, id: &u32, group: SubRowGroup) -> Option { - self.sub_rows_calls.set(self.sub_rows_calls.get() + 1); let layer = self.layer(id)?; match group { SubRowGroup::Effects => layer.effects.clone(), @@ -468,10 +450,6 @@ impl LayerTree for FakeLayers { self.hovered } - fn revision(&self) -> Option { - self.revision - } - fn footer(&self) -> LayersFooterState { let active = self.selection.active.is_some(); LayersFooterState { diff --git a/crates/layers/src/ui/panel/body.rs b/crates/layers/src/ui/panel/body.rs index 3e101044a..155359e35 100644 --- a/crates/layers/src/ui/panel/body.rs +++ b/crates/layers/src/ui/panel/body.rs @@ -77,7 +77,7 @@ pub(super) fn show_body( .selection(Bind::bound(&mut selection)) .can_rename(|key| matches!(key, LayerRowKey::Layer(id) if tree.info(id).renamable)) .accepts(|drag: &ListDrag>, _over, insert| { - accepts_drop(tree, drag, &order, insert, craft_ui::runtime::pointer::frame(&ctx).mods) + accepts_drop(tree, drag, order, insert, craft_ui::runtime::pointer::frame(&ctx).mods) }) .drag_payload({ let document = cx.document; @@ -98,7 +98,7 @@ pub(super) fn show_body( hovered = Some(id.clone()); } let row = build_row(cx, key).cells(item.cells()).state(item.row.clone()); - match rows.rows.get(item.at) { + match rows.rows().get(item.at) { Some(shown) if shown.has_children => row.depth(shown.paint_depth).group(shown.open), Some(shown) => row.depth(shown.paint_depth), None => row, @@ -107,7 +107,7 @@ pub(super) fn show_body( let mut events: Vec> = reveal.opens.iter().cloned().map(LayersEvent::Open).collect(); let drop_preview = match &out.pending_drop { - Some(PendingDrop::Reorder(mv)) if cx.options.preview_on_canvas_when_reordering => match layer_drop(mv, &order, &parent_of, filtered) { + Some(PendingDrop::Reorder(mv)) if cx.options.preview_on_canvas_when_reordering => match layer_drop(mv, order, &parent_of, filtered) { Some(LayerDrop::Layers(layers)) => Some(layers), _ => None, }, @@ -115,7 +115,7 @@ pub(super) fn show_body( }; let selection_changed = out.events.iter().any(|event| matches!(event, CollectionEvent::Selection(_))); let list_events = out.events; - map_events(cx, &order, &parent_of, filtered, lock_name, session, list_events, &mut events); + map_events(cx, order, &parent_of, filtered, lock_name, session, list_events, &mut events); if selection_changed { let mut layers: Vec = Vec::new(); for key in &selection.items { diff --git a/crates/layers/src/ui/panel/body/rows.rs b/crates/layers/src/ui/panel/body/rows.rs index c682c9f64..74e144b32 100644 --- a/crates/layers/src/ui/panel/body/rows.rs +++ b/crates/layers/src/ui/panel/body/rows.rs @@ -2,9 +2,10 @@ use craft_behavior::{ColumnKey, DisplayOrder, ItemSource, Selection}; use craft_keymap::Mods; -use craft_ui::contract::{OpenChange, SweepApply}; +use craft_ui::contract::{BodyCx, MemoKey, MemoProps, OpenChange, Revision, SweepApply, Tracked}; use craft_ui::list::{ThumbTarget, tree_steps}; use std::borrow::Cow; +use std::sync::Arc; use super::super::context::PanelContext; use super::super::events::LayerColumn; @@ -27,55 +28,91 @@ pub(in crate::ui::panel) struct DisplayRow { pub(super) open: bool, } -/// The rows of the tree as the list shows them: layers, and under each layer whose effects are open -/// the Smart Filter and effect rows. -pub(in crate::ui::panel) struct LayerRows<'t, T: LayerTree> { - tree: &'t T, - pub(in crate::ui::panel) rows: Vec>, - /// The filter left a layer out: rows list at their shown depth, so a drop finds its place by its neighbours. - pub(in crate::ui::panel) filtered: bool, - revision: Option, +/// What the display order derives from: the tree's tracked revision, the filter and the groups a reveal opens. A +/// change of any of them builds the rows again; nothing else does. +#[derive(MemoProps)] +pub(in crate::ui::panel) struct RowsKey<'a, Id: MemoProps> { + pub(in crate::ui::panel) tree: Revision, + pub(in crate::ui::panel) filter: &'a LayerFilter, + pub(in crate::ui::panel) opened: &'a [Id], } -impl<'t, T: LayerTree> LayerRows<'t, T> { - /// The rows for `filter`, with the groups in `opened` shown open besides the tree's own. - pub(in crate::ui::panel) fn new(tree: &'t T, filter: &LayerFilter, opened: &[T::Id]) -> Self { +/// The display order of the tree, derived from a [`RowsKey`] and kept across passes. +pub(in crate::ui::panel) struct RowsModel { + pub(in crate::ui::panel) rows: Vec>, + /// The row keys in display order. + keys: Vec>, + /// The filter left a layer out: rows list at their shown depth, so a drop finds its place by its neighbours. + pub(in crate::ui::panel) filtered: bool, + /// The number the list keeps its display order by: it follows the key. + revision: u64, +} + +impl RowsModel { + /// The rows of `tree` for `filter`, with the groups in `opened` shown open besides the tree's own. + fn walk>(tree: &T, filter: &LayerFilter, opened: &[Id], revision: u64) -> Self { let active = filter.active(); let mut walk = Walk { tree, filter, active, open_all: active && filter.lists_closed_contents(), opened, left_out: false }; let mut rows = Vec::new(); push_level(&mut walk, tree.children(None), Level { shown: 0, true_depth: 0 }, &mut rows); - let revision = tree.revision().filter(|_| !active && opened.is_empty()); - LayerRows { tree, rows, filtered: walk.left_out, revision } + let keys = rows.iter().map(|row| row.key.clone()).collect(); + RowsModel { rows, keys, filtered: walk.left_out, revision } + } +} + +/// The rows of the tree as the list shows them: layers, and under each layer whose effects are open +/// the Smart Filter and effect rows. +pub(in crate::ui::panel) struct LayerRows<'t, T: LayerTree> { + tree: &'t T, + model: Arc>, +} + +impl<'t, T: LayerTree> LayerRows<'t, T> { + /// The rows for `filter` and `opened`, derived by the body `cx` from the tracked `tree`. + pub(in crate::ui::panel) fn new(cx: &BodyCx<'_>, tree: &'t Tracked, filter: &LayerFilter, opened: &[T::Id]) -> Self { + let key = RowsKey { tree: tree.revision(), filter, opened }; + // The low half of the key's hash tells the list when the order changed. + let revision = MemoKey::of(&key) as u64; + let model = cx.derived(&key, || RowsModel::walk(&**tree, filter, opened, revision)); + LayerRows { tree: &**tree, model } } - pub(in crate::ui::panel) fn keys(&self) -> Vec> { - self.rows.iter().map(|row| row.key.clone()).collect() + pub(in crate::ui::panel) fn rows(&self) -> &[DisplayRow] { + &self.model.rows + } + + pub(in crate::ui::panel) fn filtered(&self) -> bool { + self.model.filtered + } + + pub(in crate::ui::panel) fn keys(&self) -> &[LayerRowKey] { + &self.model.keys } } impl DisplayOrder> for LayerRows<'_, T> { fn len(&self) -> usize { - self.rows.len() + self.model.rows.len() } fn key(&self, at: usize) -> LayerRowKey { - self.rows[at].key.clone() + self.model.rows[at].key.clone() } fn depth(&self, at: usize) -> usize { - self.rows[at].depth + self.model.rows[at].depth } fn has_children(&self, at: usize) -> bool { - self.rows[at].has_children + self.model.rows[at].has_children } fn open(&self, at: usize) -> bool { - self.rows[at].open + self.model.rows[at].open } fn text(&self, at: usize) -> Option> { - match &self.rows[at].key { + match &self.model.rows[at].key { LayerRowKey::Layer(id) | LayerRowKey::Mask(id, _) => Some(Cow::Owned(self.tree.info(id).name)), LayerRowKey::Effects(id, index) => sub_label(self.tree, id, SubRowGroup::Effects, *index), LayerRowKey::Filters(id, index) => sub_label(self.tree, id, SubRowGroup::SmartFilters, *index), @@ -83,13 +120,13 @@ impl DisplayOrder> for LayerRows<'_, T> { } fn revision(&self) -> Option { - self.revision + Some(self.model.revision) } } impl ItemSource> for LayerRows<'_, T> { fn toggled(&self, at: usize, column: &ColumnKey) -> bool { - match &self.rows[at].key { + match &self.model.rows[at].key { LayerRowKey::Layer(id) if *column == EYE => self.tree.info(id).visible, LayerRowKey::Layer(id) if *column == LOCK => self.tree.info(id).locks.any(), LayerRowKey::Effects(id, index) if *column == EYE => sub_on(self.tree, id, SubRowGroup::Effects, *index), @@ -99,7 +136,7 @@ impl ItemSource> for LayerRows<'_, T> { } fn sub_row(&self, at: usize) -> Option { - self.rows[at].sub_steps + self.model.rows[at].sub_steps } } diff --git a/crates/layers/src/ui/panel/mod.rs b/crates/layers/src/ui/panel/mod.rs index 1402b2661..c05b59c83 100644 --- a/crates/layers/src/ui/panel/mod.rs +++ b/crates/layers/src/ui/panel/mod.rs @@ -26,7 +26,7 @@ pub(crate) use row::FX_BADGE; use std::cell::RefCell; -use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _}; +use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _, Tracked}; use craft_ui::layout_components::Stack; use craft_ui::list::ListWords; use craft_ui::primitives::textures::{ThumbSource, Thumbnails}; @@ -160,7 +160,7 @@ impl Default for Session { #[derive(craft_ui::contract::Pattern)] #[pattern(probe(LayersPanel<'static, crate::ui::mock::FakeLayers>))] pub struct LayersPanel<'a, T: LayerTree> { - tree: &'a T, + tree: &'a Tracked, settings: Option<&'a LayersSettings>, thumbnails: Option>, filter: Option>, @@ -213,8 +213,9 @@ impl Outcome for LayersOutput { } impl<'a, T: LayerTree> LayersPanel<'a, T> { - /// The panel showing `tree`. - pub fn new(tree: &'a T) -> Self { + /// The panel showing `tree`. The panel derives the display order from the tracked revision, so an edit of the tree + /// through the `Tracked` is what makes it walk the tree again. + pub fn new(tree: &'a Tracked) -> Self { Self { tree, settings: None, @@ -339,7 +340,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { /// rows, the footer. Events are reported in that order. pub fn show(self, ui: &mut Ui) -> LayersOutput { let LayersPanel { - tree, + tree: tracked, settings, thumbnails, mut filter, @@ -355,6 +356,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { rename, document, } = self; + let tree: &T = tracked; let env = Env::of(ui); let words = env.words::(); let list_words = env.words::(); @@ -440,13 +442,13 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { }) .show(ui, |ui, stack| { let filter = current.borrow().clone(); - let session = stack.memory::>(); let plan = reveal_plan(tree, reveal.clone()); - let rows = LayerRows::new(tree, &filter, &plan.opened()); + let rows = LayerRows::new(stack, tracked, &filter, &plan.opened()); + let session = stack.memory::>(); if let Some(layer) = rename.clone() { start_rename(ui, list, layer); } - let body = show_body(ui, &cx, &rows, session, &plan, rows.filtered, &unlock_label); + let body = show_body(ui, &cx, &rows, session, &plan, rows.filtered(), &unlock_label); let menus = show_row_menus(ui, &cx, &body.response, row_menu.as_deref(), session); let mut reported = body.events; reported.extend(menus); diff --git a/crates/layers/src/ui/panel/stories.rs b/crates/layers/src/ui/panel/stories.rs index bbc228244..f107c14a5 100644 --- a/crates/layers/src/ui/panel/stories.rs +++ b/crates/layers/src/ui/panel/stories.rs @@ -2,6 +2,7 @@ //! tree; extra columns; effects and Smart Filters open; filtered by Artboard and by Group, which keep each group open or //! closed. +use craft_ui::contract::Tracked; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -35,14 +36,14 @@ fn layers_panel_tree(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); // PhotoCraft's Hide Layers key, which the app hands the panel. let hide_layers = craft_keymap::Chord::new(craft_keymap::Mods::CMD, craft_keymap::Key::Comma); - let shown = LayersPanel::new(&tree).visibility_key(hide_layers).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).visibility_key(hide_layers).show(ui); with_readout(data, shown) } #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::sample(); - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -50,7 +51,7 @@ fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Name, name: String::from("o"), ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } @@ -59,14 +60,14 @@ fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_target_cell(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); let target = |_: &u32, info: &LayerInfo| Icon::new(IconSpec::svg(IconId::new(if info.visible { "target" } else { "circle" }))); - let shown = LayersPanel::new(&tree).trailing(target, |_, _| {}).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).trailing(target, |_, _| {}).show(ui); with_readout(data, shown) } #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); - let shown = LayersPanel::new(&tree).lock_column(true).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).lock_column(true).show(ui); with_readout(data, shown) } @@ -75,7 +76,7 @@ fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_row_kinds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::row_kinds(); - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -84,7 +85,7 @@ fn layers_panel_row_kinds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_frame_selected(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut tree = FakeLayers::row_kinds(); tree.selection = LayerSelection::new(vec![2], Some(2), LayerPart::Pixels); - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -96,7 +97,7 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { for layer in &mut tree.layers { layer.effects_open = layer.effects.is_some() || layer.smart_filters.is_some(); } - let shown = LayersPanel::new(&tree).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).show(ui); with_readout(data, shown) } @@ -105,7 +106,7 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::boards(); let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } @@ -114,6 +115,6 @@ fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn layers_panel_by_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::fifty(); let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); + let shown = LayersPanel::new(&Tracked::new(tree)).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } diff --git a/crates/layers/src/ui/tree.rs b/crates/layers/src/ui/tree.rs index 3c13a7f1c..164295075 100644 --- a/crates/layers/src/ui/tree.rs +++ b/crates/layers/src/ui/tree.rs @@ -11,17 +11,20 @@ use std::hash::Hash; use craft_behavior::IconId; use craft_keymap::Mods; use craft_theme::LabelColor; -use craft_ui::contract::{Entry, ReorderMove}; +use craft_ui::contract::{Entry, MemoProps, PlainData, ReorderMove}; use craft_ui::list::ThumbTarget; use super::filter::{EffectKind, LayerFilter, SmartSource}; use super::panel::MenuTarget; -/// The app's view of its layers, built per pass over its document (no copies of the layers). +/// The app's model of its layers, held in a [`Tracked`](craft_ui::contract::Tracked) the panel reads +/// (`LayersPanel::new(&Tracked)`). It is plain data, so every edit moves the tracked revision, which keys what +/// the panel derives from the tree. /// /// ```ignore -/// struct PhotoLayers<'a> { doc: &'a Document, ui: &'a UiState } -/// impl LayerTree for PhotoLayers<'_> { +/// #[derive(PlainData)] +/// struct PhotoLayers { layers: LayerIndex, open: HashSet } +/// impl LayerTree for PhotoLayers { /// type Id = LayerId; /// fn children(&self, parent: Option<&LayerId>) -> Vec { /* top of the stack first */ } /// /* … */ @@ -30,11 +33,12 @@ use super::panel::MenuTarget; /// /// The panel calls [`info`](Self::info) only for the rows it draws (the rows in view and one /// above and below), so a tree of 10,000 layers costs what its visible rows cost. -/// [`children`](Self::children) and [`is_open`](Self::is_open) are walked once per pass to build -/// the display order, unless [`revision`](Self::revision) says nothing changed. -pub trait LayerTree { - /// The app's layer id: the key of a row, of its thumbnails and of every event. - type Id: Clone + Eq + Hash + Debug + Send + Sync + 'static; +/// [`children`](Self::children) and [`is_open`](Self::is_open) are walked to build the display order, and only when the +/// tracked revision, the filter or a reveal's opens changed. +pub trait LayerTree: PlainData { + /// The app's layer id: the key of a row, of its thumbnails and of every event. It feeds the memo key of the + /// display order when a reveal opens groups. + type Id: Clone + Eq + Hash + Debug + Send + Sync + MemoProps + 'static; /// Children of `parent` (`None`: the top level), topmost first. The app leaves out what the /// panel never shows: layers outside an Isolate Layers set, a Type Mask session's working text. @@ -107,18 +111,10 @@ pub trait LayerTree { fn hovered(&self) -> Option { None } - - /// A number that changes whenever rows are added, removed, moved, opened or closed, or an - /// effects or Smart Filters row is added or removed; with it - /// the panel keeps its display order between passes instead of walking the tree each pass. - /// `None` (the default) walks every pass. - fn revision(&self) -> Option { - None - } } /// What one layer row shows. Build it with [`LayerInfo::new`] and set the fields that differ. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, PlainData)] #[non_exhaustive] pub struct LayerInfo { /// The layer's name, shown on one line with an ellipsis. @@ -131,6 +127,7 @@ pub struct LayerInfo { /// Whether the row draws faint: hidden itself or inside a hidden group (the app decides). pub dimmed: bool, /// The label colour that fills the eye cell; `None` for none. + #[plain_data(assume = "a plain Copy enum of colours")] pub label: Option, /// The layer's locks: any of them shows the lock indicator. pub locks: LayerLocks, @@ -240,7 +237,7 @@ impl LayerInfo { /// The mark in a layer thumbnail's corner ([`LayerInfo::thumb_badge`]), in the badge box the mask /// badges use. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum ThumbBadge { /// A smart object: a window glyph. @@ -250,7 +247,7 @@ pub enum ThumbBadge { } /// What a layer is. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum LayerKind { /// Pixels (PhotoCraft's raster layer). @@ -284,7 +281,7 @@ pub enum LayerKind { } /// The part of a layer edits go to, and the thumbnail that stands for it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum LayerPart { /// The layer's own pixels; a frame as a whole, its shape and content together. @@ -303,7 +300,7 @@ pub enum LayerPart { } /// One mask of a layer. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub struct MaskInfo { /// [`LayerPart::LayerMask`] or [`LayerPart::VectorMask`]. @@ -316,7 +313,7 @@ pub struct MaskInfo { } /// A layer's locks. Start from `LayerLocks::default()` (nothing locked) and set the fields that are on. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub struct LayerLocks { /// Lock transparent pixels. @@ -378,7 +375,7 @@ impl LockKind { } /// The selection as the app keeps it. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, PlainData)] #[non_exhaustive] pub struct LayerSelection { /// The selected layers, in the order they were selected. @@ -406,7 +403,7 @@ impl Default for LayerSelection { } /// The key of one row of the panel, and of what a drag carries. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PlainData)] #[non_exhaustive] pub enum LayerRowKey { /// A layer's row. @@ -446,7 +443,7 @@ pub enum SubRowGroup { } /// The effects or Smart Filter rows of a layer: a header row, then the items, top first. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, PlainData)] #[non_exhaustive] pub struct SubRows { /// The "Effects" or "Smart Filters" row; its eye shows or hides them all. @@ -463,7 +460,7 @@ impl SubRows { } /// One effects or Smart Filter row. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, PlainData)] #[non_exhaustive] pub struct SubRow { /// The row's text: "Effects", "Drop Shadow", "Gaussian Blur". diff --git a/crates/layers/tests/it/main.rs b/crates/layers/tests/it/main.rs index 0fb972e0e..8bcd971ef 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -5,6 +5,7 @@ mod comps; mod panel_drag_menu; mod panel_filter; mod panel_input; +mod panel_memo; mod panel_order; mod panel_reveal; mod panel_rows; diff --git a/crates/layers/tests/it/panel_drag_menu.rs b/crates/layers/tests/it/panel_drag_menu.rs index 7e006571f..3eddc6a26 100644 --- a/crates/layers/tests/it/panel_drag_menu.rs +++ b/crates/layers/tests/it/panel_drag_menu.rs @@ -9,7 +9,7 @@ use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayerDrop, LayerSelect, LayersDrag, LayersEvent, LayersPanel, MaskMove}; use craft_layers::ui::tree::{LayerPart, LayerRowKey, LayerTree as _}; use craft_theme::LabelColor; -use craft_ui::contract::Entry; +use craft_ui::contract::{Entry, Tracked}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Modifiers, Pos2, Vec2}; use std::cell::RefCell; @@ -27,7 +27,7 @@ const PANEL: Vec2 = Vec2::new(420.0, 560.0); fn rig() -> (Fixture, Seen, Asked) { let (seen, asked): (Seen, Asked) = (Rc::default(), Rc::default()); let (sink, menus) = (Rc::clone(&seen), Rc::clone(&asked)); - let tree = FakeLayers::sample(); + let tree = Tracked::new(FakeLayers::sample()); let mut fixture = Fixture::new(move |ui| { let out = LayersPanel::new(&tree) .row_menu(|target| { diff --git a/crates/layers/tests/it/panel_filter.rs b/crates/layers/tests/it/panel_filter.rs index 18a7177bb..7a6436f60 100644 --- a/crates/layers/tests/it/panel_filter.rs +++ b/crates/layers/tests/it/panel_filter.rs @@ -6,7 +6,7 @@ use craft_layers::ui::filter::{EffectKind, FilterBy, FilterKind, LayerAttribute, use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayersEvent, LayersPanel}; use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Tracked}; use craft_ui::testing::{Fixture, trial}; use egui::Vec2; use std::cell::{Cell, RefCell}; @@ -23,14 +23,14 @@ type Shared = Rc>; /// A panel over the artboard tree and a filter the trial sets; Find Layers runs in the pass after `find` is set. struct Rig { fixture: Fixture, - tree: Shared, + tree: Shared>, filter: Shared, find: Rc>, } /// The rig, its filter set by `start`. fn rig(start: impl FnOnce(&mut LayerFilter)) -> Rig { - let tree = Rc::new(RefCell::new(FakeLayers::boards())); + let tree = Rc::new(RefCell::new(Tracked::new(FakeLayers::boards()))); let mut filter = LayerFilter::default(); start(&mut filter); let filter = Rc::new(RefCell::new(filter)); @@ -196,7 +196,7 @@ fn find_layers_puts_the_caret_in_the_name_field_with_its_text_selected() { /// Kind, reported as a filter event so the app stores it. #[trial] fn the_type_select_lists_only_the_offered_types() { - let tree = Rc::new(RefCell::new(FakeLayers::boards())); + let tree = Rc::new(RefCell::new(Tracked::new(FakeLayers::boards()))); let mut start = LayerFilter::default(); start.by = FilterBy::Artboard; let filter = Rc::new(RefCell::new(start)); @@ -226,7 +226,7 @@ fn the_type_select_lists_only_the_offered_types() { fn a_filter_the_bar_applies_deselects_what_it_hides() { let mut tree = FakeLayers::sample(); tree.selection = LayerSelection::new(vec![3, 2, 4], Some(3), LayerPart::Pixels); - let tree = Rc::new(RefCell::new(tree)); + let tree = Rc::new(RefCell::new(Tracked::new(tree))); let filter = Rc::new(RefCell::new(LayerFilter::default())); let find = Rc::new(Cell::new(false)); let seen: Shared>> = Rc::default(); diff --git a/crates/layers/tests/it/panel_input.rs b/crates/layers/tests/it/panel_input.rs index ef21ce072..129293663 100644 --- a/crates/layers/tests/it/panel_input.rs +++ b/crates/layers/tests/it/panel_input.rs @@ -5,7 +5,7 @@ use craft_behavior::{EditEvent, EditHistory, Mixed, SelectionChange}; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayerColumn, LayerDrop, LayerPosition, LayerToggle, LayersEvent, LayersPanel}; use craft_layers::ui::tree::{LayerKind, LayerPart, LayerSelection}; -use craft_ui::contract::{MemoProps, MemoView, Outbox, PlainData, Tracked}; +use craft_ui::contract::{MemoProps, MemoView, Outbox, Tracked}; use craft_ui::testing::access::focused_key; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, Target, pointer, trial}; @@ -15,7 +15,7 @@ use std::rc::Rc; /// The app around the panel: the tree it shows and what it reported. struct App { - tree: FakeLayers, + tree: Tracked, events: Vec>, } @@ -68,7 +68,7 @@ fn apply(tree: &mut FakeLayers, event: &LayersEvent) { fn show(ui: &mut Ui, app: &mut App) { let App { tree, events } = app; - let out = LayersPanel::new(&*tree).show(ui); + let out = LayersPanel::new(tree).show(ui); for event in &out.events { apply(tree, event); } @@ -77,7 +77,7 @@ fn show(ui: &mut Ui, app: &mut App) { /// The panel over `tree`, in a room tall enough for every row. fn rig(tree: FakeLayers) -> (Fixture, Shared) { - let app = Rc::new(RefCell::new(App { tree, events: Vec::new() })); + let app = Rc::new(RefCell::new(App { tree: Tracked::new(tree), events: Vec::new() })); let shared = Rc::clone(&app); let mut fixture = Fixture::new(move |ui| show(ui, &mut shared.borrow_mut())); fixture.room(PANEL); @@ -246,24 +246,17 @@ fn shift_right_and_left_open_and_close_the_active_layers_effects() { assert_eq!(fx(take(&app)), [(7, false)], "Shift+Left closes them"); } -/// The tree a memoized view of the panel shows, as the app's model. -#[derive(PlainData)] -struct Model { - #[plain_data(assume = "a mock tree: its only interior mutability is call counters, which no view shows")] - tree: FakeLayers, -} - /// A memoized view of the panel over the app's model; it applies what the panel reports to the model and sends it on. #[derive(MemoProps)] struct PanelView<'a> { - model: &'a mut Tracked, + model: &'a mut Tracked, events: Outbox<'a, LayersEvent>, } fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) { - let out = LayersPanel::new(&props.model.tree).show(ui); + let out = LayersPanel::new(props.model).show(ui); for event in out.events { - props.model.edit(|model| apply(&mut model.tree, &event)); + apply(props.model, &event); props.events.send(event); } } @@ -274,7 +267,7 @@ fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) { #[trial] fn a_rows_access_focus_action_leads_the_focused_rows_to_it() { let settled = || { - let mut model = Tracked::new(Model { tree: FakeLayers::sample() }); + let mut model = Tracked::new(FakeLayers::sample()); let mut events = Vec::new(); let mut fixture = Fixture::new(move |ui| { MemoView::new("layers", PanelView { model: &mut model, events: Outbox::new(&mut events) }, panel_view).show(ui); diff --git a/crates/layers/tests/it/panel_memo.rs b/crates/layers/tests/it/panel_memo.rs new file mode 100644 index 000000000..5f72626bf --- /dev/null +++ b/crates/layers/tests/it/panel_memo.rs @@ -0,0 +1,134 @@ +//! `LayersPanel` in a host's memoized view: what the panel derives from its tracked tree, and when. + +use craft_layers::ui::filter::{FilterBy, LayerFilter}; +use craft_layers::ui::mock::FakeLayers; +use craft_layers::ui::panel::{LayersEvent, LayersPanel}; +use craft_ui::contract::{Bind, MemoProps, MemoView, Outbox, Tracked}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, pointer, trial}; +use egui::{Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; + +/// The panel's room: wide enough for a row's parts, tall enough for the sample tree and the footer. +const PANEL: Vec2 = Vec2::new(420.0, 560.0); + +type Shared = Rc>; + +/// What a host's view of the panel reads: the tracked tree, the filter the app stores, and an outbox for the events. +#[derive(MemoProps)] +struct Host<'a> { + tree: &'a Tracked, + filter: Bind<'a, LayerFilter>, + events: Outbox<'a, LayersEvent>, +} + +fn host(props: &mut Host<'_>, ui: &mut Ui) { + let out = LayersPanel::new(props.tree).filter(props.filter.reborrowed()).show(ui); + for event in out.events { + props.events.send(event); + } +} + +/// A fixture showing the panel over `tree` in a host view, with the shared tree, filter and delivered events. +struct Rig { + fixture: Fixture, + tree: Shared>, + filter: Shared, + seen: Shared>>, +} + +fn rig(tree: FakeLayers) -> Rig { + let tree = Rc::new(RefCell::new(Tracked::new(tree))); + let filter: Shared = Rc::default(); + let seen: Shared>> = Rc::default(); + let (shown, by, sink) = (Rc::clone(&tree), Rc::clone(&filter), Rc::clone(&seen)); + let mut fixture = Fixture::new(move |ui| { + let tree = shown.borrow(); + let mut filter = by.borrow_mut(); + let mut events = sink.borrow_mut(); + MemoView::new("layers", Host { tree: &tree, filter: Bind::bound(&mut filter), events: Outbox::new(&mut events) }, host).show(ui); + }); + fixture.room(PANEL); + fixture.settle().idle(2); + Rig { fixture, tree, filter, seen } +} + +impl Rig { + /// The builds of every pass of the last frame. + fn builds(&self) -> u32 { + last_frame_derived_builds(self.fixture.ctx()).iter().map(|(_, builds)| builds).sum() + } + + /// The host view's runs and replays in the last frame. + fn host_runs(&self) -> (u32, u32) { + let runs = last_frame_memo_runs(self.fixture.ctx()); + let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count() as u32; + (count(MemoRun::Ran), count(MemoRun::Replayed)) + } + + /// One frame with no input, after the edit of the trial. + fn frame(&mut self) -> &mut Self { + self.fixture.frame(Vec::new()); + self + } +} + +/// An idle panel of 50 layers builds nothing and replays; so do the frames after it. +#[trial] +fn an_idle_panel_builds_nothing_and_replays() { + let mut rig = rig(FakeLayers::fifty()); + for _ in 0..3 { + rig.frame(); + assert_eq!(rig.builds(), 0, "an idle frame builds no display order"); + assert_eq!(rig.host_runs(), (0, 1), "the host view replays"); + } +} + +/// One layer edit through the `Tracked` builds the display order once and runs the view once, then it replays. +#[trial] +fn one_layer_edit_builds_once() { + let mut rig = rig(FakeLayers::fifty()); + rig.tree.borrow_mut().layers[3].info.name = String::from("Renamed"); + rig.frame(); + assert_eq!(rig.builds(), 1, "the edit builds the display order once"); + assert_eq!(rig.host_runs().0, 1, "and runs the view once"); + rig.frame(); + assert_eq!(rig.builds(), 0, "the next pass builds nothing"); + assert_eq!(rig.host_runs(), (0, 1), "and replays"); +} + +/// A filter change builds the display order once. +#[trial] +fn a_filter_change_builds_once() { + let mut rig = rig(FakeLayers::fifty()); + { + let mut filter = rig.filter.borrow_mut(); + filter.by = FilterBy::Name; + filter.name = String::from("mark"); + } + rig.frame(); + assert_eq!(rig.builds(), 1, "the filter builds the display order once"); + rig.frame(); + assert_eq!(rig.builds(), 0, "the next pass builds nothing"); + assert_eq!(rig.host_runs(), (0, 1), "and the view replays"); +} + +/// A pass that runs the view for another reason, the pointer over it, keeps the display order. +#[trial] +fn a_pass_that_runs_the_view_for_the_pointer_builds_nothing() { + let mut rig = rig(FakeLayers::fifty()); + rig.fixture.frame(vec![pointer::moved(egui::Pos2::new(100.0, 200.0))]); + assert_eq!(rig.host_runs().0, 1, "the pointer over the panel runs the view"); + assert_eq!(rig.builds(), 0, "and the display order is kept"); +} + +/// An event from a click reaches the host once, in the run that produced it, and not again while the view replays. +#[trial] +fn a_clicks_event_is_delivered_once_across_the_run_and_the_replays() { + let mut rig = rig(FakeLayers::sample()); + let row = rig.fixture.by_label("Title").expect("the Title row shows"); + rig.seen.borrow_mut().clear(); + rig.fixture.click(&row).idle(4); + let selects = rig.seen.borrow().iter().filter(|event| matches!(event, LayersEvent::Select(_))).count(); + assert_eq!(selects, 1, "{:?}", rig.seen.borrow()); +} diff --git a/crates/layers/tests/it/panel_order.rs b/crates/layers/tests/it/panel_order.rs index 1dda63bdb..51664da0d 100644 --- a/crates/layers/tests/it/panel_order.rs +++ b/crates/layers/tests/it/panel_order.rs @@ -1,11 +1,11 @@ //! `LayersPanel`: the order of the rows, a filter over them and where a Smart Filter drop lands. use craft_behavior::EditEvent; -use craft_layers::ui::filter::{FilterKind, LayerFilter}; +use craft_layers::ui::filter::LayerFilter; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayerDrop, LayerPosition, LayersEvent, LayersPanel}; -use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerRowKey, LayerTree, SubRowGroup}; -use craft_ui::contract::Bind; +use craft_layers::ui::tree::{LayerRowKey, LayerTree, SubRowGroup}; +use craft_ui::contract::{Bind, PlainData, Tracked}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Pos2, Vec2}; use std::cell::RefCell; @@ -22,17 +22,16 @@ const ONE_PANEL: Vec2 = by(400.0, 560.0); type Seen = Rc>>>; type Shared = Rc>; -/// What a rig holds: the fixture, the events its panel reported, the tree and the filter it shows. -struct Rig { +/// What a rig holds: the fixture, the events its panel reported, and the tracked tree it shows. +struct Rig { fixture: Fixture, seen: Seen, - tree: Shared, - filter: Shared, + tree: Shared>, } fn rig_of + 'static>(tree: T) -> Rig { let seen: Seen = Rc::default(); - let tree = Rc::new(RefCell::new(tree)); + let tree = Rc::new(RefCell::new(Tracked::new(tree))); let filter: Shared = Rc::default(); let (sink, shown, by) = (Rc::clone(&seen), Rc::clone(&tree), Rc::clone(&filter)); let mut fixture = Fixture::new(move |ui| { @@ -43,14 +42,14 @@ fn rig_of + 'static>(tree: T) -> Rig { }); fixture.room(ONE_PANEL); fixture.settle(); - Rig { fixture, seen, tree, filter } + Rig { fixture, seen, tree } } fn rig() -> Rig { rig_of(FakeLayers::sample()) } -impl Rig { +impl Rig { fn row(&self, label: &str) -> Target { self.fixture.by_label(label).unwrap_or_else(|| panic!("no row named {label}")) } @@ -140,19 +139,6 @@ fn rows_are_listed_top_first_and_closed_groups_hide_their_layers() { assert_eq!(rig.order(&all), all); } -/// A filter reads fields the tree revision does not cover, so it applies even while the revision stands. -#[trial] -fn a_filter_applies_even_while_the_tree_revision_stands() { - let mut rig = rig(); - rig.tree.borrow_mut().revision = Some(1); - rig.filter.borrow_mut().kinds = vec![FilterKind::Pixel]; - rig.fixture.idle(3); - assert!(rig.fixture.by_label("Clipped").is_some()); - rig.tree.borrow_mut().layers[1].info = LayerInfo::new("Clipped", LayerKind::Text); - rig.fixture.idle(3); - assert!(rig.fixture.by_label("Clipped").is_none(), "a kind change shows at the same revision"); -} - /// A Smart Filter moves within its own object, with the slot counted after taking it out; effects keep their order. #[trial] fn smart_filters_reorder_within_their_object_and_effects_keep_their_order() { diff --git a/crates/layers/tests/it/panel_reveal.rs b/crates/layers/tests/it/panel_reveal.rs index 59d691d35..f611cc7a2 100644 --- a/crates/layers/tests/it/panel_reveal.rs +++ b/crates/layers/tests/it/panel_reveal.rs @@ -4,6 +4,7 @@ use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{Groups, LayersEvent, LayersPanel}; use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection}; +use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Vec2}; use std::cell::{Cell, RefCell}; @@ -49,7 +50,7 @@ fn short() -> FakeLayers { struct Rig { fixture: Fixture, - docs: Vec>, + docs: Vec>>, /// The document shown, by its position in `docs`. shown: Rc>, reveal: Rc>>, @@ -59,7 +60,7 @@ struct Rig { /// The panel over the documents `docs`, each keyed by its position when there are several. The host applies the /// panel's opens in the pass that reports them, as an app does. fn rig(docs: Vec) -> Rig { - let docs: Vec> = docs.into_iter().map(|tree| Rc::new(RefCell::new(tree))).collect(); + let docs: Vec>> = docs.into_iter().map(|tree| Rc::new(RefCell::new(Tracked::new(tree)))).collect(); let keyed = docs.len() > 1; let shown: Rc> = Rc::default(); let reveal: Rc>> = Rc::default(); diff --git a/crates/layers/tests/it/panel_rows.rs b/crates/layers/tests/it/panel_rows.rs index f5acee6e2..95bdc7818 100644 --- a/crates/layers/tests/it/panel_rows.rs +++ b/crates/layers/tests/it/panel_rows.rs @@ -6,6 +6,7 @@ use craft_layers::testing; use craft_layers::ui::mock::{FakeLayers, sub_row}; use craft_layers::ui::panel::{ActivateOn, LayerDrop, LayersEvent, LayersPanel, MaskMove}; use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerRowKey, LayerSelection, MaskInfo, SubRow, SubRowGroup, SubRows}; +use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; @@ -19,7 +20,7 @@ const SMART: u32 = 2; /// The app around the panel: the tree it shows, what it reported and the layer it last called hovered. struct App { - tree: FakeLayers, + tree: Tracked, events: Vec>, hovered: Option, } @@ -58,12 +59,12 @@ fn apply(tree: &mut FakeLayers, event: &LayersEvent) { } fn rig(tree: FakeLayers) -> (Fixture, Shared) { - let app = Rc::new(RefCell::new(App { tree, events: Vec::new(), hovered: None })); + let app = Rc::new(RefCell::new(App { tree: Tracked::new(tree), events: Vec::new(), hovered: None })); let shared = Rc::clone(&app); let mut fixture = Fixture::new(move |ui| { let mut app = shared.borrow_mut(); let App { tree, events, hovered } = &mut *app; - let out = LayersPanel::new(&*tree).show(ui); + let out = LayersPanel::new(tree).show(ui); for event in &out.events { apply(tree, event); } @@ -400,12 +401,11 @@ fn long(count: usize) -> (FakeLayers, u32) { layer.effects_open = true; layer.smart_filters = Some(SubRows::new(SubRow::new("Smart Filters"), vec![sub_row("Gaussian Blur"), sub_row("Sharpen")])); tree.selection = LayerSelection::new(vec![1], Some(1), LayerPart::Pixels); - tree.revision = Some(1); (tree, id) } -/// FW15: a long layer list asks the app only for the rows in view: a settled frame makes as many `info` and -/// `sub_rows` calls for 2,000 layers as for 200, and an off-screen group or Smart Filter row lays out nothing. +/// FW15: a long layer list builds only the rows in view: a settled frame builds as many rows for 2,000 layers as +/// for 200, and an off-screen group or Smart Filter row lays out nothing. /// Scrolled into view they show; a filter selected there stays selected after it scrolls away again. #[trial] fn a_long_layer_list_asks_only_for_the_rows_in_view() { @@ -413,9 +413,8 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() { for count in [200, 2_000] { let (tree, smart) = long(count); let (mut fixture, app) = rig(tree); - let _ = (app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls()); fixture.frame(vec![]); - calls.push((app.borrow().tree.take_info_calls(), app.borrow().tree.take_sub_rows_calls())); + calls.push(craft_ui::testing::row_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum::()); for name in ["Closed Group", "Smart Object", "Gaussian Blur", "Sharpen"] { assert!(fixture.by_label(name).is_none(), "{count} layers: the off-screen row {name:?} lays out nothing"); } @@ -444,5 +443,6 @@ fn a_long_layer_list_asks_only_for_the_rows_in_view() { assert!(take(&app).iter().all(|event| !matches!(event, LayersEvent::Select(_))), "{count} layers: scrolling selects nothing"); assert_eq!(app.borrow().tree.selection.sub_row, selected, "{count} layers: the filter stays selected"); } - assert_eq!(calls[0], calls[1], "a settled frame asks for as many rows for 2,000 layers as for 200 (info, sub_rows)"); + assert!(calls[0] > 0, "the rows in view are built"); + assert_eq!(calls[0], calls[1], "a settled frame builds as many rows for 2,000 layers as for 200"); }