mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 01:08:38 +00:00
craft-ui: memoized views are the one change mechanism; the settling path goes
Lazy::settles, Lazy::content, Key::Version, the input and unsettle rules (Changes::input_through, unsettled_through, scan) and lazy::unsettle with its callers are removed. frame::request_repaint marks the record of the view it is asked in and reruns only that view; asked outside every view, every view replays. request_own_repaint goes; ui-canvas calls request_repaint. Pages measures each hidden page once per pass. The tests that used the old API are memoized views, with trials for repaints in and outside views and for given-value edits. API map rows and the framework doc describe memoized views.
This commit is contained in:
@@ -14,7 +14,7 @@ use craft_imaging::ui::transform_preview::{
|
||||
};
|
||||
use craft_imaging::ui::warp::WarpMesh;
|
||||
use craft_ui::canvas::{Canvas, PixelRect};
|
||||
use craft_ui::contract::{Lazy, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{MemoProps, MemoView, PlainData, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Color32, ColorImage, Shape};
|
||||
|
||||
@@ -385,15 +385,38 @@ type PaintedPreview = (Rc<PreviewTextures>, f32);
|
||||
/// The texture and size a painted preview showed.
|
||||
type ShownPreview = (egui::TextureId, [f32; 2]);
|
||||
|
||||
/// What the next frames paint: the previews, each at its scale, and the display every one is converted for.
|
||||
#[derive(Default, PlainData)]
|
||||
struct Painting {
|
||||
#[plain_data(assume = "the previews' textures are a cache: what they show follows their pixels, which do not change")]
|
||||
previews: Vec<PaintedPreview>,
|
||||
#[plain_data(assume = "a display is replaced, never changed: its key follows its conversion")]
|
||||
display: Option<PreviewDisplay>,
|
||||
}
|
||||
|
||||
/// What each painted preview shows: the texture and uv extent `PreviewTextures::pick` gives.
|
||||
fn picks(ui: &egui::Ui, painting: &Painting) -> Vec<Option<ShownPreview>> {
|
||||
let display = painting.display.as_ref();
|
||||
painting.previews.iter().map(|(textures, scale)| textures.pick(ui.ctx(), PreviewTextures::choose(1.0, *scale, false), display)).collect()
|
||||
}
|
||||
|
||||
/// A memoized view of the painting.
|
||||
#[derive(MemoProps)]
|
||||
struct Previews<'a> {
|
||||
painting: &'a Tracked<Painting>,
|
||||
}
|
||||
|
||||
fn previews(props: &mut Previews<'_>, ui: &mut egui::Ui) -> Vec<Option<ShownPreview>> {
|
||||
picks(ui, props.painting)
|
||||
}
|
||||
|
||||
/// Previews painted every frame of a fixture whose host runs jobs only when a trial says (upstream's 5 × 3 white
|
||||
/// image).
|
||||
struct Mips {
|
||||
fixture: Fixture,
|
||||
jobs: Arc<ManualJobs>,
|
||||
/// The previews the next frames paint, each at its scale.
|
||||
painted: Rc<RefCell<Vec<PaintedPreview>>>,
|
||||
/// The display every painted preview is converted for.
|
||||
display: Rc<RefCell<Option<PreviewDisplay>>>,
|
||||
/// What the next frames paint.
|
||||
painting: Rc<RefCell<Tracked<Painting>>>,
|
||||
/// What each painted preview showed in the last frame.
|
||||
shown: Rc<RefCell<Vec<Option<ShownPreview>>>>,
|
||||
/// The previews' uploads in the last frame, read in the frame.
|
||||
@@ -409,51 +432,50 @@ impl Mips {
|
||||
Self::with(false)
|
||||
}
|
||||
|
||||
/// The previews painted inside a settling region (`Lazy::settles`), which replays its last run while nothing the
|
||||
/// framework tracks changed for it.
|
||||
fn settling() -> Self {
|
||||
/// The previews painted inside a memoized view, which replays its last run while its painting is unchanged and no
|
||||
/// texture it shows is loading.
|
||||
fn memoized() -> Self {
|
||||
Self::with(true)
|
||||
}
|
||||
|
||||
fn with(settles: bool) -> Self {
|
||||
fn with(memoized: bool) -> Self {
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let painted = Rc::new(RefCell::new(Vec::<(Rc<PreviewTextures>, f32)>::new()));
|
||||
let display = Rc::new(RefCell::new(None::<PreviewDisplay>));
|
||||
let painting = Rc::new(RefCell::new(Tracked::new(Painting::default())));
|
||||
let shown = Rc::new(RefCell::new(Vec::new()));
|
||||
let uploads = Rc::new(Cell::new(0));
|
||||
let (paint, converted, seen, counted) = (Rc::clone(&painted), Rc::clone(&display), Rc::clone(&shown), Rc::clone(&uploads));
|
||||
let (paint, seen, counted) = (Rc::clone(&painting), Rc::clone(&shown), Rc::clone(&uploads));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let run = |ui: &mut egui::Ui| {
|
||||
let display = converted.borrow();
|
||||
let picks = paint
|
||||
.borrow()
|
||||
.iter()
|
||||
.map(|(textures, scale)| textures.pick(ui.ctx(), PreviewTextures::choose(1.0, *scale, false), display.as_ref()))
|
||||
.collect();
|
||||
*seen.borrow_mut() = picks;
|
||||
};
|
||||
if settles {
|
||||
Lazy::new("previews", 0.0).settles(true).show(ui, run);
|
||||
let painting = paint.borrow();
|
||||
let shows = if memoized {
|
||||
MemoView::new("previews", Previews { painting: &painting }, previews).show(ui).unwrap_or_default()
|
||||
} else {
|
||||
run(ui);
|
||||
}
|
||||
picks(ui, &painting)
|
||||
};
|
||||
*seen.borrow_mut() = shows;
|
||||
counted.set(PreviewTextures::statistics(ui.ctx()).uploads);
|
||||
});
|
||||
fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(jobs.clone()).build()));
|
||||
fixture.settle();
|
||||
Mips { fixture, jobs, painted, display, shown, uploads }
|
||||
Mips { fixture, jobs, painting, shown, uploads }
|
||||
}
|
||||
|
||||
/// One frame painting `previews`.
|
||||
/// A change of the previews or their scales arrives with input, as a drag's does.
|
||||
/// One frame painting `previews`; a change of the previews or their scales is an edit of the painting.
|
||||
fn paint(&mut self, previews: &[(&Rc<PreviewTextures>, f32)]) {
|
||||
let next: Vec<_> = previews.iter().map(|(textures, scale)| (Rc::clone(textures), *scale)).collect();
|
||||
let changed = {
|
||||
let painted = self.painted.borrow();
|
||||
let painting = self.painting.borrow();
|
||||
let painted = &painting.previews;
|
||||
painted.len() != next.len() || painted.iter().zip(&next).any(|(a, b)| !Rc::ptr_eq(&a.0, &b.0) || a.1 != b.1)
|
||||
};
|
||||
*self.painted.borrow_mut() = next;
|
||||
self.fixture.frame(if changed { vec![egui::Event::WindowFocused(true)] } else { Vec::new() });
|
||||
if changed {
|
||||
self.painting.borrow_mut().edit(|painting| painting.previews = next);
|
||||
}
|
||||
self.fixture.frame(Vec::new());
|
||||
}
|
||||
|
||||
/// Converts every painted preview for `display` from the next frame on.
|
||||
fn display(&mut self, display: PreviewDisplay) {
|
||||
self.painting.borrow_mut().edit(|painting| painting.display = Some(display));
|
||||
}
|
||||
|
||||
/// The texture and uv extent the `at`th preview showed.
|
||||
@@ -471,12 +493,12 @@ fn near_uv(uv: [f32; 2], want: [f32; 2]) -> bool {
|
||||
}
|
||||
|
||||
/// P91 (#13382): the frame that first needs a mip level builds none on the UI thread; level 0 stands in, the frames
|
||||
/// while its job waits do no work for it, and the landing frame uploads it once. In a settling region the frame
|
||||
/// after the job lands runs the region again with no other input and shows the level.
|
||||
/// while its job waits do no work for it, and the landing frame uploads it once. In a memoized view the frame after
|
||||
/// the job lands runs the view again with no other input and shows the level.
|
||||
#[trial]
|
||||
fn a_mip_level_first_needed_mid_drag_is_built_off_the_ui_thread() {
|
||||
for settles in [false, true] {
|
||||
mips_first_needed_mid_drag(if settles { Mips::settling() } else { Mips::new() });
|
||||
for memoized in [false, true] {
|
||||
mips_first_needed_mid_drag(if memoized { Mips::memoized() } else { Mips::new() });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,7 +553,7 @@ fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() {
|
||||
assert_eq!(mips.jobs.waiting(), 0, "a first frame at level 1 builds it in the frame");
|
||||
assert!(near_uv(mips.shown(0).1, [5.0 / 6.0, 3.0 / 4.0]), "level 1 shows at once");
|
||||
mips.paint(&[(&t, 1.0)]);
|
||||
*mips.display.borrow_mut() = Some(PreviewDisplay::new(7, ColorImage::clone));
|
||||
mips.display(PreviewDisplay::new(7, ColorImage::clone));
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
assert_eq!(mips.jobs.waiting(), 0, "nothing is uploaded for the new display, so level 1 is built in the frame");
|
||||
assert!(near_uv(mips.shown(0).1, [5.0 / 6.0, 3.0 / 4.0]));
|
||||
|
||||
@@ -5,7 +5,7 @@ use craft_behavior::{EditEvent, EditHistory, Mixed, SelectionChange};
|
||||
use craft_layers::ui::mock::FakeLayers;
|
||||
use craft_layers::ui::panel::{LayerColumn, LayerDrop, LayerPosition, LayerToggle, LayersEvent, LayersPanel};
|
||||
use craft_layers::ui::tree::{LayerKind, LayerPart, LayerSelection};
|
||||
use craft_ui::contract::Lazy;
|
||||
use craft_ui::contract::{MemoProps, MemoView, Outbox, PlainData, Tracked};
|
||||
use craft_ui::testing::access::focused_key;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
@@ -246,22 +246,44 @@ fn shift_right_and_left_open_and_close_the_active_layers_effects() {
|
||||
assert_eq!(fx(take(&app)), [(7, false)], "Shift+Left closes them");
|
||||
}
|
||||
|
||||
/// The tree a memoized view of the panel shows, as the app's model.
|
||||
#[derive(PlainData)]
|
||||
struct Model {
|
||||
#[plain_data(assume = "a mock tree: its only interior mutability is call counters, which no view shows")]
|
||||
tree: FakeLayers,
|
||||
}
|
||||
|
||||
/// A memoized view of the panel over the app's model; it applies what the panel reports to the model and sends it on.
|
||||
#[derive(MemoProps)]
|
||||
struct PanelView<'a> {
|
||||
model: &'a mut Tracked<Model>,
|
||||
events: Outbox<'a, LayersEvent<u32>>,
|
||||
}
|
||||
|
||||
fn panel_view(props: &mut PanelView<'_>, ui: &mut Ui) {
|
||||
let out = LayersPanel::new(&props.model.tree).show(ui);
|
||||
for event in out.events {
|
||||
props.model.edit(|model| apply(&mut model.tree, &event));
|
||||
props.events.send(event);
|
||||
}
|
||||
}
|
||||
|
||||
/// A row's access focus action, as a screen reader or a test driver gives it, puts key focus in the rows with the
|
||||
/// lead on that row: the access focus lands on the row's node.
|
||||
/// So does it while the panel is a settled region that replays its last run.
|
||||
/// So does it while the panel is a settled memoized view that replays its last run.
|
||||
#[trial]
|
||||
fn a_rows_access_focus_action_leads_the_focused_rows_to_it() {
|
||||
let settled = || {
|
||||
let app = Rc::new(RefCell::new(App { tree: FakeLayers::sample(), events: Vec::new() }));
|
||||
let shared = Rc::clone(&app);
|
||||
let mut model = Tracked::new(Model { tree: FakeLayers::sample() });
|
||||
let mut events = Vec::new();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Lazy::new("layers", 0.0).settles(true).show(ui, |ui| show(ui, &mut shared.borrow_mut()));
|
||||
MemoView::new("layers", PanelView { model: &mut model, events: Outbox::new(&mut events) }, panel_view).show(ui);
|
||||
});
|
||||
fixture.room(PANEL);
|
||||
fixture.settle();
|
||||
(fixture, app)
|
||||
fixture
|
||||
};
|
||||
for (mut fixture, _app) in [rig(FakeLayers::sample()), settled()] {
|
||||
for mut fixture in [rig(FakeLayers::sample()).0, settled()] {
|
||||
let styled = row(&fixture, "Styled");
|
||||
fixture.access(AccessActionKind::Focus, &styled).idle(2);
|
||||
assert!(fixture.focused_stop().is_some(), "the rows hold key focus");
|
||||
|
||||
@@ -646,7 +646,7 @@ impl<'m> ToolHost<'m> {
|
||||
}
|
||||
}
|
||||
if requests.repaint {
|
||||
frame::request_own_repaint(&ctx);
|
||||
frame::request_repaint(&ctx);
|
||||
}
|
||||
for chord in claimed_chords(state.claims) {
|
||||
keys::claim(&ctx, pass.id, chord);
|
||||
@@ -721,7 +721,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_own_repaint(ctx);
|
||||
frame::request_repaint(ctx);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ pub fn easing_view(ctx: &Context, canvas: Id) -> Option<CanvasView> {
|
||||
/// 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_own_repaint(ctx);
|
||||
frame::request_repaint(ctx);
|
||||
}
|
||||
|
||||
/// The Zoom tool's press held still: past [`DELAY`](Self::DELAY) it zooms in continuously about the press point (out
|
||||
|
||||
@@ -10,7 +10,7 @@ use craft_ui::canvas::{
|
||||
NavigationOptions, Snap, StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer, ToolRegion,
|
||||
canvas_space, tool_pass,
|
||||
};
|
||||
use craft_ui::contract::{Bind, Lazy, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, MemoProps, MemoView, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::Dialog;
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::primitives::Draw;
|
||||
@@ -21,7 +21,7 @@ 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 craft_ui::testing::{Fixture, MemoRun, ToolFixture, last_frame_memo_runs, pointer, trial};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Color32, Id, Key, Modifiers, Pos2, Rect, Shape, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -906,23 +906,29 @@ impl CanvasTool for Painter {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// A panel beside the canvas, showing its name.
|
||||
#[derive(MemoProps)]
|
||||
struct SidePanel {
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
fn side_panel(props: &mut SidePanel, ui: &mut egui::Ui) {
|
||||
Text::new(props.name).show(ui);
|
||||
}
|
||||
|
||||
/// A stroke on the canvas, whose tool asks for a repaint in every drag, runs neither of the panels beside it (each a
|
||||
/// memoized view), 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<usize>; 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 (shown_painter, shown_canvas) = (Rc::clone(&painter), 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);
|
||||
});
|
||||
for name in ["Layers", "Navigator"] {
|
||||
MemoView::new(name, SidePanel { name }, side_panel).show(ui);
|
||||
}
|
||||
});
|
||||
in_region(ui, document, |ui| {
|
||||
@@ -946,12 +952,12 @@ fn a_stroke_runs_no_settled_panel_beside_the_canvas_and_one_pass_per_move() {
|
||||
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()]));
|
||||
let runs = last_frame_memo_runs(fixture.ctx()).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count();
|
||||
frames.push((fixture.passes(), runs));
|
||||
}
|
||||
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:?}");
|
||||
assert!(frames.iter().all(|(_, runs)| *runs == 0), "no 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:?}");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `Lazy`: a child of a scroll area that runs only while it is in view, and a child that runs only when something it
|
||||
//! shows changed (`runtime::lazy`).
|
||||
//! `Lazy`: a child of a scroll area that runs only while it is in view, and the runner a memoized view shares with it
|
||||
//! (`runtime::lazy`).
|
||||
|
||||
use crate::layout::{flow_region, take_cell, take_in_flow};
|
||||
use crate::runtime::egui::alloc;
|
||||
@@ -30,15 +30,14 @@ use std::hash::Hash;
|
||||
/// `Lazy::new(key, estimate).show(ui, |ui| ..)` around each large child (a card, a section of a panel) in the scroll
|
||||
/// body.
|
||||
///
|
||||
/// A settling child ([`Lazy::settles`]) also keeps what its last run painted and registered, and while it is settled
|
||||
/// it adds that again in place of running, in view or not.
|
||||
/// A memoized view (`MemoView`) is a `Lazy` child keyed by its props: it also keeps what its last run painted and
|
||||
/// registered, and while its key and the framework inputs it read are unchanged it adds that again in place of running,
|
||||
/// in view or not.
|
||||
#[must_use]
|
||||
pub struct Lazy {
|
||||
key: u64,
|
||||
estimate: f32,
|
||||
reveal: bool,
|
||||
pub(super) settles: bool,
|
||||
content: Option<u64>,
|
||||
}
|
||||
|
||||
impl Lazy {
|
||||
@@ -48,7 +47,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, content: None }
|
||||
Lazy { key: hasher.finish(), estimate, reveal: false }
|
||||
}
|
||||
|
||||
/// When `reveal` holds, the scroll area glides until the child starts at the view's start (as far as the
|
||||
@@ -59,57 +58,17 @@ impl Lazy {
|
||||
self
|
||||
}
|
||||
|
||||
/// When `settles` holds, the child runs only when something it shows may have changed, inside a scroll area or
|
||||
/// not. Otherwise it repaints its last run and registers again what that run registered (its stops, hit shapes,
|
||||
/// widgets and accessibility nodes), as if it ran. It runs in a frame where any of these holds:
|
||||
/// - the pointer is over it or was in its last run, a press started on it, or it holds focus or held it;
|
||||
/// - 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, or its environment does: the theme, density, language
|
||||
/// or the window's active state;
|
||||
/// - 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 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<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option<R> {
|
||||
self.run(ui, |ui, _| add(ui))
|
||||
}
|
||||
|
||||
fn run<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Option<R> {
|
||||
let key = match self.content {
|
||||
Some(version) => Key::Version(version),
|
||||
None => Key::None,
|
||||
};
|
||||
match self.run_keyed(ui, "Lazy", key, add) {
|
||||
match self.run_keyed(ui, "Lazy", Key::None, |ui, _| add(ui)) {
|
||||
Shown::Ran(out) => Some(out),
|
||||
Shown::Replayed(..) | Shown::OutOfView => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The one runner of a `Lazy` child and a memoized view (`MemoView`), named `name` in the count trials: runs `add`,
|
||||
/// replays the kept run of a settling child keyed `key`, or takes the extent of a child out of view.
|
||||
/// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view.
|
||||
pub(super) fn run_keyed<R>(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown<R> {
|
||||
let ctx = ui.ctx().clone();
|
||||
let view = Env::of(ui).view().lazy_view();
|
||||
@@ -159,34 +118,28 @@ impl Lazy {
|
||||
if real && memo {
|
||||
crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass");
|
||||
}
|
||||
if self.settles
|
||||
&& let Some((size, ran_at, shift)) = lazy::settled(&ctx, owner, id, sizing.then_some(available), real.then_some(place), view, key)
|
||||
{
|
||||
let took = if memo {
|
||||
// A real replay is where the run's content went, moved with the room.
|
||||
let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) };
|
||||
place_view(ui, rect)
|
||||
} else {
|
||||
take_in_flow(ui, size).0
|
||||
};
|
||||
let mut kept = None;
|
||||
if real {
|
||||
if memo && let Some((size, ran_at, shift)) = lazy::settled(&ctx, owner, id, sizing.then_some(available), real.then_some(place), view, key) {
|
||||
// A real replay is where the run's content went, moved with the room.
|
||||
let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) };
|
||||
let took = place_view(ui, rect);
|
||||
let kept = if real {
|
||||
layout_memory::backstop(&ctx, id, size);
|
||||
kept = lazy::replay_settled(&ctx, id, &shift);
|
||||
let kept = lazy::replay_settled(&ctx, id, &shift);
|
||||
if let Some(view) = view {
|
||||
lazy::place(&ctx, &view, id, took);
|
||||
}
|
||||
} else if memo {
|
||||
kept = lazy::kept_output(&ctx, id);
|
||||
}
|
||||
kept
|
||||
} else {
|
||||
lazy::kept_output(&ctx, id)
|
||||
};
|
||||
#[cfg(feature = "testing")]
|
||||
count_memo_run(&ctx, name, id, MemoRun::Replayed, real);
|
||||
return Shown::Replayed(kept, shift);
|
||||
}
|
||||
let mark = focus::mark(&ctx);
|
||||
let mut run = Run { recording: self.settles && real, output: None };
|
||||
let mut run = Run { recording: memo && real, output: None };
|
||||
let edits = if run.recording { lazy::edits(&ctx) } else { 0 };
|
||||
let seen = if run.recording && matches!(key, Key::Memo(_)) { crate::runtime::inputs::seen(&ctx) } else { Default::default() };
|
||||
let seen = if run.recording { crate::runtime::inputs::seen(&ctx) } else { Default::default() };
|
||||
if run.recording {
|
||||
replay::open(&ctx);
|
||||
}
|
||||
@@ -205,7 +158,7 @@ impl Lazy {
|
||||
} else {
|
||||
alloc::advance_past(ui, rect);
|
||||
}
|
||||
if view.is_some() || self.settles {
|
||||
if view.is_some() || memo {
|
||||
let registered = real.then(|| record.as_ref().map_or_else(|| focus::transcript(&ctx, mark), |record| record.focus.clone()));
|
||||
lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available }, registered);
|
||||
}
|
||||
@@ -220,7 +173,7 @@ impl Lazy {
|
||||
lazy::ran(&ctx, id, record, place, rect, lazy::Ran { key, edits, seen, view, output: run.output.take() });
|
||||
}
|
||||
#[cfg(feature = "testing")]
|
||||
if self.settles {
|
||||
if memo {
|
||||
count_memo_run(&ctx, name, id, MemoRun::Ran, real);
|
||||
}
|
||||
// The name is read by the count trials only.
|
||||
|
||||
@@ -13,10 +13,20 @@ use std::sync::Arc;
|
||||
/// A memoized view: its content is a `fn`, which captures nothing, and its props ([`MemoProps`]) are its only input
|
||||
/// besides the `Ui`, so the framework sees every input it reads. While its props key equals the key of its last run,
|
||||
/// it adds that run again (paint, widgets, accessibility nodes, focus stops and the other per-pass
|
||||
/// registrations) and returns what that run returned. It runs in a pass where its key differs, or where one of the
|
||||
/// settled rules of [`Lazy::settles`] breaks: the pointer over it, focus in it, an intent routed to it, an animation in
|
||||
/// it, an edit of a bound value it read, a move, or a change of its environment. Input elsewhere in the window and
|
||||
/// repaint requests outside it do not run it: what they change in the data it shows reaches it through its props.
|
||||
/// registrations) and returns what that run returned. It runs in a pass where its key differs, or where any of these
|
||||
/// holds:
|
||||
/// - the pointer is over it or was in its last run, a press started on it, or one of its widgets is dragged or holds
|
||||
/// focus, or did;
|
||||
/// - an intent of the pass is routed to a component in it (an AccessKit request on one of its nodes);
|
||||
/// - an animation in it is not at its end, a texture it shows is still loading, something in it asked for a repaint
|
||||
/// (`frame::request_repaint`), or a wake time it asked for came;
|
||||
/// - a bound value, inspection record or command state it read changed;
|
||||
/// - its place differs from its last run (see below), or the shown life of a component it showed ended;
|
||||
/// - its last run asked for a discard pass or did something a replay cannot repeat (an overlay, paint on another
|
||||
/// layer).
|
||||
///
|
||||
/// Input elsewhere in the window and repaint requests outside it do not run it: what they change in the data it shows
|
||||
/// reaches it through its props.
|
||||
///
|
||||
/// A run that ran in an earlier pass of the same frame is replayed too, when nothing it read was edited after it
|
||||
/// started and it asked for no discard pass: a discard pass that another view's new size asked for replays every view
|
||||
@@ -82,9 +92,7 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
|
||||
/// outside every scroll area. A second view with its id in one pass is reported (a debug assertion, as for other
|
||||
/// duplicate ids).
|
||||
pub fn new(id: impl Hash, props: P, show: fn(&mut P, &mut Ui) -> R) -> MemoView<P, R> {
|
||||
let mut lazy = Lazy::new(id, 0.0);
|
||||
lazy.settles = true;
|
||||
MemoView { lazy, props, show }
|
||||
MemoView { lazy: Lazy::new(id, 0.0), props, show }
|
||||
}
|
||||
|
||||
/// Runs the view in a child `Ui` placed in flow in `ui`, or adds its last run again. Returns what the run returned,
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
use crate::layout::flow_region;
|
||||
use crate::runtime::egui::alloc;
|
||||
use crate::runtime::layout_memory;
|
||||
use crate::runtime::lazy::{self, Place};
|
||||
use crate::runtime::lazy;
|
||||
use crate::runtime::memory::sub;
|
||||
use crate::runtime::{measure, reads, replay};
|
||||
use egui::{Pos2, Rect, Ui, UiBuilder, Vec2};
|
||||
use egui::{Rect, Ui, UiBuilder, Vec2};
|
||||
use std::hash::Hash;
|
||||
|
||||
/// Pages that take turns in one place, such as the paint kinds of a paint chip's popover: one shows, and the place
|
||||
@@ -16,10 +16,9 @@ use std::hash::Hash;
|
||||
///
|
||||
/// The pages it does not show are measured only. Each runs in a measuring run (`measure::run`) inside an invisible egui
|
||||
/// sizing child, where every component stops after its measure (steps 1 to 6): it senses nothing and adds no hit
|
||||
/// shape, focus stop, access node, paint or memory write. A hidden page reuses the size its last measuring run found
|
||||
/// while nothing it read has changed, under the settled rules of `Lazy::settles` for content without a content
|
||||
/// version: it is measured again in a frame where a value it read was written, something in it still moves, the app
|
||||
/// asked for a repaint, or the frame or the one before had input other than pointer motion.
|
||||
/// shape, focus stop, access node, paint or memory write. Each hidden page is measured once per pass: the page closure
|
||||
/// reads app data the framework does not track, so a size from an earlier pass could be stale. Later runs in the pass
|
||||
/// (a measuring run of the body around it, then its real run) take that pass's size, so the pass places by one size.
|
||||
///
|
||||
/// The page closure runs for the shown page and for every hidden page it measures, so it builds what it shows from its
|
||||
/// page argument alone and changes nothing outside a component's value (a measuring run applies no edit).
|
||||
@@ -45,15 +44,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
|
||||
let layout = *ui.layout();
|
||||
let hidden = self.pages.iter().filter(|key| *key != self.current).fold(Vec2::ZERO, |largest, key| {
|
||||
let id = sub(base, hash(key));
|
||||
let place = Place {
|
||||
room: Rect::from_min_size(Pos2::ZERO, Vec2::new(region.width(), f32::INFINITY)),
|
||||
clip: Rect::EVERYTHING,
|
||||
layer: ui.layer_id(),
|
||||
layout,
|
||||
pixels_per_point: ctx.pixels_per_point(),
|
||||
env: crate::runtime::env::Env::of(ui).key,
|
||||
};
|
||||
let kept = lazy::measured(&ctx, id, place).map(|(size, reads)| {
|
||||
let kept = lazy::measured(&ctx, id).map(|(size, reads)| {
|
||||
// The page reads them again, as far as an edit later in the pass sees it.
|
||||
for key in reads {
|
||||
reads::note(&ctx, key, id, true, &[]);
|
||||
@@ -73,7 +64,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
|
||||
})
|
||||
});
|
||||
let record = replay::close(&ctx, ui.layer_id());
|
||||
lazy::measured_run(&ctx, id, record.facts, place, size);
|
||||
lazy::measured_run(&ctx, id, record.facts.reads.into_iter().collect(), size);
|
||||
size
|
||||
});
|
||||
largest.max(size)
|
||||
|
||||
@@ -1350,7 +1350,7 @@ pub(crate) fn close_bar_line(ctx: &Context, line: Id) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Empties the shapes of `held` painted this pass. The run record of a settling region is taken when it closes, after
|
||||
/// Empties the shapes of `held` painted this pass. The run record of a memoized view is taken when it closes, after
|
||||
/// this, so a replay repeats the line as it shows.
|
||||
fn take_back(ctx: &Context, held: &[HeldRule]) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
|
||||
@@ -149,7 +149,8 @@ pub(crate) fn apply_values<C: Component>(comp: &mut C, cx: &mut Cx<'_, C>) -> Va
|
||||
/// of this component took from the old value. A leaf measures itself again at each room and proposal it was measured
|
||||
/// at and asks only when a size differs; a body, whose measure runs its content, asks when any measuring run read the
|
||||
/// value. A given value has no read record, so its edit asks for no rerun: the component shows the edit itself, and
|
||||
/// the app's other views of the value show it in the next frame, which the edit requests.
|
||||
/// the app's other views of the value show it in the next frame, which the edit requests: the app writes the edit into
|
||||
/// its model, and the memoized views whose props hold that model run.
|
||||
pub(crate) fn rerun_after_edit(
|
||||
p: &mut dyn ErasedPass<'_>,
|
||||
style: &dyn StyleView,
|
||||
@@ -159,9 +160,7 @@ pub(crate) fn rerun_after_edit(
|
||||
leaf: bool,
|
||||
) {
|
||||
if edit.given {
|
||||
let ctx = &p.core_ref().ctx;
|
||||
crate::runtime::lazy::unsettle(ctx);
|
||||
ctx.request_repaint();
|
||||
p.core_ref().ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
let Some(key) = edit.key.filter(|_| edit.written || edit.shown) else { return };
|
||||
|
||||
@@ -61,7 +61,7 @@ pub(crate) fn fade(ui: &Ui, env: &Env, core: &mut CxCore<'_>) -> Option<Fade> {
|
||||
/// filling the clip the paint step set (the component's rect grown by its paint outset) with its surface's corners.
|
||||
/// Over the ground the component sits on, each colour under it shows mixed toward that ground by the disabled share.
|
||||
/// A range that painted nothing adds no veil; a later range of the same component moves the veil to its own end, so
|
||||
/// one veil covers all the component paints. The veil is a shape of the paint list, so a settled region's record,
|
||||
/// one veil covers all the component paints. The veil is a shape of the paint list, so a settled view's record,
|
||||
/// taken when the region closes, keeps it.
|
||||
pub(crate) fn unfade(ui: &Ui, core: &mut CxCore<'_>, fade: Option<Fade>) {
|
||||
core.fade = None;
|
||||
|
||||
@@ -401,11 +401,11 @@ pub(crate) fn set_layer(ctx: &Context, arena: ArenaId, layer: Layer) {
|
||||
with_arena(ctx, arena, pass_nr, |state| state.layer = Some(layer));
|
||||
}
|
||||
|
||||
// The arena registrations below are hit records like the shape record (`pointer::record_shapes`): a settled region
|
||||
// that replays its last run (`runtime::replay`) makes them again, so the arenas it shows resolve the next pass's
|
||||
// The arena registrations below are hit records like the shape record (`pointer::record_shapes`): a settled memoized
|
||||
// view that replays its last run (`runtime::replay`) makes them again, so the arenas it shows resolve the next pass's
|
||||
// press over the members, parts and roots it shows. Without them a replayed pass leaves its members out of the arena
|
||||
// around it, and an arena inside it is dropped once it has not run for two passes, while the shape record still
|
||||
// names their shapes as the press winner.
|
||||
// around it, and an arena inside it is dropped once it has not run for two passes, while the shape record still names
|
||||
// their shapes as the press winner.
|
||||
|
||||
crate::stays!(ArenaId);
|
||||
|
||||
|
||||
@@ -161,9 +161,9 @@ impl<K> Default for Pools<K> {
|
||||
/// are dropped at the next frame that draws. Asked keys move to the priority they were last asked with.
|
||||
/// - **Failures.** A job returns a `LoadFailure`; the state carries it. A job that panics is stored as
|
||||
/// `LoadFailure::Panicked`.
|
||||
/// - **Waking.** The queue asks for a pass when a job finishes; no timed repaint. A `Loading` answer notes the
|
||||
/// asking code as still moving (`runtime::replay`), so a settled region that shows a stand-in runs in that pass,
|
||||
/// asks again and shows the finished picture, and its asking keeps the job.
|
||||
/// - **Waking.** The queue asks for a pass when a job finishes; no timed repaint. A `Loading` answer notes the asking
|
||||
/// code as still moving (`runtime::replay`), so a settled memoized view that shows a stand-in runs in that pass, asks
|
||||
/// again and shows the finished picture, and its asking keeps the job.
|
||||
/// - **Without lanes** (`lanes == 0`) the first call in a frame runs one job inline.
|
||||
pub struct TextureLoader<K: TextureKey> {
|
||||
store: TextureStore<K>,
|
||||
|
||||
@@ -79,8 +79,6 @@ pub(crate) struct Board {
|
||||
numbers: HashMap<String, u32>,
|
||||
this: HashMap<StateKey, CommandState>,
|
||||
last: HashMap<StateKey, CommandState>,
|
||||
/// What the frame's input changed, under the root frame it arrived for (`set_input`).
|
||||
changed: (u64, InputChanges),
|
||||
/// Scoped commands waiting for their instance.
|
||||
queue: Vec<Fired>,
|
||||
/// App-scope commands for the next `FrameOutput`.
|
||||
@@ -117,14 +115,6 @@ pub(crate) struct Board {
|
||||
parents: HashMap<&'static str, &'static str>,
|
||||
}
|
||||
|
||||
/// What `set_input` changed for the readers of command states, which each pass of the frame notes before any component
|
||||
/// runs (`begin`).
|
||||
#[derive(Clone, Default)]
|
||||
struct InputChanges {
|
||||
/// The keymap was rebuilt: any chord shown may differ.
|
||||
keymap: bool,
|
||||
}
|
||||
|
||||
/// Whether a resolution finds the same state under `a` and `b`: no state is the default one.
|
||||
fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool {
|
||||
a.cloned().unwrap_or_default() == b.cloned().unwrap_or_default()
|
||||
@@ -163,8 +153,8 @@ fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader:
|
||||
}
|
||||
|
||||
/// Notes, in the read record, that the running code showed the state under `key`, and keeps what `reader` was shown: a
|
||||
/// settled region that showed it runs when `begin` resolves the command from the same reader to something else (a
|
||||
/// state, the gate, a modal layer or an instance changed), and a change published after it in the pass runs the pass
|
||||
/// settled memoized view that showed it runs when `begin` resolves the command from the same reader to something else
|
||||
/// (a state, the gate, a modal layer or an instance changed), and a change published after it in the pass runs the pass
|
||||
/// again.
|
||||
fn note_read(ctx: &Context, key: Option<StateKey>, reader: Reader, resolved: &ResolvedCommand) {
|
||||
let Some((number, instance)) = key else { return };
|
||||
@@ -607,7 +597,6 @@ pub(crate) fn platform(ctx: &Context) -> Platform {
|
||||
/// `begin`, which resolves again what each was shown.
|
||||
pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
let platform = platform(ctx);
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let generation = input.catalog.as_ref().map(AppCatalog::generation);
|
||||
let shadowed = with(ctx, |board| {
|
||||
let mut states = HashMap::new();
|
||||
@@ -642,7 +631,6 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) {
|
||||
}
|
||||
}
|
||||
}
|
||||
board.changed = (frame, InputChanges { keymap: stale });
|
||||
shadowed
|
||||
});
|
||||
for id in shadowed {
|
||||
@@ -911,11 +899,11 @@ fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) ->
|
||||
|
||||
/// fx.F23: resolves every command a reader of `viewport` was shown again, from that reader's own vantage under this
|
||||
/// pass's gate, states, modal facts and instances, and notes an edit of the state key of each whose resolution differs
|
||||
/// in any shown part (label, chord, enabled, checked, marked, hint), so a settled region that shows it runs; the entry
|
||||
/// keeps the new resolution. Readers of regions that did not run keep their entries: a settled region is the reader
|
||||
/// this exists for. It reads no input: a second pass of a frame compares against what the first pass's runs were shown
|
||||
/// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal
|
||||
/// layer it opened or closed), once.
|
||||
/// in any shown part (label, chord, enabled, checked, marked, hint), so a settled memoized view that shows it runs; the
|
||||
/// entry keeps the new resolution. Readers of regions that did not run keep their entries: a settled memoized view is
|
||||
/// the reader this exists for. It reads no input: a second pass of a frame compares against what the first pass's runs
|
||||
/// were shown and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed
|
||||
/// (a modal layer it opened or closed), once.
|
||||
fn wake_shown(ctx: &Context, viewport: ViewportId) {
|
||||
let mut shown = with(ctx, |board| std::mem::take(&mut board.shown));
|
||||
let mut changed = Vec::new();
|
||||
@@ -1030,7 +1018,7 @@ fn fire_in(ctx: &Context, command: &CommandRef, source: FireSource, from: Option
|
||||
}
|
||||
|
||||
/// Publishes `state` of `command` for the innermost instance in `chain`. A state other than the one resolved so far in
|
||||
/// the frame is an edit of it: a settled region that read it runs, and so does the pass, when something read it
|
||||
/// the frame is an edit of it: a settled memoized view that read it runs, and so does the pass, when something read it
|
||||
/// earlier in the pass.
|
||||
///
|
||||
/// A publish is a board effect, which a measuring run skips as it skips registration: the real run of the same content
|
||||
@@ -1196,10 +1184,6 @@ impl Returning {
|
||||
/// H7: the key stage's shortcut events, matched against the keymap in the scopes around the focused component,
|
||||
/// through the gate, to their commands.
|
||||
pub(crate) fn begin(ctx: &Context) {
|
||||
let (arrived, changed) = with(ctx, |board| board.changed.clone());
|
||||
if arrived == pass::root_frame_nr(ctx) && changed.keymap {
|
||||
lazy::unsettle(ctx);
|
||||
}
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let focused = focus::record(ctx, viewport).focused;
|
||||
let shortcuts = keys::take_shortcuts(ctx);
|
||||
|
||||
@@ -28,7 +28,7 @@ pub struct FrameInput {
|
||||
pub commands: CommandInput,
|
||||
/// The app's `Host`, read through `EnvView::host`. The app keeps one `Arc<Host>` across frames and installs a
|
||||
/// new one only to switch the language or a service: the scope's words are built again for a new host, and a new
|
||||
/// language runs every settling region again (`Lazy::settles`).
|
||||
/// language runs every memoized view again (the language is part of its place).
|
||||
pub host: Option<Arc<Host>>,
|
||||
/// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input.
|
||||
pub latched: Mods,
|
||||
@@ -402,23 +402,11 @@ pub(crate) fn announce(ctx: &Context, text: String) {
|
||||
pass_state::with::<FrameState, _>(ctx, |state| state.output.announcements.push(text));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Asks for another pass of the viewport the running pass belongs to. Asked in a memoized view's run, that view runs in
|
||||
/// the next pass, and so do the views around it, whose replay would hold its old run. Asked outside every view, every
|
||||
/// view replays: app data a view shows reaches it through its props.
|
||||
#[doc(hidden)]
|
||||
pub fn request_repaint(ctx: &Context) {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -290,8 +290,8 @@ fn write(ctx: &Context, key: Id, edit: impl FnOnce(&mut Kept) -> bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes an edit of the record `read` that `editor` made: a settled region that read it runs, and so does the pass when
|
||||
/// something read it earlier in the pass.
|
||||
/// Notes an edit of the record `read` that `editor` made: a settled memoized view that read it runs, and so does the
|
||||
/// pass when something read it earlier in the pass.
|
||||
fn edited(ctx: &Context, read: BindKey, editor: Id) {
|
||||
crate::runtime::lazy::note_edit(ctx, read);
|
||||
if reads::earlier(ctx, read, editor).other {
|
||||
|
||||
@@ -8,7 +8,7 @@ use egui::{Context, Id};
|
||||
/// Makes `owner` the receiver of the requests that target the node of `node` (registered by `register_node`) and names
|
||||
/// `part` as the target: the row of a collection is a node of the row's component, and the collection acts on it.
|
||||
pub(crate) fn redirect_node(ctx: &Context, node: Id, owner: Id, part: PartRef) {
|
||||
// Journaled after the `register_node` it amends, so a settled region's replay leaves the row's node with the
|
||||
// Journaled after the `register_node` it amends, so a settled view's replay leaves the row's node with the
|
||||
// collection, as a run does.
|
||||
crate::runtime::replay::journal(ctx, || (node, owner, part), |ctx, &(node, owner, part)| redirect_node(ctx, node, owner, part));
|
||||
current(ctx, |stage| {
|
||||
|
||||
@@ -652,7 +652,7 @@ fn route_access(ctx: &Context, request: &Action, nodes: &HashMap<u64, Node>, rou
|
||||
}
|
||||
}
|
||||
|
||||
/// The components the running pass's intents are routed to (keys, AccessKit requests, edits): a settling region that
|
||||
/// The components the running pass's intents are routed to (keys, AccessKit requests, edits): a memoized view that
|
||||
/// holds one runs, so the component takes them.
|
||||
pub(crate) fn routed_to(ctx: &Context) -> Vec<Id> {
|
||||
let (mut routed, menu_keys) = current(ctx, |stage| (stage.routed.keys().flatten().copied().collect::<Vec<_>>(), !stage.menu.is_empty()));
|
||||
|
||||
@@ -9,11 +9,10 @@
|
||||
//! its scroll position names (`Anchor`) and the first child at or after the view's start, so the area keeps the
|
||||
//! content in view in place when extents before it change.
|
||||
//!
|
||||
//! 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, its content version included (`settled`). A
|
||||
//! memoized view (`contract::MemoView`) is a settling child keyed by its props: its key replaces the content version,
|
||||
//! it also replays in a later pass of the frame it ran in, and its entry outlives a few frames of absence.
|
||||
//! A memoized view (`contract::MemoView`) 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, in a later frame
|
||||
//! or a later pass of the frame it ran in. It is settled when its props key is the one of that run and nothing else the
|
||||
//! framework tracks has changed for it since (`settled`). Its entry outlives a few frames of absence.
|
||||
|
||||
use crate::runtime::egui::areas::Layer;
|
||||
use crate::runtime::egui::{focus as focus_state, input as input_state, pass};
|
||||
@@ -32,13 +31,11 @@ use std::sync::Arc;
|
||||
/// What a memoized view's run returned, kept for its replays.
|
||||
pub(crate) type Output = Arc<dyn Any + Send + Sync>;
|
||||
|
||||
/// What a settling child's runs are keyed by.
|
||||
/// What a child's runs are keyed by.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Key {
|
||||
/// Nothing: input other than pointer motion runs it (`Lazy::settles` alone).
|
||||
/// Nothing: a `Lazy` child or a collection row, which runs whenever it is in view.
|
||||
None,
|
||||
/// The version of the app data it shows (`Lazy::content`).
|
||||
Version(u64),
|
||||
/// A memoized view's props key (`contract::MemoView`), taken again after each run.
|
||||
Memo(u128),
|
||||
}
|
||||
@@ -145,11 +142,11 @@ struct Entry {
|
||||
focus: Arc<Transcript>,
|
||||
/// Whether this pass skips the child, under the pass number that decided it.
|
||||
decided: Option<(u64, bool)>,
|
||||
/// The last real run of a settling child.
|
||||
/// The last real run of a memoized view.
|
||||
settled: Option<Arc<Settled>>,
|
||||
/// The last measuring run of a measure-only child (`measured`).
|
||||
measured: Option<MeasuredRun>,
|
||||
/// Whether this pass replays the settling child's last run, under the pass number that decided it.
|
||||
/// Whether this pass replays the memoized view's last run, under the pass number that decided it.
|
||||
replays: Option<(u64, bool)>,
|
||||
/// The last frame that read or wrote the entry.
|
||||
touched: u64,
|
||||
@@ -164,7 +161,7 @@ pub(crate) struct Measured {
|
||||
pub(crate) room: Rect,
|
||||
}
|
||||
|
||||
/// Where a settling child ran: it replays only at a place of the same size, layer, layout and environment, and its
|
||||
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout and environment, and its
|
||||
/// record moves with the room's position (`Place::shift_to`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Place {
|
||||
@@ -220,15 +217,14 @@ impl Place {
|
||||
/// out of view.
|
||||
#[derive(Clone)]
|
||||
struct MeasuredRun {
|
||||
facts: replay::Facts,
|
||||
/// The pass and the frame it ran in.
|
||||
/// The values it read.
|
||||
reads: Vec<BindKey>,
|
||||
/// The pass it ran in.
|
||||
pass: u64,
|
||||
frame: u64,
|
||||
place: Place,
|
||||
size: Vec2,
|
||||
}
|
||||
|
||||
/// The last real run of a settling child.
|
||||
/// The last real run of a memoized view.
|
||||
struct Settled {
|
||||
record: Record,
|
||||
/// The frame it ran in.
|
||||
@@ -238,7 +234,7 @@ 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,
|
||||
/// What it ran for: its content version or its memoized view's props key after the run.
|
||||
/// What it ran for: its props key after the run.
|
||||
key: Key,
|
||||
/// The pass it ran in.
|
||||
pass: u64,
|
||||
@@ -257,17 +253,9 @@ struct Settled {
|
||||
view: Option<View>,
|
||||
}
|
||||
|
||||
/// What changed in the frame for every settling child.
|
||||
/// The bound values edited in the frame, which the memoized views that read them follow.
|
||||
#[derive(Default)]
|
||||
struct Changes {
|
||||
/// 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, each with the serial of its last edit, and the frame.
|
||||
edited: (u64, HashMap<BindKey, u64>),
|
||||
/// The serial of the last edit (`note_edit`).
|
||||
@@ -286,19 +274,6 @@ fn edited_since(edited: Option<&HashMap<BindKey, u64>>, since: u64) -> Option<Ha
|
||||
edited.map(|edited| edited.iter().filter(|(_, serial)| **serial > since).map(|(key, _)| *key).collect())
|
||||
}
|
||||
|
||||
impl Changes {
|
||||
/// Looks at the input of the pass `pass_nr` of `frame` once: input other than pointer motion unsettles the children
|
||||
/// with no content version for this frame and the next.
|
||||
fn scan(&mut self, pass_nr: u64, frame: u64, input: bool) {
|
||||
if self.scanned != pass_nr {
|
||||
self.scanned = pass_nr;
|
||||
if input {
|
||||
self.input_through = self.input_through.max(frame + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Store {
|
||||
entries: IdMap<Entry>,
|
||||
@@ -410,17 +385,16 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the settling child `id` adds its last real run to this pass in place of running, the extent that run
|
||||
/// took in a run of this kind (`sizing`: the room a sizing run offers it, `None` outside a sizing pass), the rect the
|
||||
/// kept real run takes now and the shift its record moves by. The first run of a pass decides from what changed since
|
||||
/// that run; a real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot
|
||||
/// tell. A sizing run of a pass that replays takes the extent the last sizing run measured of
|
||||
/// the content the kept run showed (its key) in the room it offers now; when that sizing run showed other content or
|
||||
/// had another room, or there was none, it runs once as a measuring run, which keeps no record and leaves the decision
|
||||
/// of the pass alone, so the real run still replays.
|
||||
/// Whether the memoized view `id` adds its last real run to this pass in place of running, the extent that run took in
|
||||
/// a run of this kind (`sizing`: the room a sizing run offers it, `None` outside a sizing pass), the rect the kept real
|
||||
/// run takes now and the shift its record moves by. The first run of a pass decides from what changed since that run; a
|
||||
/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. A sizing
|
||||
/// run of a pass that replays takes the extent the last sizing run measured of the content the kept run showed (its
|
||||
/// key) in the room it offers now; when that sizing run showed other content or had another room, or there was none, it
|
||||
/// runs once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still
|
||||
/// replays.
|
||||
///
|
||||
/// It replays when its last run was in an earlier frame, or, for a memoized view, in an earlier pass of this frame, and
|
||||
/// since then:
|
||||
/// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then:
|
||||
/// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still
|
||||
/// loading, no wake time reached;
|
||||
/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and
|
||||
@@ -429,22 +403,15 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
|
||||
/// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes);
|
||||
/// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or,
|
||||
/// replaying a run of this frame, after that run started;
|
||||
/// - its key is the one of its last run (its content version, or its memoized view's props key after that run), and
|
||||
/// its environment (theme, density, scale, language, window active) the one it ran in;
|
||||
/// - for a child that is not a memoized view, 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 key: no input other than pointer motion this frame or the one before;
|
||||
/// - its key is the one of its last run (its props key after that run), and its environment (theme, density, scale,
|
||||
/// language, window active) the one it ran in;
|
||||
/// - the run did nothing a replay cannot repeat (`runtime::replay`) and asked for no discard pass: what it added is
|
||||
/// what the pass was thrown away for;
|
||||
/// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is
|
||||
/// gone.
|
||||
///
|
||||
/// - for a memoized view: no framework input its run read outside its props has moved (`runtime::inputs`), the
|
||||
/// scroll view a nested `Lazy` child of it decided by is the same (moved with it, `moved`), and no command waits for a command scope instance
|
||||
/// of it.
|
||||
///
|
||||
/// A memoized view's props hold every input it reads, so the two rules that infer a change of app data (input
|
||||
/// arrived, a repaint was asked) do not apply to it.
|
||||
/// gone;
|
||||
/// - no framework input its run read outside its props has moved (`runtime::inputs`), the scroll view a nested `Lazy`
|
||||
/// child of it decided by is the same (moved with it, `moved`), and no command waits for a command scope instance of
|
||||
/// it.
|
||||
pub(crate) fn settled(
|
||||
ctx: &Context,
|
||||
owner: Option<Id>,
|
||||
@@ -454,40 +421,33 @@ pub(crate) fn settled(
|
||||
view: Option<View>,
|
||||
key: Key,
|
||||
) -> Option<(Vec2, Rect, RecordShift)> {
|
||||
let input = ctx.input(|input| {
|
||||
input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone))
|
||||
});
|
||||
let targets = focus::targets(ctx);
|
||||
let routed = crate::runtime::keys::routed_to(ctx);
|
||||
let now = frame::clock(ctx);
|
||||
let held = (input_state::dragged(ctx), focus_state::focused(ctx));
|
||||
let memo = matches!(key, Key::Memo(_));
|
||||
let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some());
|
||||
let settled = with(ctx, |store, pass_nr, frame| {
|
||||
store.changes.scan(pass_nr, frame, input);
|
||||
let changes = &store.changes;
|
||||
// Usually `None`: only the values written this frame.
|
||||
let edited = changes.edited_in(frame);
|
||||
let unsettled = !memo && (changes.unsettled_through >= frame || (key == Key::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,
|
||||
_ => {
|
||||
let replays = !unsettled
|
||||
&& entry.settled.as_ref().is_some_and(|settled| {
|
||||
let facts = &settled.record.facts;
|
||||
// A run of this frame read the values edited before it started.
|
||||
let edited = edited_since(edited.as_ref(), if settled.frame < frame { 0 } else { settled.edits });
|
||||
(settled.frame < frame || (memo && settled.pass < pass_nr))
|
||||
&& settled.key == key
|
||||
&& !settled.engaged
|
||||
&& !facts.blocked
|
||||
&& !facts.discards
|
||||
&& facts.quiet(now, edited.as_ref())
|
||||
&& !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)) || routed.contains(&stop))
|
||||
&& !routed.iter().any(|id| settled.record.widgets.contains(id))
|
||||
&& ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget))
|
||||
});
|
||||
let replays = entry.settled.as_ref().is_some_and(|settled| {
|
||||
let facts = &settled.record.facts;
|
||||
// A run of this frame read the values edited before it started.
|
||||
let edited = edited_since(edited.as_ref(), if settled.frame < frame { 0 } else { settled.edits });
|
||||
(settled.frame < frame || settled.pass < pass_nr)
|
||||
&& settled.key == key
|
||||
&& !settled.engaged
|
||||
&& !facts.blocked
|
||||
&& !facts.discards
|
||||
&& facts.quiet(now, edited.as_ref())
|
||||
&& !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)) || routed.contains(&stop))
|
||||
&& !routed.iter().any(|id| settled.record.widgets.contains(id))
|
||||
&& ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget))
|
||||
});
|
||||
entry.replays = Some((pass_nr, replays));
|
||||
replays
|
||||
}
|
||||
@@ -519,7 +479,7 @@ pub(crate) fn settled(
|
||||
let view = place.and_then(|_| with_clip.then(|| (settled.view.map(|ran| ran.moved(shift.offset)), view)));
|
||||
if engaged(ctx, settled.place.layer, rect.intersect(shift.clip))
|
||||
|| crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives)
|
||||
|| (memo && moved(ctx, &settled, view))
|
||||
|| moved(ctx, &settled, view)
|
||||
{
|
||||
with(ctx, |store, pass_nr, _| {
|
||||
if let Some(entry) = store.entries.get_mut(&id) {
|
||||
@@ -548,8 +508,8 @@ fn engaged(ctx: &Context, layer: Layer, rect: Rect) -> bool {
|
||||
ctx.rect_contains_pointer(layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin))
|
||||
}
|
||||
|
||||
/// Adds the last real run of the settling child `id` to the running pass, in place of running it, at the place `shift`
|
||||
/// names (`settled`), and returns what a memoized view's run returned, as the run left it: the caller moves it.
|
||||
/// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift`
|
||||
/// names (`settled`), and returns what its run returned, as the run left it: the caller moves it.
|
||||
pub(crate) fn replay_settled(ctx: &Context, id: Id, shift: &RecordShift) -> Option<Output> {
|
||||
let settled = with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.clone()))?;
|
||||
replay::replay(ctx, &settled.record, shift);
|
||||
@@ -573,8 +533,8 @@ pub(crate) fn keep(ctx: &Context, owner: Option<Id>, id: Id) {
|
||||
});
|
||||
}
|
||||
|
||||
/// What a settling child's real run found besides its record: what it ran for, the edit serial and the framework
|
||||
/// inputs' generations when it started (`edits`, `inputs::seen`), the scroll view around it and what a memoized view's
|
||||
/// What a memoized view's real run found besides its record: what it ran for, the edit serial and the framework
|
||||
/// inputs' generations when it started (`edits`, `inputs::seen`), the scroll view around it and what its
|
||||
/// run returned.
|
||||
pub(crate) struct Ran {
|
||||
pub(crate) key: Key,
|
||||
@@ -584,7 +544,7 @@ pub(crate) struct Ran {
|
||||
pub(crate) output: Option<Output>,
|
||||
}
|
||||
|
||||
/// Keeps the real run `record` of the settling child `id`, which ran at `place` and took `rect`.
|
||||
/// Keeps the real run `record` of the memoized view `id`, which ran at `place` and took `rect`.
|
||||
pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, Ran { key, edits, seen, view, output }: Ran) {
|
||||
let targets = focus::targets(ctx);
|
||||
let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)));
|
||||
@@ -600,41 +560,25 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the measure-only child `id` takes the size its last measuring run at `place` found, in place of measuring
|
||||
/// again, and that size. It does when that run was in this pass, or in an earlier frame and since then none of the
|
||||
/// settled rules a measure reads has broken (`settled`): nothing in it moves or asked to be shown again, no value it
|
||||
/// read changed, no frame unsettled every child, and the frame and the one before had no input other than pointer
|
||||
/// motion. A measure-only child has no place on screen, no stops and no widgets, so the pointer, the focus and what a
|
||||
/// replay repeats do not count. Returns the values that run read with the size: the caller notes them as read again,
|
||||
/// so an edit of one later in the pass reruns it.
|
||||
pub(crate) fn measured(ctx: &Context, id: Id, place: Place) -> Option<(Vec2, Vec<BindKey>)> {
|
||||
let input = ctx.input(|input| {
|
||||
input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone))
|
||||
});
|
||||
let now = frame::clock(ctx);
|
||||
/// The size this pass's measuring run of the measure-only child `id` found, and the values it read: a later run in the
|
||||
/// pass takes that size, whatever room it has, so the pass places by one size. The caller notes the values as read
|
||||
/// again, so an edit of one later in the pass reruns it. A run of an earlier pass is not reused: the content's inputs
|
||||
/// are not tracked, so it is measured again in each pass.
|
||||
pub(crate) fn measured(ctx: &Context, id: Id) -> Option<(Vec2, Vec<BindKey>)> {
|
||||
with(ctx, |store, pass_nr, frame| {
|
||||
store.changes.scan(pass_nr, frame, input);
|
||||
let changes = &store.changes;
|
||||
let edited = edited_since(changes.edited_in(frame).as_ref(), 0);
|
||||
let unsettled = changes.unsettled_through >= frame || changes.input_through >= frame;
|
||||
let run = store.touch(None, id, frame).measured.as_ref()?;
|
||||
let same_pass = run.pass == pass_nr;
|
||||
let quiet = !unsettled && run.frame < frame && run.facts.quiet(now, edited.as_ref());
|
||||
// This pass's measuring run found the size the pass places by: a later run in the pass takes it, whatever room it
|
||||
// has.
|
||||
(same_pass || (run.place == place && quiet)).then(|| (run.size, run.facts.reads.iter().copied().collect()))
|
||||
(run.pass == pass_nr).then(|| (run.size, run.reads.clone()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps the measuring run of the measure-only child `id` at `place`: what its record found (`replay::close`) and the
|
||||
/// size it took.
|
||||
pub(crate) fn measured_run(ctx: &Context, id: Id, facts: replay::Facts, place: Place, size: Vec2) {
|
||||
/// Keeps the measuring run of the measure-only child `id` in this pass: the values it read and the size it took.
|
||||
pub(crate) fn measured_run(ctx: &Context, id: Id, reads: Vec<BindKey>, size: Vec2) {
|
||||
with(ctx, |store, pass_nr, frame| {
|
||||
store.touch(None, id, frame).measured = Some(MeasuredRun { facts, pass: pass_nr, frame, place, size });
|
||||
store.touch(None, id, frame).measured = Some(MeasuredRun { reads, pass: pass_nr, size });
|
||||
});
|
||||
}
|
||||
|
||||
/// Notes that the value `key` changed in this frame: a settling child that read it runs.
|
||||
/// Notes that the value `key` changed in this frame: a memoized view that read it runs.
|
||||
pub(crate) fn note_edit(ctx: &Context, key: BindKey) {
|
||||
with(ctx, |store, _, frame| {
|
||||
let changes = &mut store.changes;
|
||||
@@ -646,12 +590,6 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) {
|
||||
});
|
||||
}
|
||||
|
||||
/// 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));
|
||||
}
|
||||
|
||||
/// Records the extent of a row of the collection `owner` that was built this pass. The collection places the rows it
|
||||
/// does not build by it (its item layout answers for rows it never built).
|
||||
pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) {
|
||||
|
||||
@@ -306,7 +306,7 @@ pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> {
|
||||
store::with::<LeastRuns, _>(ctx, |log| log.runs.clone())
|
||||
}
|
||||
|
||||
/// How a memoized view, or a settling or scrolled `Lazy` child, took part in a pass.
|
||||
/// How a memoized view, or a scrolled `Lazy` child, took part in a pass.
|
||||
#[cfg(feature = "testing")]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! Run records: what a real run of a settling region (`Lazy::settles`) added to its pass, so a later pass adds it again
|
||||
//! in place of running the region. A measuring run of a measure-only child (a page `Pages` holds out of view) opens a
|
||||
//! record too; only its facts are kept, so a later pass takes its size in place of measuring it again. A record holds the region's paint, egui widget rects and AccessKit nodes (egui's
|
||||
//! pass records), what it registered with the focus service (`focus::Transcript`), and a journal of every other
|
||||
//! registration the services below take per pass: each service that keeps one notes it here while a record is open,
|
||||
//! as the call that makes it again. Records nest: a region's record holds the records its settled regions replayed.
|
||||
//! Run records: what a real run of a memoized view (`contract::MemoView`) added to its pass, so a later pass adds it
|
||||
//! again in place of running the view. A measuring run of a measure-only child (a page `Pages` holds out of view) opens
|
||||
//! a record too; only the values it read are kept, so a later run in the pass takes its size and notes them. A record
|
||||
//! holds the view's paint, egui widget rects and AccessKit nodes (egui's pass records), what it registered with the
|
||||
//! focus service (`focus::Transcript`), and a journal of every other registration the services below take per pass:
|
||||
//! each service that keeps one notes it here while a record is open, as the call that makes it again. Records nest: a
|
||||
//! view's record holds the records of the views inside it that replayed.
|
||||
//!
|
||||
//! The record also holds the facts the settled test reads (`runtime::lazy`): the values the run read, whether
|
||||
//! something in it still moves (an animation that is not at its end, a repaint request) and the earliest time it asked
|
||||
//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another
|
||||
//! layer, a label scope open around it). Such a record is never replayed: the region runs.
|
||||
//! layer, a label scope open around it). Such a record is never replayed: the view runs.
|
||||
|
||||
use crate::runtime::egui::areas::Layer;
|
||||
use crate::runtime::focus::{self, Transcript};
|
||||
@@ -252,8 +253,8 @@ fn with_open(ctx: &Context, f: impl FnOnce(&mut Facts)) {
|
||||
/// registers it again. `args` builds the arguments only while a record is open. `again` captures nothing (a function
|
||||
/// or a closure without captures; a capture does not compile), so everything the registration depends on is in the
|
||||
/// arguments, and two notes of the same `again` with equal arguments are the same registration. A replay at another
|
||||
/// place calls `again` with the arguments moved there (`Shift`). A service outside
|
||||
/// this crate that keeps registrations per pass (a dock's drop spots) notes each one here, so a settled region's replay
|
||||
/// place calls `again` with the arguments moved there (`Shift`). A service outside this crate that keeps registrations
|
||||
/// per pass (a dock's drop spots) notes each one here, so a settled view's replay
|
||||
/// makes it again.
|
||||
pub fn journal<A, F>(ctx: &Context, args: impl FnOnce() -> A, again: F)
|
||||
where
|
||||
|
||||
@@ -309,8 +309,8 @@ pub(super) fn with_exclusive<R>(ctx: &Context, viewport: ViewportId, f: impl FnO
|
||||
)
|
||||
}
|
||||
|
||||
/// Records that `part` of the component `owner` is, over `rect`, what `hit` says for the running viewport's window.
|
||||
/// A part declared again in the same pass replaces its entry. A settled region that replays its last run declares
|
||||
/// Records that `part` of the component `owner` is, over `rect`, what `hit` says for the running viewport's window. A
|
||||
/// part declared again in the same pass replaces its entry. A settled memoized view that replays its last run declares
|
||||
/// its parts again, so a settled title bar keeps its caption regions.
|
||||
pub(crate) fn note_exclusive(ctx: &Context, owner: Id, part: PartRef, hit: WindowHit, rect: Rect) {
|
||||
crate::runtime::replay::journal(ctx, || (owner, part, hit, rect), |ctx, &(owner, part, hit, rect)| note_exclusive(ctx, owner, part, hit, rect));
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! The frame loop: installed options, the one-press rule, the per-frame output, and the command states a settled
|
||||
//! region shows.
|
||||
//! memoized view shows.
|
||||
|
||||
use craft_ui::contract::{
|
||||
CommandSet, Common, Component, Container, ContainerProps, Cx, Lazy, Mount, Overlay, Props as _, Role, Show as _, ShowContainer as _,
|
||||
CommandSet, Common, Component, Container, ContainerProps, Cx, MemoProps, MemoView, Mount, Overlay, Props as _, Role, Show as _,
|
||||
ShowContainer as _,
|
||||
};
|
||||
use craft_ui::runtime::commands::{CommandGate, CommandInput, CommandRef};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, trial};
|
||||
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
|
||||
use egui::{Event, Id, Modifiers, PointerButton, Pos2, Rect, Response, Ui, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -85,7 +86,7 @@ fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() {
|
||||
assert_eq!(ten, forty, "context-data lookups grow with the runs: {ten} for ten leaves, {forty} for forty");
|
||||
}
|
||||
|
||||
/// The app command the settled region's probe is bound to; its modal rule is the default one, `Blocked`.
|
||||
/// The app command the settled view's probe is bound to; its modal rule is the default one, `Blocked`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "frameTrial")]
|
||||
#[non_exhaustive]
|
||||
@@ -125,26 +126,40 @@ impl Component for Modal {
|
||||
|
||||
impl Container for Modal {}
|
||||
|
||||
/// A settling region of room `room` holding a probe bound to `Shown::Apply`, and a modal layer beside it while `open`
|
||||
/// holds.
|
||||
thread_local! {
|
||||
/// What the probe in the command view recorded when it last ran.
|
||||
static COMMAND_SEEN: RefCell<Seen> = RefCell::new(Seen::default());
|
||||
/// What the probe in the routed view recorded when it last ran.
|
||||
static INSIDE_SEEN: RefCell<Seen> = RefCell::new(Seen::default());
|
||||
}
|
||||
|
||||
/// The calls of every pass of the last frame in which a memoized view ran, measuring runs included.
|
||||
fn view_runs(frames: &Frames) -> usize {
|
||||
last_frame_memo_runs(&frames.ctx).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count()
|
||||
}
|
||||
|
||||
/// The command view: a probe bound to `Shown::Apply`.
|
||||
#[derive(MemoProps)]
|
||||
struct CommandView {}
|
||||
|
||||
fn command_view(_: &mut CommandView, ui: &mut Ui) {
|
||||
COMMAND_SEEN.with(|seen| Probe::new(seen).command(Shown::Apply).show(ui));
|
||||
}
|
||||
|
||||
/// The command view in a region of room `room`, and a modal layer beside it while `open` holds.
|
||||
struct CommandScene {
|
||||
runs: Cell<usize>,
|
||||
open: Cell<bool>,
|
||||
room: Cell<Vec2>,
|
||||
seen: RefCell<Seen>,
|
||||
}
|
||||
|
||||
impl CommandScene {
|
||||
fn new() -> CommandScene {
|
||||
CommandScene { runs: Cell::new(0), open: Cell::new(false), room: Cell::new(Vec2::new(200.0, 80.0)), seen: RefCell::new(Seen::default()) }
|
||||
CommandScene { open: Cell::new(false), room: Cell::new(Vec2::new(200.0, 80.0)) }
|
||||
}
|
||||
|
||||
fn show(&self, ui: &mut Ui) {
|
||||
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), self.room.get()), |ui| {
|
||||
Lazy::new("commands", 0.0).settles(true).show(ui, |ui| {
|
||||
self.runs.set(self.runs.get() + 1);
|
||||
Probe::new(&self.seen).command(Shown::Apply).show(ui);
|
||||
});
|
||||
MemoView::new("commands", CommandView {}, command_view).show(ui);
|
||||
});
|
||||
if self.open.get() {
|
||||
let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal()));
|
||||
@@ -152,11 +167,10 @@ impl CommandScene {
|
||||
}
|
||||
}
|
||||
|
||||
/// The region's runs in one frame with no input.
|
||||
/// The view's runs in one frame with no input.
|
||||
fn frame(&self, frames: &mut Frames) -> usize {
|
||||
self.runs.set(0);
|
||||
frames.frame(vec![], |ui| self.show(ui));
|
||||
self.runs.get()
|
||||
view_runs(frames)
|
||||
}
|
||||
|
||||
fn settle(&self, frames: &mut Frames) {
|
||||
@@ -165,14 +179,14 @@ impl CommandScene {
|
||||
|
||||
/// Whether the probe's node is disabled in the last frame's tree.
|
||||
fn disabled(&self, frames: &mut Frames) -> bool {
|
||||
let id: Id = self.seen.borrow().id.expect("the probe ran");
|
||||
let id: Id = COMMAND_SEEN.with(|seen| seen.borrow().id.expect("the probe ran"));
|
||||
frames.tree().is_disabled(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// fx.F23: a settled region shows a command's new enabled state after a frame whose only change is the app's gate, and
|
||||
/// fx.F23: a settled view shows a command's new enabled state after a frame whose only change is the app's gate, and
|
||||
/// after a modal layer beside it closes with no input. Each pass resolves again, before any component runs, what every
|
||||
/// reader was shown, and the settled region whose resolution changed runs. The access tree hides what sits behind an
|
||||
/// reader was shown, and the settled view whose resolution changed runs. The access tree hides what sits behind an
|
||||
/// open modal layer, so the region's run under the modal (its room changed) is read only through what it shows once
|
||||
/// the layer closed.
|
||||
#[trial]
|
||||
@@ -184,7 +198,7 @@ fn a_command_state_change_with_no_input_repaints_the_settled_region() {
|
||||
assert!(!scene.disabled(&mut frames), "Apply starts enabled");
|
||||
|
||||
frames.commands(gate(true));
|
||||
assert!(scene.frame(&mut frames) > 0, "the gate refusing Apply runs the settled region");
|
||||
assert!(scene.frame(&mut frames) > 0, "the gate refusing Apply runs the settled view");
|
||||
assert!(scene.disabled(&mut frames), "the region shows Apply disabled in the frame the gate refuses it");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames), 0, "it settles again");
|
||||
@@ -209,7 +223,7 @@ fn a_command_state_change_with_no_input_repaints_the_settled_region() {
|
||||
}
|
||||
|
||||
/// fx.F23's count relation: a frame given a new gate closure that answers as the last one did resolves every reader to
|
||||
/// what it was shown, so no settled region runs, in a frame's first pass or in a discard pass the frame reruns. A gate
|
||||
/// what it was shown, so no settled view runs, in a frame's first pass or in a discard pass the frame reruns. A gate
|
||||
/// that answers otherwise runs the region.
|
||||
#[trial]
|
||||
fn an_unchanged_gate_reruns_no_settled_region() {
|
||||
@@ -219,10 +233,9 @@ fn an_unchanged_gate_reruns_no_settled_region() {
|
||||
scene.settle(&mut frames);
|
||||
for frame in 0..4 {
|
||||
frames.commands(gate(false));
|
||||
assert_eq!(scene.frame(&mut frames), 0, "frame {frame} with a fresh, equal gate ran the settled region");
|
||||
assert_eq!(scene.frame(&mut frames), 0, "frame {frame} with a fresh, equal gate ran the settled view");
|
||||
}
|
||||
frames.commands(gate(false));
|
||||
scene.runs.set(0);
|
||||
let mut first = true;
|
||||
let passes = frames.frame(vec![], |ui| {
|
||||
scene.show(ui);
|
||||
@@ -231,7 +244,7 @@ fn an_unchanged_gate_reruns_no_settled_region() {
|
||||
}
|
||||
});
|
||||
assert_eq!(passes, 2, "the frame reruns its pass");
|
||||
assert_eq!(scene.runs.get(), 0, "neither pass of the frame ran the settled region");
|
||||
assert_eq!(view_runs(&frames), 0, "neither pass of the frame ran the settled view");
|
||||
frames.commands(gate(true));
|
||||
assert!(scene.frame(&mut frames) > 0, "a gate that refuses the region's command runs it");
|
||||
}
|
||||
@@ -255,36 +268,39 @@ fn frames_over_a_given_context_run_on_it() {
|
||||
assert!(second, "a second driver over the installed context runs on it");
|
||||
}
|
||||
|
||||
/// An AccessKit request routed to a component inside a settled region reaches it: the region runs once in the pass
|
||||
/// that routes a Focus to its probe's node, though it has a content version (so input alone does not run it), and not
|
||||
/// at all in the same frame whose Focus goes to a probe outside it. The probes take no focus, so no focus request
|
||||
/// runs the region in their place.
|
||||
/// The routed view: a probe labelled Inside that senses clicks.
|
||||
#[derive(MemoProps)]
|
||||
struct Routed {}
|
||||
|
||||
fn routed(_: &mut Routed, ui: &mut Ui) {
|
||||
INSIDE_SEEN.with(|seen| Probe::new(seen).label("Inside").sense(craft_behavior::Sense::CLICK).show(ui));
|
||||
}
|
||||
|
||||
/// An AccessKit request routed to a component inside a settled memoized view reaches it: the view runs once in the
|
||||
/// pass that routes a Focus to its probe's node, and not at all in the same frame whose Focus goes to a probe outside
|
||||
/// it. The probes take no focus, so no focus request runs the view in their place.
|
||||
#[trial]
|
||||
fn a_routed_access_request_runs_its_settled_region_once() {
|
||||
fn a_routed_access_request_runs_its_settled_view_once() {
|
||||
use craft_ui::testing::focus::{AccessActionKind, access_request};
|
||||
let runs = Cell::new(0usize);
|
||||
let (inside, outside) = (RefCell::new(Seen::default()), RefCell::new(Seen::default()));
|
||||
let outside = RefCell::new(Seen::default());
|
||||
let show = |ui: &mut Ui| {
|
||||
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(200.0, 80.0)), |ui| {
|
||||
Lazy::new("routed", 0.0).settles(true).content(1).show(ui, |ui| {
|
||||
runs.set(runs.get() + 1);
|
||||
Probe::new(&inside).label("Inside").sense(craft_behavior::Sense::CLICK).show(ui);
|
||||
});
|
||||
MemoView::new("routed", Routed {}, routed).show(ui);
|
||||
Probe::new(&outside).label("Outside").sense(craft_behavior::Sense::CLICK).show(ui);
|
||||
});
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(30, show);
|
||||
let (inside_id, outside_id) = (inside.borrow().id.expect("the inside probe ran"), outside.borrow().id.expect("the outside probe ran"));
|
||||
let inside_id = INSIDE_SEEN.with(|seen| seen.borrow().id.expect("the inside probe ran"));
|
||||
let outside_id = outside.borrow().id.expect("the outside probe ran");
|
||||
assert_ne!(inside_id, outside_id, "two probes");
|
||||
let count = |frames: &mut Frames, target: Id| {
|
||||
runs.set(0);
|
||||
let passes = frames.frame(vec![access_request(AccessActionKind::Focus, target)], show);
|
||||
(runs.get(), passes)
|
||||
(view_runs(frames), passes)
|
||||
};
|
||||
let (elsewhere, _) = count(&mut frames, outside_id);
|
||||
assert_eq!(elsewhere, 0, "a Focus routed outside the settled region runs it in no pass");
|
||||
assert_eq!(elsewhere, 0, "a Focus routed outside the settled view runs it in no pass");
|
||||
frames.idle(30, show);
|
||||
let (routed, passes) = count(&mut frames, inside_id);
|
||||
assert_eq!(routed, 1, "a Focus routed into the settled region runs it once ({passes} passes in the frame)");
|
||||
assert_eq!(routed, 1, "a Focus routed into the settled view runs it once ({passes} passes in the frame)");
|
||||
}
|
||||
|
||||
@@ -461,8 +461,8 @@ impl<P: Clone + Send + 'static> DockTargets<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registrations of a pass. A settled region's run record keeps each one to make it again and compares it with a
|
||||
/// real run's, so the panel type is `Sync`, `PartialEq` and `Debug`.
|
||||
/// The registrations of a pass. A settled memoized view's run record keeps each one to make it again and compares it
|
||||
/// with a real run's, so the panel type is `Sync`, `PartialEq` and `Debug`.
|
||||
impl<P: Clone + PartialEq + Debug + Send + Sync + 'static> DockTargets<P> {
|
||||
/// Registers `spot` over `rect` for the dock `dock` in the running pass of this viewport. Group and column
|
||||
/// rendering call it; it does nothing outside a pass. A floating window registers on its own egui layer, and
|
||||
@@ -516,7 +516,7 @@ impl<P: Clone + PartialEq + Debug + Send + Sync + 'static> DockTargets<P> {
|
||||
Self::with_dock(ctx, dock, |targets| targets.room = Some(room));
|
||||
}
|
||||
|
||||
/// Notes a registration in the records of the settling regions around the running code, so a region that settles
|
||||
/// Notes a registration in the records of the memoized views around the running code, so a region that settles
|
||||
/// registers its drop spots again when it replays its last run.
|
||||
fn journal<A, F>(ctx: &Context, args: impl FnOnce() -> A, again: F)
|
||||
where
|
||||
|
||||
@@ -8,14 +8,14 @@ use craft_i18n::Direction;
|
||||
use craft_ui::bars::{Bar, BarItem, BarItems, BarKind, ConstraintFields, ItemDisplay};
|
||||
use craft_ui::buttons::{Button, IconButton};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Entry, Lazy, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::contract::{Bind, Entry, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::{Divider, Elide, Text};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::primitives::TextRun;
|
||||
use craft_ui::runtime::commands::EditCommands;
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::{Fixture, Frames, trial};
|
||||
use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, trial};
|
||||
use craft_ui::value_drag::Slider;
|
||||
use egui::{Pos2, Rect, Shape, Ui, Vec2};
|
||||
use std::cell::Cell;
|
||||
@@ -196,27 +196,32 @@ fn a_rule_before_a_member_the_bar_hides_is_not_drawn() {
|
||||
assert!(!draws_rule(&cut, rects), "the rule before the hidden button is drawn");
|
||||
}
|
||||
|
||||
/// A settled region holding a bar whose rule was taken back replays the bar without the rule.
|
||||
/// A view holding the rule bar `width` wide.
|
||||
#[derive(MemoProps)]
|
||||
struct RuleBar {
|
||||
width: f32,
|
||||
}
|
||||
|
||||
fn rule_bar_view(props: &mut RuleBar, ui: &mut Ui) {
|
||||
rule_bar(ui, props.width, &Cell::new((Rect::NOTHING, Rect::NOTHING)));
|
||||
}
|
||||
|
||||
/// A settled memoized view holding a bar whose rule was taken back replays the bar without the rule.
|
||||
#[trial]
|
||||
fn a_settled_bar_replays_the_rule_it_took_back() {
|
||||
let (_, wide) = rule_bar_shapes(900.0);
|
||||
let width = cutting_width(wide);
|
||||
let runs = std::cell::Cell::new(0);
|
||||
let rects = std::cell::Cell::new((Rect::NOTHING, Rect::NOTHING));
|
||||
let scene = |ui: &mut Ui| {
|
||||
Lazy::new("bar", 0.0).settles(true).show(ui, |ui| {
|
||||
runs.set(runs.get() + 1);
|
||||
rule_bar(ui, width, &rects);
|
||||
});
|
||||
MemoView::new("bar", RuleBar { width }, rule_bar_view).show(ui);
|
||||
};
|
||||
let runs = |frames: &Frames| last_frame_memo_runs(&frames.ctx).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count();
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(vec![], scene);
|
||||
assert!(runs.get() > 0, "the first frame runs the region");
|
||||
assert!(runs(&frames) > 0, "the first frame runs the view");
|
||||
frames.idle(30, scene);
|
||||
for frame in 0..4 {
|
||||
runs.set(0);
|
||||
let shapes = frames.frame_shapes(scene);
|
||||
assert_eq!(runs.get(), 0, "settled frame {frame} ran the region");
|
||||
assert_eq!(runs(&frames), 0, "settled frame {frame} ran the view");
|
||||
assert!(!draws_rule(&shapes, wide), "settled frame {frame} replays the rule the run took back");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Settled memoized views: a settled view adds its last run to the pass in place of running, and runs when one of the
|
||||
//! settled rules breaks: the pointer over it, a bound value, inspection record or command state it read, its room, its
|
||||
//! environment (theme, density, language), an animation or a repaint asked inside it. Input elsewhere in the window
|
||||
//! does not run it.
|
||||
|
||||
use crate::values::kit::{AT, INITIAL, Scrub, Seen};
|
||||
use craft_theme::{Contrast, Mode, Size};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::{Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
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::{frame, inspect};
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, last_pass_measuring_runs, trial};
|
||||
use egui::{Context, Id, Pos2, Rect, Ui, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
const ORIGIN: Pos2 = Pos2::new(10.0, 60.0);
|
||||
const ROOM: Vec2 = Vec2::new(300.0, 200.0);
|
||||
/// Where the bound scrub of the reader view is shown, inside that view's room.
|
||||
const READER: Rect = Rect { min: Pos2::new(150.0, 70.0), max: Pos2::new(250.0, 90.0) };
|
||||
/// Settled frames a trial looks at.
|
||||
const SETTLED: usize = 4;
|
||||
|
||||
thread_local! {
|
||||
/// What the reader view's scrub recorded when it last ran.
|
||||
static SEEN: Seen = Seen::default();
|
||||
/// The id and rect of the button each view of `Scene` showed when it last ran.
|
||||
static BUTTONS: [Cell<(Id, Rect)>; 2] = const { [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))] };
|
||||
/// The buttons of `Shown`, `Beside`, `Published` and `Measured`, as the command scene's views last showed them.
|
||||
static COMMAND_BUTTONS: [Cell<Id>; 4] = const { [Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL)] };
|
||||
}
|
||||
|
||||
/// A props type's name without its path and generics: `Reader` for `it::body::memo_settled::Reader<'_>`.
|
||||
fn short_name(name: &'static str) -> &'static str {
|
||||
let name = name.split('<').next().unwrap_or(name);
|
||||
name.rsplit("::").next().unwrap_or(name)
|
||||
}
|
||||
|
||||
/// The calls of every pass of the last frame in which the views whose props type is `name` ran, measuring runs
|
||||
/// included.
|
||||
fn runs_of(ctx: &Context, name: &str) -> usize {
|
||||
last_frame_memo_runs(ctx).iter().filter(|(of, _, run)| short_name(of) == name && *run == MemoRun::Ran).count()
|
||||
}
|
||||
|
||||
/// The reader view: a button and a scrub bound to the value.
|
||||
#[derive(MemoProps)]
|
||||
struct Reader<'a> {
|
||||
value: Bind<'a, f32>,
|
||||
}
|
||||
|
||||
fn reader(props: &mut Reader<'_>, ui: &mut Ui) {
|
||||
let response = Button::new("Alpha").show(ui).response;
|
||||
BUTTONS.with(|buttons| buttons[0].set((response.id, response.rect)));
|
||||
SEEN.with(|seen| Scrub::new(props.value.reborrowed()).id_salt("reader").seen(seen).show_at(ui, READER));
|
||||
}
|
||||
|
||||
/// The other view: a button in a body, a spinner when `spinner` holds, and a repaint request in each run while
|
||||
/// `repaints` holds.
|
||||
#[derive(MemoProps)]
|
||||
struct Other {
|
||||
repaints: bool,
|
||||
spinner: bool,
|
||||
}
|
||||
|
||||
fn other(props: &mut Other, ui: &mut Ui) {
|
||||
if props.repaints {
|
||||
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;
|
||||
BUTTONS.with(|buttons| buttons[1].set((response.id, response.rect)));
|
||||
});
|
||||
if props.spinner {
|
||||
Spinner::new().show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two memoized views, `reader` and `other`, and a scrub outside them bound to the value the reader's own scrub shows.
|
||||
/// The scrub that edits comes before the views in the pass when `editor_first`, else after them.
|
||||
struct Scene {
|
||||
value: RefCell<f32>,
|
||||
room: Cell<Vec2>,
|
||||
editor_first: bool,
|
||||
spinner: bool,
|
||||
repaints: Cell<bool>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new(editor_first: bool, spinner: bool) -> Scene {
|
||||
Scene { value: RefCell::new(INITIAL), room: Cell::new(ROOM), editor_first, spinner, repaints: Cell::new(false) }
|
||||
}
|
||||
|
||||
fn show(&self, ui: &mut Ui) {
|
||||
if self.editor_first {
|
||||
self.editor(ui);
|
||||
}
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| {
|
||||
MemoView::new("reader", Reader { value: Bind::bound(&mut *self.value.borrow_mut()) }, reader).show(ui);
|
||||
MemoView::new("other", Other { repaints: self.repaints.get(), spinner: self.spinner }, other).show(ui);
|
||||
});
|
||||
if !self.editor_first {
|
||||
self.editor(ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn editor(&self, ui: &mut Ui) {
|
||||
Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("editor").show_at(ui, AT);
|
||||
}
|
||||
|
||||
/// The runs of each view in one frame with `events`.
|
||||
fn frame(&self, frames: &mut Frames, events: Vec<egui::Event>) -> [usize; 2] {
|
||||
frames.frame(events, |ui| self.show(ui));
|
||||
[runs_of(&frames.ctx, "Reader"), runs_of(&frames.ctx, "Other")]
|
||||
}
|
||||
|
||||
/// Frames with no input until both views are settled.
|
||||
fn settle(&self, frames: &mut Frames) {
|
||||
frames.idle(30, |ui| self.show(ui));
|
||||
}
|
||||
|
||||
/// The id and rect of the button view `at` showed.
|
||||
fn button(at: usize) -> (Id, Rect) {
|
||||
BUTTONS.with(|buttons| buttons[at].get())
|
||||
}
|
||||
}
|
||||
|
||||
fn painted(frames: &Frames, text: &str) -> bool {
|
||||
frames.texts().iter().any(|run| run.text == text)
|
||||
}
|
||||
|
||||
/// An untouched settled view runs no component, yet its paint shows in each frame and its accessibility nodes stay
|
||||
/// in the tree, under the same parents.
|
||||
#[trial]
|
||||
fn a_settled_view_does_not_run_and_still_paints() {
|
||||
let scene = Scene::new(false, false);
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(vec![], |ui| scene.show(ui));
|
||||
let ids = [0, 1].map(|at| Scene::button(at).0);
|
||||
let tree = frames.tree();
|
||||
let parents = ids.map(|id| tree.parent_of(id));
|
||||
assert!(parents.iter().all(Option::is_some), "the buttons have nodes in a frame that runs them");
|
||||
scene.settle(&mut frames);
|
||||
for frame in 0..SETTLED {
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "settled frame {frame} ran a view");
|
||||
assert!(painted(&frames, "Alpha") && painted(&frames, "Beta"), "settled frame {frame} paints both views");
|
||||
let tree = frames.tree();
|
||||
assert_eq!(
|
||||
ids.map(|id| tree.name(id).map(str::to_owned)),
|
||||
[Some("Alpha".to_owned()), Some("Beta".to_owned())],
|
||||
"settled frame {frame} keeps the nodes"
|
||||
);
|
||||
assert_eq!(ids.map(|id| tree.parent_of(id)), parents, "settled frame {frame} keeps the nodes' parents");
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer over a settled view runs it, and only it, in the frame it arrives, from the measures its last run
|
||||
/// kept; leaving, the view runs until its hover has faded out, then settles again.
|
||||
#[trial]
|
||||
fn hovering_a_settled_view_runs_it_alone() {
|
||||
let scene = Scene::new(false, false);
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
let over = Scene::button(1).1.center();
|
||||
let [reader, other] = scene.frame(&mut frames, vec![moved(over)]);
|
||||
assert!(other > 0, "the hovered view runs in the frame the pointer arrives");
|
||||
let measured = last_pass_measuring_runs(&frames.ctx);
|
||||
assert!(measured.is_empty(), "the hovered view's body takes its kept measure: {measured:?}");
|
||||
assert_eq!(reader, 0, "the view beside it stays settled");
|
||||
let away = Pos2::new(ORIGIN.x + ROOM.x - 2.0, ORIGIN.y + ROOM.y - 2.0);
|
||||
let [_, other] = scene.frame(&mut frames, vec![moved(away)]);
|
||||
assert!(other > 0, "the view the pointer left runs to show its hover leaving");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "once its hover faded, the view settles again");
|
||||
}
|
||||
|
||||
/// Drags the editor right in steps; returns per frame from the press on the passes, the runs of each view, and whether
|
||||
/// the reader showed the dragged value.
|
||||
fn drag(scene: &Scene) -> Vec<(usize, [usize; 2], bool)> {
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
let from = Pos2::new(AT.left() + 10.0, AT.center().y);
|
||||
scene.frame(&mut frames, vec![moved(from)]);
|
||||
let mut seen = Vec::new();
|
||||
for step in 0..=4 {
|
||||
let event = if step == 0 { press(from) } else { moved(from + Vec2::new(10.0 * step as f32 + 10.0, 0.0)) };
|
||||
let passes = frames.frame(vec![event], |ui| scene.show(ui));
|
||||
let shows = SEEN.with(|seen| seen.shown.get()) == Some(*scene.value.borrow());
|
||||
seen.push((passes, [runs_of(&frames.ctx, "Reader"), runs_of(&frames.ctx, "Other")], shows));
|
||||
}
|
||||
scene.frame(&mut frames, vec![release(from + Vec2::new(50.0, 0.0))]);
|
||||
seen
|
||||
}
|
||||
|
||||
/// A drag of a control outside both views, bound to a value one of them reads, runs that view in each drag frame and
|
||||
/// leaves the other settled, with the editor before the views in the pass and after them. The press, input outside
|
||||
/// both views, runs neither.
|
||||
#[trial]
|
||||
fn an_edit_runs_the_settled_view_that_read_the_value() {
|
||||
for editor_first in [true, false] {
|
||||
let frames = drag(&Scene::new(editor_first, false));
|
||||
assert_eq!(frames[0].1, [0, 0], "the press runs no view (editor first: {editor_first}): {frames:?}");
|
||||
for (passes, [reader, other], shows) in &frames[2..] {
|
||||
assert!(*reader > 0, "the reader runs in each drag frame (editor first: {editor_first}): {frames:?}");
|
||||
assert_eq!(*other, 0, "the other view stays settled (editor first: {editor_first}): {frames:?}");
|
||||
assert!(*shows, "the reader shows the dragged value (editor first: {editor_first}): {frames:?}");
|
||||
let expected = if editor_first { 1 } else { 2 };
|
||||
assert_eq!(*passes, expected, "passes per drag frame (editor first: {editor_first}): {frames:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A settled view whose room changes runs in that frame.
|
||||
#[trial]
|
||||
fn a_settled_view_runs_when_its_room_changes() {
|
||||
let scene = Scene::new(false, false);
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
scene.room.set(ROOM + Vec2::new(40.0, 0.0));
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [1, 1], "both views run at the new room");
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "and settle at it");
|
||||
}
|
||||
|
||||
/// A view with a running animation (a spinner) runs every frame; the view beside it stays settled.
|
||||
#[trial]
|
||||
fn a_view_with_a_running_animation_runs_every_frame() {
|
||||
let scene = Scene::new(false, 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 spinner's view runs, the other does not");
|
||||
}
|
||||
}
|
||||
|
||||
/// The app commands the command scene's views show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "settleTrial")]
|
||||
#[non_exhaustive]
|
||||
enum Shown {
|
||||
#[command(label = "Shown", modal = "always")]
|
||||
Visible,
|
||||
#[command(label = "Beside", modal = "always")]
|
||||
Beside,
|
||||
#[command(label = "Measured", modal = "always")]
|
||||
Measured,
|
||||
}
|
||||
|
||||
/// A command whose state an instance after the views publishes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "settleScopedTrial", scope = "trial.settle")]
|
||||
#[non_exhaustive]
|
||||
enum Scoped {
|
||||
#[command(label = "Published", modal = "always")]
|
||||
Published,
|
||||
}
|
||||
|
||||
const SCOPED: CommandScope = <Scoped as CommandSet>::SCOPE;
|
||||
|
||||
/// The inspection record whose pointed element the command reader view reads.
|
||||
const POINTED: &str = "settle-pointed";
|
||||
|
||||
/// The command reader view: the commands `Shown` and `Published`, and `Measured` in a content-sized body; it reads the
|
||||
/// element `POINTED` points at.
|
||||
#[derive(MemoProps)]
|
||||
struct CommandReader {}
|
||||
|
||||
fn command_reader(_: &mut CommandReader, ui: &mut Ui) {
|
||||
let shown = Button::command(Shown::Visible).show(ui).id;
|
||||
let published = Button::command(Scoped::Published).show(ui).id;
|
||||
COMMAND_BUTTONS.with(|buttons| {
|
||||
buttons[0].set(shown);
|
||||
buttons[2].set(published);
|
||||
});
|
||||
Stack::new().sizing(Sizing::Content).id_salt("measured").show(ui, |ui, _| {
|
||||
let id = Button::command(Shown::Measured).show(ui).id;
|
||||
COMMAND_BUTTONS.with(|buttons| buttons[3].set(id));
|
||||
});
|
||||
inspect::pointed(ui.ctx(), Id::NULL.with(POINTED));
|
||||
}
|
||||
|
||||
/// The view beside the reader: the command `Beside`.
|
||||
#[derive(MemoProps)]
|
||||
struct Beside {}
|
||||
|
||||
fn beside(_: &mut Beside, ui: &mut Ui) {
|
||||
let id = Button::command(Shown::Beside).show(ui).id;
|
||||
COMMAND_BUTTONS.with(|buttons| buttons[1].set(id));
|
||||
}
|
||||
|
||||
/// Two memoized views, the command reader and the view beside it. After them, an instance of `Published`'s scope, a
|
||||
/// content-sized body, publishes its state, and the record is pointed at `pointed`.
|
||||
struct CommandScene {
|
||||
published: Cell<bool>,
|
||||
pointed: Cell<Option<usize>>,
|
||||
}
|
||||
|
||||
impl CommandScene {
|
||||
fn new() -> CommandScene {
|
||||
CommandScene { published: Cell::new(true), pointed: Cell::new(None) }
|
||||
}
|
||||
|
||||
fn show(&self, ui: &mut Ui) {
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, ROOM), |ui| {
|
||||
MemoView::new("reader", CommandReader {}, command_reader).show(ui);
|
||||
MemoView::new("beside", Beside {}, beside).show(ui);
|
||||
Stack::new().command_scope(SCOPED).sizing(Sizing::Content).id_salt("publisher").show(ui, |_, cx| {
|
||||
cx.publish(Scoped::Published, CommandState::new().enabled(self.published.get()));
|
||||
});
|
||||
});
|
||||
inspect::point_at(ui.ctx(), Id::NULL.with(POINTED), self.pointed.get());
|
||||
}
|
||||
|
||||
/// The passes of one frame with no input, and the runs of each view in it.
|
||||
fn frame(&self, frames: &mut Frames) -> (usize, [usize; 2]) {
|
||||
let passes = frames.frame(vec![], |ui| self.show(ui));
|
||||
(passes, [runs_of(&frames.ctx, "CommandReader"), runs_of(&frames.ctx, "Beside")])
|
||||
}
|
||||
|
||||
fn settle(&self, frames: &mut Frames) {
|
||||
frames.idle(30, |ui| self.show(ui));
|
||||
}
|
||||
|
||||
/// Whether the button of `at` is disabled in the last frame's tree.
|
||||
fn disabled(&self, frames: &mut Frames, at: usize) -> bool {
|
||||
frames.tree().is_disabled(COMMAND_BUTTONS.with(|buttons| buttons[at].get()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The app disabling a command a settled view shows runs that view, and only it, in the same frame, which then shows
|
||||
/// the command disabled; settled again, it keeps showing it so.
|
||||
#[trial]
|
||||
fn an_app_command_state_runs_the_settled_view_that_shows_it() {
|
||||
let scene = CommandScene::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
assert!(!scene.disabled(&mut frames, 0), "Shown starts enabled");
|
||||
let disable = |enabled: bool| CommandInput::new().state(Shown::Visible, CommandState::new().enabled(enabled));
|
||||
frames.commands(disable(false));
|
||||
let (_, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "only the view that shows Shown runs: {reader}, {beside}");
|
||||
assert!(scene.disabled(&mut frames, 0), "it shows Shown disabled in the frame the app disables it");
|
||||
assert!(!scene.disabled(&mut frames, 1), "Beside stays enabled");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "both views settle again");
|
||||
assert!(scene.disabled(&mut frames, 0), "a settled frame keeps Shown disabled");
|
||||
frames.commands(disable(true));
|
||||
let (_, [reader, _]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && !scene.disabled(&mut frames, 0), "enabling it again runs the view, which shows it enabled");
|
||||
}
|
||||
|
||||
/// A state published after a settled view that shows it, and a record pointed at after a settled view that read it,
|
||||
/// run that view in the same frame: the change reruns the pass.
|
||||
#[trial]
|
||||
fn a_change_after_a_settled_reader_runs_it_in_the_same_frame() {
|
||||
let scene = CommandScene::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
assert!(!scene.disabled(&mut frames, 2), "Published starts enabled");
|
||||
assert_eq!(scene.frame(&mut frames).0, 1, "a steady frame whose measured body publishes the same state takes one pass");
|
||||
scene.published.set(false);
|
||||
let (passes, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "only the view that shows Published runs: {reader}, {beside}");
|
||||
assert!(passes > 1, "the publish reruns the pass");
|
||||
assert!(scene.disabled(&mut frames, 2), "it shows Published disabled in the frame it is published");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "both views settle again");
|
||||
assert!(scene.disabled(&mut frames, 2), "a settled frame keeps Published disabled");
|
||||
scene.pointed.set(Some(1));
|
||||
let (_, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "pointing the record runs only the view that read it: {reader}, {beside}");
|
||||
}
|
||||
|
||||
/// A command shown in a content-sized body, whose measuring run resolves it too, settles; the app disabling the command
|
||||
/// runs the view that shows it in the same frame, which then shows it disabled.
|
||||
#[trial]
|
||||
fn a_command_read_in_a_measured_body_settles_and_runs_when_its_state_changes() {
|
||||
let scene = CommandScene::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "the view holding the measured body settles");
|
||||
frames.commands(CommandInput::new().state(Shown::Measured, CommandState::new().enabled(false)));
|
||||
let (_, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "only the view that shows Measured runs: {reader}, {beside}");
|
||||
assert!(scene.disabled(&mut frames, 3), "it shows Measured disabled in the frame the app disables it");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "it settles again");
|
||||
assert!(scene.disabled(&mut frames, 3), "a settled frame keeps Measured disabled");
|
||||
}
|
||||
|
||||
/// The radio view: a group of three radios bound to the picked size.
|
||||
#[derive(MemoProps)]
|
||||
struct Radios<'a> {
|
||||
value: Bind<'a, u8>,
|
||||
}
|
||||
|
||||
fn radios(props: &mut Radios<'_>, ui: &mut Ui) {
|
||||
RadioGroup::new("Size", props.value.reborrowed()).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for (at, label) in [(1u8, "Small"), (2, "Medium"), (3, "Large")] {
|
||||
Radio::new(at).label(label).show(ui);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A settled view's replay keeps the arenas it shows: a press that arrives with the pointer, in the frame the pointer
|
||||
/// first comes over the view, reaches the radio under it, though the group ran last several frames ago.
|
||||
#[trial]
|
||||
fn a_press_with_the_pointer_arriving_reaches_a_member_of_a_settled_view() {
|
||||
let mut frames = Frames::new();
|
||||
let picked = Cell::new(1u8);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let mut value = picked.get();
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, ROOM), |ui| {
|
||||
MemoView::new("radios", Radios { value: Bind::bound(&mut value) }, radios).show(ui);
|
||||
});
|
||||
picked.set(value);
|
||||
};
|
||||
frames.frame(vec![], &mut show);
|
||||
let medium = frames.texts().iter().find(|run| run.text == "Medium").map(|run| run.rect.center()).expect("Medium is painted");
|
||||
frames.idle(30, &mut show);
|
||||
frames.frame(vec![moved(medium), press(medium)], &mut show);
|
||||
frames.frame(vec![release(medium)], &mut show);
|
||||
assert_eq!(picked.get(), 2, "the press that came with the pointer picks Medium");
|
||||
}
|
||||
|
||||
/// A view showing one button.
|
||||
#[derive(MemoProps)]
|
||||
struct Labelled {
|
||||
label: &'static str,
|
||||
}
|
||||
|
||||
fn labelled(props: &mut Labelled, ui: &mut Ui) {
|
||||
Button::new(props.label).show(ui);
|
||||
}
|
||||
|
||||
/// A fixture showing a view of the button `label`, settled.
|
||||
fn labelled_fixture(label: &'static str) -> Fixture {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
MemoView::new("labelled", Labelled { label }, labelled).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
fixture
|
||||
}
|
||||
|
||||
/// The runs of the button view in one frame with no input.
|
||||
fn labelled_frame(fixture: &mut Fixture) -> usize {
|
||||
fixture.frame(Vec::new());
|
||||
runs_of(fixture.ctx(), "Labelled")
|
||||
}
|
||||
|
||||
/// A view runs when the theme changes, whose tokens it painted with, and when the density does; it settles again after
|
||||
/// each.
|
||||
#[trial]
|
||||
fn a_settled_view_runs_when_the_theme_or_density_changes() {
|
||||
let mut fixture = labelled_fixture("Themed");
|
||||
assert_eq!(labelled_frame(&mut fixture), 0, "the view settles");
|
||||
fixture.theme(Mode::Light, Contrast::High);
|
||||
assert!(labelled_frame(&mut fixture) > 0, "a theme change runs it");
|
||||
assert_eq!(labelled_frame(&mut fixture), 0, "and it settles in the new theme");
|
||||
fixture.density(Size::Comfortable);
|
||||
assert!(labelled_frame(&mut fixture) > 0, "a density change runs it");
|
||||
}
|
||||
|
||||
/// A view runs when the host switches the language, and settles again in it.
|
||||
#[trial]
|
||||
fn a_settled_view_runs_when_the_language_changes() {
|
||||
let mut fixture = labelled_fixture("Save");
|
||||
assert_eq!(labelled_frame(&mut fixture), 0, "the view settles");
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned([("de".to_owned(), String::new(), "@id\ttrial.save\tSpeichern\n".to_owned())], &["de"]);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let host = craft_host::Host::builder(craft_host::AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(std::sync::Arc::new(i18n)).build();
|
||||
fixture.host(std::sync::Arc::new(host));
|
||||
assert!(labelled_frame(&mut fixture) > 0, "a new language runs it");
|
||||
assert_eq!(labelled_frame(&mut fixture), 0, "and it settles in that language, the host kept");
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
//! Memoized views (`MemoView`): a view runs only when its props key or a settled rule changes. Count trials: how views
|
||||
//! took part in a pass (`last_pass_memo_runs`), as relations.
|
||||
|
||||
use crate::values::kit::Scrub;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, MemoProps, MemoView, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::contract::{Bind, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey};
|
||||
use craft_ui::runtime::inspect;
|
||||
use craft_ui::runtime::memory::{SaveKey, set_saved_value};
|
||||
use craft_ui::runtime::{frame, inspect};
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::layout::{in_region, measured_block};
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
@@ -855,3 +856,128 @@ fn a_view_cut_by_its_clip_runs_when_it_moves_under_it() {
|
||||
let both = clip.translate(Vec2::new(0.0, 32.0));
|
||||
assert_eq!(moving_frame(&mut frames, moving_room(102.0), Some(both), 1).runs, [MemoRun::Replayed], "a cut run moved with its clip replays");
|
||||
}
|
||||
|
||||
/// A props type's name without its path and generics: `Reader` for `it::body::memo_settled::Reader<'_>`.
|
||||
fn short_name(name: &'static str) -> &'static str {
|
||||
let name = name.split('<').next().unwrap_or(name);
|
||||
name.rsplit("::").next().unwrap_or(name)
|
||||
}
|
||||
|
||||
/// A view that asks for a repaint in each run while `asks` holds.
|
||||
#[derive(MemoProps)]
|
||||
struct Asking {
|
||||
asks: bool,
|
||||
}
|
||||
|
||||
fn asking(props: &mut Asking, ui: &mut Ui) {
|
||||
if props.asks {
|
||||
frame::request_repaint(ui.ctx());
|
||||
}
|
||||
Button::new("Asking").show(ui);
|
||||
}
|
||||
|
||||
/// A view of the app's level.
|
||||
#[derive(MemoProps)]
|
||||
struct Level<'a> {
|
||||
level: &'a Tracked<f32>,
|
||||
}
|
||||
|
||||
fn level(props: &mut Level<'_>, ui: &mut Ui) {
|
||||
Button::new(format!("Level {}", **props.level)).show(ui);
|
||||
}
|
||||
|
||||
/// The app state of the repaint and edit trials: a level that a scrub outside every view edits as a given value, a view
|
||||
/// of the level, a view that asks for repaints while `asks` holds, and the title view, which holds neither. The app
|
||||
/// asks for a repaint outside every view while `app_asks` holds.
|
||||
struct Repaints {
|
||||
level: Tracked<f32>,
|
||||
asks: bool,
|
||||
app_asks: bool,
|
||||
}
|
||||
|
||||
impl Repaints {
|
||||
fn new() -> Repaints {
|
||||
Repaints { level: Tracked::new(10.0), asks: false, app_asks: false }
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui) {
|
||||
if self.app_asks {
|
||||
frame::request_repaint(ui.ctx());
|
||||
}
|
||||
let edited = Scrub::new(Bind::given(*self.level)).id_salt("level").show_at(ui, OUTSIDE);
|
||||
for event in edited.events {
|
||||
if let Some(value) = event.value().copied() {
|
||||
self.level.edit(|level| *level = value);
|
||||
}
|
||||
}
|
||||
in_region(ui, region(0), |ui| MemoView::new("title", Title { title: "Title".to_owned() }, title).show(ui));
|
||||
in_region(ui, region(1), |ui| MemoView::new("level", Level { level: &self.level }, level).show(ui));
|
||||
in_region(ui, region(2), |ui| MemoView::new("asking", Asking { asks: self.asks }, asking).show(ui));
|
||||
}
|
||||
|
||||
/// One frame with `events`; returns the views that ran in any of its passes, by props type name, measuring runs
|
||||
/// included.
|
||||
fn frame(&mut self, frames: &mut Frames, events: Vec<egui::Event>) -> Vec<&'static str> {
|
||||
frames.frame(events, |ui| self.show(ui));
|
||||
let ran = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran);
|
||||
ran.map(|(name, _, _)| short_name(name)).collect()
|
||||
}
|
||||
|
||||
fn settle(&mut self, frames: &mut Frames) {
|
||||
for _ in 0..SETTLE {
|
||||
self.frame(frames, vec![]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An app repaint request outside every view runs none of them: every view replays in that frame and the next. What
|
||||
/// the app changed reaches a view through its props.
|
||||
#[trial]
|
||||
fn an_app_repaint_outside_every_view_leaves_every_view_replaying() {
|
||||
let mut scene = Repaints::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
scene.app_asks = true;
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), Vec::<&str>::new(), "the frame the app asks in runs no view");
|
||||
let replayed = last_pass_memo_runs(&frames.ctx).iter().filter(|(_, _, run)| *run == MemoRun::Replayed).count();
|
||||
assert_eq!(replayed, 3, "every view replays");
|
||||
scene.app_asks = false;
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), Vec::<&str>::new(), "nor does the frame after it");
|
||||
}
|
||||
|
||||
/// A repaint asked in a view's run runs that view again in the next frame, and only it; once it stops asking, it runs
|
||||
/// once more for the props change and then replays.
|
||||
#[trial]
|
||||
fn a_repaint_asked_inside_a_view_runs_only_that_view() {
|
||||
let mut scene = Repaints::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
scene.asks = true;
|
||||
for frame in 0..4 {
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), ["Asking"], "frame {frame}: only the view that asks runs");
|
||||
}
|
||||
scene.asks = false;
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), ["Asking"], "the view runs for its props change");
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), Vec::<&str>::new(), "and then replays");
|
||||
}
|
||||
|
||||
/// A drag of a scrub outside every view that shows the app's level as a given value: the app writes each edit into
|
||||
/// its `Tracked` level, which runs the view whose props hold it in the same frame; the other views replay.
|
||||
#[trial]
|
||||
fn a_given_value_edit_runs_only_the_views_whose_props_hold_it() {
|
||||
let mut scene = Repaints::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
let from = Pos2::new(OUTSIDE.left() + 10.0, OUTSIDE.center().y);
|
||||
scene.frame(&mut frames, vec![moved(from)]);
|
||||
assert_eq!(scene.frame(&mut frames, vec![press(from)]), Vec::<&str>::new(), "the press runs no view");
|
||||
let start = *scene.level;
|
||||
let mut runs = Vec::new();
|
||||
for step in 1..=4 {
|
||||
runs.push(scene.frame(&mut frames, vec![moved(from + Vec2::new(12.0 * step as f32, 0.0))]));
|
||||
}
|
||||
scene.frame(&mut frames, vec![release(from + Vec2::new(48.0, 0.0))]);
|
||||
assert_ne!(*scene.level, start, "the drag edited the level");
|
||||
assert!(runs.iter().all(|ran| ran.iter().all(|name| *name == "Level")), "only the level's view runs in a drag frame: {runs:?}");
|
||||
assert!(runs[1..].iter().all(|ran| !ran.is_empty()), "the level's view runs in each drag frame that edits: {runs:?}");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The body step and the mount host: regions, scrolling, move and resize, and viewport mounts.
|
||||
|
||||
mod memo_reads;
|
||||
mod memo_settled;
|
||||
mod memo_view;
|
||||
mod scroll;
|
||||
mod settle;
|
||||
|
||||
@@ -1,486 +0,0 @@
|
||||
//! 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, its content version, its environment (theme, density), an animation or a repaint asked inside it.
|
||||
|
||||
use crate::values::kit::{AT, INITIAL, Scrub, Seen};
|
||||
use craft_theme::{Contrast, Mode, Size};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::{Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
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::{frame, inspect};
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial};
|
||||
use egui::{Id, Pos2, Rect, Ui, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
const ORIGIN: Pos2 = Pos2::new(10.0, 60.0);
|
||||
const ROOM: Vec2 = Vec2::new(300.0, 200.0);
|
||||
/// Where the bound scrub of the reader child is shown, inside that child's room.
|
||||
const READER: Rect = Rect { min: Pos2::new(150.0, 70.0), max: Pos2::new(250.0, 90.0) };
|
||||
/// Settled frames a trial looks at.
|
||||
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. 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<f32>,
|
||||
room: Cell<Vec2>,
|
||||
editor_first: bool,
|
||||
spinner: bool,
|
||||
versions: [Cell<Option<u64>>; 2],
|
||||
repaints: Cell<bool>,
|
||||
app_repaints: Cell<bool>,
|
||||
runs: [Cell<usize>; 2],
|
||||
buttons: [Cell<(Id, Rect)>; 2],
|
||||
seen: Seen,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new(editor_first: bool, spinner: bool) -> Scene {
|
||||
Scene {
|
||||
value: RefCell::new(INITIAL),
|
||||
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| {
|
||||
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);
|
||||
});
|
||||
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;
|
||||
self.buttons[1].set((response.id, response.rect));
|
||||
});
|
||||
if self.spinner {
|
||||
Spinner::new().show(ui);
|
||||
}
|
||||
});
|
||||
});
|
||||
if !self.editor_first {
|
||||
self.editor(ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn editor(&self, ui: &mut Ui) {
|
||||
Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("editor").show_at(ui, AT);
|
||||
}
|
||||
|
||||
/// The runs of each child in one frame with `events`.
|
||||
fn frame(&self, frames: &mut Frames, events: Vec<egui::Event>) -> [usize; 2] {
|
||||
self.runs.iter().for_each(|runs| runs.set(0));
|
||||
frames.frame(events, |ui| self.show(ui));
|
||||
[self.runs[0].get(), self.runs[1].get()]
|
||||
}
|
||||
|
||||
/// Frames with no input until both children are settled.
|
||||
fn settle(&self, frames: &mut Frames) {
|
||||
frames.idle(30, |ui| self.show(ui));
|
||||
}
|
||||
}
|
||||
|
||||
fn painted(frames: &Frames, text: &str) -> bool {
|
||||
frames.texts().iter().any(|run| run.text == text)
|
||||
}
|
||||
|
||||
/// An untouched settled child runs no component, yet its paint shows in each frame and its accessibility nodes stay
|
||||
/// in the tree, under the same parents.
|
||||
#[trial]
|
||||
fn a_settled_child_does_not_run_and_still_paints() {
|
||||
let scene = Scene::new(false, false);
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(vec![], |ui| scene.show(ui));
|
||||
let ids = scene.buttons.each_ref().map(|button| button.get().0);
|
||||
let tree = frames.tree();
|
||||
let parents = ids.map(|id| tree.parent_of(id));
|
||||
assert!(parents.iter().all(Option::is_some), "the buttons have nodes in a frame that runs them");
|
||||
scene.settle(&mut frames);
|
||||
for frame in 0..SETTLED {
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "settled frame {frame} ran a child");
|
||||
assert!(painted(&frames, "Alpha") && painted(&frames, "Beta"), "settled frame {frame} paints both children");
|
||||
let tree = frames.tree();
|
||||
assert_eq!(
|
||||
ids.map(|id| tree.name(id).map(str::to_owned)),
|
||||
[Some("Alpha".to_owned()), Some("Beta".to_owned())],
|
||||
"settled frame {frame} keeps the nodes"
|
||||
);
|
||||
assert_eq!(ids.map(|id| tree.parent_of(id)), parents, "settled frame {frame} keeps the nodes' parents");
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer over a settled child runs it, and only it, in the frame it arrives, from the measures its last run
|
||||
/// kept; leaving, the child runs until its hover has faded out, then settles again.
|
||||
#[trial]
|
||||
fn hovering_a_settled_child_runs_it_alone() {
|
||||
let scene = Scene::new(false, false);
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
let over = scene.buttons[1].get().1.center();
|
||||
let [reader, other] = scene.frame(&mut frames, vec![moved(over)]);
|
||||
assert!(other > 0, "the hovered child runs in the frame the pointer arrives");
|
||||
let measured = last_pass_measuring_runs(&frames.ctx);
|
||||
assert!(measured.is_empty(), "the hovered child's body takes its kept measure: {measured:?}");
|
||||
assert_eq!(reader, 0, "the child beside it stays settled");
|
||||
let away = Pos2::new(ORIGIN.x + ROOM.x - 2.0, ORIGIN.y + ROOM.y - 2.0);
|
||||
let [_, other] = scene.frame(&mut frames, vec![moved(away)]);
|
||||
assert!(other > 0, "the child the pointer left runs to show its hover leaving");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "once its hover faded, the child settles again");
|
||||
}
|
||||
|
||||
/// Drags the editor right in steps; returns per drag frame the passes, the runs of each child, and whether the
|
||||
/// reader showed the dragged value.
|
||||
fn drag(scene: &Scene) -> Vec<(usize, [usize; 2], bool)> {
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
let from = Pos2::new(AT.left() + 10.0, AT.center().y);
|
||||
scene.frame(&mut frames, vec![moved(from)]);
|
||||
scene.frame(&mut frames, vec![press(from)]);
|
||||
let mut seen = Vec::new();
|
||||
for step in 1..=4 {
|
||||
scene.runs.iter().for_each(|runs| runs.set(0));
|
||||
let passes = frames.frame(vec![moved(from + Vec2::new(10.0 * step as f32 + 10.0, 0.0))], |ui| scene.show(ui));
|
||||
let shows = scene.seen.shown.get() == Some(*scene.value.borrow());
|
||||
seen.push((passes, [scene.runs[0].get(), scene.runs[1].get()], shows));
|
||||
}
|
||||
scene.frame(&mut frames, vec![release(from + Vec2::new(50.0, 0.0))]);
|
||||
seen
|
||||
}
|
||||
|
||||
/// A drag of a control outside both children, bound to a value one of them reads, runs that child in each drag frame
|
||||
/// and leaves the other settled, with the editor before the children in the pass and after them. The frame after the
|
||||
/// press runs both: input unsettles every child for its frame and the next.
|
||||
#[trial]
|
||||
fn an_edit_runs_the_settled_child_that_read_the_value() {
|
||||
for editor_first in [true, false] {
|
||||
let frames = drag(&Scene::new(editor_first, false));
|
||||
for (passes, [reader, other], shows) in &frames[1..] {
|
||||
assert!(*reader > 0, "the reader runs in each drag frame (editor first: {editor_first}): {frames:?}");
|
||||
assert_eq!(*other, 0, "the other child stays settled (editor first: {editor_first}): {frames:?}");
|
||||
assert!(*shows, "the reader shows the dragged value (editor first: {editor_first}): {frames:?}");
|
||||
let expected = if editor_first { 1 } else { 2 };
|
||||
assert_eq!(*passes, expected, "passes per drag frame (editor first: {editor_first}): {frames:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A settled child whose room changes runs in that frame.
|
||||
#[trial]
|
||||
fn a_settled_child_runs_when_its_room_changes() {
|
||||
let scene = Scene::new(false, false);
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
scene.room.set(ROOM + Vec2::new(40.0, 0.0));
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [1, 1], "both children run at the new room");
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "and settle at it");
|
||||
}
|
||||
|
||||
/// A child with a running animation (a spinner) runs every frame; the child beside it stays settled.
|
||||
#[trial]
|
||||
fn a_child_with_a_running_animation_runs_every_frame() {
|
||||
let scene = Scene::new(false, 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 spinner's child runs, the other does not");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")]
|
||||
#[non_exhaustive]
|
||||
enum Shown {
|
||||
#[command(label = "Shown", modal = "always")]
|
||||
Visible,
|
||||
#[command(label = "Beside", modal = "always")]
|
||||
Beside,
|
||||
#[command(label = "Measured", modal = "always")]
|
||||
Measured,
|
||||
}
|
||||
|
||||
/// A command whose state an instance after the children publishes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "settleScopedTrial", scope = "trial.settle")]
|
||||
#[non_exhaustive]
|
||||
enum Scoped {
|
||||
#[command(label = "Published", modal = "always")]
|
||||
Published,
|
||||
}
|
||||
|
||||
const SCOPED: CommandScope = <Scoped as CommandSet>::SCOPE;
|
||||
|
||||
/// The inspection record whose pointed element the reader child reads.
|
||||
const POINTED: &str = "settle-pointed";
|
||||
|
||||
/// Two settling children: `reader` shows the commands `Shown` and `Published`, and `Measured` in a content-sized body,
|
||||
/// and reads the element `POINTED` points at; `beside` shows `Beside`. After them, an instance of `Published`'s scope,
|
||||
/// a content-sized body, publishes its state, and the record is pointed at `pointed`.
|
||||
struct CommandScene {
|
||||
published: Cell<bool>,
|
||||
pointed: Cell<Option<usize>>,
|
||||
runs: [Cell<usize>; 2],
|
||||
/// The buttons of `Shown`, `Beside`, `Published` and `Measured`.
|
||||
buttons: [Cell<Id>; 4],
|
||||
}
|
||||
|
||||
impl CommandScene {
|
||||
fn new() -> CommandScene {
|
||||
CommandScene {
|
||||
published: Cell::new(true),
|
||||
pointed: Cell::new(None),
|
||||
runs: Default::default(),
|
||||
buttons: [Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL)],
|
||||
}
|
||||
}
|
||||
|
||||
fn show(&self, ui: &mut Ui) {
|
||||
let pointed = Id::NULL.with(POINTED);
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, ROOM), |ui| {
|
||||
Lazy::new("reader", 0.0).settles(true).show(ui, |ui| {
|
||||
self.runs[0].set(self.runs[0].get() + 1);
|
||||
self.buttons[0].set(Button::command(Shown::Visible).show(ui).id);
|
||||
self.buttons[2].set(Button::command(Scoped::Published).show(ui).id);
|
||||
Stack::new().sizing(Sizing::Content).id_salt("measured").show(ui, |ui, _| {
|
||||
self.buttons[3].set(Button::command(Shown::Measured).show(ui).id);
|
||||
});
|
||||
inspect::pointed(ui.ctx(), pointed);
|
||||
});
|
||||
Lazy::new("beside", 0.0).settles(true).show(ui, |ui| {
|
||||
self.runs[1].set(self.runs[1].get() + 1);
|
||||
self.buttons[1].set(Button::command(Shown::Beside).show(ui).id);
|
||||
});
|
||||
Stack::new().command_scope(SCOPED).sizing(Sizing::Content).id_salt("publisher").show(ui, |_, cx| {
|
||||
cx.publish(Scoped::Published, CommandState::new().enabled(self.published.get()));
|
||||
});
|
||||
});
|
||||
inspect::point_at(ui.ctx(), pointed, self.pointed.get());
|
||||
}
|
||||
|
||||
/// The passes of one frame with no input, and the runs of each child in it.
|
||||
fn frame(&self, frames: &mut Frames) -> (usize, [usize; 2]) {
|
||||
self.runs.iter().for_each(|runs| runs.set(0));
|
||||
let passes = frames.frame(vec![], |ui| self.show(ui));
|
||||
(passes, [self.runs[0].get(), self.runs[1].get()])
|
||||
}
|
||||
|
||||
fn settle(&self, frames: &mut Frames) {
|
||||
frames.idle(30, |ui| self.show(ui));
|
||||
}
|
||||
|
||||
/// Whether the button of `at` is disabled in the last frame's tree.
|
||||
fn disabled(&self, frames: &mut Frames, at: usize) -> bool {
|
||||
frames.tree().is_disabled(self.buttons[at].get())
|
||||
}
|
||||
}
|
||||
|
||||
/// The app disabling a command a settled child shows runs that child, and only it, in the same frame, which then shows
|
||||
/// the command disabled; settled again, it keeps showing it so.
|
||||
#[trial]
|
||||
fn an_app_command_state_runs_the_settled_child_that_shows_it() {
|
||||
let scene = CommandScene::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
assert!(!scene.disabled(&mut frames, 0), "Shown starts enabled");
|
||||
let disable = |enabled: bool| CommandInput::new().state(Shown::Visible, CommandState::new().enabled(enabled));
|
||||
frames.commands(disable(false));
|
||||
let (_, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "only the child that shows Shown runs: {reader}, {beside}");
|
||||
assert!(scene.disabled(&mut frames, 0), "it shows Shown disabled in the frame the app disables it");
|
||||
assert!(!scene.disabled(&mut frames, 1), "Beside stays enabled");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "both children settle again");
|
||||
assert!(scene.disabled(&mut frames, 0), "a settled frame keeps Shown disabled");
|
||||
frames.commands(disable(true));
|
||||
let (_, [reader, _]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && !scene.disabled(&mut frames, 0), "enabling it again runs the child, which shows it enabled");
|
||||
}
|
||||
|
||||
/// A state published after a settled child that shows it, and a record pointed at after a settled child that read it,
|
||||
/// run that child in the same frame: the change reruns the pass.
|
||||
#[trial]
|
||||
fn a_change_after_a_settled_reader_runs_it_in_the_same_frame() {
|
||||
let scene = CommandScene::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
assert!(!scene.disabled(&mut frames, 2), "Published starts enabled");
|
||||
assert_eq!(scene.frame(&mut frames).0, 1, "a steady frame whose measured body publishes the same state takes one pass");
|
||||
scene.published.set(false);
|
||||
let (passes, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "only the child that shows Published runs: {reader}, {beside}");
|
||||
assert!(passes > 1, "the publish reruns the pass");
|
||||
assert!(scene.disabled(&mut frames, 2), "it shows Published disabled in the frame it is published");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "both children settle again");
|
||||
assert!(scene.disabled(&mut frames, 2), "a settled frame keeps Published disabled");
|
||||
scene.pointed.set(Some(1));
|
||||
let (_, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "pointing the record runs only the child that read it: {reader}, {beside}");
|
||||
}
|
||||
|
||||
/// A command shown in a content-sized body, whose measuring run resolves it too, settles; the app disabling the command
|
||||
/// runs the child that shows it in the same frame, which then shows it disabled.
|
||||
#[trial]
|
||||
fn a_command_read_in_a_measured_body_settles_and_runs_when_its_state_changes() {
|
||||
let scene = CommandScene::new();
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "the child holding the measured body settles");
|
||||
frames.commands(CommandInput::new().state(Shown::Measured, CommandState::new().enabled(false)));
|
||||
let (_, [reader, beside]) = scene.frame(&mut frames);
|
||||
assert!(reader > 0 && beside == 0, "only the child that shows Measured runs: {reader}, {beside}");
|
||||
assert!(scene.disabled(&mut frames, 3), "it shows Measured disabled in the frame the app disables it");
|
||||
scene.settle(&mut frames);
|
||||
assert_eq!(scene.frame(&mut frames).1, [0, 0], "it settles again");
|
||||
assert!(scene.disabled(&mut frames, 3), "a settled frame keeps Measured disabled");
|
||||
}
|
||||
|
||||
/// A settled child's replay keeps the arenas it shows: a press that arrives with the pointer, in the frame the pointer
|
||||
/// first comes over the child, reaches the radio under it, though the group ran last several frames ago.
|
||||
#[trial]
|
||||
fn a_press_with_the_pointer_arriving_reaches_a_member_of_a_settled_child() {
|
||||
let mut frames = Frames::new();
|
||||
let picked = Cell::new(1u8);
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let mut value = picked.get();
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, ROOM), |ui| {
|
||||
Lazy::new("radios", 0.0).settles(true).show(ui, |ui| {
|
||||
RadioGroup::new("Size", Bind::bound(&mut value)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for (at, label) in [(1u8, "Small"), (2, "Medium"), (3, "Large")] {
|
||||
Radio::new(at).label(label).show(ui);
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
});
|
||||
picked.set(value);
|
||||
};
|
||||
frames.frame(vec![], &mut show);
|
||||
let medium = frames.texts().iter().find(|run| run.text == "Medium").map(|run| run.rect.center()).expect("Medium is painted");
|
||||
frames.idle(30, &mut show);
|
||||
frames.frame(vec![moved(medium), press(medium)], &mut show);
|
||||
frames.frame(vec![release(medium)], &mut show);
|
||||
assert_eq!(picked.get(), 2, "the press that came with the pointer picks Medium");
|
||||
}
|
||||
|
||||
/// A child with a content version runs when the theme changes, whose tokens it painted with, and when the density
|
||||
/// does; it settles again after each.
|
||||
#[trial]
|
||||
fn a_settled_child_runs_when_the_theme_or_density_changes() {
|
||||
let runs = std::rc::Rc::new(Cell::new(0));
|
||||
let counted = std::rc::Rc::clone(&runs);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Lazy::new("themed", 0.0).settles(true).content(1).show(ui, |ui| {
|
||||
counted.set(counted.get() + 1);
|
||||
Button::new("Themed").show(ui);
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
let frame = |fixture: &mut Fixture| {
|
||||
runs.set(0);
|
||||
fixture.frame(Vec::new());
|
||||
runs.get()
|
||||
};
|
||||
assert_eq!(frame(&mut fixture), 0, "the child settles");
|
||||
fixture.theme(Mode::Light, Contrast::High);
|
||||
assert!(frame(&mut fixture) > 0, "a theme change runs it");
|
||||
assert_eq!(frame(&mut fixture), 0, "and it settles in the new theme");
|
||||
fixture.density(Size::Comfortable);
|
||||
assert!(frame(&mut fixture) > 0, "a density change runs it");
|
||||
}
|
||||
|
||||
/// A child with a content version runs when the host switches the language, and settles again in it.
|
||||
#[trial]
|
||||
fn a_settled_child_runs_when_the_language_changes() {
|
||||
let runs = std::rc::Rc::new(Cell::new(0));
|
||||
let counted = std::rc::Rc::clone(&runs);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Lazy::new("worded", 0.0).settles(true).content(1).show(ui, |ui| {
|
||||
counted.set(counted.get() + 1);
|
||||
Button::new("Save").show(ui);
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
let frame = |fixture: &mut Fixture| {
|
||||
runs.set(0);
|
||||
fixture.frame(Vec::new());
|
||||
runs.get()
|
||||
};
|
||||
assert_eq!(frame(&mut fixture), 0, "the child settles");
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned([("de".to_owned(), String::new(), "@id\ttrial.save\tSpeichern\n".to_owned())], &["de"]);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let host = craft_host::Host::builder(craft_host::AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(std::sync::Arc::new(i18n)).build();
|
||||
fixture.host(std::sync::Arc::new(host));
|
||||
assert!(frame(&mut fixture) > 0, "a new language runs it");
|
||||
assert_eq!(frame(&mut fixture), 0, "and it settles in that language, the host kept");
|
||||
}
|
||||
@@ -7,13 +7,13 @@ use craft_behavior::IconId;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_theme::{Opacity, Srgba};
|
||||
use craft_ui::buttons::{Button, IconButton};
|
||||
use craft_ui::contract::{Lazy, Props as _, Show as _};
|
||||
use craft_ui::contract::{MemoProps, MemoView, Props as _, Show as _};
|
||||
use craft_ui::list::ThumbAspect;
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::DataColor;
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, trial};
|
||||
use craft_ui::tile_grid::{BadgeKind, BadgeSlot, Tile, TileBadge};
|
||||
use egui::epaint::ColorMode;
|
||||
use egui::{Color32, Rect, Shape, Ui, pos2};
|
||||
@@ -125,27 +125,36 @@ fn a_disabled_faded_component_paints_its_enabled_look_faded_once() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A settled region holding a disabled faded tile runs nothing, and replays the veiled paint of the frame that ran.
|
||||
/// A view holding a disabled tile.
|
||||
#[derive(MemoProps)]
|
||||
struct Faded {}
|
||||
|
||||
fn faded(_: &mut Faded, ui: &mut Ui) {
|
||||
tile(ui, false);
|
||||
}
|
||||
|
||||
/// The runs of every view in the last frame.
|
||||
fn view_runs(frames: &Frames) -> usize {
|
||||
last_frame_memo_runs(&frames.ctx).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count()
|
||||
}
|
||||
|
||||
/// A settled memoized view holding a disabled faded tile runs nothing, and replays the veiled paint of the frame that
|
||||
/// ran.
|
||||
#[trial]
|
||||
fn a_settled_region_replays_a_faded_component_without_running_it() {
|
||||
let runs = Cell::new(0);
|
||||
fn a_settled_view_replays_a_faded_component_without_running_it() {
|
||||
let scene = |ui: &mut Ui| {
|
||||
Lazy::new("faded", 0.0).settles(true).show(ui, |ui| {
|
||||
runs.set(runs.get() + 1);
|
||||
tile(ui, false);
|
||||
});
|
||||
MemoView::new("faded", Faded {}, faded).show(ui);
|
||||
};
|
||||
let ran = colors(&settled_shapes(&mut Frames::new(), |ui| {
|
||||
tile(ui, false);
|
||||
}));
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(vec![], scene);
|
||||
assert!(runs.get() > 0, "the first frame runs the region");
|
||||
assert!(view_runs(&frames) > 0, "the first frame runs the view");
|
||||
frames.idle(30, scene);
|
||||
for frame in 0..4 {
|
||||
runs.set(0);
|
||||
let shapes = frames.frame_shapes(scene);
|
||||
assert_eq!(runs.get(), 0, "settled frame {frame} ran the region");
|
||||
assert_eq!(view_runs(&frames), 0, "settled frame {frame} ran the view");
|
||||
assert_eq!(colors(&shapes), ran, "settled frame {frame} paints the veiled colours a run paints");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,22 +239,31 @@ fn a_row_whose_label_changed_since_the_menu_last_opened_takes_its_new_letter() {
|
||||
assert_eq!(runs.get(), 1, "O runs the row that reads Open");
|
||||
}
|
||||
|
||||
/// A menu bar that settles (in a title bar slot with a content version) still takes its keys while it replays its
|
||||
/// last run: F10 takes the focus to the bar, and Alt with a title's marked letter opens that menu.
|
||||
/// A view of a menu bar with a File menu.
|
||||
#[derive(craft_ui::contract::MemoProps)]
|
||||
struct MainMenu {}
|
||||
|
||||
fn main_menu(_: &mut MainMenu, ui: &mut egui::Ui) {
|
||||
let titles = vec![MenuTitle::new("&File", |ui| {
|
||||
MenuItem::new("&New").show(ui);
|
||||
})];
|
||||
MenuBar::new("Main menu", titles).show(ui);
|
||||
}
|
||||
|
||||
/// A menu bar in a memoized view still takes its keys while the view replays its last run: F10 takes the focus to the
|
||||
/// bar, and Alt with a title's marked letter opens that menu.
|
||||
#[trial]
|
||||
fn a_settled_menu_bar_takes_its_mnemonics_and_f10() {
|
||||
use craft_ui::contract::Lazy;
|
||||
use craft_ui::contract::MemoView;
|
||||
use craft_ui::testing::{MemoRun, last_frame_memo_runs};
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
Lazy::new("title", 0.0).settles(true).content(1).show(ui, |ui| {
|
||||
let titles = vec![MenuTitle::new("&File", |ui| {
|
||||
MenuItem::new("&New").show(ui);
|
||||
})];
|
||||
MenuBar::new("Main menu", titles).show(ui);
|
||||
});
|
||||
MemoView::new("title", MainMenu {}, main_menu).show(ui);
|
||||
});
|
||||
fixture.os(Os::Linux);
|
||||
fixture.settle().idle(2);
|
||||
assert!(fixture.focused_stop().is_none(), "nothing holds the focus at the start");
|
||||
let runs = last_frame_memo_runs(fixture.ctx());
|
||||
assert!(runs.iter().all(|(_, _, run)| *run == MemoRun::Replayed) && !runs.is_empty(), "the bar's view replays: {runs:?}");
|
||||
fixture.key(Key::F10, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
assert!(fixture.focused_stop().is_some(), "F10 takes the focus to the bar");
|
||||
|
||||
@@ -323,6 +323,8 @@ Content runs in every pass, and its sizes come from this pass. Layouts also read
|
||||
|
||||
**Layout memory.** A record of layout memory holds a measure or a text. A body whose inputs did not change takes its kept measurement instead of running a measuring run. A text that a measuring run found for content outside the body (a value readout beside a story, for example) is kept with the measurement: `layout_memory::emit_text` hands it forward, `layout_memory::text` reads it, and a body that takes its kept measurement gives the text its measuring run found. A real run that finds another text marks the kept transcript as changed.
|
||||
|
||||
**Memoized views.** A memoized view (`MemoView::new(id, props, show).show(ui)`) runs only when one of its inputs changed, and otherwise adds its last real run to the pass again: its paint, widgets, accessibility nodes, focus stops and the other per-pass registrations, and the value its run returned. Its content is a `fn` that captures nothing, and its props (`#[derive(MemoProps)]`) hold every app input it reads, so the compiler checks that the framework sees them; large app data goes in a `Tracked<T>`, which keys by revision. The view runs when its props key differs from its last run's, when its place or environment differs (room, clip, layer, scale, theme, density, language, the scope's inherited values), when a framework input it read moved (modifiers, pointer, keymap, focus, a bound value, a command state), when it is engaged (the pointer over it, focus in it, a press or drag in it, an intent routed to it), and while something in it still moves (an animation, a loading texture, a repaint asked in its run with `frame::request_repaint`, a wake time). Input elsewhere in the window and repaint requests outside every view run no view: what changed reaches a view through its props. Content outside every memoized view runs in every pass.
|
||||
|
||||
**Out-of-view content.** Content inside a scroll area that is out of view this pass does not run. It keeps what it last showed: the extent it had in the last pass that showed it, which changes only in a pass that shows the content, and the stops it registered there. One mechanism (`runtime::lazy`, one store) serves every use:
|
||||
|
||||
- Only content that meets the view runs. A `Lazy` child out of view registers the focus records of its last real run again in its place (its stops, the scopes it pushed and the roving groups of its stops; `focus::Transcript`), so Tab and F6 reach its stops; Tab onto one runs the child and the reveal scrolls it in.
|
||||
@@ -353,7 +355,7 @@ Content runs in every pass, and its sizes come from this pass. Layouts also read
|
||||
- `Context::set_layer_order`, which moves unlisted sublayers with their listed parent
|
||||
- OpenType features per text section (epaint)
|
||||
- `IdTypeMap::insert_temp_boxed` keeps the allocation of a value taken out, and `Context::ptr_eq`
|
||||
- `Context::pass_mark`, `pass_records_since` and `replay_pass_records`: a settled region replays its last pass's records
|
||||
- `Context::pass_mark`, `pass_records_since` and `replay_pass_records`: a settled memoized view replays its last run's records
|
||||
- `Event::SystemTheme` reports the OS's light or dark preference
|
||||
- `egui_kittest`'s eframe harness runs `App::raw_input_hook` before each pass, as eframe does, so an app's `embed::before_input` runs in its tests
|
||||
|
||||
|
||||
@@ -98,3 +98,28 @@ note = "`EnvView::text_direction()` is the paragraph direction of text (the inte
|
||||
old = "commands::take_for_instance(ctx, instance, from_ref)"
|
||||
new = "commands::take_for_instance(ctx, instance, app, from_ref)"
|
||||
note = "Crate-internal: the signature is `take_for_instance(ctx: &Context, instance: Option<Id>, app: bool, from_ref: fn(&CommandRef) -> Option<S>)`; `app` is true for an app-scope command set, which takes from the frame's output."
|
||||
|
||||
[[call]]
|
||||
old = "Lazy::new(_, _).settles(_)"
|
||||
new = "MemoView::new(_, props, show).show(ui)"
|
||||
note = "A view that runs only when its inputs change is a memoized view: `show` is a `fn(&mut P, &mut Ui) -> R` that captures nothing and `props` (`#[derive(MemoProps)]`) hold every input it reads. While its props key and the framework inputs it read are unchanged it replays its last run. `Lazy` keeps only the in-view rule of a scroll area's child."
|
||||
|
||||
[[call]]
|
||||
old = "_.content(version)"
|
||||
new = ""
|
||||
note = "Removed with `Lazy::settles`: the app data a view shows goes into its props, large data as a `Tracked<T>`, which keys by revision."
|
||||
|
||||
[[call]]
|
||||
old = "frame::request_own_repaint(ctx)"
|
||||
new = "frame::request_repaint(ctx)"
|
||||
note = "One repaint request: asked in a memoized view's run, it runs that view (and the views around it) in the next pass; asked outside every view, every view replays."
|
||||
|
||||
[[call]]
|
||||
old = "DockPanels::content(_, _)"
|
||||
new = ""
|
||||
note = "Removed, with `DockPanels::spec_version`, `DockColumn::content` and `IconicColumn::content`: the dock's chrome is memoized from the panel specs, and a host memoizes a panel's content inside `DockPanels::body` with a `MemoView`."
|
||||
|
||||
[[call]]
|
||||
old = "Slot::content(_)"
|
||||
new = ""
|
||||
note = "Removed, with `Slot::content_version` and `AppShell::content`: a slot's body runs every pass, and the app memoizes what it shows there with a `MemoView`."
|
||||
|
||||
Reference in New Issue
Block a user