diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index be3dac329..d82603585 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -75,7 +75,7 @@ pub use navigate::{ Autoscroll, FlickPan, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, TouchpadGlide, WheelAction, WheelInput, WheelNavigation, pan, }; pub use rotate::{RotateView, RotateViewOutput, RotateViewStyle, ViewTurn}; -pub use tools::{HandTool, RotateViewTool, ViewCommands, ViewTarget, ZoomTool}; +pub use tools::{HandTool, LayerBounds, RotateViewTool, ViewCommands, ViewTarget, ZoomTool}; pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag, easing_view}; mod rulers; @@ -157,13 +157,15 @@ pub struct Canvas<'a> { view: Option>, /// The view the binding held when the pass began. given: Option, - /// The document the view shows: its size in document units (a `Size` is enough), and the artboard, layer bounds - /// and resolution some view commands need ([`ViewTarget`]). With a view and a document, the canvas fits a view + /// The document the view shows: its size in document units (a `Size` is enough), and the artboard and resolution + /// some view commands need ([`ViewTarget`]). With a view and a document, the canvas fits a view /// never shown, keeps the wheel's zoom inside the document's zoom range, keeps the document in view with Overscroll /// off, and applies the view commands routed to it ([`ViewCommands`]); without either, the view commands are /// disabled for it, and so is each command whose fact the target lacks. #[prop(into)] document: Option, + /// The bounds Fit Layers on Screen shows ([`layer_bounds`](Self::layer_bounds)). + layer_bounds: Option>, /// The user's navigation options: how the wheel and a pinch move the view ([`WheelNavigation`]), whether a zoom /// eases (Animated Zoom) and whether the view may leave the document (Overscroll). #[prop] @@ -231,6 +233,7 @@ impl<'a> Canvas<'a> { view: None, given: None, document: None, + layer_bounds: None, navigation: NavigationOptions::default(), show_rulers: false, keys_to_body: false, @@ -273,6 +276,14 @@ impl<'a> Canvas<'a> { self } + /// The bounds Fit Layers on Screen shows, asked only in the pass that runs the command. Without it Fit Layers is + /// disabled for this canvas. + #[must_use] + pub fn layer_bounds(mut self, bounds: LayerBounds<'a>) -> Self { + self.layer_bounds = Some(bounds); + self + } + /// Eases from `from`, the view the app drew last, to the view given this pass, as the canvas eases its own zoom /// commands: an app's zoom step made outside the canvas (a menu row, a Zoom tool click before the app's tools run /// on the tool host). `anchor` keeps a document point under a screen point along the way. With Animated Zoom off, @@ -306,13 +317,13 @@ impl<'a> Canvas<'a> { let pixels_per_point = cx.env.scale().0; let target = view.zip(self.document); for command in ViewCommands::ALL { - let enabled = target.is_some_and(|(view, document)| command.available(&view, &document, pixels_per_point)); + let enabled = target.is_some_and(|(view, document)| command.available(&view, &document, self.layer_bounds, pixels_per_point)); cx.publish(command, CommandState::new().enabled(enabled)); } let (view, document) = target?; let (mut next, mut zoomed) = (view, false); while let Some((command, _)) = cx.take_command::() { - zoomed |= command.apply(&mut next, &document, pixels_per_point) && command.zooms(); + zoomed |= command.apply(&mut next, &document, self.layer_bounds, pixels_per_point) && command.zooms(); } (next != view).then_some((next, zoomed)) } @@ -341,7 +352,7 @@ impl<'a> Canvas<'a> { let never_shown = !(view.rect.width() > 0.0 && view.rect.height() > 0.0); view.rect = area; if never_shown && let Some(document) = self.document { - ViewCommands::FitOnScreen.apply(&mut view, &document, pixels_per_point); + ViewCommands::FitOnScreen.apply(&mut view, &document, None, pixels_per_point); } } let mut jumped = false; diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index 131198bb0..bbcdb4eb4 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -619,7 +619,7 @@ impl<'m> ToolHost<'m> { } } if requests.repaint { - frame::request_repaint(&ctx); + frame::request_own_repaint(&ctx); } for chord in claimed_chords(state.claims) { keys::claim(&ctx, canvas.response.id, chord); @@ -694,7 +694,7 @@ impl<'m> ToolHost<'m> { tool.cancel(reason, &mut cx); if let Some(view) = cx.take_requests().view { with_session(ctx, state_id(canvas), |state: &mut HostState| state.cancelled_view = Some(view)); - frame::request_repaint(ctx); + frame::request_own_repaint(ctx); } true } diff --git a/crates/ui-canvas/src/canvas/tools.rs b/crates/ui-canvas/src/canvas/tools.rs index 51d190a12..00f095bf2 100644 --- a/crates/ui-canvas/src/canvas/tools.rs +++ b/crates/ui-canvas/src/canvas/tools.rs @@ -34,7 +34,8 @@ const SCREEN_PPI: f64 = 72.0; /// What the view commands act on: the document's size and the facts some commands need. The app gives it to /// [`Canvas::document`](super::Canvas::document); a command whose fact is absent is disabled -/// ([`ViewCommands::available`]). +/// ([`ViewCommands::available`]). Fit Layers reads the layers' bounds from [`LayerBounds`] instead, which only the +/// command runs. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct ViewTarget { @@ -42,8 +43,6 @@ pub struct ViewTarget { pub document: Size, /// The artboard Fit Artboard on Screen shows (the active layer's board, else the last one), in document units. pub artboard: Option, - /// The bounds Fit Layer(s) on Screen shows (the selected layers' content), in document units. - pub layers: Option, /// The document's resolution in pixels per inch, for Print Size. pub ppi: Option, /// The screen resolution Print Size shows the document at, in pixels per inch (Preferences, Units & Rulers). @@ -52,9 +51,9 @@ pub struct ViewTarget { } impl ViewTarget { - /// A document of `size` with no artboard, no layer bounds and no resolution. + /// A document of `size` with no artboard and no resolution. pub fn new(document: Size) -> Self { - Self { document, artboard: None, layers: None, ppi: None, screen_ppi: SCREEN_PPI } + Self { document, artboard: None, ppi: None, screen_ppi: SCREEN_PPI } } /// The artboard Fit Artboard on Screen shows. @@ -64,13 +63,6 @@ impl ViewTarget { self } - /// The bounds Fit Layer(s) on Screen shows. - #[must_use] - pub fn layers(mut self, layers: Rect) -> Self { - self.layers = Some(layers); - self - } - /// The document's resolution, for Print Size. #[must_use] pub fn ppi(mut self, ppi: f64) -> Self { @@ -97,6 +89,11 @@ impl From for ViewTarget { } } +/// The bounds Fit Layer(s) on Screen shows (the selected layers' content), in document units, asked only when the +/// command runs: an app finds them by walking its layers' pixels, which no other pass needs. The app gives it to +/// [`Canvas::layer_bounds`](super::Canvas::layer_bounds); `None` from it changes nothing. +pub type LayerBounds<'a> = &'a dyn Fn() -> Option; + /// A rect with area, or none. fn with_area(rect: Option) -> Option { rect.map(|rect| rect.abs()).filter(|rect| rect.width() > 0.0 && rect.height() > 0.0) @@ -167,9 +164,9 @@ impl ViewCommands { ViewCommands::ResetRotation, ]; - /// Applies the command to `view` for `target` at `pixels_per_point`. Returns whether the view changed: a command - /// whose fact `target` lacks changes nothing. - pub fn apply(self, view: &mut CanvasView, target: &ViewTarget, pixels_per_point: f32) -> bool { + /// Applies the command to `view` for `target` and the layers' bounds `layers` at `pixels_per_point`. Returns whether + /// the view changed: a command whose fact is absent changes nothing. Only Fit Layers asks `layers`. + pub fn apply(self, view: &mut CanvasView, target: &ViewTarget, layers: Option>, pixels_per_point: f32) -> bool { let before = *view; let size = target.document; let zoom_about_centre = |view: &mut CanvasView, device: f64| { @@ -198,7 +195,7 @@ impl ViewCommands { } } ViewCommands::FitLayers => { - if let Some(bounds) = with_area(target.layers) { + if let Some(bounds) = with_area(layers.and_then(|layers| layers())) { zoom::fit_rect(view, bounds, size, pixels_per_point, LAYERS_MARGIN); } } @@ -211,14 +208,15 @@ impl ViewCommands { *view != before } - /// Whether the command can run on `view` for `target`: Zoom In and Zoom Out stop at the ends of the zoom range, - /// Print Size needs the document's resolution, Fit Artboard an artboard and Fit Layers the layers' bounds. - pub fn available(self, view: &CanvasView, target: &ViewTarget, pixels_per_point: f32) -> bool { + /// Whether the command can run on `view` for `target` and the layers' bounds `layers`: Zoom In and Zoom Out stop at + /// the ends of the zoom range, Print Size needs the document's resolution, Fit Artboard an artboard and Fit Layers + /// the layers' bounds, which it does not ask for here. + pub fn available(self, view: &CanvasView, target: &ViewTarget, layers: Option>, pixels_per_point: f32) -> bool { match self { - ViewCommands::ZoomIn | ViewCommands::ZoomOut => self.apply(&mut view.clone(), target, pixels_per_point), + ViewCommands::ZoomIn | ViewCommands::ZoomOut => self.apply(&mut view.clone(), target, None, pixels_per_point), ViewCommands::PrintSize => target.print_zoom().is_some(), ViewCommands::FitArtboard => with_area(target.artboard).is_some(), - ViewCommands::FitLayers => with_area(target.layers).is_some(), + ViewCommands::FitLayers => layers.is_some(), _ => true, } } diff --git a/crates/ui-canvas/src/canvas/zoom_motion.rs b/crates/ui-canvas/src/canvas/zoom_motion.rs index 7766af2f7..e2a6188f3 100644 --- a/crates/ui-canvas/src/canvas/zoom_motion.rs +++ b/crates/ui-canvas/src/canvas/zoom_motion.rs @@ -163,7 +163,7 @@ pub fn easing_view(ctx: &Context, canvas: Id) -> Option { /// tool host for a tool's view, the Navigator for a preview zoom. The canvas applies it in its next pass. pub(crate) fn steer(ctx: &Context, canvas: Id, steer: Steer) { with_session(ctx, ViewMotion::id(canvas), |slot: &mut ViewMotion| slot.steer = Some(steer)); - frame::request_repaint(ctx); + frame::request_own_repaint(ctx); } /// The Zoom tool's press held still: past [`DELAY`](Self::DELAY) it zooms in continuously about the press point (out diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index 96657f782..2a9ce407f 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -9,7 +9,7 @@ use craft_ui::canvas::{ Autoscroll, Canvas, CanvasScrollbars, CanvasTool, ContextRequest, CropOverlay, HandTool, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, Snap, StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer, canvas_space, }; -use craft_ui::contract::{Bind, Sampler as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Lazy, Sampler as _, Show as _, ShowContainer as _}; use craft_ui::dialog::Dialog; use craft_ui::display::Text; use craft_ui::primitives::Draw; @@ -19,6 +19,7 @@ use craft_ui::runtime::frame; use craft_ui::runtime::windows::WindowHost; use craft_ui::style::DataColor; use craft_ui::testing::input::key_press; +use craft_ui::testing::layout::in_region; use craft_ui::testing::{Fixture, ToolFixture, pointer, trial}; use egui::{Color32, Id, Key, Modifiers, Pos2, Rect, Shape, Vec2}; use std::cell::{Cell, RefCell}; @@ -803,6 +804,80 @@ fn an_injected_pen_reading_reaches_the_tool() { assert!(pressures.len() == 2 && (pressures[0] - 0.3).abs() < 1e-4 && (pressures[1] - 0.7).abs() < 1e-4, "{pressures:?}"); } +/// A tool that asks for a repaint in every drag, as a brush that previews its stroke does. +#[derive(Default)] +struct Painter { + drags: usize, +} + +impl CanvasTool for Painter { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) { + self.drags += 1; + cx.request_repaint(); + } + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Freehand("the painter only asks for repaints") + } +} + +/// A stroke on the canvas, whose tool asks for a repaint in every drag, runs neither of the settled panels beside it +/// (each shows a content version), from its press to its release, and each of its move frames runs one pass. +#[trial] +fn a_stroke_runs_no_settled_panel_beside_the_canvas_and_one_pass_per_move() { + let painter = Rc::new(RefCell::new(Painter::default())); + let runs: Rc<[Cell; 2]> = Rc::default(); + let canvas = Rc::new(Cell::new(Id::NULL)); + let (shown_painter, shown_runs, shown_canvas) = (Rc::clone(&painter), Rc::clone(&runs), Rc::clone(&canvas)); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let (side, document) = room.split_left_right_at_x(room.left() + 160.0); + in_region(ui, side, |ui| { + for (at, name) in ["Layers", "Navigator"].into_iter().enumerate() { + Lazy::new(name, 0.0).settles(true).content(1).show(ui, |ui| { + shown_runs[at].set(shown_runs[at].get() + 1); + Text::new(name).show(ui); + }); + } + }); + in_region(ui, document, |ui| { + let view = CanvasView::new(document, Point::new(600.0, 450.0), 1.0); + let shown = Canvas::new("Document").document(DOCUMENT).view(view).show(ui, |_, _| {}); + shown_canvas.set(shown.output.response.id); + let _ = ToolHost::new().run(ui, &shown.output, &mut *shown_painter.borrow_mut()); + }); + }); + fixture.settle(); + let at = fixture.by_role(Role::CANVAS)[0].rect.center(); + let ctx = fixture.ctx().clone(); + ToolHost::inject(&ctx, canvas.get(), ToolInput::down(PointerButton::Primary, at)); + for step in 1..=6 { + ToolHost::inject(&ctx, canvas.get(), ToolInput::moved(at + Vec2::new(8.0 * step as f32, 4.0 * step as f32))); + } + ToolHost::inject(&ctx, canvas.get(), ToolInput::up(at + Vec2::new(48.0, 24.0))); + let host = WindowHost::of(&ctx); + let mut frames = Vec::new(); + while !host.injected_idle() && frames.len() < 64 { + runs.iter().for_each(|runs| runs.set(0)); + fixture.frame(Vec::new()); + frames.push((fixture.passes(), [runs[0].get(), runs[1].get()])); + } + assert!(painter.borrow().drags > 0, "the moves reach the tool, which asks for repaints"); + assert!(frames.iter().all(|(_, runs)| *runs == [0, 0]), "no settled panel runs during the stroke: {frames:?}"); + let moves = &frames[1..frames.len() - 1]; + assert!(moves.iter().all(|(passes, _)| *passes == 1), "each move frame runs one pass: {frames:?}"); +} + /// A queued Space starts the momentary Hand as the real key does: the press it is held over pans the view, and the /// press after its release runs the selected tool. /// A canvas with the momentary set and `main` as the selected tool, zoomed in, so the document is larger than the diff --git a/crates/ui-canvas/tests/it/canvas/tools.rs b/crates/ui-canvas/tests/it/canvas/tools.rs index d210ac082..e2fe50c91 100644 --- a/crates/ui-canvas/tests/it/canvas/tools.rs +++ b/crates/ui-canvas/tests/it/canvas/tools.rs @@ -4,8 +4,10 @@ use craft_behavior::CanvasView; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::Vec2 as DocVec; use craft_behavior::kurbo::{Point, Rect, Size}; -use craft_ui::canvas::{Canvas, CanvasTool, HandTool, NavigationOptions, RotateViewTool, ToolHost, ViewCommands, ViewTarget, ZoomTool}; -use craft_ui::contract::ShowContainer as _; +use craft_ui::canvas::{Canvas, CanvasTool, HandTool, LayerBounds, NavigationOptions, RotateViewTool, ToolHost, ViewCommands, ViewTarget, ZoomTool}; +use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::runtime::access::Role; +use craft_ui::runtime::commands::{self, FireSource}; use craft_ui::testing::{Fixture, ToolFixture, pointer, trial}; use egui::{Event, Modifiers, Pos2}; use std::cell::{Cell, RefCell}; @@ -138,8 +140,10 @@ fn view_commands_run_with_their_facts_and_are_disabled_without() { let size = Size::new(4000.0, 3000.0); let board = Rect::new(2500.0, 400.0, 3500.0, 1200.0); let layers = Rect::new(100.0, 2000.0, 300.0, 2900.0); - let full = ViewTarget::new(size).artboard(board).layers(layers).ppi(300.0); + let full = ViewTarget::new(size).artboard(board).ppi(300.0); let bare = ViewTarget::from(size); + let bounds = || Some(layers); + let given: Option> = Some(&bounds); let start = CanvasView::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0)), Point::new(2000.0, 1500.0), 0.1); let device = |view: &CanvasView| zoom::device(view, ppp); let shows = |view: &CanvasView, rect: Rect| { @@ -156,15 +160,15 @@ fn view_commands_run_with_their_facts_and_are_disabled_without() { ]; for (command, owed) in rows { let mut view = start; - assert!(command.available(&start, &full, ppp), "{command:?} runs with its fact"); - assert!(command.apply(&mut view, &full, ppp) && owed(&view), "{command:?} gives {view:?}"); + assert!(command.available(&start, &full, given, ppp), "{command:?} runs with its fact"); + assert!(command.apply(&mut view, &full, given, ppp) && owed(&view), "{command:?} gives {view:?}"); if command == ViewCommands::TwoHundredPercent { - assert!(command.available(&start, &bare, ppp), "200% needs no fact"); + assert!(command.available(&start, &bare, None, ppp), "200% needs no fact"); continue; } let mut view = start; - assert!(!command.available(&start, &bare, ppp), "{command:?} is disabled without its fact"); - assert!(!command.apply(&mut view, &bare, ppp) && view == start, "{command:?} leaves the view without its fact"); + assert!(!command.available(&start, &bare, None, ppp), "{command:?} is disabled without its fact"); + assert!(!command.apply(&mut view, &bare, None, ppp) && view == start, "{command:?} leaves the view without its fact"); } } @@ -287,7 +291,7 @@ fn the_rotate_commands_step_fifteen_degrees_on_screen_in_a_flipped_view_too() { for (command, screen_turn) in [(ViewCommands::RotateClockwise, 15.0), (ViewCommands::RotateCounterclockwise, -15.0)] { let before = turned(room, 20.0, flip_x); let mut view = before; - assert!(command.apply(&mut view, &target, 1.0), "{command:?} turns the view"); + assert!(command.apply(&mut view, &target, None, 1.0), "{command:?} turns the view"); let turned_by = (angle(&view) - angle(&before) + 540.0).rem_euclid(360.0) - 180.0; assert!( (turned_by - screen_turn).abs() < 0.01, @@ -405,3 +409,35 @@ fn a_held_zoom_press_zooms_about_its_point_at_a_frame_rate_independent_rate() { rig.release(at + egui::vec2(100.0, 0.0), FRAME); assert!((rig.device() / device - 2.0).abs() < 1e-3, "a drag scrubs one doubling per 100 points: {}", rig.device() / device); } + +/// A canvas asks the app for the layers' bounds only in the pass that runs Fit Layers: passes that only show the +/// command enabled never walk the layers. +#[trial] +fn a_canvas_asks_for_the_layer_bounds_only_when_fit_layers_runs() { + let size = Size::new(4000.0, 3000.0); + let layers = Rect::new(100.0, 2000.0, 300.0, 2900.0); + let unshown = CanvasView::new(egui::Rect::NOTHING, Point::new(2000.0, 1500.0), 1.0); + let (asked, view) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(unshown))); + let (shown_asked, shown_view) = (Rc::clone(&asked), Rc::clone(&view)); + let mut fixture = Fixture::new(move |ui| { + let bounds = || { + shown_asked.set(shown_asked.get() + 1); + Some(layers) + }; + let mut held = shown_view.get(); + Canvas::new("Document").document(size).layer_bounds(&bounds).view(Bind::bound(&mut held)).show(ui, |_, _| {}); + shown_view.set(held); + }); + fixture.settle(); + let canvas = fixture.by_role(Role::CANVAS)[0]; + fixture.click(&canvas).settle(); + assert_eq!(asked.get(), 0, "showing the canvas and its enabled commands asks for no bounds"); + let before = view.get(); + assert!(commands::fire(fixture.ctx(), ViewCommands::FitLayers, FireSource::Menu), "a menu row fires Fit Layers"); + fixture.frame(vec![]); + assert!(asked.get() > 0, "the pass that runs Fit Layers asks for the bounds"); + assert_ne!(view.get(), before, "and fits them"); + let once = asked.get(); + fixture.idle(3); + assert_eq!(asked.get(), once, "later passes ask no more"); +} diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 121d98f97..61fb64fe0 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -36,6 +36,7 @@ pub struct Lazy { estimate: f32, reveal: bool, settles: bool, + content: Option, } impl Lazy { @@ -45,7 +46,7 @@ impl Lazy { use std::hash::Hasher; let mut hasher = std::collections::hash_map::DefaultHasher::new(); key.hash(&mut hasher); - Lazy { key: hasher.finish(), estimate, reveal: false, settles: false } + Lazy { key: hasher.finish(), estimate, reveal: false, settles: false, content: None } } /// When `reveal` holds, the scroll area glides until the child starts at the view's start (as far as the @@ -63,18 +64,30 @@ impl Lazy { /// - an animation in it is not at its end, something in it asked for a repaint, or a wake time it asked for came; /// - a bound value it read was written; /// - its place, room, clip or scale differs from its last run; - /// - the frame or the one before had input other than pointer motion, the app asked for a repaint, or a given - /// value was edited: the framework cannot see which children show plain app data, so every child runs then; + /// - its [`content`](Self::content) version differs from its last run; + /// - the app asked for a repaint outside every settling child (`frame::request_repaint`), or a given value was + /// edited: the framework cannot see which children show that app data, so every child runs then; + /// - for a child with no content version: the frame or the one before had input other than pointer motion, which + /// may have changed app data it shows; /// - its last run showed an overlay or painted on another layer. /// /// A bound value is known by where it lives, so a settled reader needs a binding that stays in place between /// frames: a value copied into a local each frame and bound there is a new place each frame, and an edit of it - /// does not reach the reader until the next frame with input. + /// does not reach the reader until the next frame it runs. pub fn settles(mut self, settles: bool) -> Lazy { self.settles = settles; self } + /// The version of the app data a settling child shows that the framework does not track (a document's revision, + /// a job's progress): the child runs when it differs from the version of its last run. A child with a version + /// does not run for input that reaches other parts of the window: what that input changes in the data it shows + /// moves the version, or reaches it as a command or app repaint request. + pub fn content(mut self, version: u64) -> Lazy { + self.content = Some(version); + self + } + /// Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not /// run. pub fn show(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option { @@ -115,7 +128,7 @@ impl Lazy { let layout = *ui.layout(); let place = Place { room: available, clip: ui.clip_rect(), layer: ui.layer_id(), layout, pixels_per_point: ctx.pixels_per_point() }; if self.settles - && let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place)) + && let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place), self.content) { let (took, _) = take_in_flow(ui, size); if real { @@ -153,7 +166,7 @@ impl Lazy { lazy::place(&ctx, &view, id, rect); } if let Some(record) = record { - lazy::ran(&ctx, id, record, place, rect); + lazy::ran(&ctx, id, record, place, rect, self.content); } Some(out) } diff --git a/crates/ui-contract/src/contract/overlay/popups.rs b/crates/ui-contract/src/contract/overlay/popups.rs index b51774de6..4b3f4dbfe 100644 --- a/crates/ui-contract/src/contract/overlay/popups.rs +++ b/crates/ui-contract/src/contract/overlay/popups.rs @@ -11,8 +11,7 @@ use crate::runtime::overlay::{self, CloseReason}; use crate::runtime::pass_state; use craft_behavior::Intent; use craft_behavior::{EditEvent, Mixed}; -use egui::{Context, Id}; -use std::collections::HashMap; +use egui::{Context, Id, IdMap}; /// An id and a name; `Copy`, never a snapshot of the open state. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -77,7 +76,7 @@ pub(crate) struct Popups { pub(super) anchors: Vec<(Id, PopupShown)>, /// The opener that opened each layer with openers, by the layer's first opener: its id and trigger (two /// openers on one response differ by trigger) and how it fired. - pub(super) opened_by: HashMap, + pub(super) opened_by: IdMap<(Id, Trigger, Opening)>, /// The popups whose layer is a container running now (`OverlayUi::show_container`), innermost last. pub(super) layers: Vec, } @@ -159,7 +158,7 @@ pub(crate) fn popup_shown(ctx: &Context, owner: Id) -> bool { } /// Step 10: the open state of every popup `owner` registered, with the closes `request_close` queued applied. -pub(crate) fn open_map(stage: &mut MemoryStage, owner: Id) -> HashMap { +pub(crate) fn open_map(stage: &mut MemoryStage, owner: Id) -> IdMap { let ctx = stage.ctx().clone(); let popups: Vec = with_popups(&ctx, |popups| popups.registered.iter().filter(|(registered, _)| *registered == owner).map(|(_, popup)| *popup).collect()); diff --git a/crates/ui-contract/src/contract/overlay/ui.rs b/crates/ui-contract/src/contract/overlay/ui.rs index 341f36f60..3618fbf7b 100644 --- a/crates/ui-contract/src/contract/overlay/ui.rs +++ b/crates/ui-contract/src/contract/overlay/ui.rs @@ -17,8 +17,7 @@ use crate::runtime::motion::{self}; use crate::runtime::overlay::{self, CloseReason}; use crate::style::SurfaceKind; use craft_behavior::PartRef; -use egui::{Context, Id, Rect, Ui, UiBuilder}; -use std::collections::HashMap; +use egui::{Context, Id, IdMap, Rect, Ui, UiBuilder}; /// What the `overlay` hook gets: one call per anchored popup of this component, built at step 10 with the open state /// of every popup `cx.popup` registered this pass. @@ -33,7 +32,7 @@ pub struct OverlayUi<'a> { pub(crate) to_screen: egui::emath::TSTransform, pub(crate) resolved: &'a Resolved<'a>, pub(crate) env: Env, - pub(crate) open: HashMap, + pub(crate) open: IdMap, /// Popups whose dismissal or body request was decided in this pass; step 15 writes their slots. #[doc(hidden)] pub closed: Vec<(Id, CloseReason)>, @@ -49,7 +48,7 @@ pub(crate) struct OverlayOwner { } impl<'a> OverlayUi<'a> { - pub(crate) fn new(ctx: &'a Context, owner: OverlayOwner, ui: &'a mut Ui, resolved: &'a Resolved<'a>, env: Env, open: HashMap) -> Self { + pub(crate) fn new(ctx: &'a Context, owner: OverlayOwner, ui: &'a mut Ui, resolved: &'a Resolved<'a>, env: Env, open: IdMap) -> Self { let to_screen = areas::layer_to_screen(ctx, ui.layer_id()); let OverlayOwner { id, anchor, parts } = owner; OverlayUi { ctx, ui, owner: id, anchor, to_screen, resolved, env, open, closed: Vec::new(), parts } diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 7e0acd15b..9d0ee03d7 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -20,7 +20,7 @@ use crate::runtime::{commands, focus, inspect, keys, memory}; use crate::style::{Ink, StateSet, StyleCx, StyleView, UiTokens}; use craft_behavior::{Flow, Input, KeyRole, NavMove, PartRef, PressState, Proposal, Roving, Sense}; use craft_theme::Variant; -use egui::{Context, Id, Pos2, Rect, Response, Ui, Vec2}; +use egui::{Context, Id, IdMap, Pos2, Rect, Response, Ui, Vec2}; use std::any::TypeId; use std::cell::RefCell; use std::collections::HashMap; @@ -1213,7 +1213,7 @@ pub(crate) fn bar_member(ctx: &Context, env: &Env, hit: Rect, rule: bool) -> boo /// The rules a bar line shows this pass that wait for the member after them: the shapes each painted, by line. #[derive(Default)] -pub(crate) struct BarRules(HashMap>); +pub(crate) struct BarRules(IdMap>); /// A rule's paint: `shapes` of the paint list of `layer`, in the pass `pass`. struct HeldRule { diff --git a/crates/ui-contract/src/contract/steps/id.rs b/crates/ui-contract/src/contract/steps/id.rs index 7b107e364..b1f65f7e5 100644 --- a/crates/ui-contract/src/contract/steps/id.rs +++ b/crates/ui-contract/src/contract/steps/id.rs @@ -4,15 +4,15 @@ use crate::contract::IdSource; use crate::runtime::egui::pass; use crate::runtime::frame::{PerViewport, Stamped}; use crate::runtime::inspect; -use egui::{Context, Id, Ui}; +use egui::{Context, Id, IdMap, IdSet, Ui}; use std::any::TypeId; -use std::collections::{HashMap, HashSet}; /// The `Auto` ordinals and the ids registered in one pass of one viewport. #[derive(Default)] pub(crate) struct IdPass { - next: HashMap<(Id, TypeId), u32>, - seen: HashSet, + /// Under the scope's id joined with the component type's. + next: IdMap, + seen: IdSet, } /// Runs `f` as a measuring run that leaves the `Auto` ordinals as it found them, so the run that follows in the same @@ -36,7 +36,7 @@ pub(crate) fn draft(ctx: &Context, run: impl FnOnce() -> R, keep: impl FnOnce pub(crate) fn keeping_ids(ctx: &Context, f: impl FnOnce() -> (R, bool)) -> R { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); - let ordinals = |take: Option>| { + let ordinals = |take: Option>| { PerViewport::>::with_pass( ctx, viewport, @@ -80,7 +80,7 @@ pub(crate) fn id(ui: &Ui, source: &IdSource, register: bool, advance: bool, ty: pass_nr, |pass, _| *pass = IdPass::default(), |pass| { - let slot = pass.next.entry((scope, ty)).or_insert(0); + let slot = pass.next.entry(scope.with(ty)).or_insert(0); let n = *slot; if advance { *slot += 1; diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 28fc1c390..465c02679 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -9,9 +9,8 @@ use crate::runtime::measure; use crate::runtime::memory::sub; use crate::runtime::pass_state; use craft_behavior::{Axis, ColumnWidth, Flow, GridCursor, GridMeasure}; -use egui::{Id, Rect, Ui, Vec2}; +use egui::{Id, IdMap, Rect, Ui, Vec2}; use std::borrow::Cow; -use std::collections::HashMap; /// How a body lays out its children, in reading order: mirrored under a right-to-left direction. #[derive(Clone, Debug, PartialEq)] @@ -87,16 +86,16 @@ impl BodyLayout { /// The cursors of the `Grid` and spread `Row` bodies running this pass, by body id. #[derive(Default)] -pub(crate) struct Cursors(HashMap); +pub(crate) struct Cursors(IdMap); /// The number of children that fill the main axis of each `Stack` or `Row` body measured this pass, by body id. #[derive(Default)] -pub(crate) struct FillCounts(HashMap); +pub(crate) struct FillCounts(IdMap); /// The narrowest width a held fill-width child of each content-sized `Stack` column measured at in the first sweep of /// the column's measuring run (`report_held`), by column id. #[derive(Default)] -pub(crate) struct HeldWidths(HashMap); +pub(crate) struct HeldWidths(IdMap); /// Reports a held fill-width child of the content-sized column `column` in its first sweep: the `width` it measured /// at. A column with no first sweep open takes no report. @@ -112,11 +111,11 @@ pub(crate) fn report_held(ctx: &egui::Context, column: Id, width: f32) { /// of its first line's centre, or `None` for a child with no line of its own. A container's measuring sweep opens and /// closes its header's and body's targets; a body's sweep starts its own target afresh. #[derive(Default)] -pub(crate) struct FirstLines(HashMap>); +pub(crate) struct FirstLines(IdMap>); /// What the children of each unwrapped `Row` body took in the sweep of a measuring run running now, by body id. #[derive(Default)] -pub(crate) struct RowLines(HashMap); +pub(crate) struct RowLines(IdMap); /// What the children of a row took about its line. #[derive(Clone, Copy, Default)] @@ -279,11 +278,11 @@ impl ShrinkUnit { /// The units each `Row` body counting this pass reported, in order, by body id. #[derive(Default)] -pub(crate) struct ShrinkReports(HashMap>); +pub(crate) struct ShrinkReports(IdMap>); /// The least widths the body units of each `Row` body asking for them this pass reported, by row id. #[derive(Default)] -pub(crate) struct LeastReports(HashMap>); +pub(crate) struct LeastReports(IdMap>); /// Reports the widths of the unit `leaf` of the row `row` that counts them: a leaf's whole and least widths, or `None` /// for a body. @@ -520,7 +519,7 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> if probe { #[cfg(feature = "testing")] measure::count_least(&ctx, id); - pass_state::with::(&ctx, |reports| reports.0.insert(id, HashMap::new())); + pass_state::with::(&ctx, |reports| reports.0.insert(id, IdMap::default())); crate::contract::keeping_ids(&ctx, || { layout_memory::probing(&ctx, || { let mut least = ui.new_child(egui::UiBuilder::new().layout(layout)); diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index f5a341de5..bc7bc63cc 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -20,7 +20,7 @@ use craft_behavior::{ }; use craft_keymap::Mods; use craft_theme::Flags; -use egui::{Context, Id, Pos2, Rect, Response, Ui, ViewportId}; +use egui::{Context, Id, IdMap, Pos2, Rect, Response, Ui, ViewportId}; use smallvec::SmallVec; use std::collections::HashMap; use std::sync::Arc; @@ -243,7 +243,7 @@ struct ArenaState { #[derive(Default)] pub(crate) struct Arenas { - by_root: HashMap, + by_root: IdMap, swept: u64, /// The end sweep is registered; the runtime layer below cannot register it at install. sweep_registered: bool, diff --git a/crates/ui-contract/src/runtime/access/text.rs b/crates/ui-contract/src/runtime/access/text.rs index b25a575f6..87d4fe449 100644 --- a/crates/ui-contract/src/runtime/access/text.rs +++ b/crates/ui-contract/src/runtime/access/text.rs @@ -8,8 +8,7 @@ use crate::runtime::egui::memory::Service; use crate::runtime::keys; use crate::runtime::memory::sub; use craft_behavior::{AccessRequest, PartKey, PartRef, TextPos}; -use egui::{Context, Id, Rect}; -use std::collections::HashMap; +use egui::{Context, Id, IdMap, Rect}; use std::ops::Range; /// The part key of a run node, indexed in document order. @@ -58,7 +57,7 @@ struct Entry { } #[derive(Default)] -struct Tables(HashMap>); +struct Tables(IdMap>); pub(crate) fn run_id(owner: Id, line: usize, run: usize) -> Id { sub(owner, ("text_run", line, run)) diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 3d231e9b9..a5fd553ee 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -10,10 +10,10 @@ mod text; mod tree; use crate::runtime::pass_state; -#[cfg(feature = "testing")] -use egui::FullOutput; use egui::{Context, Id, ViewportId}; -use std::collections::{HashMap, HashSet}; +#[cfg(feature = "testing")] +use egui::{FullOutput, IdMap, IdSet}; +use std::collections::HashMap; use super::pass; @@ -106,9 +106,9 @@ pub(crate) fn set_focus(ctx: &Context, id: Id) { #[derive(Default)] struct Emitted { order: HashMap, - written: HashSet, + written: IdSet, /// Text widgets whose node folds into their owner's node, each with its owner. - folded: HashMap, + folded: IdMap, /// Whether the runtime reported a focused node this pass. focus_set: bool, } @@ -182,7 +182,7 @@ pub(crate) fn order_children(ctx: &Context) { /// While a modal layer is open in `viewport`, hides the nodes the runtime wrote on layers below it: what sits behind /// a modal is inert for assistive technology, as it is for the pointer and the keys. -fn hide_behind_modal(ctx: &Context, viewport: ViewportId, written: &HashSet) { +fn hide_behind_modal(ctx: &Context, viewport: ViewportId, written: &IdSet) { // Without a modal nothing is behind one; this spares reading every written node's response. if crate::runtime::commands::modal_root(ctx, viewport).is_none() { return; diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 896ce7653..9f7a93826 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -395,10 +395,24 @@ pub(crate) fn announce(ctx: &Context, text: String) { pass_state::with::(ctx, |state| state.output.announcements.push(text)); } -/// Asks for another pass of the viewport the running pass belongs to. +/// Asks for another pass of the viewport the running pass belongs to. Asked inside a settling child +/// (`Lazy::settles`), that child runs again; asked outside every one, the app says data it shows changed, so every +/// settling child runs. #[doc(hidden)] pub fn request_repaint(ctx: &Context) { - crate::runtime::lazy::unsettle(ctx); + if crate::runtime::replay::recording(ctx) { + crate::runtime::replay::note_unsettled(ctx); + } else { + crate::runtime::lazy::unsettle(ctx); + } + raw_input::request_repaint_of(ctx, pass::current_viewport(ctx)); +} + +/// Asks for another pass of the viewport the running pass belongs to, to move what the caller itself shows (a tool's +/// preview, a view that eases): no app data changed, so only the settling child it is asked in runs again. +#[doc(hidden)] +pub fn request_own_repaint(ctx: &Context) { + crate::runtime::replay::note_unsettled(ctx); raw_input::request_repaint_of(ctx, pass::current_viewport(ctx)); } diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index e328be9df..18e4138cf 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -8,8 +8,7 @@ use crate::runtime::egui::sizing::{Rerun, request_discard}; use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, measure, pass_state, pointer}; use craft_behavior::PartRef; -use egui::{Context, Id, Rect, Ui}; -use std::collections::{HashMap, HashSet}; +use egui::{Context, Id, IdMap, IdSet, Rect, Ui}; use std::sync::Arc; /// A rule a component broke that the pipeline reports instead of panicking. @@ -27,13 +26,13 @@ pub struct Finding { #[derive(Default)] pub(crate) struct Log { - steps: HashMap>, + steps: IdMap>, findings: Vec, canvas_controls: Vec<&'static str>, /// The inspected regions open in the running pass, innermost last. open: Vec, /// The latest record of each region, and the element its list points at, by the region's key. - kept: HashMap, + kept: IdMap, } /// Whether records are kept: in frames a test fixture drives, and inside an inspected region in any build. @@ -289,7 +288,7 @@ fn edited(ctx: &Context, read: BindKey, editor: Id) { fn finish(ctx: &Context, open: Open) -> Recorded { let from_screen = areas::layer_to_screen(ctx, open.layer).inverse(); let to_region = |layer: Layer, rect: Rect| from_screen * (areas::layer_to_screen(ctx, layer) * rect); - let ids: HashSet = open.elements.iter().map(|(element, _)| element.id).collect(); + let ids: IdSet = open.elements.iter().map(|(element, _)| element.id).collect(); let mut elements: Vec = Vec::with_capacity(open.elements.len() + open.parts.len()); let mut parts = open.parts; let labels = open.labels; @@ -316,7 +315,7 @@ fn finish(ctx: &Context, open: Open) -> Recorded { } name_from_labels(&mut elements); // The sensing core keeps its shapes by root, in no order; a record compares equal to the same region's next one. - let place: HashMap = elements.iter().enumerate().rev().map(|(index, element)| (element.id, index)).collect(); + let place: IdMap = elements.iter().enumerate().rev().map(|(index, element)| (element.id, index)).collect(); hits.sort_by(|a, b| { let key = |hit: &HitArea| (place.get(&hit.owner).copied(), hit.rect.min.y, hit.rect.min.x); key(a).partial_cmp(&key(b)).unwrap_or(std::cmp::Ordering::Equal) @@ -341,7 +340,7 @@ fn finish(ctx: &Context, open: Open) -> Recorded { /// Names each node without a name of its own by the nodes of the region that label it, as a screen reader reads it. fn name_from_labels(elements: &mut [Element]) { - let names: HashMap = elements + let names: IdMap = elements .iter() .filter(|element| element.part.is_none()) .filter_map(|element| Some((element.id, element.facts.as_ref()?.name.clone()?))) diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index 98a29bc1a..19e8deca2 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -7,7 +7,7 @@ use crate::runtime::egui::input::Action; use crate::runtime::frame::PerViewport; use craft_behavior::EditCommand; use craft_keymap::{Chord, Key, KeyInput, Layout, Mods}; -use egui::{Context, Id, Vec2, ViewportId}; +use egui::{Context, Id, IdMap, Vec2, ViewportId}; use std::collections::HashMap; use std::sync::Arc; @@ -218,7 +218,7 @@ pub(crate) struct Stage { layout: Layout, nodes: HashMap, last_nodes: HashMap, - activated: HashMap, + activated: IdMap, alt: AltTrack, /// The keys down now, as the input hook read them before it withheld any press. down: Vec, diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index 5fb875e97..363c1b346 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -12,7 +12,7 @@ use craft_behavior::keys; use craft_behavior::{EditCommand, Intent, KeyOwner, MoveMods, NavMove, OwnerClass}; use craft_host::target::Os; use craft_keymap::{Chord, Key, Layout, Mods}; -use egui::{Context, Id, Vec2}; +use egui::{Context, Id, IdMap, Vec2}; use std::collections::HashMap; use std::sync::Arc; @@ -47,7 +47,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { stage.enter_stale }); let mut routed: HashMap, Routed> = HashMap::new(); - let mut activated = HashMap::new(); + let mut activated = IdMap::default(); let mut consumed = vec![Taken::No; batch.presses.len()]; let driven = target.as_ref().and_then(|rec| Driven::of(ctx, rec)); let field_list = target.as_ref().filter(|_| driven.is_none()).and_then(|rec| list_of_field(ctx, rec)); @@ -542,7 +542,7 @@ fn apply_press( press: &Press, route: PressRoute, routed: &mut HashMap, Routed>, - activated: &mut HashMap, + activated: &mut IdMap, ) -> Taken { let stop = &rec.stop; let id = Some(stop.id); @@ -572,7 +572,7 @@ fn apply_press( /// `Activate` of a group member goes to the group's root, which reads `activated_member`. A child or part of a /// collection row activates itself. -fn route_activate(ctx: &Context, rec: &StopRec, routed: &mut HashMap, Routed>, activated: &mut HashMap) { +fn route_activate(ctx: &Context, rec: &StopRec, routed: &mut HashMap, Routed>, activated: &mut IdMap) { let target = if rec.stop.group.is_some() && !focus::is_row_child(ctx, &rec.stop) { activated.insert(rec.stop.root, rec.stop.id); rec.stop.root @@ -595,13 +595,7 @@ fn nudge_of(key: Key, mods: Mods) -> Option<(Vec2, Mods)> { } /// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2). -fn route_access( - ctx: &Context, - request: &Action, - nodes: &HashMap, - routed: &mut HashMap, Routed>, - activated: &mut HashMap, -) { +fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, routed: &mut HashMap, Routed>, activated: &mut IdMap) { let Some(node) = nodes.get(&request.node()).copied() else { return }; let owner = Some(node.owner); if node.focusable { diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 4b0d28219..be16b6dd5 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -17,9 +17,9 @@ use crate::runtime::egui::sizing; use crate::runtime::frame::{self, PerViewport}; use craft_behavior::layout_memory::{SizeTween, measure_tolerance, measured_change_asks_for_discard}; use craft_behavior::{Axis, Proposal}; -use egui::{Context, Id, Vec2}; +use egui::{Context, Id, IdMap, IdSet, Vec2}; use std::any::Any; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::sync::{Arc, Mutex}; /// What an entry holds. @@ -111,7 +111,7 @@ enum Item { } /// The inputs outside a measure that it read (`read_input`), by key: the widest value of each. -pub(crate) type Inputs = HashMap; +pub(crate) type Inputs = IdMap; /// One measure call a component got, the inputs besides its room it read, and its answer. #[derive(Clone)] @@ -135,10 +135,10 @@ struct Transcript { /// The inputs the run measured under. key: Box, items: Vec, - leaves: HashMap, + leaves: IdMap, /// What the real run of the pass that measured found for the body's regions and its rows that run lazily: the /// backstop for content that allocates without a component. - real: Mutex>>, + real: Mutex>>, } /// A record of this pass's runs. @@ -191,7 +191,7 @@ enum Undo { impl Scope { fn boundary() -> Scope { - Scope { body: None, boundary: true, served: None, fresh: None, visited: HashSet::new(), fills: HashSet::new(), reported: Vec::new() } + Scope { body: None, boundary: true, served: None, fresh: None, visited: IdSet::default(), fills: IdSet::default(), reported: Vec::new() } } } @@ -202,7 +202,7 @@ enum Open { Body { id: Id, items: Vec, - leaves: HashMap, + leaves: IdMap, inputs: Inputs, }, Boundary, @@ -223,19 +223,19 @@ struct Scope { /// this pass left (whose `real` this run fills). served: Option>, fresh: Option>, - visited: HashSet, - fills: HashSet, + visited: IdSet, + fills: IdSet, /// What the real run contributed in this scope. reported: Vec<(Id, f32)>, } #[derive(Default)] pub(crate) struct Entries { - entries: HashMap, - measured: HashMap, - kept: HashMap, + entries: IdMap, + measured: IdMap, + kept: IdMap, /// The bodies whose records a kept transcript gave in this pass, with that transcript. - served: HashMap>, + served: IdMap>, measuring: Vec, scopes: Vec, /// The kept calls a real run asks again, as the transcript, the component and the call's index, innermost last: @@ -252,7 +252,7 @@ impl Entries { /// inside, up to the first boundary, and asks for the discard pass. fn changed(&mut self, frame: u64, body: Option) { log::debug!(target: sizing::RERUN_LOG, "the content of {body:?} changed from its kept transcript"); - let invalidate = |kept: &mut HashMap, body: Id| { + let invalidate = |kept: &mut IdMap, body: Id| { if let Some(kept) = kept.get_mut(&body) { kept.valid = false; kept.moved = Some(frame); @@ -598,10 +598,10 @@ pub(crate) fn read_input(ctx: &Context, from: usize, key: Id, value: f32) -> f32 /// outside its room, which the call's transcript entry keeps. pub(crate) fn measure_call(ctx: &Context, f: impl FnOnce() -> R) -> (R, Inputs) { if !crate::runtime::measure::active(ctx) { - return (f(), Inputs::new()); + return (f(), Inputs::default()); } let moment = Moment::of(ctx); - with(ctx, &moment, |memory| memory.measuring.push(Open::Call { inputs: Inputs::new() })); + with(ctx, &moment, |memory| memory.measuring.push(Open::Call { inputs: Inputs::default() })); let out = f(); let inputs = with(ctx, &moment, |memory| { let at = memory.measuring.iter().rposition(|open| matches!(open, Open::Call { .. }))?; @@ -898,7 +898,9 @@ pub(crate) fn run_found(ctx: &Context, id: Id) -> bool { /// Opens the measuring run of `body`: what it hands forward until `end_measure` becomes its transcript. pub(crate) fn begin_measure(ctx: &Context, body: Id) { let moment = Moment::of(ctx); - with(ctx, &moment, |memory| memory.measuring.push(Open::Body { id: body, items: Vec::new(), leaves: HashMap::new(), inputs: Inputs::new() })); + with(ctx, &moment, |memory| { + memory.measuring.push(Open::Body { id: body, items: Vec::new(), leaves: IdMap::default(), inputs: Inputs::default() }) + }); } /// Closes the measuring run of `body` and keeps its transcript under the inputs `key` it ran under. diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 4ad20aa82..4f897ea44 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -11,7 +11,7 @@ //! //! A settling child (`Lazy::settles`) also keeps its last real run (`runtime::replay`): while it is settled, it adds //! that run to the pass again in place of running, in view or not, inside a scroll area or not. It is settled when -//! nothing the framework tracks has changed for it since that run (`settled`). +//! nothing the framework tracks has changed for it since that run, its content version included (`settled`). use crate::runtime::egui::areas::Layer; use crate::runtime::egui::{focus as focus_state, input as input_state, pass}; @@ -19,8 +19,8 @@ use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; use crate::runtime::reads::BindKey; use crate::runtime::replay::{self, Record}; -use egui::{Context, Id, Layout, Rect, Vec2}; -use std::collections::{HashMap, HashSet}; +use egui::{Context, Id, IdMap, IdSet, Layout, Rect, Vec2}; +use std::collections::HashSet; use std::sync::Arc; /// The view of the innermost scroll area, as the run that lays its content out sees it: the rect the pass shows, @@ -140,14 +140,19 @@ struct Settled { rect: Rect, /// The pointer was over it, or one of its stops held focus: it runs again to show that they left. engaged: bool, + /// The version of the app data it showed (`Lazy::content`). + content: Option, } /// What changed in the frame for every settling child. #[derive(Default)] struct Changes { - /// Every settling child runs through this frame: a frame with input other than pointer motion, an app's repaint - /// request or an edit of a given value unsettles every child for that frame and the next. + /// Every settling child runs through this frame: an app's repaint request outside every settling child or an edit + /// of a given value unsettles every child for that frame and the next. unsettled_through: u64, + /// Every settling child with no content version runs through this frame: a frame with input other than pointer + /// motion unsettles them for that frame and the next. + input_through: u64, /// The pass whose input was looked at. scanned: u64, /// The values changed in a frame, and the frame. @@ -156,12 +161,12 @@ struct Changes { #[derive(Default)] pub(crate) struct Store { - entries: HashMap, + entries: IdMap, changes: Changes, /// The last frame each scroll area reached one of its children in. - reached: HashMap, + reached: IdMap, /// What the real run that lays a scroll area's content out found, by area, from `begin` to `placed`. - placed: HashMap, + placed: IdMap, /// The frame the entries were last pruned in. pruned: u64, } @@ -191,7 +196,7 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { store.entries.retain(|_, entry| { entry.touched + 1 >= frame || entry.owner.is_some_and(|owner| reached.get(&owner).is_none_or(|ran| ran + 1 < frame)) }); - let owners: HashSet = store.entries.values().filter_map(|entry| entry.owner).collect(); + let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect(); store.reached.retain(|owner, _| owners.contains(owner)); } f(store, pass_nr, frame) @@ -254,10 +259,12 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// none of that held in its last run; /// - none of its stops holds focus or is the target of a focus request, now or in its last run; /// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`); -/// - no frame unsettled every child (`unsettle`): input other than pointer motion this frame or the one before, an app's -/// repaint request or an edit of a given value; +/// - its content version is the one of its last run; +/// - no frame unsettled every child (`unsettle`): an app's repaint request outside every settling child or an edit of a +/// given value, this frame or the one before; +/// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). -pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option) -> Option { +pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); @@ -268,13 +275,13 @@ pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, pl if store.changes.scanned != pass_nr { store.changes.scanned = pass_nr; if input { - store.changes.unsettled_through = store.changes.unsettled_through.max(frame + 1); + store.changes.input_through = store.changes.input_through.max(frame + 1); } } let changes = &store.changes; // Usually empty: only the values written this frame. let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone()); - let unsettled = changes.unsettled_through >= frame; + let unsettled = changes.unsettled_through >= frame || (content.is_none() && changes.input_through >= frame); let entry = store.touch(owner, id, frame); let replays = match entry.replays { Some((decided_in, replays)) if decided_in == pass_nr => replays, @@ -283,6 +290,7 @@ pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, pl && entry.settled.as_ref().is_some_and(|settled| { let facts = &settled.record.facts; settled.frame < frame + && settled.content == content && !settled.engaged && !facts.unsettled && !facts.blocked @@ -338,11 +346,12 @@ pub(crate) fn keep(ctx: &Context, owner: Option, id: Id) { }); } -/// Keeps the real run `record` of the settling child `id`, which ran at `place` and took `rect`. -pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect) { +/// Keeps the real run `record` of the settling child `id`, which ran at `place`, took `rect` and showed the app data +/// of version `content`. +pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, content: Option) { let targets = focus::targets(ctx); let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); - let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now }; + let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, content }; settled.engaged |= engaged(ctx, &settled); with(ctx, |store, _, frame| { settled.frame = frame; @@ -363,7 +372,8 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) { }); } -/// Unsettles every settling child for this frame and the next: a change the framework cannot attribute to a child. +/// Unsettles every settling child for this frame and the next: a change of app data the framework cannot attribute to +/// a child. pub(crate) fn unsettle(ctx: &Context) { with(ctx, |store, _, frame| store.changes.unsettled_through = store.changes.unsettled_through.max(frame + 1)); } diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index d9fc95f82..641a9a3b3 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -9,13 +9,12 @@ use crate::runtime::pending::{self, Job, Pending}; use craft_behavior::eviction::owner_due; use craft_host::Host; use craft_settings::Remembered; -use egui::{Context, Id, ViewportId}; +use egui::{Context, Id, IdSet, ViewportId}; use serde::Serialize; use serde::de::DeserializeOwned; use std::any::{Any, TypeId}; use std::borrow::Cow; use std::cell::RefCell; -use std::collections::HashSet; use std::fmt::Debug; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; @@ -246,7 +245,7 @@ pub(crate) fn evict(ctx: &Context) { let live = pass::live_viewports(ctx); pass_state::with::(ctx, |reg| { let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr(ctx, r.viewport), now, live.contains(&r.viewport)); - let dead: HashSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect(); + let dead: IdSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect(); if dead.is_empty() { return; } @@ -457,13 +456,8 @@ impl MemoryStage { self.claimed.borrow_mut().push(base); let viewport = pass::current_viewport(&self.ctx); let pass_nr = pass::pass_nr(&self.ctx, viewport); - let duplicate = PerViewport::>>::with_pass( - &self.ctx, - viewport, - pass_nr, - |claimed, _| claimed.clear(), - |claimed| !claimed.insert(base), - ); + let duplicate = + PerViewport::>::with_pass(&self.ctx, viewport, pass_nr, |claimed, _| claimed.clear(), |claimed| !claimed.insert(base)); debug_assert!(!duplicate, "an id is the base of two open stages in one pass"); } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index e365ee9ee..646d80efd 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -12,9 +12,8 @@ use crate::runtime::pointer; use craft_behavior::OwnerClass; use craft_behavior::overlay::Side; use egui::emath::TSTransform; -use egui::{Context, Id, Pos2, Rect, ViewportId}; +use egui::{Context, Id, IdMap, IdSet, Pos2, Rect, ViewportId}; use smallvec::SmallVec; -use std::collections::HashMap; /// A modal's backdrop. #[derive(Clone, Copy, Debug, PartialEq)] @@ -235,7 +234,7 @@ pub(crate) struct TopModal { #[derive(Default)] pub(crate) struct Persist { - raised: HashMap, + raised: IdMap, counter: u64, modal: bool, /// The layers of the last pass, bottom to top, as `end_pass` handed them to egui. @@ -252,9 +251,9 @@ pub(crate) struct Persist { /// A popup stands over a modal layer here, as of the last finished pass. popup_over_modal: bool, /// The layers that first showed while the primary button was held, until that press ends. - held_open: std::collections::HashSet, + held_open: IdSet, /// The root frame and pass each shown layer first ran its body in; gone with the layer's last entry. - appeared: HashMap, + appeared: IdMap<(u64, u64)>, } /// The closes queued and not yet taken, each with the root frame that queued it and whether it is carried: a carried @@ -674,7 +673,7 @@ pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) { } /// Groups `entries` into families, each parent first, ordered bottom to top. -fn families(entries: &[OpenEntry], raised: &HashMap) -> Vec> { +fn families(entries: &[OpenEntry], raised: &IdMap) -> Vec> { let root_of = |entry: &OpenEntry| { let mut at = entry; while let Some(parent) = at.parent.and_then(|parent| entries.iter().find(|other| other.id == parent)) { diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 869d91667..269ef500b 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -12,7 +12,7 @@ use crate::runtime::egui::memory::Service; use crate::runtime::frame::{self, PerViewport, Stamped, Stored}; -use egui::Context; +use egui::{Context, IdSet}; use std::cell::RefCell; use std::sync::Arc; @@ -137,7 +137,7 @@ pass_state! { ids: crate::contract::steps::id::IdPass, pass_pointer: Arc, overlay_pass: crate::runtime::overlay::Pass, - shown_ids: std::collections::HashSet, + shown_ids: IdSet, } } diff --git a/crates/ui-contract/src/runtime/pending.rs b/crates/ui-contract/src/runtime/pending.rs index 43f343e0a..bb2165f55 100644 --- a/crates/ui-contract/src/runtime/pending.rs +++ b/crates/ui-contract/src/runtime/pending.rs @@ -7,9 +7,8 @@ use crate::runtime::frame; use crate::runtime::memory::{self, MemoryStage}; use craft_host::queue::{Cancel, JobQueue, Priority, QueueOptions}; use craft_host::{Jobs, Wake}; -use egui::{Context, Id, ViewportId}; +use egui::{Context, Id, IdMap, ViewportId}; use std::any::TypeId; -use std::collections::HashMap; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; @@ -199,7 +198,7 @@ type Queue = (Arc, Arc>); #[derive(Default)] struct PendingState { queue: Option, - tracked: HashMap, + tracked: IdMap, } fn queue_of(ctx: &Context, jobs: &Arc) -> Arc> { diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 577bce824..25ac0814a 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -13,7 +13,7 @@ use craft_behavior::{ }; use craft_keymap::Mods; use craft_theme::HitSizes; -use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId}; +use egui::{Context, Id, IdMap, Pos2, Rect, Vec2, ViewportId}; use std::collections::HashMap; use std::sync::Arc; @@ -97,7 +97,7 @@ pub(crate) struct Memory { /// Whether any arena of the viewport holds an open press; sensing registers it, as the layer above. press_probe: Option bool>, /// The arena roots whose members the next pass resolves without (`withhold_members`), with the pass that asked. - withheld: HashMap, + withheld: IdMap, } /// What one root registered on one layer: its shapes and its egui widgets. @@ -110,7 +110,7 @@ struct RootRecord { click: bool, } -type LayerRecord = HashMap>; +type LayerRecord = HashMap>; #[derive(Default)] pub(crate) struct Shapes { diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index d95012672..d08ead49e 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -14,7 +14,7 @@ use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; -use egui::{Context, Id}; +use egui::{Context, Id, IdSet}; use std::collections::HashSet; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -70,11 +70,12 @@ pub(crate) struct Record { journal: Vec, egui: egui::PassRecords, /// The egui widgets of the run. - pub(crate) widgets: HashSet, + pub(crate) widgets: IdSet, pub(crate) facts: Facts, } -fn recording(ctx: &Context) -> bool { +/// Whether a record is open around the running code. +pub(crate) fn recording(ctx: &Context) -> bool { OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| !recorder.open.is_empty()) } diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index 585b281f0..1e17eb818 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -34,6 +34,14 @@ pub trait DockPanels

