From 9341d4d4787a4c540e2c45edbb5b0b35c1efb82e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 17:24:44 +0000 Subject: [PATCH 1/4] Settling children: a content version, repaints scoped to the child that asks, input elsewhere leaves versioned children settled Lazy::content gives the version of the app data a settling child shows; it runs when the version changes. frame::request_repaint asked inside a settling child runs only that child; outside every one it still runs them all. frame::request_own_repaint moves only what the caller shows: the tool host and the canvas zoom ease use it. Input other than pointer motion unsettles only the children without a content version. --- crates/ui-canvas/src/canvas/tool_host.rs | 4 +- crates/ui-canvas/src/canvas/zoom_motion.rs | 2 +- crates/ui-contract/src/contract/lazy.rs | 25 +++++++-- crates/ui-contract/src/runtime/frame.rs | 18 +++++- crates/ui-contract/src/runtime/lazy.rs | 34 ++++++++---- crates/ui-contract/src/runtime/replay.rs | 3 +- crates/ui-widgets/tests/it/body/settle.rs | 64 ++++++++++++++++++++-- 7 files changed, 121 insertions(+), 29 deletions(-) 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/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-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/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/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 4ad20aa82..ff10aca5e 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}; @@ -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. @@ -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/replay.rs b/crates/ui-contract/src/runtime/replay.rs index d95012672..30919103b 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -74,7 +74,8 @@ pub(crate) struct Record { 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-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index 3fd56b7f3..0a375329f 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -1,6 +1,6 @@ //! Settling children (`Lazy::settles`): a settled child adds its last run to the pass in place of running, and runs //! when something it shows may have changed: the pointer over it, a bound value, inspection record or command state it -//! read, its room, an animation. +//! read, its room, its content version, an animation or a repaint asked inside it. use crate::values::kit::{AT, INITIAL, Scrub, Seen}; use craft_ui::buttons::Button; @@ -8,7 +8,7 @@ use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowCont use craft_ui::display::Spinner; use craft_ui::layout_components::Stack; use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _}; -use craft_ui::runtime::inspect; +use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Frames, last_pass_measuring_runs, trial}; @@ -23,12 +23,17 @@ const READER: Rect = Rect { min: Pos2::new(150.0, 70.0), max: Pos2::new(250.0, 9 const SETTLED: usize = 4; /// Two settling children, `reader` and `other`, under a scrub bound to the value the reader's own scrub shows. The -/// scrub that edits comes before the children in the pass when `editor_first`, else after them. +/// scrub that edits comes before the children in the pass when `editor_first`, else after them. Each child shows the +/// content version in `versions`, if any; `other` asks for a repaint in each run while `repaints` holds, and the app +/// asks for one outside both children while `app_repaints` holds. struct Scene { value: RefCell, room: Cell, editor_first: bool, spinner: bool, + versions: [Cell>; 2], + repaints: Cell, + app_repaints: Cell, runs: [Cell; 2], buttons: [Cell<(Id, Rect)>; 2], seen: Seen, @@ -41,25 +46,43 @@ impl Scene { room: Cell::new(ROOM), editor_first, spinner, + versions: Default::default(), + repaints: Cell::new(false), + app_repaints: Cell::new(false), runs: Default::default(), buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))], seen: Seen::default(), } } + /// The settling child `key`, with the content version of child `at`. + fn child(&self, key: &str, at: usize) -> Lazy { + let child = Lazy::new(key, 0.0).settles(true); + match self.versions[at].get() { + Some(version) => child.content(version), + None => child, + } + } + fn show(&self, ui: &mut Ui) { + if self.app_repaints.get() { + frame::request_repaint(ui.ctx()); + } if self.editor_first { self.editor(ui); } in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { - Lazy::new("reader", 0.0).settles(true).show(ui, |ui| { + self.child("reader", 0).show(ui, |ui| { self.runs[0].set(self.runs[0].get() + 1); let response = Button::new("Alpha").show(ui).response; self.buttons[0].set((response.id, response.rect)); Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); }); - Lazy::new("other", 0.0).settles(true).show(ui, |ui| { + self.child("other", 1).show(ui, |ui| { self.runs[1].set(self.runs[1].get() + 1); + if self.repaints.get() { + frame::request_repaint(ui.ctx()); + } // In a body, whose measure a run that is not settled takes from what its last run kept. Stack::new().show(ui, |ui, _| { let response = Button::new("Beta").show(ui).response; @@ -199,6 +222,37 @@ fn a_child_with_a_running_animation_runs_every_frame() { } } +/// A repaint asked inside a settling child runs that child again, and only it. +#[trial] +fn a_repaint_asked_inside_a_settled_child_runs_only_that_child() { + let scene = Scene::new(false, false); + scene.repaints.set(true); + let mut frames = Frames::new(); + scene.settle(&mut frames); + for frame in 0..SETTLED { + assert_eq!(scene.frame(&mut frames, vec![]), [0, 1], "frame {frame}: the child that asks runs, the other does not"); + } +} + +/// A child with a content version runs in the frame its version changes, and only then; input elsewhere in the window +/// leaves it settled, and a repaint the app asks for outside every child runs it. +#[trial] +fn a_child_with_a_content_version_runs_when_it_changes() { + let scene = Scene::new(false, false); + scene.versions.iter().for_each(|version| version.set(Some(1))); + let mut frames = Frames::new(); + scene.settle(&mut frames); + let away = Pos2::new(ORIGIN.x + ROOM.x + 90.0, ORIGIN.y + ROOM.y + 40.0); + for events in [vec![moved(away)], vec![press(away)], vec![release(away)], vec![]] { + assert_eq!(scene.frame(&mut frames, events.clone()), [0, 0], "input elsewhere ({events:?}) runs no versioned child"); + } + scene.versions[0].set(Some(2)); + assert_eq!(scene.frame(&mut frames, vec![]), [1, 0], "the child whose version changed runs, the other does not"); + assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "both settle at the new version"); + scene.app_repaints.set(true); + assert_eq!(scene.frame(&mut frames, vec![]), [1, 1], "an app repaint outside both children runs both"); +} + /// The app commands the command scene's children show. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] #[command(prefix = "settleTrial")] From 9b8dbfb332e45298678abfacb7f92786094c281e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 17:28:04 +0000 Subject: [PATCH 2/4] Shell slots and dock panel bodies settle when they give a content version Slot::content and AppShell::content give a slot the version of the app data it shows; DockPanels::content gives one per panel body. With one, the slot or body runs in a settling Lazy. Trials: a versioned slot and a versioned panel body run only when their version changes; a stroke whose tool asks for repaints runs no versioned panel beside the canvas and one pass per move frame. --- crates/ui-canvas/tests/it/canvas/tool.rs | 77 +++++++++++++++++++- crates/ui-panels/src/docking/panels.rs | 8 ++ crates/ui-patterns/src/patterns/dock/area.rs | 22 ++++-- crates/ui-patterns/tests/it/docking/runs.rs | 50 ++++++++++++- crates/ui-shell/src/shell/app_shell.rs | 23 +++++- crates/ui-shell/src/shell/regions.rs | 23 +++++- crates/ui-shell/tests/it/shell/app_shell.rs | 43 ++++++++++- 7 files changed, 227 insertions(+), 19 deletions(-) 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-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 46310dcfa..18a9ee759 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -3,7 +3,9 @@ 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 _}; +use crate::contract::{ + 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}; use crate::docking::tree::FrameRules; @@ -816,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) }; @@ -1147,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 d7718edc6..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