diff --git a/crates/pages/src/ui/mod.rs b/crates/pages/src/ui/mod.rs index 4d0ba29d6..d96cdca02 100644 --- a/crates/pages/src/ui/mod.rs +++ b/crates/pages/src/ui/mod.rs @@ -61,4 +61,4 @@ pub use text_selection::{ pub use thumbnails::{ PageThumbnails, PageThumbnailsOutput, THUMBNAIL_ZOOM, ThumbnailEvent, ThumbnailMarks, ThumbnailSection, ThumbnailWords, moved_page, }; -pub use view::{PageBody, PageRegion, PageSnap, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage}; +pub use view::{PageBody, PageRegion, PageSnap, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PICTURE_REACH, PlacedPage}; diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 1c963c0d5..af0714022 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -32,7 +32,7 @@ use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; use craft_behavior::{Axis, CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder}; use craft_ui::canvas::{ BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, PageKey, Pasteboard, PasteboardOutput, Snap, ToolPass, - ToolRegion, canvas_space, tool_pass, + ToolRegion, canvas_space, pixel_aligned, tool_pass, }; use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::EditorPurpose; @@ -283,9 +283,10 @@ pub struct PageViewOutput { impl PageViewOutput { /// How many page pictures the view holds after this pass: its pages' own pictures and the pictures of the part - /// in view of pages larger than the texture side, shown or kept for later, as their stores count them. The - /// stores evict the pictures drawn longest ago past their budget, so the count stays bounded however many pages - /// the view scrolls through. 0 for a pass that drew nothing. + /// in view of pages larger than the texture side, shown or kept for later, as their stores count them. A page + /// scrolled out of [`PageView::picture_reach`] gives its pictures back, and the stores evict the pictures drawn + /// longest ago past their budget, so the count stays bounded by the pages near the view however many pages the + /// view scrolls through. 0 for a pass that drew nothing. pub fn resident_pictures(&self) -> usize { self.resident } @@ -313,8 +314,11 @@ impl PageViewOutput { /// view's style, recomputed when the viewport or the pages change; the zoom is written back so it equals what /// shows. Pages draw as [`PageFrame`]s on a [`Pasteboard`], the page picture over each through `Thumbnails` at /// `Priority::VISIBLE`, one row either side at `Priority::NEAR`; a page larger than the texture side adds a -/// second picture of the part in view. Sharp renders wait while a zoom gesture or ease runs. -/// - Layout: a scale the fit or the app changes keeps the page at the top of the view in place. +/// second picture of the part in view. Sharp renders wait while a zoom gesture or ease runs. A page scrolled +/// further than [`picture_reach`](Self::picture_reach) from the view gives its picture back. +/// - Layout: a scale the fit or the app changes keeps the page at the top of the view in place. A zoom about the +/// pointer keeps the point under it in place relative to the page there (or, in a gap, the nearest page), and one +/// that does not ease draws its new layout, reflowed, in the pass it happens, so the next pass moves nothing. /// - Scrolling: the canvas folds in the wheel (the wheel scrolls, Shift or Ctrl/Cmd + wheel scrolls sideways, Alt + /// wheel and a pinch zoom about the pointer, as [`NavigationOptions`] say) and the view commands; the view /// reads the result back into its state. [`CanvasScrollbars`] land in their own pass. Not continuous, a page @@ -337,8 +341,13 @@ pub struct PageView<'a> { snap: Option, tool_regions: Vec, rulers: bool, + reach: f32, } +/// How far from the view, in view heights above and below it (and one view width either side), the page view keeps a +/// page's picture once it has scrolled out: three, as WordCraft kept its page textures (#811). +pub const PICTURE_REACH: f32 = 3.0; + impl<'a> PageView<'a> { /// A view named `label` of the pages of `source`, with `state` kept by the app between passes, on pages of the /// document's `paper` colour. @@ -356,6 +365,7 @@ impl<'a> PageView<'a> { snap: None, tool_regions: Vec::new(), rulers: false, + reach: PICTURE_REACH, } } @@ -417,6 +427,18 @@ impl<'a> PageView<'a> { self } + /// How far from the view a page's picture is kept once it has scrolled out, in view heights above and below the + /// view; sideways the view keeps one view width either side. A page further away loses its picture (and the + /// picture of its part in view) in the pass it leaves that reach and is rendered again when it comes back, so the + /// pictures held are bounded by the pages near the view, not only by the stores' budget. The pages drawn and the + /// pages asked for ahead (one row either side) are always kept. [`PICTURE_REACH`] by default; a negative or + /// non-finite reach is taken as 0. + #[must_use] + pub fn picture_reach(mut self, screens: f32) -> Self { + self.reach = if screens.is_finite() { screens.max(0.0) } else { 0.0 }; + self + } + /// Shows the view in the room left in `ui`, and runs `body` for the app's canvas controls (margins, zones, /// marks, grids), which it shows with `show_at(ui, body.rect)`, and its tool host, which runs on `body.pass`. /// `body` runs on every run of the canvas body (the measuring run and the real one), so it builds what it shows @@ -432,7 +454,7 @@ impl<'a> PageView<'a> { } fn run(self, ui: &mut Ui, rect: Rect, take_room: bool, mut body: impl FnMut(&mut Ui, &PageBody<'_>)) -> PageViewOutput { - let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers } = self; + let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers, reach } = self; let spacing = PageMetrics::new().show_at(ui, Rect::from_min_size(rect.min, Vec2::ZERO)).spacing; let count = source.page_count(); @@ -460,7 +482,7 @@ impl<'a> PageView<'a> { let mut held = Held::new(Bind::bound(state)); let mut seen: Option = None; let mut canvas_body = |ui: &mut Ui, cx: &mut BodyCx<'_>| { - let next = run_pass(ui, cx, &mut held, &Inputs { source, describer, build: &build, rect, given, paper })?; + let next = run_pass(ui, cx, &mut held, &Inputs { source, describer, build: &build, rect, given, paper, reach })?; let pass = tool_pass(&cx.env); body(ui, &PageBody { rect: cx.rect, pages: &next.pages, view: next.view, pass: pass.as_ref() }); let decided = next.next.clone(); @@ -507,6 +529,8 @@ struct Inputs<'a> { rect: Rect, given: CanvasView, paper: DataColor, + /// `PageView::picture_reach`. + reach: f32, } /// What a pass found out, for the output. @@ -651,7 +675,7 @@ fn placed_region(region: &PageRegion, geo: &Placed, frame: &Frame) -> Option, held: &mut Held<'_, PageViewState>, inputs: &Inputs<'_>) -> Option { - let Inputs { source, describer, build, rect, given, paper } = *inputs; + let Inputs { source, describer, build, rect, given, paper, reach } = *inputs; let mut state = held.read(cx)?; let started = state.clone(); let space = canvas_space(&cx.env)?; @@ -691,6 +715,8 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> let fixed = (target.center - given.center) * (given.zoom * target.zoom / (target.zoom - given.zoom)); let pointer = rect.center() + Vec2::new(fixed.x as f32, fixed.y as f32); geo = zoom_about(build, &mut state, &geo, rect, pointer, target.zoom / given.zoom); + let (xs, ys) = (offset_range(geo.doc.x0, geo.doc.x1, vw), offset_range(geo.doc.y0, geo.doc.y1, vh)); + state.offset = (state.offset.0.clamp(xs.0, xs.1), state.offset.1.clamp(ys.0, ys.1)); want = state.offset; } else { // The canvas was given the view the pass started with, so its change of it is the pan; the state's offset @@ -706,6 +732,20 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> if wheel_left == 0.0 { mem.overshoot = 0.0; } + // A zoom that does not ease draws the layout it made in its own pass, through the view of the anchored offset: the + // pages reflow and the point under the pointer stays in the pass the zoom happens, and the next pass, given that + // view, moves nothing. (Drawing the layout the pass started with, scaled, put the reflow and the spacing that does + // not scale one pass late.) An ease draws the layout it started from, scaled, until it lands. + let (drawn, drawn_frame, shown) = if zooming && !space.easing() { + let frame = Frame::of(&geo); + let mut view = frame.view(rect, state.offset, geo.scale / SCREEN_POINTS_PER_POINT); + // As the canvas places a given view: in its own rect (inside the rulers), about the same centre. + view.rect = target.rect; + let view = if shown == target { view } else { pixel_aligned(view, ui.ctx().pixels_per_point()) }; + (Arc::clone(&geo), frame, view) + } else { + (drawn, drawn_frame, shown) + }; let keys = KeyMoves::of(space.keys(), &state, &geo, rect); want.0 += keys.pan.0; want.1 = if keys.to_end { f64::INFINITY } else { want.1 + keys.pan.1 }; @@ -780,7 +820,20 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> (page, Vec2::new(size.width as f32, size.height as f32)) }) .collect(); - let pictures = PagePictures::new(source, &pages, &near, paper).label(words.text.clone()).hold(zooming || ratio != 1.0); + // The pages whose pictures stay: those drawn, those asked for ahead, and those of the shown row within the reach. + let reach = f64::from(reach); + let around = DocRect::new( + in_view.x0 - in_view.width(), + in_view.y0 - reach * in_view.height(), + in_view.x1 + in_view.width(), + in_view.y1 + reach * in_view.height(), + ); + let mut keep: Vec = + drawn.row.clone().filter(|&p| p < drawn.layout.rects.len() && overlaps(band_rect(&drawn.layout, p), around)).collect(); + keep.extend(rows.iter().copied().chain(near.iter().map(|&(page, _)| page))); + keep.sort_unstable(); + keep.dedup(); + let pictures = PagePictures::new(source, &pages, &near, &keep, paper).label(words.text.clone()).hold(zooming || ratio != 1.0); let resident = match describer { Some(describer) => pictures.describer(describer).show_at(ui, cx.rect), None => pictures.show_at(ui, cx.rect), @@ -1083,12 +1136,14 @@ fn zoom_about(build: &Geometry, state: &mut PageViewState, old: &Placed, rect: R state.fit = Fit::None; state.zoom = (state.zoom * delta).clamp(*ZOOM_RANGE.start(), *ZOOM_RANGE.end()); let new = build.of(state); - let (x, y) = match crate::layout::page_at(&old.layout, at) { - Some(page) => { + // The page under the pointer, or in a gap (between columns, rows or pages) the nearest: the point keeps its place + // relative to that page, outside it too, since the gaps keep their size and the pages may reflow. + let (x, y) = match crate::layout::page_at(&old.layout, at).or_else(|| nearest_page(&old.layout, at)) { + Some(page) if page < new.layout.rects.len() => { let (before, after) = (old.layout.rects[page], new.layout.rects[page]); (after.x0 + (at.x - before.x0) / before.width() * after.width(), after.y0 + (at.y - before.y0) / before.height() * after.height()) } - None => { + _ => { let ratio = new.scale / old.scale; (at.x * ratio, at.y * ratio) } @@ -1097,6 +1152,17 @@ fn zoom_about(build: &Geometry, state: &mut PageViewState, old: &Placed, rect: R new } +/// The page whose shown band lies nearest `p` (content coordinates); the earlier page on a tie, `None` with no pages. +fn nearest_page(layout: &PagedLayout, p: Point) -> Option { + let distance = |page: usize| { + let band = band_rect(layout, page); + let dx = (band.x0 - p.x).max(p.x - band.x1).max(0.0); + let dy = (band.y0 - p.y).max(p.y - band.y1).max(0.0); + dx.hypot(dy) + }; + (0..layout.rects.len().min(layout.bands.len())).min_by(|&a, &b| distance(a).total_cmp(&distance(b))) +} + /// The pages one row either side of what shows: the neighbouring rows, or the neighbouring row of a single shown /// row. fn near_pages(placed: &Placed, continuous: bool, visible: &Range, count: usize, options: &LayoutOptions) -> Vec { diff --git a/crates/pages/src/ui/view/pictures.rs b/crates/pages/src/ui/view/pictures.rs index e62061ac2..a6128e090 100644 --- a/crates/pages/src/ui/view/pictures.rs +++ b/crates/pages/src/ui/view/pictures.rs @@ -126,6 +126,8 @@ pub(super) struct PagePictures<'a> { source: &'a dyn PageSource, pages: &'a [PlacedPage], near: &'a [(usize, Vec2)], + /// The pages whose pictures the stores keep, sorted; every other page's are dropped. + keep: &'a [usize], /// The document's paper under each picture. paper: DataColor, /// Sharp renders wait: a zoom is under way. @@ -137,8 +139,14 @@ pub(super) struct PagePictures<'a> { } impl<'a> PagePictures<'a> { - pub(super) fn new(source: &'a dyn PageSource, pages: &'a [PlacedPage], near: &'a [(usize, Vec2)], paper: DataColor) -> Self { - PagePictures { common: Common::new(), source, pages, near, paper, hold: false, describer: None } + pub(super) fn new( + source: &'a dyn PageSource, + pages: &'a [PlacedPage], + near: &'a [(usize, Vec2)], + keep: &'a [usize], + paper: DataColor, + ) -> Self { + PagePictures { common: Common::new(), source, pages, near, keep, paper, hold: false, describer: None } } } @@ -197,6 +205,12 @@ impl Component for PagePictures<'_> { let request = ThumbRequest::for_cell(size.x.max(size.y), ppp); thumbs.state(&ctx, self.source, &page, &request, Priority::NEAR); } + // Pages scrolled out of reach give their pictures back (#811: a long scroll held every page it had shown); + // a part-in-view picture is only of use while its page shows. + let keep = self.keep; + thumbs.retain(&ctx, |page| keep.binary_search(page).is_ok()); + let shown = self.pages; + details.retain(&ctx, |page| shown.iter().any(|p| p.page == *page)); } fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { diff --git a/crates/pages/src/ui/view/stories.rs b/crates/pages/src/ui/view/stories.rs index e0bd69e6d..31e1ee456 100644 --- a/crates/pages/src/ui/view/stories.rs +++ b/crates/pages/src/ui/view/stories.rs @@ -42,6 +42,16 @@ fn spreads(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { view(ui, data, false, |state| state.display = PageDisplay::TwoUp) } +/// A long document whose view keeps only the pictures of the pages drawn and the row either side +/// (`picture_reach(0.0)`): a page scrolled away is rendered again when it comes back. +#[story(PageView<'static>, covers = [], drive = Drive::Never)] +fn pictures_near_the_view_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let state = data.value("view", PageViewState::default()); + let pages = DemoPages::new(8 * PAGES); + let out = PageView::new("Pages", &pages, state, PAPER).options(LayoutOptions::ACROBAT).picture_reach(0.0).show(ui, |_, _| ()); + out.canvas.response.into() +} + #[story(PageView<'static>, covers = [], drive = Drive::Never)] fn one_page_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { view(ui, data, false, |state| state.continuous = false) @@ -116,7 +126,9 @@ fn page_pictures(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let placed = demo_placed(1, Pos2::new(room.min.x + 20.0, room.min.y + 10.0)); let view = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0); let near: [(usize, Vec2); 0] = []; - let shown = - Canvas::new("Document").view(view).show_at(ui, room, |ui, body| PagePictures::new(&pages, &placed, &near, PAPER).show_at(ui, body.rect)); + let keep = [0]; + let shown = Canvas::new("Document") + .view(view) + .show_at(ui, room, |ui, body| PagePictures::new(&pages, &placed, &near, &keep, PAPER).show_at(ui, body.rect)); shown.inner.map(StoryOutput::from).unwrap_or_default() } diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index abc677037..61b1a9cd5 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -98,6 +98,164 @@ fn the_pictures_a_view_holds_stay_bounded_as_it_scrolls_through_many_pages() { assert!(held > 0 && held <= bound, "{held} pictures held over {count} pages scrolled through, at most {bound} expected"); } +/// The most pictures a continuous view of 40 Letter pages at 100 % in a 900 × 600 room holds while it scrolls from +/// the top to the bottom 400 points a step, with `reach` (`None`: the default), and the most pages it drew in a pass. +fn most_held_scrolling(reach: Option) -> (usize, usize) { + let state = Rc::new(RefCell::new(state_with(|s| { + s.continuous = true; + s.fit = Fit::None; + s.zoom = 1.0; + }))); + let most = Rc::new(Cell::new((0_usize, 0_usize))); + let (kept, seen) = (Rc::clone(&state), Rc::clone(&most)); + let pages = DemoPages::new(40); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept.borrow().clone(); + let view = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::ACROBAT); + let view = match reach { + Some(screens) => view.picture_reach(screens), + None => view, + }; + let out = view.show(ui, |_, _| ()); + let (held, drawn) = seen.get(); + seen.set((held.max(out.resident_pictures()), drawn.max(out.pages.len()))); + *kept.borrow_mut() = now; + }); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + let mut last = f64::NAN; + while state.borrow().offset.1 != last { + last = state.borrow().offset.1; + state.borrow_mut().offset.1 += 400.0; + fixture.idle(2); + } + assert!(last > 30_000.0, "the view scrolled through the pages: {last}"); + most.get() +} + +#[trial] +fn pages_scrolled_out_of_reach_give_their_pictures_back() { + // WordCraft (#811) kept the textures of the pages within three screens of the view: a 600-point view holds the + // pages over 4'200 points, four or five 1'056-point pages, and the row either side; never the 40 it went past. + let (held, drawn) = most_held_scrolling(None); + assert!(drawn > 0, "the view drew pages"); + assert!(held > 0 && held <= 8, "{held} pictures held while scrolling 40 pages with the default reach"); + // With no reach only the pages drawn and the row either side keep theirs. + let (held, drawn) = most_held_scrolling(Some(0.0)); + assert!(held > 0 && held <= drawn + 2, "{held} pictures held with no reach, {drawn} pages drawn"); +} + +/// What a pass of the zoom rig showed: the area the pages show in, the pages drawn and the screen points per page point. +#[derive(Clone)] +struct ZoomSeen { + area: egui::Rect, + pages: Vec<(usize, egui::Rect)>, + scale: f64, +} + +impl ZoomSeen { + /// Pages across: those level with the first page drawn. + fn columns(&self) -> usize { + self.pages.first().map_or(0, |(_, first)| self.pages.iter().filter(|(_, r)| (r.top() - first.top()).abs() < 1.0).count()) + } + + fn rect(&self, page: usize) -> Option { + self.pages.iter().find(|(p, _)| *p == page).map(|(_, r)| *r) + } +} + +/// WordCraft's Ctrl + wheel zoom out (#1340): the point under the pointer stays where it is in every frame, the +/// pages reflow into rows in the frame of the notch that makes room for them, and a frame without input moves +/// nothing. Pointer in the middle of the area inside the rulers, many pages down, a notch every 8 frames; the pages +/// pass through a gutter between columns under the pointer on the way. +#[trial] +fn a_ctrl_wheel_zoom_keeps_the_point_under_the_pointer_and_settles_in_its_own_frame() { + let state = Rc::new(RefCell::new(state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }))); + let seen = Rc::new(RefCell::new(ZoomSeen { area: egui::Rect::NOTHING, pages: Vec::new(), scale: 0.0 })); + let (kept, shown) = (Rc::clone(&state), Rc::clone(&seen)); + let pages = DemoPages::new(200); + let mut navigation = craft_ui::canvas::NavigationOptions::default(); + navigation.wheel = craft_ui::canvas::WheelScheme::Document; + let mut fixture = Fixture::new(move |ui| { + let mut now = kept.borrow().clone(); + let mut area = egui::Rect::NOTHING; + let out = PageView::new("Pages", &pages, &mut now, PAPER) + .options(LayoutOptions::WORD) + .navigation(navigation) + .rulers(true) + .show(ui, |_, body| area = body.view.rect); + let scale = out.pages.first().map_or(0.0, |p| p.scale); + *shown.borrow_mut() = ZoomSeen { area, pages: out.pages.iter().map(|p| (p.page, p.rect)).collect(), scale }; + *kept.borrow_mut() = now; + }); + fixture.ctx().options_mut(|options| options.input_options.zoom_modifier = Modifiers::NONE); + fixture.room(vec2(1280.0, 760.0)); + fixture.settle(); + // Far enough down that zooming out never meets the top of the document, whose clamp would move the place. + state.borrow_mut().offset.1 = 40.4 * 1056.0; + fixture.settle(); + let pointer = seen.borrow().area.center(); + fixture.frame(vec![egui::Event::PointerMoved(pointer)]).settle(); + let start = seen.borrow().clone(); + let (page, _) = *start + .pages + .iter() + .min_by(|(_, a), (_, b)| a.distance_to_pos(pointer).total_cmp(&b.distance_to_pos(pointer))) + .expect("pages show"); + assert!(page >= 30, "many pages down: page {page}"); + let under = |seen: &ZoomSeen| seen.rect(page).map(|r| (pointer - r.min) / seen.scale as f32); + let at = under(&start).expect("the page shows"); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + fixture.frame(vec![egui::Event::ModifiersChanged(ctrl)]); + let mut last = seen.borrow().clone(); + for n in 0..40 { + let notch = n % 8 == 0; + let events = if notch { + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + modifiers: ctrl, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }] + } else { + Vec::new() + }; + fixture.frame(events); + let now = seen.borrow().clone(); + let here = under(&now).unwrap_or_else(|| panic!("frame {n}: page {page} shows")); + let off = (here - at) * now.scale as f32; + // Across, the place holds while the pages stay one a row; in rows they fit the window side by side. + let across = now.columns() > start.columns() || off.x.abs() < 2.0; + assert!( + across && off.y.abs() < 2.0, + "frame {n} at scale {:.3}: {here:?} on page {page}, was {at:?}; {:?} after {:?}", + now.scale, + now.pages, + last.pages + ); + if !notch { + assert_eq!(now.columns(), last.columns(), "frame {n}: the pages reflow only in a notch's frame"); + assert_eq!(now.pages, last.pages, "frame {n}: a frame without input moves nothing"); + } + last = now; + } + assert!(last.scale < start.scale * 0.6, "zoomed out: {} -> {}", start.scale, last.scale); + assert!( + last.columns() > start.columns(), + "the pages reflowed into rows on the way: {} to {} at {} in {:?}: {:?}", + start.columns(), + last.columns(), + last.scale, + last.area, + last.pages + ); +} + /// A wheel step of `lines` over the middle of the room. fn wheel(fixture: &mut Fixture, lines: f32) { let middle = pos2(450.0, 300.0); diff --git a/crates/ui-contract/src/runtime/egui/memory.rs b/crates/ui-contract/src/runtime/egui/memory.rs index 33f852545..94656f023 100644 --- a/crates/ui-contract/src/runtime/egui/memory.rs +++ b/crates/ui-contract/src/runtime/egui/memory.rs @@ -46,13 +46,12 @@ pub(crate) fn peek_copy(ctx: &Context, id: Id) -> O ctx.data(|data| data.get_temp::(id)) } -/// Stores `mark` under `id` unless a value of its type is there already; true when it stored it. -pub(crate) fn mark_seen(data: &mut Map, id: Id, mark: T) -> bool { - let absent = data.get_temp::(id).is_none(); - if absent { - data.insert_temp(id, mark); - } - absent +/// Stores `mark(None)` under `id`, or `mark(Some(old))` over the value of its type there already; true when there +/// was none. `T` is a plain mark: `Copy`, so no slot code runs under the data lock. +pub(crate) fn mark_seen(data: &mut Map, id: Id, mark: impl FnOnce(Option) -> T) -> bool { + let old = data.get_temp::(id); + data.insert_temp(id, mark(old)); + old.is_none() } /// Puts a taken-out box back under `id`, in the allocation it left in. The value it replaced, if any, is returned diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 97f85fb67..c96cd7450 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -98,7 +98,8 @@ pub trait Remember { /// The result of the job `start` returns, one per `key`: it is submitted once, cancelled when the owner is /// evicted, and a landed result asks for a pass. fn pending(&mut self, key: K, start: impl FnOnce() -> Job) -> &Pending; - /// True on the first pass a shown stage exists for this id. + /// True on the first pass a shown stage exists for this id, and on the first pass after the id was left unshown + /// for a frame of its viewport (a page left and opened again), through that frame's passes. fn appeared(&self) -> bool; } @@ -222,10 +223,35 @@ pub(crate) struct Registry { written: usize, } -/// Marks a base whose stage was written back: the frame it was first shown in, for `appeared`. A discard pass -/// repeats the frame, so `appeared` stays true through it. +/// Marks a base whose stage was written back, for `appeared`: the frame it appeared in and the last frame it was +/// shown in. A discard pass repeats the frame, so `appeared` stays true through it. A frame of its viewport that did +/// not show the base (a page left and opened again before its owner was evicted) makes its next showing an +/// appearance again, as WordCraft told a reopened page by a gap in the frames it was drawn in. #[derive(Clone, Copy)] -struct Seen(u64); +struct Seen { + first: u64, + last: u64, +} + +impl Seen { + /// Whether the frames since the base was last shown leave a gap before `frame`. + fn gap_before(self, frame: u64) -> bool { + self.last.saturating_add(1) < frame + } + + /// Whether a stage of this base in `frame` is the base appearing. + fn appears(self, frame: u64) -> bool { + self.first == frame || self.gap_before(frame) + } + + /// The mark after a write-back in `frame`. + fn shown(old: Option, frame: u64) -> Seen { + match old { + Some(seen) if !seen.gap_before(frame) => Seen { first: seen.first, last: frame.max(seen.last) }, + _ => Seen { first: frame, last: frame }, + } + } +} /// Registers `owner`'s pass, at step 3: eviction tests only owners. Shown entries of an owner not registered /// for 3 passes of the viewport that last showed it and 0.5 s are evicted by `evict`. @@ -495,14 +521,15 @@ impl MemoryStage { self.owner } - /// True for the first pass a base id is shown; per base id, so a body and its component differ. + /// True for the first pass a base id is shown, and for the first after a frame that did not show it; per base id, + /// so a body and its component differ. pub(crate) fn appeared_at(&self, base: Id) -> bool { let mut touched = self.touched.borrow_mut(); if !touched.contains(&base) { touched.push(base); } let frame = pass::frame_nr(&self.ctx, pass::current_viewport(&self.ctx)); - store::peek_copy::(&self.ctx, base).is_none_or(|seen| seen.0 == frame) + store::peek_copy::(&self.ctx, base).is_none_or(|seen| seen.appears(frame)) } #[allow(clippy::unreachable, reason = "the entry key holds the lifetime and the type, so the downcast cannot fail")] @@ -650,7 +677,7 @@ impl MemoryStage { replaced.extend((entry.write_back)(entry.value, data, id)); } for base in touched { - if store::mark_seen(data, base, Seen(frame)) || retags { + if store::mark_seen(data, base, |old| Seen::shown(old, frame)) || retags { record.push(((base, SHOWN, TypeId::of::()), take_raw::)); } } diff --git a/crates/ui-contract/tests/it/runtime/memory.rs b/crates/ui-contract/tests/it/runtime/memory.rs index 22b250086..351a3c9f0 100644 --- a/crates/ui-contract/tests/it/runtime/memory.rs +++ b/crates/ui-contract/tests/it/runtime/memory.rs @@ -112,6 +112,36 @@ fn set_saved_value_is_read_back_by_saved_value_and_stored_once() { assert_eq!(store.writes(), 2, "a changed value is stored once"); } +/// A component left unshown for a frame and shown again well inside the eviction grace (a backstage page left and +/// reopened) appears again through every pass of the frame it comes back in, and only then; its shown entries stay. +#[trial] +fn a_component_shown_again_after_a_frame_without_it_appears_again() { + let mut frames = Frames::new(); + let id = global("page", ()); + let passes = RefCell::new(Vec::::new()); + let mut show = |ui: &mut Ui| { + let mut stage = Stage::open(ui.ctx(), id); + passes.borrow_mut().push(stage.appeared()); + *stage.memory::() += 1; + stage.finish(); + }; + frames.frame(vec![], &mut show); + frames.frame(vec![], &mut show); + assert_eq!(passes.borrow().last(), Some(&false), "a component shown every frame appears once"); + frames.frame(vec![], |_| {}); + passes.borrow_mut().clear(); + frames.frame(vec![], &mut show); + let back = passes.take(); + assert!(!back.is_empty() && back.iter().all(|&appeared| appeared), "every pass of the frame it is shown again in: {back:?}"); + frames.frame(vec![], |ui| { + let mut stage = Stage::open(ui.ctx(), id); + passes.borrow_mut().push(stage.appeared()); + assert!(*stage.memory::() >= 3, "the shown entry stayed inside the grace"); + stage.finish(); + }); + assert_eq!(passes.take(), vec![false], "the next frame is no appearance"); +} + /// The lifetimes of 7.2, through `Remember`: shown entries go with their owner; session and saved ones only /// through `forget` and `forget_saved`; a press entry goes when its press ends. #[trial]