{ /// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge. fn body(&mut self, panel: &P, ui: &mut Ui, cx: &mut BodyCx<'_>); + /// The version of the app data `panel`'s body shows that the framework does not track (a document's revision, a + /// job's progress). With one, the body settles (`Lazy::settles` with `Lazy::content`): it runs only when its + /// version, its room or something the framework tracks in it changed, the pointer is over it or focus is in it, and + /// otherwise repaints its last run. `None` (the default) runs the body every pass. + fn content(&self, _panel: &P) -> Option { + None + } + /// Takes the group holding `panels`, whose tab `active` is selected, in place of its tab strip and body: at /// `GroupAt::Show(rect)` it shows its view in `ui`, which the dock holds to `rect` and clips to it; at /// `GroupAt::Measure(width)` it measures that view at `width` the way it shows it. It returns the height the view diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 1052fbd34..18a9ee759 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -4,7 +4,7 @@ use super::hide::{self, Shown}; use crate::contract::overlay::PlacementChange; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, Lazy, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; @@ -818,20 +818,19 @@ impl Pass<'_, P> { }; let rect = match at { GroupAt::Measure(width) => { - let measured = - make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panels.borrow_mut().body(shown, ui, body)); + let measured = make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panel_body(&panels, shown, ui, body)); return Some(measured.y); } GroupAt::Show(rect) => rect, }; - let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panels.borrow_mut().body(shown, ui, body)).output; + let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output; // The size `panel` floats at out of this group: the group's width, and the height the group measures at with // `panel` shown in a floating window's room, so content that fills the body takes that room. let fitted = |ui: &Ui, panel: &P| { let at = members.iter().position(|member| member == panel).unwrap_or(active); let room = Vec2::new(rect.width(), scene.space.content_room()); let measured = make(at, false).id(output.response.id).measure_in(ui, Proposal::Size(room), |ui, body| { - panels.borrow_mut().body(&members[at], ui, body); + panel_body(&panels, &members[at], ui, body); }); Vec2::new(rect.width(), measured.y) }; @@ -1149,3 +1148,14 @@ fn window_edit( _ => moving.take().map(|held| EditEvent::cancel(held.id, CancelReason::Dismissed, Some(Mixed::Same(held.before)))), } } + +/// Shows `panel`'s body in a group's body; a panel with a content version settles (`DockPanels::content`). +fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) { + let content = panels.borrow().content(panel); + match content { + Some(version) => { + Lazy::new(("panel", PanelKey::of(panel).0), 0.0).settles(true).content(version).show(ui, |ui| panels.borrow_mut().body(panel, ui, body)); + } + None => panels.borrow_mut().body(panel, ui, body), + } +} diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 774332749..cd4dca5e5 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -1,5 +1,5 @@ -//! The runs of a settled docked layout: each group adds the same runs whatever its tab count, and a closed menu, the -//! group's header controls and its tabs add none. +//! The runs of a settled docked layout: each group adds the same runs whatever its tab count, a closed menu, the +//! group's header controls and its tabs add none, and a panel body with a content version runs only when it changes. use craft_behavior::Axis; use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; @@ -9,6 +9,8 @@ use craft_ui::menu::PanelRow; use craft_ui::patterns::dock::DockArea; use craft_ui::testing::{Fixture, last_pass_runs, trial}; use egui::{Ui, Vec2}; +use std::cell::Cell; +use std::rc::Rc; struct Panels; @@ -70,3 +72,47 @@ fn a_settled_dock_group_runs_the_same_whatever_its_tab_count() { let parts: Vec<_> = shown.iter().filter(|(ty, _)| matches!(short(ty), "Row" | "Tab" | "IconButton" | "GroupGrip")).collect(); assert!(parts.is_empty(), "a settled dock ran header parts as runs: {parts:?}"); } + +/// Two panels in two groups: panel 0 gives the content version `version`, panel 1 none. Each body counts its runs. +struct Versioned { + runs: Rc<[Cell; 2]>, + version: Rc>, +} + +impl DockPanels for Versioned { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn body(&mut self, panel: &usize, _: &mut Ui, _: &mut BodyCx<'_>) { + self.runs[*panel].set(self.runs[*panel].get() + 1); + } + + fn content(&self, panel: &usize) -> Option { + (*panel == 0).then(|| self.version.get()) + } +} + +/// A panel body with a content version runs in the frame its version changes and settles otherwise; a body without one +/// runs every frame. +#[trial] +fn a_panel_body_with_a_content_version_runs_only_when_its_version_changes() { + let (runs, version): (Rc<[Cell; 2]>, _) = (Rc::default(), Rc::new(Cell::new(1))); + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0)); + let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); + let mut panels = Versioned { runs: Rc::clone(&runs), version: Rc::clone(&version) }; + let mut fixture = Fixture::new(move |ui| { + DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + let mut frame = || { + runs.iter().for_each(|runs| runs.set(0)); + fixture.frame(Vec::new()); + [runs[0].get(), runs[1].get()] + }; + let [versioned, plain] = frame(); + assert!(versioned == 0 && plain > 0, "the versioned body settles, the other runs: {versioned}, {plain}"); + version.set(2); + assert!(frame()[0] > 0, "a new version runs the versioned body"); + assert_eq!(frame()[0], 0, "and it settles at it"); +} diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index d2af1c8ca..b220395c3 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -14,13 +14,13 @@ use super::screen_mode::{ScreenMode, ScreenModeCommands, ScreenModeFollow}; use super::words::ShellWords; use crate::contract::overlay::Resize; use crate::contract::{ - Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, PaneEdge, Props as _, Remember as _, Role, - ShellPane, ShowContainer as _, Sizing, + Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, Lazy, Mount, NoValue, Outcome, PaneEdge, Props as _, Remember as _, + Role, ShellPane, ShowContainer as _, Sizing, }; use crate::notices::ToastStack; use crate::runtime::commands::{CommandAccess as _, CommandSet as _}; use crate::runtime::egui::pass; -use crate::runtime::env::{AppValues, BodyMode, Env, Label, RevealEdge, ShellCx, ShellEntry, ShellRegions, WindowKey}; +use crate::runtime::env::{AppValues, BodyMode, Env, Label, RevealEdge, ShellCx, ShellEntry, ShellRegions, SlotKey, WindowKey}; use crate::runtime::focus::FocusPolicy; use crate::runtime::frame::{note_shell, take_chrome_toggles}; use crate::runtime::overlay::{OpenFilter, any_open}; @@ -411,6 +411,15 @@ impl<'a, S> AppShell<'a, S> { self } + /// Gives the slot keyed `key`, added before, the version of the app data it shows ([`Slot::content`]), for the + /// slots the `options_bar`, `tools` and `status` builders make. + pub fn content(mut self, key: SlotKey, version: u64) -> Self { + for placed in self.title.iter_mut().chain(self.slots.iter_mut()).filter(|placed| placed.slot.key() == key) { + placed.slot = placed.slot.clone().content(version); + } + self + } + /// Lays out the slots, then the body in what is left, runs the window's dialogs over them and shows the toasts of /// the window. Each slot and the body get `app`, one after the other: the slots that do not cover the body, then the /// body, then the slots a reveal lays over it. @@ -542,7 +551,13 @@ impl<'a, S> AppShell<'a, S> { if let Some(label) = slot.name().cloned().or_else(|| named.map(|name| name(&words))) { region = region.label(label); } - region.show(ui, |ui, bcx| add(ui, bcx, app)); + let content = slot.content_version(); + region.show(ui, |ui, bcx| match content { + Some(version) => { + Lazy::new(("slot", slot.key()), 0.0).settles(true).content(version).show(ui, |ui| add(ui, bcx, app)); + } + None => add(ui, bcx, app), + }); } }; show_slots(ui, false, app); diff --git a/crates/ui-shell/src/shell/regions.rs b/crates/ui-shell/src/shell/regions.rs index b36c63450..e94e90aad 100644 --- a/crates/ui-shell/src/shell/regions.rs +++ b/crates/ui-shell/src/shell/regions.rs @@ -44,9 +44,9 @@ impl SlotSize { } } -/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size and its AccessKit -/// name. The shell paints the chrome surface over the whole slot and a divider along its edge toward the body; the -/// title slot's bar paints its own. +/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size, its AccessKit +/// name and the version of the app data it shows. The shell paints the chrome surface over the whole slot and a divider +/// along its edge toward the body; the title slot's bar paints its own. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Slot { @@ -56,13 +56,14 @@ pub struct Slot { visible: bool, reveal: bool, label: Option