diff --git a/crates/layers/src/ui/panel/body/rows.rs b/crates/layers/src/ui/panel/body/rows.rs index 4f720e895..42be30a64 100644 --- a/crates/layers/src/ui/panel/body/rows.rs +++ b/crates/layers/src/ui/panel/body/rows.rs @@ -204,24 +204,12 @@ impl RevealPlan { } } -/// The reveal of the layer the app named, or of the active layer when it changed since the last pass. -pub(in crate::ui::panel) fn reveal_plan( - tree: &T, - active: Option<&T::Id>, - named: Option, - session: &mut Session, -) -> RevealPlan { - let previous = session.seen_active.replace(active.cloned()); - if let Some(id) = named { - let opens = closed_ancestor_opens(tree, &id); - return RevealPlan { target: Some(id), opens }; +/// The reveal the app named: the layer, past its closed ancestors opened. +pub(in crate::ui::panel) fn reveal_plan(tree: &T, named: Option) -> RevealPlan { + match named { + Some(id) => RevealPlan { opens: closed_ancestor_opens(tree, &id), target: Some(id) }, + None => RevealPlan { target: None, opens: Vec::new() }, } - let changed = previous.as_ref().is_some_and(|previous| previous.as_ref() != active); - let opens = match (active, changed) { - (Some(active), true) => closed_ancestor_opens(tree, active), - _ => Vec::new(), - }; - RevealPlan { target: active.cloned().filter(|_| changed), opens } } /// The tree's selection as the list holds it: the selected layers and the sub-row selected on its own, that row or diff --git a/crates/layers/src/ui/panel/events.rs b/crates/layers/src/ui/panel/events.rs index 6d94339c9..2bdae6c46 100644 --- a/crates/layers/src/ui/panel/events.rs +++ b/crates/layers/src/ui/panel/events.rs @@ -52,7 +52,8 @@ pub enum LayersEvent { color: Option, }, /// A group asked to open or close: its disclosure (Alt for every group), the arrow keys, a - /// screen reader, or the reveal of the active layer. A view change: no undo step. + /// screen reader, or a reveal ([`LayersPanel::reveal`](super::LayersPanel::reveal)). A + /// view change: no undo step. Open(OpenChange), /// A layer's effects and Smart Filter rows asked to open or close: the `fx` disclosure, or the /// effects commands on the lead; `all` (Alt) for every layer. diff --git a/crates/layers/src/ui/panel/mod.rs b/crates/layers/src/ui/panel/mod.rs index 22d3a4b76..3645dba66 100644 --- a/crates/layers/src/ui/panel/mod.rs +++ b/crates/layers/src/ui/panel/mod.rs @@ -109,8 +109,6 @@ pub(super) struct Session { /// The selection anchor the list left, with the layers of the pick that left it. anchor: Option>, produced: Vec, - /// The active layer of the last pass, to reveal it when it changes. - seen_active: Option>, /// The menu the last context request chose. menu: Option>, /// The eye or lock sweep in progress. @@ -121,7 +119,7 @@ pub(super) struct Session { impl Default for Session { fn default() -> Self { - Session { anchor: None, produced: Vec::new(), seen_active: None, menu: None, sweeps: ToggleSweeps::default(), filter: LayerFilter::default() } + Session { anchor: None, produced: Vec::new(), menu: None, sweeps: ToggleSweeps::default(), filter: LayerFilter::default() } } } @@ -177,6 +175,7 @@ pub struct LayersPanel<'a, T: LayerTree> { trailing: Option + 'a>>, reveal: Option, rename: Option, + document: Option, } /// What [`LayersPanel::show`] returns. @@ -222,6 +221,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { trailing: None, reveal: None, rename: None, + document: None, } } @@ -304,13 +304,23 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { self } - /// Reveals `layer` this pass: its closed ancestors open ([`LayersEvent::Open`]) and its row - /// scrolls into view when hidden. The active layer is revealed by itself when it changes. + /// Reveals `layer` this pass: its closed groups open ([`LayersEvent::Open`]) and its row scrolls into view when it + /// is not wholly in view. The app calls it in the pass its active layer changes. pub fn reveal(mut self, layer: T::Id) -> Self { self.reveal = Some(layer); self } + /// The document the panel shows: the rows keep their scroll position and lead per document, so each document + /// shows again where it was left. Without it every document shares one. + pub fn document(mut self, key: impl std::hash::Hash) -> Self { + use std::hash::Hasher as _; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + key.hash(&mut hasher); + self.document = Some(hasher.finish()); + self + } + /// Opens the rename field of `layer`'s row this pass, where the layer is renamable: the app calls /// it in the pass it handles its Rename Layer command from the row menu. pub fn start_rename(mut self, layer: T::Id) -> Self { @@ -336,13 +346,17 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { trailing, reveal, rename, + document, } = self; let env = Env::of(ui); let words = env.words::(); let list_words = env.words::(); let fallback = LayersSettings::default(); let settings = settings.unwrap_or(&fallback); - let list = ui.scope_id().with("layers-rows"); + let list = match document { + Some(document) => ui.scope_id().with(("layers-rows", document)), + None => ui.scope_id().with("layers-rows"), + }; let cx = PanelContext { list, tree, @@ -419,7 +433,7 @@ 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, cx.selection.active.as_ref(), reveal.clone(), session); + let plan = reveal_plan(tree, reveal.clone()); let rows = LayerRows::new(tree, &filter, &plan.opened()); if let Some(layer) = rename.clone() { start_rename(ui, list, layer); diff --git a/crates/layers/tests/it/main.rs b/crates/layers/tests/it/main.rs index 9942f93bd..59e498702 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -4,6 +4,7 @@ mod panel_drag_menu; mod panel_filter; mod panel_input; mod panel_order; +mod panel_reveal; mod panel_rows; fn main() { diff --git a/crates/layers/tests/it/panel_reveal.rs b/crates/layers/tests/it/panel_reveal.rs new file mode 100644 index 000000000..c9b3a1930 --- /dev/null +++ b/crates/layers/tests/it/panel_reveal.rs @@ -0,0 +1,169 @@ +//! `LayersPanel` reveals: the layer the app names scrolls into view with its closed groups opened, and each document +//! keeps its own scroll position. + +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::testing::{Fixture, trial}; +use egui::{Rect, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +/// One panel's room: shorter than the tall tree, inside the 800 by 600 screen of a fixture. +const ONE_PANEL: Vec2 = Vec2::new(400.0, 480.0); + +type Shared = Rc>; + +/// The layers of the tall tree the trials name. +struct Tall { + top: u32, + group: u32, + inner: u32, +} + +/// 30 layers above a closed group holding "Inner", then the Background: Inner is far below the view. +fn tall() -> (FakeLayers, Tall) { + let mut tree = FakeLayers::default(); + let mut top = 0; + for n in (0..30).rev() { + let id = tree.add(None, LayerInfo::new(format!("Stack {n:02}"), LayerKind::Pixel), false); + if n == 29 { + top = id; + } + } + let group = tree.add(None, LayerInfo::new("Group", LayerKind::Group), false); + let inner = tree.add(Some(group), LayerInfo::new("Inner", LayerKind::Pixel), false); + tree.add(None, LayerInfo::new("Background", LayerKind::Pixel), false); + tree.selection = LayerSelection::new(vec![top], Some(top), LayerPart::Pixels); + (tree, Tall { top, group, inner }) +} + +/// A short document: two layers. +fn short() -> FakeLayers { + let mut tree = FakeLayers::default(); + let top = tree.add(None, LayerInfo::new("Short Top", LayerKind::Pixel), false); + tree.add(None, LayerInfo::new("Short Background", LayerKind::Pixel), false); + tree.selection = LayerSelection::new(vec![top], Some(top), LayerPart::Pixels); + tree +} + +struct Rig { + fixture: Fixture, + docs: Vec>, + /// The document shown, by its position in `docs`. + shown: Rc>, + reveal: Rc>>, + seen: Shared>>, +} + +/// 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 keyed = docs.len() > 1; + let shown: Rc> = Rc::default(); + let reveal: Rc>> = Rc::default(); + let seen: Shared>> = Rc::default(); + let (trees, which, asked, sink) = (docs.clone(), Rc::clone(&shown), Rc::clone(&reveal), Rc::clone(&seen)); + let mut fixture = Fixture::new(move |ui| { + let tree = &trees[which.get()]; + let events = { + let held = tree.borrow(); + let mut panel = LayersPanel::new(&*held); + if keyed { + panel = panel.document(which.get()); + } + if let Some(id) = asked.take() { + panel = panel.reveal(id); + } + panel.show(ui).events + }; + for event in &events { + if let LayersEvent::Open(change) = event { + tree.borrow_mut().layer_mut(change.key).open = change.open; + } + } + sink.borrow_mut().extend(events); + }); + fixture.room(ONE_PANEL); + fixture.settle(); + Rig { fixture, docs, shown, reveal, seen } +} + +impl Rig { + /// The rows' view: the list's node. + fn view(&self) -> Rect { + self.fixture.by_label("Layers").expect("the rows list is shown").rect + } + + /// Whether the row `name` is drawn wholly inside the rows' view. + fn in_view(&self, name: &str) -> bool { + self.fixture.by_label(name).is_some_and(|row| self.view().contains_rect(row.rect)) + } + + /// Where the row `name` is drawn. + fn row(&self, name: &str) -> Rect { + self.fixture.by_label(name).expect("the row is drawn").rect + } + + /// One frame that reveals `id`, with what it reported; asserts that the frame ran once and measured no row twice. + fn reveal(&mut self, id: u32) -> Vec> { + self.seen.borrow_mut().clear(); + self.reveal.set(Some(id)); + self.fixture.idle(1); + assert_eq!(self.fixture.passes(), 1, "a reveal runs its frame once"); + let measures = craft_ui::runtime::measure::row_measures(self.fixture.ctx()); + assert!(measures.iter().all(|(_, count)| *count == 1), "a reveal measures no row twice: {measures:?}"); + self.seen.borrow_mut().drain(..).collect() + } + + fn select(&self, id: u32) { + self.docs[self.shown.get()].borrow_mut().selection = LayerSelection::new(vec![id], Some(id), LayerPart::Pixels); + } +} + +/// #152: the layer the app reveals opens its closed groups and scrolls wholly into view in the frame that reveals it; +/// a row already in view doesn't move the list, and a pass with no reveal reports nothing. +#[trial] +fn a_revealed_layer_opens_its_groups_and_scrolls_into_view() { + let (tree, Tall { top, group, inner }) = tall(); + let mut rig = rig(vec![tree]); + assert!(rig.in_view("Stack 29"), "the panel starts at the top"); + assert!(rig.fixture.by_label("Inner").is_none(), "Inner is hidden in its closed group"); + + rig.select(inner); + let events = rig.reveal(inner); + assert!(matches!(events.as_slice(), [LayersEvent::Open(change)] if change.key == group && change.open), "the closed group opens: {events:?}"); + assert!(rig.in_view("Inner"), "Inner is scrolled wholly into view"); + assert!(!rig.in_view("Stack 29"), "the top scrolled away"); + rig.fixture.idle(2); + assert!(rig.in_view("Inner") && rig.seen.borrow().is_empty(), "the next passes keep the place and report nothing"); + + rig.select(top); + rig.reveal(top); + assert!(rig.in_view("Stack 29"), "scrolled back to the top"); + let before = rig.row("Stack 29"); + let events = rig.reveal(top + 1); + assert!(events.is_empty(), "a reveal of a layer in view reports nothing: {events:?}"); + assert_eq!(rig.row("Stack 29"), before, "no scroll for a row in view"); +} + +/// Each document keeps its own scroll position: a short document shown between doesn't move the tall one's. +#[trial] +fn each_document_keeps_its_scroll_position() { + let (tree, Tall { inner, .. }) = tall(); + let mut rig = rig(vec![tree, short()]); + rig.select(inner); + rig.reveal(inner); + rig.fixture.settle(); + let at = rig.row("Inner"); + assert!(rig.in_view("Inner"), "the tall document is scrolled to Inner"); + for _ in 0..3 { + rig.shown.set(1); + rig.fixture.settle(); + assert!(rig.in_view("Short Top"), "the short document shows from its top"); + rig.shown.set(0); + rig.fixture.settle(); + assert_eq!(rig.row("Inner"), at, "the tall document shows again where it was left"); + } +} diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index e30835ec9..f9b84b640 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -190,6 +190,10 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { drags: Drags, /// The row a key move brought to the lead in a collection without its own scroll: the page's scroll owner shows it. page_reveal: Option, + /// The row this pass scrolls into view, placed before the rows are built (`place_reveal`). + revealing: Option, + /// The rows `place_reveal` built and measured this pass: the build places them by that measure. + measured_for_reveal: Vec, /// The row the collection's own press is held on this pass, and where on it. pressed: Option<(usize, crate::contract::collection::RowPressed)>, /// The rows above and below the edge-press band declared this pass. @@ -252,6 +256,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { header: Header::default(), drags: Drags::default(), page_reveal: None, + revealing: None, + measured_for_reveal: Vec::new(), pressed: None, edge: None, } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 75601c76d..a9eb2d292 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -366,7 +366,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.drag_step(comp, cx, &layout, (rect, offset, rtl), &props); self.marquee_step(comp, cx, &layout, (rect, offset, rtl), &props); self.navigate(comp, cx, &layout, view, header_held); - self.switch_page(comp, cx, &props, &layout, view); + self.switch_page(comp, cx, &props, &layout); let lead_at = self.lead.key.as_ref().and_then(|key| self.index_of(key)).or(lead_at); self.intent_actions(comp, cx, &props, lead_at, header_held); self.context_key(cx, &layout, at, lead_at); @@ -374,9 +374,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.toggle_by_access(cx, &layout, at); self.node_by_access(comp, cx, &layout, at); self.reorder_and_rename(comp, cx, &props, lead_at); - self.requested_rename(comp, cx, &props, &layout, view); - self.requested_reveal(comp, &layout, view); - self.type_ahead(comp, cx, &layout, view, lead_at); + self.requested_rename(comp, cx, &props, &layout); + self.requested_reveal(comp, &layout); + self.type_ahead(comp, cx, &layout, lead_at); request::record_lead(&cx.core.ctx, cx.core.id, self.lead.key.as_ref().and_then(|key| self.index_of(key))); if let Some(at) = self.page_reveal.take().filter(|&at| layout.shown(at)) { cx.core.reveal = Some(self.screen(&layout, rect, at, ScrollPos::default(), rtl)); @@ -411,6 +411,19 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } let rtl = env.direction.is_rtl(); let node = matches!(C::ROLE, Role::Node(_)); + let (child_size, child_glyphs) = (comp.props(Internal::new()).child_size, comp.props(Internal::new()).child_glyphs); + // The rows sit on the surface the collection paints, else on the one the collection sits on. + let own = surface.or_else(|| cx.style.surface().and_then(|look| look.kind_in(&cx.core.state))); + let base_env = env.derive(|scoped| { + scoped.extend_values(values); + scoped.arena = Some(ArenaId::new(id)); + scoped.size = child_size.unwrap_or(cx.core.resolved.size); + if let Some(role) = child_glyphs { + scoped.glyphs = role; + } + scoped.surface = SurfaceKind::under(own, scoped.surface); + }); + self.place_reveal(comp, ui, (id, cx.core.env, &base_env), &mut layout, rect); let offset = ScrollPos { x: self.offset_x, y: self.offset }; Arc::make_mut(&mut layout).set_view(rect.size(), offset); if self.scrolls { @@ -436,18 +449,6 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if let Some(scope) = command_scope { crate::runtime::commands::register_instance(&ctx, scope, id); } - let (child_size, child_glyphs) = (comp.props(Internal::new()).child_size, comp.props(Internal::new()).child_glyphs); - // The rows sit on the surface the collection paints, else on the one the collection sits on. - let own = surface.or_else(|| cx.style.surface().and_then(|look| look.kind_in(&cx.core.state))); - let base_env = env.derive(|scoped| { - scoped.extend_values(values); - scoped.arena = Some(ArenaId::new(id)); - scoped.size = child_size.unwrap_or(cx.core.resolved.size); - if let Some(role) = child_glyphs { - scoped.glyphs = role; - } - scoped.surface = SurfaceKind::under(own, scoped.surface); - }); self.header.paint(ui, cx, env, id, rtl); let len = self.source.len(); let tree = matches!(layout.nav(), craft_behavior::NavShape::Tree); @@ -609,8 +610,10 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { (None, Some((members_ui, _))) => members_ui, (None, None) => unreachable!("a row is a run or a member"), }; - if layout.is_auto(at) { + if layout.is_auto(at) && !self.measured_for_reveal.contains(&at) { let measured = item.measure_in(measure_ui, Proposal::Width(row.width())).y; + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_measure(&ctx, rows::measured_id(id, &key)); rows::record_measure(&ctx, id, rows::measured_id(id, &key), Vec2::new(row.width(), measured)); if measured != row.height() { Arc::make_mut(&mut layout).set_height(at, measured); diff --git a/crates/ui-contract/src/contract/items/keys.rs b/crates/ui-contract/src/contract/items/keys.rs index c85de66ac..6e40ed3cf 100644 --- a/crates/ui-contract/src/contract/items/keys.rs +++ b/crates/ui-contract/src/contract/items/keys.rs @@ -49,12 +49,12 @@ impl ItemsHooks<'_, '_, C> { match step { NavStep::Moved(to) if cells => { let reveal = self.cell_move(comp, layout, mv, to, state.column, mods); - self.reveal_with(layout, reveal, view); + self.reveal_with(layout, reveal); } NavStep::Column(column) if cells => { if let Some((at, _)) = start { let reveal = self.cell_move(comp, layout, mv, at, column, mods); - self.reveal_with(layout, reveal, view); + self.reveal_with(layout, reveal); } } // An arrow at the edge of the grid still runs the rules: it collapses the selection to the active cell. @@ -72,7 +72,7 @@ impl ItemsHooks<'_, '_, C> { } else if !mods.lead && !mods.extend && comp.items().arrows_select { self.pick(comp, to, false, false); } - self.reveal_with(layout, to, view); + self.reveal_with(layout, to); } NavStep::Expand(at) => self.events.push(CollectionEvent::Open(OpenChange::new(self.source.key(at), true))), NavStep::Collapse(at) => self.events.push(CollectionEvent::Open(OpenChange::new(self.source.key(at), false))), @@ -83,7 +83,7 @@ impl ItemsHooks<'_, '_, C> { /// Ctrl+Tab and its platform equivalents at a collection of pages: the lead and the selection move to the next /// (or previous) item that can be taken, wrapping at the ends. - pub(super) fn switch_page(&mut self, comp: &C, cx: &mut Cx<'_, C>, props: &CollectionProps, layout: &C::ItemLayout, view: f32) { + pub(super) fn switch_page(&mut self, comp: &C, cx: &mut Cx<'_, C>, props: &CollectionProps, layout: &C::ItemLayout) { if !props.pages { return; } @@ -101,7 +101,7 @@ impl ItemsHooks<'_, '_, C> { if let Some(to) = to { self.move_lead(to, LeadSource::Keys); self.pick(comp, to, false, false); - self.reveal_with(layout, to, view); + self.reveal_with(layout, to); } } @@ -261,7 +261,7 @@ impl ItemsHooks<'_, '_, C> { } /// Typed text moves the lead to the next row whose label starts with it. - pub(super) fn type_ahead(&mut self, comp: &C, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, view: f32, lead_at: Option) { + pub(super) fn type_ahead(&mut self, comp: &C, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, lead_at: Option) { let (ctx, id, len) = (cx.core.ctx.clone(), cx.core.id, self.source.len()); while let Some(text) = cx.core.intents.take_text() { let now = frame::clock(&ctx); @@ -275,7 +275,7 @@ impl ItemsHooks<'_, '_, C> { if let Some(to) = TypeAhead::pick(&prefix, lead_at, len, |at| source.text(at).unwrap_or_default()) { self.move_lead(to, LeadSource::Keys); self.pick(comp, to, false, false); - self.reveal_with(layout, to, view); + self.reveal_with(layout, to); } } } diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index a7a97b2be..3fefcf765 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -8,7 +8,7 @@ use crate::contract::collection::RowState; use crate::contract::run::{Measuring, ShowAt}; use crate::contract::{Collection, Internal, ItemCx, Props, Show as _, Sizing}; use crate::runtime::access::SetPosition; -use crate::runtime::env::{Env, ItemFacts}; +use crate::runtime::env::{Env, EnvView, ItemFacts}; use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; use crate::style::{StyleCx, UiTokens}; @@ -132,61 +132,14 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { let mut memory = MemoryStage::open_peek(&ctx, id); let cells: Vec<(craft_behavior::ColumnKey, Rect)> = self.header.columns(0.0).into_iter().map(|(key, width)| (key, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, 0.0)))).collect(); - let columns: Vec = cells.iter().map(|(key, _)| key.clone()).collect(); - let toggles: Vec = self.header.toggle_columns().map(|(key, _)| key).collect(); - let aligns = self.header.aligns(); - let len = self.source.len(); let mut largest = Vec2::ZERO; let mut widest: Vec<(craft_behavior::ColumnKey, f32)> = Vec::new(); - for at in 0..len { + for at in 0..self.source.len() { if self.source.section_stop(at) { continue; } - let key = self.source.key(at); - let item_id = sub(id, ("key", key_hash(&key))); - let position = - SetPosition::new(at - self.source.section_stops_before(at)).of(len - self.source.section_stops_before(len)).columns(cells.len()); - let mut icx = ItemCx { - key: &key, - at, - rect: Rect::ZERO, - row: RowState::default(), - depth: self.source.depth(at), - set: position, - row_index: at, - row_count: len, - column_count: cells.len(), - env: env.view(), - id: sub(item_id, "item"), - cells: cells.clone(), - grid: None, - tip: None, - openers: Vec::new(), - item: item_id, - memory: &mut memory, - }; - let item = (self.item)(&key, &mut icx); - let mut item = Props::id(comp.dress(item, &RowState::default()), item_id); - let facts = ItemFacts { - item: item_id, - flags: crate::style::Flags::empty(), - position, - columns: columns.clone(), - toggles: toggles.clone(), - toggle_keys: Vec::new(), - aligns: aligns.clone(), - pressed: None, - menu_open: false, - }; - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - scoped.item = Some(item_id); - scoped.row = Some(rows::row_group(item_id)); - scoped.item_facts = Some(std::sync::Arc::new(facts)); - }), - ); - let (size, cells) = crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, Proposal::Ideal)); + let row = RowMeasure { at, rect: Rect::ZERO, cells: cells.clone(), proposal: Proposal::Ideal }; + let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row); largest = largest.max(size); for (column, width) in cells { match widest.iter_mut().find(|(held, _)| *held == column) { @@ -194,10 +147,82 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { None => widest.push((column, width)), } } - Env::restore(&ctx, installed); } (largest, widest) } + + /// Builds the item of `row.at` as the collection `id` builds it, with the default row state, under `installed` + /// (`view` is what the item builder sees), and measures it at `row.proposal` without allocating: its size and the + /// widths its column cells reported. Item memory goes to `memory`. + pub(super) fn measure_row( + &mut self, + comp: &C, + ui: &Ui, + (id, view, installed): (Id, EnvView<'_>, &Env), + memory: &mut MemoryStage, + row: RowMeasure, + ) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) { + let ctx = ui.ctx().clone(); + let RowMeasure { at, rect, cells, proposal } = row; + let len = self.source.len(); + let key = self.source.key(at); + let item_id = sub(id, ("key", key_hash(&key))); + let position = + SetPosition::new(at - self.source.section_stops_before(at)).of(len - self.source.section_stops_before(len)).columns(cells.len()); + let columns: Vec = cells.iter().map(|(key, _)| key.clone()).collect(); + let column_count = cells.len(); + let mut icx = ItemCx { + key: &key, + at, + rect, + row: RowState::default(), + depth: self.source.depth(at), + set: position, + row_index: at, + row_count: len, + column_count, + env: view, + id: sub(item_id, "item"), + cells, + grid: None, + tip: None, + openers: Vec::new(), + item: item_id, + memory, + }; + let item = (self.item)(&key, &mut icx); + let mut item = Props::id(comp.dress(item, &RowState::default()), item_id); + let facts = ItemFacts { + item: item_id, + flags: crate::style::Flags::empty(), + position, + columns, + toggles: self.header.toggle_columns().map(|(key, _)| key).collect(), + toggle_keys: Vec::new(), + aligns: self.header.aligns(), + pressed: None, + menu_open: false, + }; + let env = Env::install_for( + ui, + installed.derive_local(|scoped| { + scoped.item = Some(item_id); + scoped.row = Some(rows::row_group(item_id)); + scoped.item_facts = Some(std::sync::Arc::new(facts)); + }), + ); + let measured = crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal)); + Env::restore(&ctx, env); + measured + } +} + +/// A row to build and measure (`measure_row`): its position, rect and column cells, and the proposal it is measured at. +pub(super) struct RowMeasure { + pub(super) at: usize, + pub(super) rect: Rect, + pub(super) cells: Vec<(craft_behavior::ColumnKey, Rect)>, + pub(super) proposal: Proposal, } /// The inputs a kept measure of the items serves under. diff --git a/crates/ui-contract/src/contract/items/rename.rs b/crates/ui-contract/src/contract/items/rename.rs index f0d327ec2..c5e329712 100644 --- a/crates/ui-contract/src/contract/items/rename.rs +++ b/crates/ui-contract/src/contract/items/rename.rs @@ -19,7 +19,7 @@ impl ItemsHooks<'_, '_, C> { /// A rename requested from outside (`request_rename`): the lead moves to the item, the item is revealed and its /// rename field opens. - pub(super) fn requested_rename(&mut self, comp: &C, cx: &mut Cx<'_, C>, props: &CollectionProps, layout: &C::ItemLayout, view: f32) { + pub(super) fn requested_rename(&mut self, comp: &C, cx: &mut Cx<'_, C>, props: &CollectionProps, layout: &C::ItemLayout) { let Some(key) = request::take_rename::(&cx.core.ctx, cx.core.id) else { return }; if let Some(at) = self.index_of(&key) && !self.source.section_stop(at) @@ -27,7 +27,7 @@ impl ItemsHooks<'_, '_, C> { && comp.can_rename(&key) { self.move_lead(at, LeadSource::Keys); - self.reveal_with(layout, at, view); + self.reveal_with(layout, at); self.begin_rename(comp, cx, at); } } diff --git a/crates/ui-contract/src/contract/items/reveal.rs b/crates/ui-contract/src/contract/items/reveal.rs index 2d9951228..94be7096e 100644 --- a/crates/ui-contract/src/contract/items/reveal.rs +++ b/crates/ui-contract/src/contract/items/reveal.rs @@ -1,30 +1,95 @@ //! Bringing a row into view: a requested reveal and the scroll that does it. -use super::ItemsHooks; +use super::measure::RowMeasure; +use super::{ItemsHooks, rows}; use crate::contract::Collection; use crate::contract::collection::LeadSource; -use craft_behavior::{ItemLayout, ScrollPos}; +use crate::runtime::env::{Env, EnvView}; +use crate::runtime::memory::MemoryStage; +use craft_behavior::{ItemLayout, Proposal, ScrollPos}; +use egui::{Id, Rect, Ui, Vec2}; +use std::sync::Arc; impl ItemsHooks<'_, '_, C> { /// The item the collection was asked to reveal (`Collection::reveal`, a one-shot request of the pass): the lead /// moves to it and it scrolls into view. - pub(super) fn requested_reveal(&mut self, comp: &C, layout: &C::ItemLayout, view: f32) { + pub(super) fn requested_reveal(&mut self, comp: &C, layout: &C::ItemLayout) { if let Some(at) = comp.reveal().and_then(|key| self.index_of(key)).filter(|&at| !self.source.section_stop(at)) { self.move_lead(at, LeadSource::Keys); - self.reveal_with(layout, at, view); + self.reveal_with(layout, at); } } - /// Brings row `at` into view: the collection's own scroll moves, or, without one, the page's scroll owner is asked - /// at the end of the item step (`page_reveal`). - pub(super) fn reveal_with(&mut self, layout: &C::ItemLayout, at: usize, view: f32) { + /// Brings row `at` into view: the collection's own scroll moves before the rows are built (`place_reveal`), or, + /// without one, the page's scroll owner is asked at the end of the item step (`page_reveal`). + pub(super) fn reveal_with(&mut self, layout: &C::ItemLayout, at: usize) { if !layout.shown(at) { return; } - if !self.scrolls { + if self.scrolls { + self.revealing = Some(at); + } else { self.page_reveal = Some(at); - return; } + } + + /// Scrolls the row this pass reveals into the rows' view `view`, before the rows are built. A row the pass builds + /// for the first time takes its measured height when built and moves the rows after it, so the auto rows that + /// share the view with the revealed row, up to it, and have no kept height are built and measured first, under the + /// rows' env `installed`, until the scroll that shows the row places it by measured heights only. The build takes + /// those heights (`measured_for_reveal`) and does not measure the rows again. + pub(super) fn place_reveal( + &mut self, + comp: &C, + ui: &Ui, + (id, view_env, installed): (Id, EnvView<'_>, &Env), + layout: &mut Arc, + view: Rect, + ) { + let Some(at) = self.revealing.take().filter(|&at| layout.shown(at)) else { return }; + let ctx = ui.ctx().clone(); + loop { + self.aim_reveal(layout, at, view.height()); + let mut in_view = Vec::new(); + layout.visible(ScrollPos { x: self.offset_x, y: self.offset }, view.size(), &mut in_view); + let source = self.source; + let unmeasured: Vec = rows::measured_heights(&ctx, id, |height| { + in_view + .into_iter() + .chain([at]) + .filter(|&row| row <= at && layout.is_auto(row) && !source.section_stop(row)) + .filter(|row| !self.measured_for_reveal.contains(row) && height(rows::measured_id(id, &source.key(*row))).is_none()) + .collect() + }); + if unmeasured.is_empty() { + return; + } + let mut memory = MemoryStage::open_peek(&ctx, id); + for row in unmeasured { + if self.measured_for_reveal.contains(&row) { + continue; + } + let rect = layout.rect(row, ScrollPos::default()); + let mut cells = Vec::new(); + layout.cells(row, ScrollPos::default(), &mut cells); + let measure = RowMeasure { at: row, rect, cells, proposal: Proposal::Width(rect.width()) }; + let (size, _) = + crate::contract::steps::measuring(&ctx, || self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure)); + let measured = rows::measured_id(id, &self.source.key(row)); + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_measure(&ctx, measured); + rows::record_measure(&ctx, id, measured, Vec2::new(rect.width(), size.y)); + Arc::make_mut(layout).set_height(row, size.y); + self.measured_for_reveal.push(row); + } + let content = layout.content_size(); + self.content = Vec2::new(content.x as f32, content.y as f32); + } + } + + /// Moves the offset so that row `at` shows wholly in a view `view` high, from the nearer edge, by the layout's + /// extents. + fn aim_reveal(&mut self, layout: &C::ItemLayout, at: usize, view: f32) { let rect = layout.rect(at, ScrollPos { x: 0.0, y: self.offset }); if rect.min.y < 0.0 { self.offset += f64::from(rect.min.y); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 9667c730d..7d73c5e8d 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -74,6 +74,14 @@ struct WidestRuns { runs: Vec<(Id, u32)>, } +/// The auto rows of collections built and measured for their height, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +struct RowMeasures { + pass: u64, + rows: Vec<(Id, u32)>, +} + /// The rows that asked their body units for their least widths, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -253,6 +261,28 @@ pub fn widest_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| if log.pass == last { log.runs.clone() } else { Vec::new() }) } +/// Counts a build and measure of the height of a collection's auto row, kept under `id`, in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_row_measure(ctx: &Context, id: Id) { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = RowMeasures { pass, rows: Vec::new() }; + } + match log.rows.iter_mut().find(|(row, _)| *row == id) { + Some((_, count)) => *count += 1, + None => log.rows.push((id, 1)), + } + }); +} + +/// The auto rows of collections built and measured for their height in the last pass, and how many times each. +#[cfg(feature = "testing")] +pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 913087827..aa85d64bc 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -40,7 +40,7 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, - last_pass_runs, least_runs as shrink_least_runs, run as measuring_run, take_effects, widest_runs, + last_pass_runs, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index 91fb97b02..c7d11b746 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -735,3 +735,43 @@ fn a_list_without_an_edge_press_gives_the_line_to_the_rows() { assert!(!events.iter().any(|event| matches!(event, CollectionEvent::EdgePressed { .. })), "{events:?}"); assert!(events.iter().any(|event| matches!(event, CollectionEvent::Selection(_))), "{events:?}"); } + +/// A revealed row far below the view, past rows no pass built yet and taller than the list's estimate, shows wholly +/// in view in the frame that reveals it: the list measures the rows it scrolls past before it places them, runs the +/// frame once, and measures no row twice. +#[trial] +fn a_revealed_row_past_unbuilt_rows_taller_than_the_estimate_shows_wholly_in_one_pass() { + use craft_ui::list::ThumbSize; + use std::cell::Cell; + const ROWS: usize = 40; + let names: Vec = (0..ROWS).map(|at| format!("Photo {at:02}")).collect(); + let reveal = Rc::new(Cell::new(None::)); + let asked = reveal.clone(); + let mut fixture = Fixture::new(move |ui| { + let keys: Vec = (0..ROWS).collect(); + let source = keyed(&keys, |key: &usize| *key); + let mut list = List::new("Photos"); + if let Some(key) = asked.take() { + list = list.reveal(key); + } + list.show_items(ui, &source, &mut |key, _| ListRow::new(names[*key].clone()).thumb(ThumbSize::Large, |_, _| {})); + }); + fixture.room(Vec2::new(300.0, 300.0)); + fixture.settle(); + let view = |fixture: &Fixture| fixture.by_label("Photos").expect("the list's node").rect; + let in_view = |fixture: &Fixture, name: &str| fixture.by_label(name).is_some_and(|row| view(fixture).contains_rect(row.rect)); + assert!(in_view(&fixture, "Photo 00") && !in_view(&fixture, "Photo 39"), "the list starts at the top"); + + reveal.set(Some(ROWS - 1)); + fixture.idle(1); + assert!(in_view(&fixture, "Photo 39"), "the revealed row shows wholly in the frame that reveals it"); + assert_eq!(fixture.passes(), 1, "the reveal runs the frame once"); + let measures = craft_ui::runtime::measure::row_measures(fixture.ctx()); + assert!(!measures.is_empty() && measures.iter().all(|(_, count)| *count == 1), "no row is measured twice in the pass: {measures:?}"); + fixture.idle(2); + assert!(in_view(&fixture, "Photo 39"), "the row stays in view"); + + reveal.set(Some(0)); + fixture.idle(1); + assert!(in_view(&fixture, "Photo 00"), "the first row scrolls back wholly into view"); +} diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 19a25da81..6eceb1582 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -329,7 +329,7 @@ Content runs in every pass, and its sizes come from this pass. Layouts also read - Every scroll input moves the offset at step 4, before the content runs, so the decision sees the offset the pass paints. Wheel, page keys and reveals arrive there directly. A thumb drag, a track press or an AccessKit scroll action is sensed after the content ran: the pass queues it for step 4 and asks for a discard pass, so the move shows in the same frame. - A scroll position the framework holds is also named by content: the first child at or after the view's start and its place in the view (`lazy::Anchor`, kept with the offset). When extents before that child change (estimates replaced by real extents, rows regrouped), the offset follows the child and the pass runs again, so the content in view does not move. An offset bound to the app (`Component::scroll`) is the app's plain offset, and a region that follows its end follows the end. - A scroll area that does not run (a tab switched away) keeps its children's entries, and its content extent lives beside its offset (`ScrollState`) with the same lifetime, so it shows again at the same offset after any length of hide; one that runs drops the entries of the children it did not reach. -- A collection builds the rows in view, plus its lead, anchor, renaming and grabbed rows. Its rows are no Tab entries (Tab moves past the collection, arrows move its lead), so a row out of view has no stops to keep. It places the rows it does not build by the extents they had when last built, from the same store, and its output lists the rows in view and the kept rows. Rows it never built take its item layout's estimate, as a `Lazy` takes its own, so a long list is never built whole. +- A collection builds the rows in view, plus its lead, anchor, renaming and grabbed rows. Its rows are no Tab entries (Tab moves past the collection, arrows move its lead), so a row out of view has no stops to keep. It places the rows it does not build by the extents they had when last built, from the same store, and its output lists the rows in view and the kept rows. Rows it never built take its item layout's estimate, as a `Lazy` takes its own, so a long list is never built whole. A reveal (a requested one, a key move, type-ahead, a rename) places the row by measured heights: before the rows are built, the collection builds and measures the rows that will share the view with the revealed row, up to it, that no pass built yet, and the build takes those measures, so the row shows wholly in the pass that reveals it. - Each built row is a run of the collection's item component, or, for a collection that sets `Collection::MEMBERS` (a tab strip's tabs, a colour table's cells), a member of the collection's own run: sensed with its parts in its arena, updated, painted and finished at its row, and reported as an access sub-node of the collection with its parts' nodes under it, with no run of its own. Its output gives the item event, as a run's does. Selection, activation, drags and AccessKit requests on the row are the collection's either way. - The access tree covers the view, by the same rule: content that runs reports its access nodes (a collection's built rows and their section headings included). A component that lays out section rows as its own parts (TileGrid's group headings and tail rows) reports the nodes of those in view. Content out of view (`Lazy` children and collection rows) is absent from the access tree until it scrolls in. AccessKit scroll actions still reach it, because they move the offset. - Content that was never shown has only its estimate and no stops: Tab reaches it once it was shown. An app brings it into view with `.reveal(true)`.