diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index c75251ce4..86066450f 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -111,6 +111,11 @@ jobs: # feature off, which an all-features build cannot reach. cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench + # The replay audit (craft-libs#2336), on Linux: the UI crates' tests again, from the same build, with every + # memoized view that would replay also run for real and compared with its replay. + if [ "$RUNNER_OS" = Linux ]; then + CRAFT_UI_AUDIT_REPLAY=1 cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests -E 'package(craft-ui-contract) | package(craft-ui-widgets) | package(craft-ui-panels) | package(craft-ui-patterns) | package(craft-ui-shell) | package(craft-ui-gallery) | package(craft-menu)' + fi cargo test --workspace --doc --all-features --locked cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests diff --git a/Cargo.lock b/Cargo.lock index c773302f0..2fe181826 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2083,6 +2083,8 @@ dependencies = [ "craft-host", "craft-keymap", "craft-theme", + "craft-tracked", + "craft-ui-macros", "emath", "kurbo", "serde", @@ -4316,6 +4318,7 @@ dependencies = [ "smallvec", "syn 2.0.119", "toml", + "typeid", "web-time", ] @@ -12923,6 +12926,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.1" diff --git a/Cargo.toml b/Cargo.toml index e47b4eb8c..d0e2a9271 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -272,6 +272,7 @@ scoped-tls = "1" smallvec = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" +typeid = "1" proptest = "1" # Character sets of the WHATWG Encoding Standard (craft-mime). (Apache-2.0 OR MIT) AND BSD-3-Clause. encoding_rs = "0.8" diff --git a/crates/behavior/Cargo.toml b/crates/behavior/Cargo.toml index bb6332a39..571f3a7ad 100644 --- a/crates/behavior/Cargo.toml +++ b/crates/behavior/Cargo.toml @@ -21,6 +21,9 @@ bitflags = "2" craft-host = { workspace = true } craft-keymap = { workspace = true } craft-theme = { workspace = true } +# Value types readers hold in `Tracked` derive its `PlainData` marker. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } # The dock layout is a persisted shape. serde = { workspace = true } diff --git a/crates/behavior/src/canvas/view.rs b/crates/behavior/src/canvas/view.rs index 3b7d80dc4..f4269ae05 100644 --- a/crates/behavior/src/canvas/view.rs +++ b/crates/behavior/src/canvas/view.rs @@ -13,12 +13,14 @@ use kurbo::{Affine, Point, Rect, Vec2}; /// [`aspect`](Self::aspect) stretches it along its x axis and before /// [`flip_x`](Self::flip_x) mirrors the result, PhotoCraft's `ViewXform`. DesignCraft's quarter /// turns are `rotation = 90 × q`; VectorCraft's radians are converted to degrees. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui_macros::PlainData)] #[non_exhaustive] pub struct CanvasView { /// The canvas on screen, inside the rulers. + #[plain_data(assume = "screen geometry: plain numbers, no interior mutability")] pub rect: ScreenRect, /// The document point drawn at `rect.center()`. + #[plain_data(assume = "document geometry: plain numbers, no interior mutability")] pub center: Point, /// Screen points per document unit. In PhotoCraft's model this is the view zoom over the /// pixels per point, so 100 % shows one device pixel per document pixel. diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index 4b0953fda..e3ffa2745 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -68,7 +68,7 @@ impl From> for IconId { } /// A mark beside a painted cursor. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CursorBadge { /// A plus. @@ -100,7 +100,7 @@ pub enum CursorBadge { } /// The kind of a [`CursorBadge::Count`] mark. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CountMark { /// A point is added. diff --git a/crates/behavior/src/hit.rs b/crates/behavior/src/hit.rs index 0ca496cdd..8fd12da30 100644 --- a/crates/behavior/src/hit.rs +++ b/crates/behavior/src/hit.rs @@ -93,6 +93,47 @@ impl HitShape { } } + /// The shape moved by `by`. + #[must_use] + pub fn translated(&self, by: Vec2) -> Self { + let points = |points: &[Pos2]| points.iter().map(|point| *point + by).collect(); + match self { + HitShape::Rect(rect) => HitShape::Rect(rect.translate(by)), + HitShape::Circle { center, radius } => HitShape::Circle { center: *center + by, radius: *radius }, + HitShape::Segment { a, b } => HitShape::Segment { a: *a + by, b: *b + by }, + HitShape::Polyline { points: line, closed, reach } => HitShape::Polyline { points: points(line), closed: *closed, reach: *reach }, + HitShape::Polygon(polygon) => HitShape::Polygon(points(polygon)), + HitShape::OutsidePolygon { within, polygon } => HitShape::OutsidePolygon { within: within.translate(by), polygon: points(polygon) }, + } + } + + /// The shape with each coordinate taken from `to`'s where the two lie within `within` points, when both are the + /// same kind of shape with as many points: two shapes `==` finds equal after it differ by no more than `within`. + #[must_use] + pub fn snapped(&self, to: &HitShape, within: f32) -> Self { + let near = |value: f32, to: f32| if (value - to).abs() <= within { to } else { value }; + let pos = |value: Pos2, to: Pos2| Pos2::new(near(value.x, to.x), near(value.y, to.y)); + let rect = |value: Rect, to: Rect| Rect::from_min_max(pos(value.min, to.min), pos(value.max, to.max)); + let points = |values: &[Pos2], to: &[Pos2]| { + if values.len() == to.len() { values.iter().zip(to).map(|(value, to)| pos(*value, *to)).collect() } else { values.to_vec() } + }; + match (self, to) { + (HitShape::Rect(value), HitShape::Rect(to)) => HitShape::Rect(rect(*value, *to)), + (HitShape::Circle { center, radius }, HitShape::Circle { center: to_center, radius: to_radius }) => { + HitShape::Circle { center: pos(*center, *to_center), radius: near(*radius, *to_radius) } + } + (HitShape::Segment { a, b }, HitShape::Segment { a: to_a, b: to_b }) => HitShape::Segment { a: pos(*a, *to_a), b: pos(*b, *to_b) }, + (HitShape::Polyline { points: line, closed, reach }, HitShape::Polyline { points: to_line, reach: to_reach, .. }) => { + HitShape::Polyline { points: points(line, to_line), closed: *closed, reach: near(*reach, *to_reach) } + } + (HitShape::Polygon(polygon), HitShape::Polygon(to_polygon)) => HitShape::Polygon(points(polygon, to_polygon)), + (HitShape::OutsidePolygon { within: area, polygon }, HitShape::OutsidePolygon { within: to_area, polygon: to_polygon }) => { + HitShape::OutsidePolygon { within: rect(*area, *to_area), polygon: points(polygon, to_polygon) } + } + _ => self.clone(), + } + } + /// Whether `point` hits the shape grown to be at least `across` wide and high: the hit area of a part is never /// smaller than the pointer's target size. fn hit_across(&self, point: Pos2, across: f32) -> bool { @@ -232,6 +273,22 @@ pub struct Shape { pub min_across: f32, } +impl Shape { + /// The shape moved by `by`. + #[must_use] + pub fn translated(&self, by: Vec2) -> Self { + Shape { shape: self.shape.translated(by), owner: self.owner.clone(), ..*self } + } + + /// The shape with its geometry and least size across taken from `to`'s where they lie within `within` points + /// ([`HitShape::snapped`]). + #[must_use] + pub fn snapped(&self, to: &Shape, within: f32) -> Self { + let min_across = if (self.min_across - to.min_across).abs() <= within { to.min_across } else { self.min_across }; + Shape { shape: self.shape.snapped(&to.shape, within), owner: self.owner.clone(), min_across, ..*self } + } +} + impl Shape { /// A shape of `owner` at stack `position`. pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self { diff --git a/crates/behavior/src/selection.rs b/crates/behavior/src/selection.rs index 13acb9fb5..371cebb9d 100644 --- a/crates/behavior/src/selection.rs +++ b/crates/behavior/src/selection.rs @@ -193,7 +193,7 @@ pub trait SelectionModel: Value + Default { } /// A set of keys with a lead and an anchor. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] #[non_exhaustive] pub struct Selection { /// The selected keys. diff --git a/crates/browse/src/ui/compare/stories.rs b/crates/browse/src/ui/compare/stories.rs index 6f3bff93c..3a876b535 100644 --- a/crates/browse/src/ui/compare/stories.rs +++ b/crates/browse/src/ui/compare/stories.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::sync::{Mutex, PoisonError}; use craft_theme::Srgba; -use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::contract::{Show as _, ShowContainer as _}; use craft_ui::display::Divider; use craft_ui::layout_components::Row; use craft_ui::patterns::form_dialogs::PreviewView; @@ -71,16 +71,16 @@ fn compare_pair(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let labels = ["Select", "Candidate"]; let output = filling(ui, |ui, area| { let mut active = *data.value("active", 0usize); - let view = data.value("view", PreviewView::fitting()); + let (view, view_at) = data.value_at("view", PreviewView::fitting()); let pair = ComparePair::new(space).rtl(rtl); let [left, right] = pair.rects(area); Divider::vertical().show_at(ui, pair.divider(area)); let select = - CompareTile::new(labels[0], Bind::bound(view), image(1)).caption(caption(labels[0], "IMG_0001.jpg")).active(active == 0).place(ui, left); + CompareTile::new(labels[0], view_at.bind(view), image(1)).caption(caption(labels[0], "IMG_0001.jpg")).active(active == 0).place(ui, left); if select.clicked { active = 0; } - let candidate = CompareTile::new(labels[1], Bind::bound(view), image(2)) + let candidate = CompareTile::new(labels[1], view_at.bind(view), image(2)) .caption(caption(labels[1], "IMG_0002.jpg")) .active(active == 1) .rejected(true) @@ -98,9 +98,9 @@ fn compare_pair(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(CompareTile<'static>, covers = [LongText], drive = Drive::Never)] fn compare_tile_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { filling(ui, |ui, area| { - let view = data.value("view", PreviewView::fitting()); + let (view, view_at) = data.value_at("view", PreviewView::fitting()); let rect = Rect::from_min_size(area.min, Vec2::splat(area.width() * NARROW_SHARE)); - CompareTile::new("Select", Bind::bound(view), image(1)) + CompareTile::new("Select", view_at.bind(view), image(1)) .caption(caption("Select", "A_file_name_much_longer_than_the_tile.jpeg")) .place(ui, rect) .into() @@ -110,8 +110,8 @@ fn compare_tile_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(CompareTile<'static>, covers = [], drive = Drive::Never)] fn compare_tile_pending(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { filling(ui, |ui, area| { - let view = data.value("view", PreviewView::fitting()); - CompareTile::new("Candidate", Bind::bound(view), image(2)) + let (view, view_at) = data.value_at("view", PreviewView::fitting()); + CompareTile::new("Candidate", view_at.bind(view), image(2)) .caption(caption("Candidate", "IMG_0002.jpg")) .state(RenderState::Pending(true)) .place(ui, area) @@ -122,8 +122,8 @@ fn compare_tile_pending(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(CompareTile<'static>, covers = [], drive = Drive::Never)] fn compare_tile_failed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { filling(ui, |ui, area| { - let view = data.value("view", PreviewView::fitting()); - CompareTile::new("Candidate", Bind::bound(view), CompareImage::None) + let (view, view_at) = data.value_at("view", PreviewView::fitting()); + CompareTile::new("Candidate", view_at.bind(view), CompareImage::None) .caption(CompareCaption::new("Candidate", "IMG_0002.jpg")) .state(RenderState::Failed("The renderer stopped".into())) .place(ui, area) @@ -138,12 +138,12 @@ fn compare_survey(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { const ASPECT: f32 = 1.5; let rtl = Env::of(ui).view().direction().is_rtl(); filling(ui, |ui, area| { - let view = data.value("view", PreviewView::fitting()); + let (view, view_at) = data.value_at("view", PreviewView::fitting()); let mut outs = Vec::new(); for at in 0..COUNT { let rect = survey_cell(COUNT, at, area, ASPECT, rtl); let name = format!("IMG_{at:04}.jpg"); - let out = CompareTile::new(name.clone(), Bind::bound(view), image(at as u64)) + let out = CompareTile::new(name.clone(), view_at.bind(view), image(at as u64)) .caption(CompareCaption::new("", name)) .survey(true) .place(ui, rect); diff --git a/crates/browse/src/ui/places/stories.rs b/crates/browse/src/ui/places/stories.rs index afaadc74c..b43bfd15f 100644 --- a/crates/browse/src/ui/places/stories.rs +++ b/crates/browse/src/ui/places/stories.rs @@ -162,8 +162,9 @@ fn show_places(ui: &mut Ui, data: &mut StoryData, setup: Setup) -> StoryOutput { }) .clone(); let mut demo = demo.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // The framework's repaint runs the story's view again, where the next jobs run. if !setup.slow && demo.jobs.run_all() > 0 { - ctx.request_repaint(); + craft_ui::runtime::frame::request_repaint(&ctx); } let current = demo.current.clone(); let places = { diff --git a/crates/browse/src/ui/relink/badge.rs b/crates/browse/src/ui/relink/badge.rs index b1981a39d..574bb0958 100644 --- a/crates/browse/src/ui/relink/badge.rs +++ b/crates/browse/src/ui/relink/badge.rs @@ -22,7 +22,7 @@ const BANG_DROP: f32 = 0.09375; const BAN_RING: f32 = 0.55; /// A status badge drawn from the theme: a solid shape in the status colour with its mark in `text.on_status`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)] enum StatusGlyph { /// A `status.bad.solid` disc with `?`. Missing, diff --git a/crates/browse/src/ui/relink/stories.rs b/crates/browse/src/ui/relink/stories.rs index 690c2260c..c31fc41bd 100644 --- a/crates/browse/src/ui/relink/stories.rs +++ b/crates/browse/src/ui/relink/stories.rs @@ -13,7 +13,7 @@ use craft_behavior::Selection; use craft_docpath::Refused; use craft_docpath::links::{FakeLinkFiles, Link, LinkIdentity, LinkStatus, identity_of}; use craft_host::{Jobs, ManualJobs}; -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::dialog::{DialogStack, StackDialog as _}; use craft_ui::display::Text; use craft_ui::list::ThumbSize; @@ -68,7 +68,7 @@ fn links() -> (Vec>, HashMap) { } fn list_story(ui: &mut Ui, data: &mut StoryData, links: &[Link], statuses: &HashMap) -> StoryOutput { - let state = data.value( + let (state, state_at) = data.value_at( "state", LinkListState { selection: Selection::single(2), @@ -80,7 +80,7 @@ fn list_story(ui: &mut Ui, data: &mut StoryData, links: &[Link], statuses: let info = lead.map_or_else(|| words.info_none.as_str().to_owned(), |link| words.info_path.fill(&[("path", &link.stored)])); let thumbs = Thumbnails::::in_context(ui.ctx(), "craft-browse-link-list-story", ThumbnailOptions::new()); let pictures = FakeThumbSource::::new().aspect(4, 3); - LinkList::new("Links", links, statuses, Bind::bound(state)) + LinkList::new("Links", links, statuses, state_at.bind(state)) .thumbnails(&thumbs, &pictures) .info(move |ui| { Text::new(info.clone()).show(ui); @@ -156,10 +156,11 @@ fn dialog_story(ui: &mut Ui, data: &mut StoryData, search: bool, finish: bool) - if search && !*started { *started = true; dialog.begin_search(); - ui.ctx().request_repaint(); + craft_ui::runtime::frame::request_repaint(ui.ctx()); } + // The framework's repaint runs the story's view again, where the next jobs run. if finish && demo.jobs.run_all() > 0 { - ui.ctx().request_repaint(); + craft_ui::runtime::frame::request_repaint(ui.ctx()); } StoryOutput::default() } diff --git a/crates/color-ui/src/ui/area/stories.rs b/crates/color-ui/src/ui/area/stories.rs index a78116c23..c31c37e72 100644 --- a/crates/color-ui/src/ui/area/stories.rs +++ b/crates/color-ui/src/ui/area/stories.rs @@ -3,7 +3,7 @@ use super::{AreaShape, ColorArea}; use crate::AreaMode; use craft_theme::{ColorModel, HsbModel, Srgba}; -use craft_ui::contract::{Bind, Props as _, Show as _, Validity}; +use craft_ui::contract::{Props as _, Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use craft_ui::value_drag::PointPicker; @@ -13,33 +13,33 @@ use egui::Ui; /// shows inside itself. #[story(ColorArea<'static>, covers = [Default], drive = Drive::DragChild(Grip::new(PointPicker::WELL)))] fn color_area(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values)).show(ui).into() } /// The Color Picker dialog's field: a square, `size.plot.width` on a side. #[story(ColorArea<'static>, covers = [], drive = Drive::Never)] fn color_area_square(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).shape(AreaShape::Square).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values)).shape(AreaShape::Square).show(ui).into() } #[story(ColorArea<'static>, covers = [], drive = Drive::Never)] fn color_area_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8))); - ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).quantize(6).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8))); + ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values)).quantize(6).show(ui).into() } #[story(ColorArea<'static>, covers = [Invalid], drive = Drive::Never)] fn color_area_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_dim = |values: &craft_theme::ModelValues| if values.values[2] < 50.0 { Validity::Refuse(Message::new("Too dim")) } else { Validity::Ok }; - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3))); - ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values).check(refuse_dim)).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3))); + ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values).check(refuse_dim)).show(ui).into() } #[story(ColorArea<'static>, covers = [], drive = Drive::Never)] fn color_area_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).enabled(false).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values)).enabled(false).show(ui).into() } diff --git a/crates/color-ui/src/ui/disc/stories.rs b/crates/color-ui/src/ui/disc/stories.rs index ccf1d9d8a..7124d4a23 100644 --- a/crates/color-ui/src/ui/disc/stories.rs +++ b/crates/color-ui/src/ui/disc/stories.rs @@ -2,7 +2,7 @@ use super::{ColorDisc, DiscMove, MARKER}; use craft_theme::Srgba; -use craft_ui::contract::{Bind, Props as _, Show as _, Validity}; +use craft_ui::contract::{Props as _, Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::Ui; @@ -11,19 +11,19 @@ const MARKERS: [Srgba; 3] = [Srgba::rgb(0.9, 0.2, 0.2), Srgba::rgb(0.2, 0.7, 0.4 #[story(ColorDisc<'static>, covers = [Default], drive = Drive::Drag(Grip::part(MARKER.at(1))))] fn color_disc(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let moved = data.value("move", DiscMove::new(0, 0.0, 0.7)); - ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).chosen(1).show(ui).into() + let (moved, moved_at) = data.value_at("move", DiscMove::new(0, 0.0, 0.7)); + ColorDisc::new("Harmony", &MARKERS, moved_at.bind(moved)).chosen(1).show(ui).into() } #[story(ColorDisc<'static>, covers = [Invalid], drive = Drive::Never)] fn color_disc_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_pale = |moved: &DiscMove| if moved.saturation < 0.5 { Validity::Refuse(Message::new("Too pale")) } else { Validity::Ok }; - let moved = Bind::bound(data.value("pale", DiscMove::new(1, 0.0, 0.2))).check(refuse_pale); + let moved = data.bind("pale", DiscMove::new(1, 0.0, 0.2)).check(refuse_pale); ColorDisc::new("Harmony", &MARKERS, moved).chosen(1).show(ui).into() } #[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Disabled")] fn color_disc_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let moved = data.value("move", DiscMove::new(0, 0.0, 0.7)); - ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).chosen(1).enabled(false).show(ui).into() + let (moved, moved_at) = data.value_at("move", DiscMove::new(0, 0.0, 0.7)); + ColorDisc::new("Harmony", &MARKERS, moved_at.bind(moved)).chosen(1).enabled(false).show(ui).into() } diff --git a/crates/color-ui/src/ui/droppers/stories.rs b/crates/color-ui/src/ui/droppers/stories.rs index 4fcc7df7e..cfc5d02c6 100644 --- a/crates/color-ui/src/ui/droppers/stories.rs +++ b/crates/color-ui/src/ui/droppers/stories.rs @@ -1,13 +1,12 @@ //! Stories of `DropperButton`. use super::{DropperButton, DropperKind}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; fn button(ui: &mut Ui, data: &mut StoryData, kind: DropperKind, armed: bool) -> StoryOutput { - let armed = data.value("armed", armed); - StoryOutput::from(DropperButton::new("Sample in image", Bind::bound(armed)).kind(kind).show(ui)) + let (armed, armed_at) = data.value_at("armed", armed); + StoryOutput::from(DropperButton::new("Sample in image", armed_at.bind(armed)).kind(kind).show(ui)) } #[story(DropperButton<'static>, covers = [], drive = Drive::Never)] diff --git a/crates/color-ui/src/ui/eyedropper/stories.rs b/crates/color-ui/src/ui/eyedropper/stories.rs index 51d0565e0..a53ff2ed0 100644 --- a/crates/color-ui/src/ui/eyedropper/stories.rs +++ b/crates/color-ui/src/ui/eyedropper/stories.rs @@ -2,14 +2,14 @@ use super::{EyedropperBar, EyedropperOptions, SampleSize, SampleSizeSelect}; use craft_ui::bars::{Bar, BarKind}; -use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::contract::ShowContainer as _; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; #[story(SampleSizeSelect<'static>, covers = [], drive = Drive::Never)] fn sample_size_select(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let size = data.value("size", SampleSize::Point); - StoryOutput::from(SampleSizeSelect::new(Bind::bound(size)).show(ui)) + let (size, size_at) = data.value_at("size", SampleSize::Point); + StoryOutput::from(SampleSizeSelect::new(size_at.bind(size)).show(ui)) } #[story(EyedropperBar<'static>, covers = [], drive = Drive::Never)] diff --git a/crates/color-ui/src/ui/gradient/editor/stories.rs b/crates/color-ui/src/ui/gradient/editor/stories.rs index e9aecfe33..47f8b80dc 100644 --- a/crates/color-ui/src/ui/gradient/editor/stories.rs +++ b/crates/color-ui/src/ui/gradient/editor/stories.rs @@ -3,7 +3,6 @@ use super::{GradientEditor, GradientEditorOutput}; use crate::ui::gradient::{ColorStop, GradientStops, OpacityStop, StopRef, StopRows, StopRules}; use craft_theme::Srgba; -use craft_ui::contract::Bind; use craft_ui::runtime::env::Env; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -56,34 +55,34 @@ fn combined() -> GradientStops { #[story(GradientEditor<'static, u8>, covers = [Default], drive = Drive::Never)] fn gradient_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let stops = data.value("stops", split()); - let output = GradientEditor::new("Gradient", Bind::bound(stops)).show(ui); + let (stops, stops_at) = data.value_at("stops", split()); + let output = GradientEditor::new("Gradient", stops_at.bind(stops)).show(ui); hinted(ui, data, output) } #[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never)] fn gradient_editor_combined(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let stops = data.value("stops", combined()); - let output = GradientEditor::new("Gradient", Bind::bound(stops)).rules(StopRules::new(StopRows::Combined)).show(ui); + let (stops, stops_at) = data.value_at("stops", combined()); + let output = GradientEditor::new("Gradient", stops_at.bind(stops)).rules(StopRules::new(StopRows::Combined)).show(ui); hinted(ui, data, output) } #[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never)] fn gradient_editor_color_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let stops = data.value("stops", GradientStops::new(vec![color(0.0, [0.0, 0.0, 0.0]), color(1.0, [1.0, 1.0, 1.0])])); - GradientEditor::new("Gradient map", Bind::bound(stops)).rules(StopRules::new(StopRows::ColorOnly).stops(2, 64)).show(ui).into() + let (stops, stops_at) = data.value_at("stops", GradientStops::new(vec![color(0.0, [0.0, 0.0, 0.0]), color(1.0, [1.0, 1.0, 1.0])])); + GradientEditor::new("Gradient map", stops_at.bind(stops)).rules(StopRules::new(StopRows::ColorOnly).stops(2, 64)).show(ui).into() } /// The colour popover on, a colour stop selected. #[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never)] fn gradient_editor_popover(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (stops, selected) = data.value("state", (split(), Some(StopRef::Color(0)))); - let output = GradientEditor::new("Gradient", Bind::bound(stops)).color_popover(true).shared_selection(Bind::bound(selected)).show(ui); + let ((stops, selected), state_at) = data.value_at("state", (split(), Some(StopRef::Color(0)))); + let output = GradientEditor::new("Gradient", state_at.bind(stops)).color_popover(true).shared_selection(state_at.bind(selected)).show(ui); hinted(ui, data, output) } #[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never, title = "Disabled")] fn gradient_editor_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let stops = data.value("stops", split()); - GradientEditor::new("Gradient", Bind::bound(stops)).enabled(false).show(ui).into() + let (stops, stops_at) = data.value_at("stops", split()); + GradientEditor::new("Gradient", stops_at.bind(stops)).enabled(false).show(ui).into() } diff --git a/crates/color-ui/src/ui/harmony/stories.rs b/crates/color-ui/src/ui/harmony/stories.rs index 72866abca..9e201fce9 100644 --- a/crates/color-ui/src/ui/harmony/stories.rs +++ b/crates/color-ui/src/ui/harmony/stories.rs @@ -3,7 +3,7 @@ use super::{HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel}; use crate::harmony::Harmony; use craft_theme::Srgba; -use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::contract::ShowContainer as _; use craft_ui::layout_components::Stack; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -12,13 +12,13 @@ const BASE: Srgba = Srgba::rgb(0.86, 0.24, 0.16); #[story(HarmonyPanel<'static>, covers = [], drive = Drive::Never)] fn harmony_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (state, picked) = data.value("guide", (triad(), HarmonyPicked::default())); + let ((state, picked), guide_at) = data.value_at("guide", (triad(), HarmonyPicked::default())); let colors = state.rule.apply(BASE); // The wheel above the panel shows the panel's rule on the base colour, as a Color Guide works with the wheel. Stack::new() .show(ui, |ui, _| { let _ = HarmonyWheel::new("Harmony", &colors).selected_marker(Some(0)).show(ui); - StoryOutput::from(HarmonyPanel::new(Bind::bound(&mut *state), Bind::bound(&mut *picked), BASE).show(ui)) + StoryOutput::from(HarmonyPanel::new(guide_at.bind(&mut *state), guide_at.bind(&mut *picked), BASE).show(ui)) }) .inner .unwrap_or_default() diff --git a/crates/color-ui/src/ui/lut_picker/stories.rs b/crates/color-ui/src/ui/lut_picker/stories.rs index 4ebef50f1..ad5a24abe 100644 --- a/crates/color-ui/src/ui/lut_picker/stories.rs +++ b/crates/color-ui/src/ui/lut_picker/stories.rs @@ -1,7 +1,7 @@ //! Stories of the LUT picker. use super::{LutChoice, LutPicker}; -use craft_ui::contract::{Bind, Props as _, Role, Show as _, Validity}; +use craft_ui::contract::{Props as _, Role, Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::{Key, Modifiers, Ui}; @@ -19,14 +19,14 @@ fn pick_second(fixture: &mut Fixture) { #[story(LutPicker<'static>, covers = [Default], drive = Drive::Custom(pick_second))] fn lut_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let shown = LutPicker::new(Bind::bound(data.value("lut", LutChoice::Builtin("warm")))).label("3D LUT File").show(ui); + let shown = LutPicker::new(data.bind("lut", LutChoice::Builtin("warm"))).label("3D LUT File").show(ui); let chosen = format!("Chosen: {:?}", data.value("lut", LutChoice::Builtin("warm"))); StoryOutput::from(shown).readout(chosen) } #[story(LutPicker<'static>, covers = [], drive = Drive::Never)] fn lut_picker_loaded(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let shown = LutPicker::new(Bind::bound(data.value("lut", LutChoice::loaded("Film", 33)))).label("3D LUT File").show(ui); + let shown = LutPicker::new(data.bind("lut", LutChoice::loaded("Film", 33))).label("3D LUT File").show(ui); let chosen = format!("Chosen: {:?}", data.value("lut", LutChoice::loaded("Film", 33))); StoryOutput::from(shown).readout(chosen) } @@ -37,7 +37,7 @@ fn lut_picker_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { LutChoice::Builtin(_) => Validity::Refuse(Message::new("Load a file")), _ => Validity::Ok, }; - let shown = LutPicker::new(Bind::bound(data.value("lut", LutChoice::Builtin("warm"))).check(refuse_builtin)).label("3D LUT File").show(ui); + let shown = LutPicker::new(data.bind("lut", LutChoice::Builtin("warm")).check(refuse_builtin)).label("3D LUT File").show(ui); let chosen = format!("Chosen: {:?}", data.value("lut", LutChoice::Builtin("warm"))); StoryOutput::from(shown).readout(chosen) } diff --git a/crates/color-ui/src/ui/paint_chip/stories.rs b/crates/color-ui/src/ui/paint_chip/stories.rs index ced50b8e4..576037f00 100644 --- a/crates/color-ui/src/ui/paint_chip/stories.rs +++ b/crates/color-ui/src/ui/paint_chip/stories.rs @@ -36,8 +36,8 @@ const BLUE: Srgba = Srgba::rgb(0.2, 0.4, 0.8); fn chip(ui: &mut Ui, data: &mut StoryData, paint: Paint) -> StoryOutput { let stops = vec![(0.0, BLUE), (1.0, Srgba::rgb(1.0, 1.0, 1.0))]; - let held = data.value("paint", paint); - PaintChip::new("Fill", Bind::bound(held), BLUE).gradient_editor(GradientPreview::new(stops), |_: &mut Ui| None).show(ui).into() + let (held, held_at) = data.value_at("paint", paint); + PaintChip::new("Fill", held_at.bind(held), BLUE).gradient_editor(GradientPreview::new(stops), |_: &mut Ui| None).show(ui).into() } /// A fill, a gradient fill and a stroke with no colour, in one column; the drives use the first. @@ -60,8 +60,8 @@ fn paint_chip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(PaintChip<'static>, covers = [Mixed], drive = Drive::Never)] fn paint_chip_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let held = data.value("mixed", Mixed::::Mixed); - PaintChip::new("Fill", Bind::bound_mixed(held), BLUE).show(ui).into() + let (held, held_at) = data.value_at("mixed", Mixed::::Mixed); + PaintChip::new("Fill", held_at.bind_mixed(held), BLUE).show(ui).into() } #[story(PaintChip<'static>, covers = [Open], drive = Drive::Custom(open_popover))] @@ -81,8 +81,8 @@ fn paint_chip_open_with_recents_and_swatches(ui: &mut Ui, data: &mut StoryData) SwatchGroup { name: "Pastels".to_owned(), entries: vec![entry("Rose", [1.0, 0.8, 0.85]), entry("Mint", [0.75, 1.0, 0.85])] }, ]; let recent = [BLUE, Srgba::rgb(0.9, 0.5, 0.1), Srgba::rgb(0.1, 0.6, 0.3)]; - let (held, folders) = data.value("state", (Paint::Solid(BLUE), PresetState::::new())); - PaintChip::new("Fill", Bind::bound(held), BLUE).recent(&recent).swatches(&groups, Bind::bound(folders)).full_picker(true).show(ui).into() + let ((held, folders), state_at) = data.value_at("state", (Paint::Solid(BLUE), PresetState::::new())); + PaintChip::new("Fill", state_at.bind(held), BLUE).recent(&recent).swatches(&groups, state_at.bind(folders)).full_picker(true).show(ui).into() } #[story(PaintChip<'static>, covers = [], drive = Drive::Never)] @@ -102,8 +102,8 @@ fn paint_chip_pattern(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(PaintChip<'static>, covers = [], drive = Drive::Never)] fn paint_chip_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let held = data.value("paint", Paint::Solid(Srgba { r: 0.9, g: 0.2, b: 0.2, a: 0.6 })); - PaintChip::new("Fill", Bind::bound(held), BLUE).enabled(false).show(ui).into() + let (held, held_at) = data.value_at("paint", Paint::Solid(Srgba { r: 0.9, g: 0.2, b: 0.2, a: 0.6 })); + PaintChip::new("Fill", held_at.bind(held), BLUE).enabled(false).show(ui).into() } fn paints() -> Vec<(String, Paint)> { @@ -118,14 +118,14 @@ fn paints() -> Vec<(String, Paint)> { #[story(PaintList<'static>, covers = [Default], drive = Drive::Never)] fn paint_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let paints = paints(); - PaintList::new("Paints", &paints, Bind::bound(data.value("selected", None::))).show(ui).into() + PaintList::new("Paints", &paints, data.bind("selected", None::)).show(ui).into() } #[story(PaintList<'static>, covers = [], drive = Drive::Never)] fn paint_list_selection_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let paints = paints(); let rows = [PaintRow::linked(PaintLink::new("Primary / Blue", PaintLinkKind::Style))]; - PaintList::new("Selection colors", &paints, Bind::bound(data.value("selected", Some(0usize)))) + PaintList::new("Selection colors", &paints, data.bind("selected", Some(0usize))) .options(PaintListOptions { select_users: true, bind: true, remove: true, add: true, ..PaintListOptions::SELECTION_COLORS }) .rows(&rows) .show(ui) @@ -135,6 +135,6 @@ fn paint_list_selection_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput #[story(PaintChip<'static>, covers = [Invalid], drive = Drive::Never)] fn paint_chip_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_none = |paint: &Paint| if matches!(paint, Paint::None) { Validity::Refuse(Message::new("A fill is required")) } else { Validity::Ok }; - let held = Bind::bound(data.value("paint", Paint::None)).check(refuse_none); + let held = data.bind("paint", Paint::None).check(refuse_none); PaintChip::new("Fill", held, BLUE).show(ui).into() } diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 3b1204c6d..cc5779017 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -564,7 +564,7 @@ fn outline(at: Rect, style: &SwatchPairStyle) -> PaintShape { /// The glyphs of the pair's buttons, drawn on a square grid of `GRID` units; they picture the pair, so they mirror /// with it. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, craft_ui::contract::MemoProps)] enum PairGlyph { /// Default colours: a black square over a white one, as the wells stand. Defaults, diff --git a/crates/color-ui/src/ui/pair/stories.rs b/crates/color-ui/src/ui/pair/stories.rs index 69b07c192..3941bdef6 100644 --- a/crates/color-ui/src/ui/pair/stories.rs +++ b/crates/color-ui/src/ui/pair/stories.rs @@ -3,7 +3,7 @@ use super::{PairWell, SwatchPair, Well}; use craft_behavior::Mixed; use craft_theme::Srgba; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -34,10 +34,10 @@ struct Colors { /// popup's picker edits the well it opened on. With `ring` the secondary well is a ring, as DesignCraft's stroke. fn editing(ui: &mut Ui, data: &mut StoryData, names: [&'static str; 2], start: [Srgba; 2], ring: bool) -> StoryOutput { let defaults = [Srgba::rgb(0.0, 0.0, 0.0), Srgba::rgb(1.0, 1.0, 1.0)]; - let state = data.value("colors", Colors { active: Well::Primary, colors: start }); + let (state, state_at) = data.value_at("colors", Colors { active: Well::Primary, colors: start }); let wells = [PairWell::new(names[0], state.colors[0]), PairWell::new(names[1], state.colors[1]).ring(ring)]; let shown = - SwatchPair::new("Colours", wells, Bind::bound(&mut state.active)).swap_button("Swap colours").default_button("Default colours").show(ui); + SwatchPair::new("Colours", wells, state_at.bind(&mut state.active)).swap_button("Swap colours").default_button("Default colours").show(ui); if shown.swap { state.colors.swap(0, 1); } @@ -69,13 +69,13 @@ fn swatch_pair_ring(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] fn swatch_pair_host_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).popover(false).click_activates(false).show(ui).into() + SwatchPair::new("Colours", wells(false), data.bind("active", Well::Primary)).popover(false).click_activates(false).show(ui).into() } #[story(SwatchPair<'static>, covers = [Mixed], drive = Drive::Never)] fn swatch_pair_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let wells = [PairWell::new("Fill", Mixed::::Mixed), PairWell::new("Stroke", Srgba::rgb(0.1, 0.3, 0.8)).ring(true)]; - SwatchPair::new("Fill and stroke", wells, Bind::bound(data.value("active", Well::Primary))).show(ui).into() + SwatchPair::new("Fill and stroke", wells, data.bind("active", Well::Primary)).show(ui).into() } /// Opens the picker of the focused well with Enter. @@ -87,26 +87,26 @@ fn open_picker(fixture: &mut Fixture) { #[story(SwatchPair<'static>, covers = [Open], drive = Drive::Custom(open_picker))] fn swatch_pair_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).show(ui).into() + SwatchPair::new("Colours", wells(false), data.bind("active", Well::Primary)).show(ui).into() } #[story(SwatchPair<'static>, covers = [Invalid], drive = Drive::Never)] fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_secondary = |well: &Well| if *well == Well::Secondary { Validity::Refuse(Message::new("Only the foreground can be edited")) } else { Validity::Ok }; - SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Secondary)).check(refuse_secondary)).show(ui).into() + SwatchPair::new("Colours", wells(false), data.bind("active", Well::Secondary).check(refuse_secondary)).show(ui).into() } /// The pair in a tool rail's footer, as PhotoCraft's colour chips: the gap round the front well takes the rail's chrome. #[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let active = data.value("active", Well::Primary); + let (active, active_at) = data.value_at("active", Well::Primary); let (slots, last): (Vec>, LastUsed) = (Vec::new(), LastUsed::default()); let wells = [PairWell::new("Foreground colour", Srgba::rgb(0.0, 0.0, 0.0)), PairWell::new("Background colour", Srgba::rgb(1.0, 1.0, 1.0))]; let mut shown = None; ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| { shown = Some( - SwatchPair::new("Colours", wells.clone(), Bind::bound(&mut *active)) + SwatchPair::new("Colours", wells.clone(), active_at.bind(&mut *active)) .popover(false) .swap_button("Swap colours") .default_button("Default colours") diff --git a/crates/color-ui/src/ui/palette/stories.rs b/crates/color-ui/src/ui/palette/stories.rs index 16b2eaf88..cd6cfc72b 100644 --- a/crates/color-ui/src/ui/palette/stories.rs +++ b/crates/color-ui/src/ui/palette/stories.rs @@ -2,7 +2,6 @@ use super::SwatchPalette; use craft_theme::Srgba; -use craft_ui::contract::Bind; use craft_ui::runtime::env::Label; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -30,7 +29,7 @@ fn named(entries: impl IntoIterator) -> Vec<(Label, Srgb #[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)] fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color))); - let shown = SwatchPalette::new("Swatches", Bind::bound(data.value("color", PALETTE[8].1)), &swatches).show(ui); + let shown = SwatchPalette::new("Swatches", data.bind("color", PALETTE[8].1), &swatches).show(ui); let last = data.note("last", String::new()); if let Some(event) = &shown.edit { *last = format!("{event:?}"); diff --git a/crates/color-ui/src/ui/panel/stories.rs b/crates/color-ui/src/ui/panel/stories.rs index 40a9e5c87..23e32da68 100644 --- a/crates/color-ui/src/ui/panel/stories.rs +++ b/crates/color-ui/src/ui/panel/stories.rs @@ -2,7 +2,6 @@ use super::{ColorPanel, ColorPanelMode, ColorPanelRamp, ColorPanelState}; use craft_theme::Srgba; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -10,7 +9,7 @@ use egui::Ui; const COLORS: [Srgba; 2] = [Srgba::rgb(0.07, 0.65, 0.58), Srgba::rgb(1.0, 1.0, 1.0)]; fn panel(ui: &mut Ui, data: &mut StoryData, state: ColorPanelState) -> StoryOutput { - ColorPanel::new(Bind::bound(data.value("state", state)), COLORS).show(ui).into() + ColorPanel::new(data.bind("state", state), COLORS).show(ui).into() } #[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] diff --git a/crates/color-ui/src/ui/picker/stories.rs b/crates/color-ui/src/ui/picker/stories.rs index 5918102c3..8fcceccf1 100644 --- a/crates/color-ui/src/ui/picker/stories.rs +++ b/crates/color-ui/src/ui/picker/stories.rs @@ -114,16 +114,16 @@ fn start() -> PickedColor { /// The compact popup's picker: the default models and the screen-pick button. #[story(ColorPicker<'static>, covers = [Default], drive = Drive::Never)] fn color_picker_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let color = data.value("color", start()); - let shown = ColorPicker::new("Foreground color", Bind::bound(color)).eyedropper(true).show(ui); + let (color, color_at) = data.value_at("color", start()); + let shown = ColorPicker::new("Foreground color", color_at.bind(color)).eyedropper(true).show(ui); with_readout(data, shown) } /// The compact picker with the opacity row. #[story(ColorPicker<'static>, covers = [], drive = Drive::Never)] fn color_picker_compact_alpha(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let color = data.value("color", start()); - let shown = ColorPicker::new("Foreground color", Bind::bound(color)).alpha(true).eyedropper(true).show(ui); + let (color, color_at) = data.value_at("color", start()); + let shown = ColorPicker::new("Foreground color", color_at.bind(color)).alpha(true).eyedropper(true).show(ui); with_readout(data, shown) } @@ -132,8 +132,8 @@ fn color_picker_compact_alpha(ui: &mut Ui, data: &mut StoryData) -> StoryOutput fn color_picker_web_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let web = *data.value("web", true); let mut web = web; - let color = data.value("color", start()); - let shown = ColorPicker::new("Foreground color", Bind::bound(color)).web_colors(Bind::bound(&mut web)).show(ui); + let (color, color_at) = data.value_at("color", start()); + let shown = ColorPicker::new("Foreground color", color_at.bind(color)).web_colors(Bind::bound(&mut web)).show(ui); with_readout(data, shown) } @@ -143,9 +143,9 @@ fn color_picker_web_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn color_picker_full(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut mode = *data.value("mode", AreaMode::default()); let current = Srgba::rgb(0.9, 0.2, 0.1); - let color = data.value("color", PickedColor::rgb(Srgba::rgb(1.0, 0.0, 1.0))); + let (color, color_at) = data.value_at("color", PickedColor::rgb(Srgba::rgb(1.0, 0.0, 1.0))); let models: [&'static dyn ColorModel; 4] = [&HsbModel, &RgbModel, &LabModel, &CMYK_MODEL]; - let shown = ColorPicker::new("Foreground color", Bind::bound(color)) + let shown = ColorPicker::new("Foreground color", color_at.bind(color)) .layout(ColorPickerLayout::Full) .models(models) .mode(Bind::bound(&mut mode)) @@ -162,9 +162,9 @@ fn color_picker_full(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// An InDesign-like model set: RGB in the first group; Lab, OKLCH (with its radios) and the host's CMYK in the second. #[story(ColorPicker<'static>, covers = [Many], drive = Drive::Never)] fn color_picker_full_models(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let color = data.value("color", start()); + let (color, color_at) = data.value_at("color", start()); let models: [&'static dyn ColorModel; 4] = [&RgbModel, &LabModel, &OklchModel, &CMYK_MODEL]; - let shown = ColorPicker::new("Foreground color", Bind::bound(color)).layout(ColorPickerLayout::Full).models(models).show(ui); + let shown = ColorPicker::new("Foreground color", color_at.bind(color)).layout(ColorPickerLayout::Full).models(models).show(ui); with_readout(data, shown) } @@ -187,9 +187,9 @@ fn track_ramp(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(ChannelRow<'static>, covers = [], drive = Drive::Never)] fn channel_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("value", 40.0_f64); + let (value, value_at) = data.value_at("value", 40.0_f64); let channel = HsbModel.channels()[1]; - let row = ChannelRow::new("Saturation", Bind::bound(value), ChannelRule::of(&channel)) + let row = ChannelRow::new("Saturation", value_at.bind(value), ChannelRule::of(&channel)) .track(vec![Srgba::rgb(1.0, 1.0, 1.0), Srgba::rgb(1.0, 0.0, 0.0)]); match row.show(ui) { Some(edit) => StoryOutput::from(edit), diff --git a/crates/color-ui/src/ui/popover/stories.rs b/crates/color-ui/src/ui/popover/stories.rs index c6e347900..f3b28f934 100644 --- a/crates/color-ui/src/ui/popover/stories.rs +++ b/crates/color-ui/src/ui/popover/stories.rs @@ -16,15 +16,15 @@ fn picked() -> PickedColor { #[story(ColorPopover<'static>, covers = [Default], drive = Drive::Never)] fn closed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - StoryOutput::from(ColorPopover::new("Fill colour", Bind::bound(data.value("color", picked()))).show(ui)) + StoryOutput::from(ColorPopover::new("Fill colour", data.bind("color", picked())).show(ui)) } #[story(ColorPopover<'static>, covers = [], drive = Drive::Never)] fn open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let color = data.value("color", picked()); + let (color, color_at) = data.value_at("color", picked()); let shown = Stack::new().show(ui, |ui, _| { let opener = Button::new("Stop").show(ui); - ColorPopover::new("Stop colour", Bind::bound(&mut *color)).anchor(&opener, Bind::given(true)).show(ui) + ColorPopover::new("Stop colour", color_at.bind(&mut *color)).anchor(&opener, Bind::given(true)).show(ui) }); match shown.inner { Some(output) => StoryOutput::from(output), diff --git a/crates/color-ui/src/ui/ramp/stories.rs b/crates/color-ui/src/ui/ramp/stories.rs index 88c7717b1..1c83c2142 100644 --- a/crates/color-ui/src/ui/ramp/stories.rs +++ b/crates/color-ui/src/ui/ramp/stories.rs @@ -2,7 +2,7 @@ use super::{ColorRamp, RampKind, RampPick}; use craft_theme::Srgba; -use craft_ui::contract::{Bind, Props as _, Show as _, Validity}; +use craft_ui::contract::{Props as _, Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::Ui; @@ -13,17 +13,17 @@ fn pick() -> RampPick { #[story(ColorRamp<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::BAR)))] fn color_ramp(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", pick()))).kind_name("RGB Spectrum").show(ui).into() + ColorRamp::new("Color ramp", RampKind::Spectrum, data.bind("pick", pick())).kind_name("RGB Spectrum").show(ui).into() } #[story(ColorRamp<'static>, covers = [], drive = Drive::Never)] fn color_ramp_grayscale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - ColorRamp::new("Color ramp", RampKind::Grayscale, Bind::bound(data.value("pick", pick()))).kind_name("Grayscale").show(ui).into() + ColorRamp::new("Color ramp", RampKind::Grayscale, data.bind("pick", pick())).kind_name("Grayscale").show(ui).into() } #[story(ColorRamp<'static>, covers = [], drive = Drive::Never)] fn color_ramp_between(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - ColorRamp::new("Color ramp", RampKind::Between, Bind::bound(data.value("pick", pick()))) + ColorRamp::new("Color ramp", RampKind::Between, data.bind("pick", pick())) .ends([Srgba::rgb(0.9, 0.2, 0.1), Srgba::rgb(0.1, 0.3, 0.9)]) .kind_name("Foreground to background") .show(ui) @@ -32,20 +32,17 @@ fn color_ramp_between(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(ColorRamp<'static>, covers = [], drive = Drive::Never)] fn color_ramp_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", pick()))).web_safe(true).kind_name("Web colors").show(ui).into() + ColorRamp::new("Color ramp", RampKind::Spectrum, data.bind("pick", pick())).web_safe(true).kind_name("Web colors").show(ui).into() } #[story(ColorRamp<'static>, covers = [Invalid], drive = Drive::Never)] fn color_ramp_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_dark = |pick: &RampPick| if pick.color.b < 0.5 { Validity::Refuse(Message::new("Too dark")) } else { Validity::Ok }; let dark = RampPick::new(Srgba::rgb(0.1, 0.1, 0.1), false); - ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", dark)).check(refuse_dark)) - .kind_name("RGB Spectrum") - .show(ui) - .into() + ColorRamp::new("Color ramp", RampKind::Spectrum, data.bind("pick", dark).check(refuse_dark)).kind_name("RGB Spectrum").show(ui).into() } #[story(ColorRamp<'static>, covers = [], drive = Drive::Never, title = "Disabled")] fn color_ramp_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", pick()))).kind_name("RGB Spectrum").enabled(false).show(ui).into() + ColorRamp::new("Color ramp", RampKind::Spectrum, data.bind("pick", pick())).kind_name("RGB Spectrum").enabled(false).show(ui).into() } diff --git a/crates/color-ui/src/ui/readout/stories.rs b/crates/color-ui/src/ui/readout/stories.rs index 360df1838..05a68d780 100644 --- a/crates/color-ui/src/ui/readout/stories.rs +++ b/crates/color-ui/src/ui/readout/stories.rs @@ -2,7 +2,7 @@ use craft_behavior::Mixed; use craft_theme::Rgba; -use craft_ui::contract::{Bind, Validity}; +use craft_ui::contract::Validity; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -11,19 +11,19 @@ use super::ColorReadout; #[story(ColorReadout<'static>, covers = [Default], drive = Drive::Never)] fn color_readout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let color = data.value("color", Rgba::rgb(0x33, 0x66, 0x99)); - ColorReadout::new("Color", Bind::bound(color)).show(ui).into() + let (color, color_at) = data.value_at("color", Rgba::rgb(0x33, 0x66, 0x99)); + ColorReadout::new("Color", color_at.bind(color)).show(ui).into() } #[story(ColorReadout<'static>, covers = [], drive = Drive::Never)] fn color_readout_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let color = data.value("mixed", Mixed::::Mixed); - ColorReadout::new("Color", Bind::bound_mixed(color)).show(ui).into() + let (color, color_at) = data.value_at("mixed", Mixed::::Mixed); + ColorReadout::new("Color", color_at.bind_mixed(color)).show(ui).into() } #[story(ColorReadout<'static>, covers = [Invalid], drive = Drive::Never)] fn color_readout_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_dark = |color: &Rgba| if color.0[2] < 0x80 { Validity::Refuse(Message::new("Too dark")) } else { Validity::Ok }; - let color = data.value("dark", Rgba::rgb(0x33, 0x33, 0x33)); - ColorReadout::new("Color", Bind::bound(color).check(refuse_dark)).show(ui).into() + let (color, color_at) = data.value_at("dark", Rgba::rgb(0x33, 0x33, 0x33)); + ColorReadout::new("Color", color_at.bind(color).check(refuse_dark)).show(ui).into() } diff --git a/crates/color-ui/src/ui/samplers/stories.rs b/crates/color-ui/src/ui/samplers/stories.rs index 76d4cefd3..741608b61 100644 --- a/crates/color-ui/src/ui/samplers/stories.rs +++ b/crates/color-ui/src/ui/samplers/stories.rs @@ -97,9 +97,8 @@ fn sample_points_carrying_a_new_point(ui: &mut Ui, _: &mut StoryData) -> StoryOu #[story(SamplerOptions<'static>, covers = [], drive = Drive::Never)] fn options(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let size = data.value("size", crate::ui::SampleSize::Point); - let shown = - Bar::new("Color sampler options", BarKind::Options).show(ui, |ui, _| SamplerOptions::new(3, craft_ui::contract::Bind::bound(size)).show(ui)); + let (size, size_at) = data.value_at("size", crate::ui::SampleSize::Point); + let shown = Bar::new("Color sampler options", BarKind::Options).show(ui, |ui, _| SamplerOptions::new(3, size_at.bind(size)).show(ui)); match shown.inner { Some(output) => StoryOutput::from(output), None => StoryOutput::from(shown.output), diff --git a/crates/color-ui/src/ui/strip/stories.rs b/crates/color-ui/src/ui/strip/stories.rs index b581fc3ac..eb0b655ab 100644 --- a/crates/color-ui/src/ui/strip/stories.rs +++ b/crates/color-ui/src/ui/strip/stories.rs @@ -3,33 +3,33 @@ use super::ColorStrip; use crate::AreaMode; use craft_theme::{ColorModel, HsbModel, Srgba}; -use craft_ui::contract::{Bind, Props as _, Show as _, Validity}; +use craft_ui::contract::{Props as _, Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; #[story(ColorStrip<'static>, covers = [Default], drive = Drive::Step)] fn color_strip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values)).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + ColorStrip::new("Hue", AreaMode::Hue, values_at.bind(values)).show(ui).into() } #[story(ColorStrip<'static>, covers = [], drive = Drive::Never)] fn color_strip_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8))); - ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values)).quantize(6).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8))); + ColorStrip::new("Hue", AreaMode::Hue, values_at.bind(values)).quantize(6).show(ui).into() } #[story(ColorStrip<'static>, covers = [Invalid], drive = Drive::Never)] fn color_strip_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_dim = |values: &craft_theme::ModelValues| if values.values[2] < 50.0 { Validity::Refuse(Message::new("Too dim")) } else { Validity::Ok }; - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3))); - ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values).check(refuse_dim)).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3))); + ColorStrip::new("Hue", AreaMode::Hue, values_at.bind(values).check(refuse_dim)).show(ui).into() } #[story(ColorStrip<'static>, covers = [], drive = Drive::Never)] fn color_strip_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values)).enabled(false).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + ColorStrip::new("Hue", AreaMode::Hue, values_at.bind(values)).enabled(false).show(ui).into() } diff --git a/crates/color-ui/src/ui/swatches/stories.rs b/crates/color-ui/src/ui/swatches/stories.rs index 49beddde7..b95cb079f 100644 --- a/crates/color-ui/src/ui/swatches/stories.rs +++ b/crates/color-ui/src/ui/swatches/stories.rs @@ -1,15 +1,14 @@ //! Stories of `SwatchesPanel`. use super::{SwatchLibrary, SwatchesPanel, SwatchesState}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; /// The panel over a library and state kept in the story's data; the reported edits run on the library, so the story stays /// interactive. fn interactive(ui: &mut Ui, data: &mut StoryData, name: &'static str, start: SwatchLibrary) -> StoryOutput { - let (library, state) = data.value(name, (start, SwatchesState::default())); - let out = SwatchesPanel::new(&library.groups, Bind::bound(state), craft_theme::Srgba::rgb(0.2, 0.4, 0.6)).show(ui); + let ((library, state), library_state_at) = data.value_at(name, (start, SwatchesState::default())); + let out = SwatchesPanel::new(&library.groups, library_state_at.bind(state), craft_theme::Srgba::rgb(0.2, 0.4, 0.6)).show(ui); for edit in &out.edits { library.apply(edit); } diff --git a/crates/color-ui/src/ui/wheel/stories.rs b/crates/color-ui/src/ui/wheel/stories.rs index adb2ee80c..e1ba26fae 100644 --- a/crates/color-ui/src/ui/wheel/stories.rs +++ b/crates/color-ui/src/ui/wheel/stories.rs @@ -2,15 +2,15 @@ use super::ColorWheel; use craft_theme::{ColorModel, HsbModel, Srgba}; -use craft_ui::contract::{Bind, Props as _, Show as _, Validity}; +use craft_ui::contract::{Props as _, Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::Ui; #[story(ColorWheel<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::RING)))] fn color_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - let shown = ColorWheel::new("Color wheel", Bind::bound(values)).show(ui); + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + let shown = ColorWheel::new("Color wheel", values_at.bind(values)).show(ui); let last = data.note("last", String::new()); if let Some(event) = shown.events.last() { *last = format!("{event:?}"); @@ -23,12 +23,12 @@ fn color_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn color_wheel_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_dim = |values: &craft_theme::ModelValues| if values.values[2] < 50.0 { Validity::Refuse(Message::new("Too dim")) } else { Validity::Ok }; - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3))); - ColorWheel::new("Color wheel", Bind::bound(values).check(refuse_dim)).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3))); + ColorWheel::new("Color wheel", values_at.bind(values).check(refuse_dim)).show(ui).into() } #[story(ColorWheel<'static>, covers = [], drive = Drive::Never, title = "Disabled")] fn color_wheel_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); - ColorWheel::new("Color wheel", Bind::bound(values)).enabled(false).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8))); + ColorWheel::new("Color wheel", values_at.bind(values)).enabled(false).show(ui).into() } diff --git a/crates/color-ui/tests/it/color_parts.rs b/crates/color-ui/tests/it/color_parts.rs index 4dca47585..909a3eec9 100644 --- a/crates/color-ui/tests/it/color_parts.rs +++ b/crates/color-ui/tests/it/color_parts.rs @@ -41,8 +41,8 @@ fn the_wheel_geometry_round_trips() { } fn web_safe_area(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.4, 0.6, 0.8))); - ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).quantize(6).show(ui).into() + let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.4, 0.6, 0.8))); + ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values)).quantize(6).show(ui).into() } /// A key on a quantising area steps by the channel's step and goes on until the colour is a different one, so each diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 5e6a187c9..3748d3b16 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -141,11 +141,22 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ /// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that /// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. const NO_GLOBAL_STATE: &[(&str, &str)] = &[ - // The trait's home crate: it implements `MemoProps` by hand for std and framework value types. + // The trait's home crate: it implements `MemoProps` by hand for std and framework value types, and for the + // framework's own keys the derive cannot write: a binding by its source's address, its check and the check's `fn` + // (values.rs), an icon's glyph by the type of its `dyn Glyph` (icon.rs), and the write-only `Outbox` (memo_view.rs). ("crates/ui-contract/src/contract/memo.rs", "MemoProps"), - // Settled fact: `ModalRules` holds a closure the derive cannot take; it keys on its plain fields and the revision - // the app moves with every rule change, which stands for the closure. - ("crates/menu/src/modal.rs", "MemoProps"), + ("crates/ui-contract/src/contract/values.rs", "MemoProps"), + ("crates/ui-contract/src/contract/memo_view.rs", "MemoProps"), + ("crates/ui-contract/src/primitives/icon.rs", "MemoProps"), + // Settled fact: a card's view of a story's state keys by the story value's revision, whether the start is taken, the + // dialog's flags and the reset count; the view of every shown story's state is one fixed-size digest of those keys. + // Both are props held as `&mut`, which the derive does not take. + ("crates/ui-gallery/src/viewer/picks.rs", "MemoProps"), + // Settled fact: the names of a preset group key by a walk over the group and its folders (`dyn EachName`), which + // the derive cannot see through. + ("crates/ui-patterns/src/patterns/presets/model/library.rs", "MemoProps"), + // Settled fact: a name check keys by its inputs and its `fn` behind `dyn NameChecker`, as `Bind::check_with` does. + ("crates/ui-patterns/src/patterns/presets/named.rs", "MemoProps"), // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. ("crates/ui-contract/src/fonts/defaults.rs", "HACK"), ("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"), diff --git a/crates/dialogs/src/ui/path_field.rs b/crates/dialogs/src/ui/path_field.rs index 464c3de04..0aa48b730 100644 --- a/crates/dialogs/src/ui/path_field.rs +++ b/crates/dialogs/src/ui/path_field.rs @@ -72,10 +72,10 @@ impl<'a> PathField<'a> { let before = held.read(cx).unwrap_or_default(); let looks = must_exist && cx.env.shell().caps.contains(Caps::FILE_SYSTEM); let not_found = words.not_found.clone(); - let check = move |path: &String| { - if looks && path_is_missing(path) { Validity::Warn(Message::new(not_found.clone())) } else { Validity::Ok } - }; - let row = PathRow::new(label.clone(), Bind::given(before.clone()).check(check)).pick(request.clone()).show(ui); + let value = Bind::given(before.clone()).check_with((looks, not_found), |(looks, not_found), path| { + if *looks && path_is_missing(path) { Validity::Warn(Message::new(not_found.clone())) } else { Validity::Ok } + }); + let row = PathRow::new(label.clone(), value).pick(request.clone()).show(ui); browsing = row.browsing; let answered = row.picked; let typed = row diff --git a/crates/dialogs/src/ui/stories.rs b/crates/dialogs/src/ui/stories.rs index a7abee55c..c99110975 100644 --- a/crates/dialogs/src/ui/stories.rs +++ b/crates/dialogs/src/ui/stories.rs @@ -5,27 +5,23 @@ use std::sync::Arc; use super::{FileChooser, PathField}; use craft_browse::places::{FakeDirectories, FolderCache, StandardFolder}; use craft_host::{ManualJobs, PickRequest, Wake}; -use craft_ui::contract::Bind; use craft_ui::dialog::stories::hosted_with; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; #[story(PathField<'static>, covers = [Default], drive = Drive::Never)] fn path_field_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - PathField::new("Save to", Bind::bound(data.value("empty", String::new())), PickRequest::save("export")).show(ui).into() + PathField::new("Save to", data.bind("empty", String::new()), PickRequest::save("export")).show(ui).into() } #[story(PathField<'static>, covers = [], drive = Drive::Never)] fn path_field_filled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - PathField::new("Save to", Bind::bound(data.value("filled", "/photos/trip/sunrise.png".to_owned())), PickRequest::save("export")).show(ui).into() + PathField::new("Save to", data.bind("filled", "/photos/trip/sunrise.png".to_owned()), PickRequest::save("export")).show(ui).into() } #[story(PathField<'static>, covers = [], drive = Drive::Never)] fn path_field_missing_file(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - PathField::new("Open", Bind::bound(data.value("missing", "/photos/trip/missing.png".to_owned())), PickRequest::open("import")) - .must_exist(true) - .show(ui) - .into() + PathField::new("Open", data.bind("missing", "/photos/trip/missing.png".to_owned()), PickRequest::open("import")).must_exist(true).show(ui).into() } /// The folders the chooser stories browse: a home with documents, pictures, a hidden folder and an empty folder. diff --git a/crates/draw/src/geometry/presets.rs b/crates/draw/src/geometry/presets.rs index 06febb2b3..fd6a38483 100644 --- a/crates/draw/src/geometry/presets.rs +++ b/crates/draw/src/geometry/presets.rs @@ -32,6 +32,7 @@ const HEART_POINTS: usize = 32; /// One entry of the shape menu. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[non_exhaustive] pub enum ShapePreset { /// A rectangle. diff --git a/crates/draw/src/ui/brush_presets/stories.rs b/crates/draw/src/ui/brush_presets/stories.rs index 619d16d5b..1a1d10efe 100644 --- a/crates/draw/src/ui/brush_presets/stories.rs +++ b/crates/draw/src/ui/brush_presets/stories.rs @@ -1,7 +1,6 @@ //! Stories of the Brush Preset picker. use craft_behavior::Mixed; -use craft_ui::contract::Bind; use craft_ui::patterns::presets::PresetRow; use craft_ui::runtime::env::Env; use craft_ui::testing::pictures::{SampleTip, paint_tip, paint_wave}; @@ -39,10 +38,10 @@ fn rows(env: &Env, parts: BrushCardParts) -> Vec> { #[story(BrushPresetPicker<'static, u32>, covers = [Default], drive = Drive::Never)] fn picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let env = Env::of(ui); - let (current, state) = data.value("brush", (Some(SOFT), BrushPickerState::::new())); + let ((current, state), brush_at) = data.value_at("brush", (Some(SOFT), BrushPickerState::::new())); let rows = rows(&env, state.parts); let values = BrushPickerValues::new(SOFT_SIZE, Some(0.8)); - BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), values) + BrushPresetPicker::new("Brush Preset picker", brush_at.bind(current), &rows, brush_at.bind(state), values) .max_diameter(MAX_SIZE) .import() .show(ui) @@ -55,13 +54,13 @@ fn picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let env = Env::of(ui); let at = ui.max_rect().min; - let (current, state, open) = data.value("open", (Some(SOFT), BrushPickerState::::new(), true)); + let ((current, state, open), open_at2) = data.value_at("open", (Some(SOFT), BrushPickerState::::new(), true)); let rows = rows(&env, state.parts); let values = BrushPickerValues::new(SOFT_SIZE, Some(0.8)).with_tip(TipAngle::new(30.0, 0.6)); - BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), values) + BrushPresetPicker::new("Brush Preset picker", open_at2.bind(current), &rows, open_at2.bind(state), values) .max_diameter(MAX_SIZE) .import() - .open_at(at, Bind::bound(open)) + .open_at(at, open_at2.bind(open)) .show(ui) .into() } @@ -69,34 +68,34 @@ fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(BrushesPanel<'static, u32>, covers = [Default], drive = Drive::Never)] fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let env = Env::of(ui); - let (state, diameter) = data.value("panel", (PresetState::::new(), SOFT_SIZE)); + let ((state, diameter), panel_at) = data.value_at("panel", (PresetState::::new(), SOFT_SIZE)); let rows = rows(&env, BrushCardParts::ALL); - BrushesPanel::new("Brushes", &rows, Bind::bound(state), Bind::bound(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into() + BrushesPanel::new("Brushes", &rows, panel_at.bind(state), panel_at.bind(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into() } #[story(BrushPresetPicker<'static, u32>, covers = [Mixed], drive = Drive::Never)] fn picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let env = Env::of(ui); - let (current, state) = data.value("mixed", (Mixed::>::Mixed, BrushPickerState::::new())); + let ((current, state), mixed_at) = data.value_at("mixed", (Mixed::>::Mixed, BrushPickerState::::new())); let rows = rows(&env, state.parts); let values = BrushPickerValues::new(HARD_SIZE, None); - BrushPresetPicker::new("Brush Preset picker", Bind::bound_mixed(current), &rows, Bind::bound(state), values).show(ui).into() + BrushPresetPicker::new("Brush Preset picker", mixed_at.bind_mixed(current), &rows, mixed_at.bind(state), values).show(ui).into() } #[story(BrushPresetPicker<'static, u32>, covers = [], drive = Drive::Never)] fn picker_sampled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let env = Env::of(ui); - let (current, state) = data.value("sampled", (Some(HARD), BrushPickerState::::new())); + let ((current, state), sampled_at) = data.value_at("sampled", (Some(HARD), BrushPickerState::::new())); let rows = rows(&env, state.parts); - BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), BrushPickerValues::new(HARD_SIZE, None)) + BrushPresetPicker::new("Brush Preset picker", sampled_at.bind(current), &rows, sampled_at.bind(state), BrushPickerValues::new(HARD_SIZE, None)) .show(ui) .into() } #[story(BrushPresetPicker<'static, u32>, covers = [], drive = Drive::Never)] fn picker_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (current, state) = data.value("empty", (None::, BrushPickerState::::new())); - BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &[], Bind::bound(state), BrushPickerValues::new(SOFT_SIZE, Some(1.0))) + let ((current, state), empty_at) = data.value_at("empty", (None::, BrushPickerState::::new())); + BrushPresetPicker::new("Brush Preset picker", empty_at.bind(current), &[], empty_at.bind(state), BrushPickerValues::new(SOFT_SIZE, Some(1.0))) .show(ui) .into() } diff --git a/crates/draw/src/ui/brush_settings/stories.rs b/crates/draw/src/ui/brush_settings/stories.rs index 8d8264379..29e91bd1c 100644 --- a/crates/draw/src/ui/brush_settings/stories.rs +++ b/crates/draw/src/ui/brush_settings/stories.rs @@ -223,8 +223,8 @@ fn panel_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(BrushSectionList<'static, u8>, covers = [Default], drive = Drive::Never)] fn section_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let brush = data.value("brush", Brush::new(true)); - let output = BrushSectionList::new("Brush settings sections", &brush.sections, Bind::bound(&mut brush.shown)).link_row().show(ui); + let (brush, brush_at) = data.value_at("brush", Brush::new(true)); + let output = BrushSectionList::new("Brush settings sections", &brush.sections, brush_at.bind(&mut brush.shown)).link_row().show(ui); let events = output.events.clone(); let facts = StoryOutput::from(output); for event in events { @@ -240,20 +240,20 @@ fn angle_note(angle: TipAngle) -> String { #[story(TipEllipse<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::ellipse::ARROW)))] fn tip_ellipse(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let shown = TipEllipse::new("Tip angle and roundness", Bind::bound(data.value("angle", ANGLE))).show(ui); + let shown = TipEllipse::new("Tip angle and roundness", data.bind("angle", ANGLE)).show(ui); let note = angle_note(*data.value("angle", ANGLE)); StoryOutput::from(shown).readout(note) } #[story(TipEllipse<'static>, covers = [Mixed], drive = Drive::Never)] fn tip_ellipse_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TipEllipse::new("Tip angle and roundness", Bind::bound_mixed(data.value("mixed", Mixed::::Mixed))).show(ui).into() + TipEllipse::new("Tip angle and roundness", data.bind_mixed("mixed", Mixed::::Mixed)).show(ui).into() } #[story(TipEllipse<'static>, covers = [Invalid], drive = Drive::Never)] fn tip_ellipse_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_flat = |angle: &TipAngle| if angle.roundness < 0.5 { Validity::Refuse(Message::new("Too flat")) } else { Validity::Ok }; - let shown = TipEllipse::new("Tip angle and roundness", Bind::bound(data.value("flat", ANGLE)).check(refuse_flat)).show(ui); + let shown = TipEllipse::new("Tip angle and roundness", data.bind("flat", ANGLE).check(refuse_flat)).show(ui); let note = angle_note(*data.value("flat", ANGLE)); StoryOutput::from(shown).readout(note) } @@ -263,12 +263,12 @@ fn tip_ellipse_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn dynamic_control_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let words = Env::of(ui).words::(); let controls = controls(); - let (rows, size) = data.value("rows", ((ControlRow::new(Control::Fade), ControlRow::new(Control::PenPressure)), SIZE)); + let ((rows, size), rows_at) = data.value_at("rows", ((ControlRow::new(Control::Fade), ControlRow::new(Control::PenPressure)), SIZE)); let (fade, curve) = rows; Stack::new().show(ui, |ui, _| { fade.show(ui, &controls); curve.show(ui, &controls); - let _ = BrushSizeField::new("Size", Bind::bound(&mut *size), MAX_SIZE).restore(ORIGINAL).show(ui); + let _ = BrushSizeField::new("Size", rows_at.bind(&mut *size), MAX_SIZE).restore(ORIGINAL).show(ui); }); let output = StoryOutput::default(); if curve.curve_open { output.readout(words.curve_open.as_str().to_owned()) } else { output } @@ -281,5 +281,5 @@ fn stroke_strip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(BrushSizeField<'static>, covers = [Default], drive = Drive::Never)] fn size_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - BrushSizeField::new("Size", Bind::bound(data.value("size", SIZE)), MAX_SIZE).restore(ORIGINAL).show(ui).into() + BrushSizeField::new("Size", data.bind("size", SIZE), MAX_SIZE).restore(ORIGINAL).show(ui).into() } diff --git a/crates/draw/src/ui/connector/stories.rs b/crates/draw/src/ui/connector/stories.rs index d74d391a2..d438cd001 100644 --- a/crates/draw/src/ui/connector/stories.rs +++ b/crates/draw/src/ui/connector/stories.rs @@ -71,7 +71,7 @@ fn on_canvas>(ui: &mut Ui, targets: &[ConnectionTarget], mu #[story(ConnectorHandles<'static>, covers = [Default], drive = Drive::Drag(Grip::part(super::handles::END.at(0)).toward(vec2(0.0, 1.0))))] fn connector_glued_at_both_ends(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let targets = targets(); - let item = data.value( + let (item, item_at) = data.value_at( "item", ConnectorItem { id: 9, @@ -81,7 +81,7 @@ fn connector_glued_at_both_ends(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu path: None, }, ); - on_canvas(ui, &targets, |ui, at| ConnectorHandles::new("Connector", Bind::bound(&mut *item), &targets).show_at(ui, at)) + on_canvas(ui, &targets, |ui, at| ConnectorHandles::new("Connector", item_at.bind(&mut *item), &targets).show_at(ui, at)) } /// The arrowhead previews of the cap choices, at the line's start or end. diff --git a/crates/draw/src/ui/corner/stories.rs b/crates/draw/src/ui/corner/stories.rs index ef25594fb..13bd4e0f3 100644 --- a/crates/draw/src/ui/corner/stories.rs +++ b/crates/draw/src/ui/corner/stories.rs @@ -9,7 +9,7 @@ use std::hash::{DefaultHasher, Hash as _, Hasher as _}; use crate::geometry::fillet::fillet; use craft_behavior::kurbo::{BezPath, Point, Vec2}; use craft_ui::canvas::RasterSource as _; -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::runtime::env::Env; use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, accent, on_picture, paint_shapes}; use craft_ui::testing::{Drive, EditKind, Grip, StoryData, StoryOutput, story}; @@ -144,12 +144,12 @@ fn edit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let hide_above = *data.ranged("hide above", 177.0, 90.0..=180.0); let individual = *data.value("individual", true); let mut last = data.note::>("last", None).clone(); - let targets = data.value("targets", edited(individual)); + let (targets, targets_at) = data.value_at("targets", edited(individual)); if let Some(path) = targets.iter_mut().find(|target| target.key == 3) { path.individual = individual; } let output = on_canvas(ui, targets, |ui, at, targets| { - let shown = CornerWidgets::new("Corner radius", Bind::bound(&mut *targets)).kinds(kinds).hide_above(hide_above).show_at(ui, at); + let shown = CornerWidgets::new("Corner radius", targets_at.bind(&mut *targets)).kinds(kinds).hide_above(hide_above).show_at(ui, at); let kind = shown.edit.events.iter().filter_map(EditKind::of).next_back().and_then(|kind| match kind { EditKind::Begin => Some(&words.began), EditKind::Update => Some(&words.updated), @@ -181,6 +181,8 @@ fn edit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(CornerWidgets<'static>, covers = [], drive = Drive::Never)] fn cycling_kinds_and_a_wide_angle_limit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let targets = data.value("kinds", targets()); - on_canvas(ui, targets, |ui, at, targets| CornerWidgets::new("Corner radius", Bind::bound(targets)).kinds(true).hide_above(120.0).show_at(ui, at)) + let (targets, targets_at) = data.value_at("kinds", targets()); + on_canvas(ui, targets, |ui, at, targets| { + CornerWidgets::new("Corner radius", targets_at.bind(targets)).kinds(true).hide_above(120.0).show_at(ui, at) + }) } diff --git a/crates/draw/src/ui/crop/perspective_bar/stories.rs b/crates/draw/src/ui/crop/perspective_bar/stories.rs index c29ee5e15..73b30701c 100644 --- a/crates/draw/src/ui/crop/perspective_bar/stories.rs +++ b/crates/draw/src/ui/crop/perspective_bar/stories.rs @@ -4,7 +4,7 @@ use super::super::options::{CropLength, CropSizeFields}; use super::super::session::{CropDocKey, CropDocument}; use super::PerspectiveCropBar; use craft_ui::bars::{Bar, BarKind}; -use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::contract::ShowContainer as _; use craft_ui::runtime::env::UnitKind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -19,10 +19,10 @@ fn perspective_crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { resolution: "300".into(), ..CropSizeFields::default() }; - let (size, grid) = data.value("bar", (fields, true)); + let ((size, grid), bar_at) = data.value_at("bar", (fields, true)); let mut output = None; Bar::new("Options", BarKind::Options).show(ui, |ui, _| { - output = Some(PerspectiveCropBar::new(&mut *size, &document, Bind::bound(&mut *grid)).show(ui)); + output = Some(PerspectiveCropBar::new(&mut *size, &document, bar_at.bind(&mut *grid)).show(ui)); }); output.map(StoryOutput::from).unwrap_or_default() } diff --git a/crates/draw/src/ui/crop/perspective_crop/stories.rs b/crates/draw/src/ui/crop/perspective_crop/stories.rs index 59aa1e1b9..92c46eda4 100644 --- a/crates/draw/src/ui/crop/perspective_crop/stories.rs +++ b/crates/draw/src/ui/crop/perspective_crop/stories.rs @@ -6,7 +6,7 @@ use super::{CORNER, PerspectiveCropQuad, PerspectiveQuad}; use craft_behavior::CanvasView; use craft_behavior::kurbo::{BezPath, Point}; use craft_ui::canvas::{CropShield, RasterSource as _}; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, on_picture, paint_shapes}; use craft_ui::testing::{Drive, Grip, StoryData, StoryHost, StoryOutput, ToolStory, story, tool_story}; @@ -38,15 +38,17 @@ fn on_canvas>(ui: &mut Ui, mut quad: impl FnMut(&mut Ui, eg #[story(PerspectiveCropQuad<'static>, covers = [Default], drive = Drive::Drag(Grip::part(CORNER.at(0))))] fn skewed_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let quad = data.value("quad", Some(PAGE)); - on_canvas(ui, |ui, at| PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)).shield(CropShield::PERSPECTIVE).show_at(ui, at).edit) + let (quad, quad_at) = data.value_at("quad", Some(PAGE)); + on_canvas(ui, |ui, at| { + PerspectiveCropQuad::new("Perspective crop", quad_at.bind(&mut *quad)).shield(CropShield::PERSPECTIVE).show_at(ui, at).edit + }) } #[story(PerspectiveCropQuad<'static>, covers = [Invalid], drive = Drive::Drag(Grip::part(CORNER.at(0))))] fn bent_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let quad = data.value("quad", Some(BENT)); + let (quad, quad_at) = data.value_at("quad", Some(BENT)); on_canvas(ui, |ui, at| { - let bind = Bind::bound(&mut *quad).check(|quad: &PerspectiveQuad| match quad { + let bind = quad_at.bind(&mut *quad).check(|quad: &PerspectiveQuad| match quad { Some(quad) if !super::is_valid(quad) => Validity::Refuse(Message::new("The corners do not make a convex quad")), _ => Validity::Ok, }); diff --git a/crates/draw/src/ui/gradient/gradient_overlay/stories.rs b/crates/draw/src/ui/gradient/gradient_overlay/stories.rs index 51fae205b..5b8d1c6b6 100644 --- a/crates/draw/src/ui/gradient/gradient_overlay/stories.rs +++ b/crates/draw/src/ui/gradient/gradient_overlay/stories.rs @@ -83,25 +83,27 @@ fn gradient_overlay(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(GradientOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::new(END).toward(vec2(0.0, 1.0))))] fn gradient_overlay_extent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("gradient", gradient()); + let (value, value_at) = data.value_at("gradient", gradient()); let picture = ramp(value, true); on_canvas(ui, &picture, |ui, at| { - GradientOverlay::new("Gradient", Bind::bound(&mut *value)).style(GradientStyle::Radial).reverse().show_at(ui, at).edit + GradientOverlay::new("Gradient", value_at.bind(&mut *value)).style(GradientStyle::Radial).reverse().show_at(ui, at).edit }) } #[story(GradientOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::new(END).toward(vec2(0.0, 1.0))))] fn gradient_overlay_mirror(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("gradient", gradient()); + let (value, value_at) = data.value_at("gradient", gradient()); let picture = ramp(value, false); - on_canvas(ui, &picture, |ui, at| GradientOverlay::new("Gradient", Bind::bound(&mut *value)).style(GradientStyle::Reflected).show_at(ui, at).edit) + on_canvas(ui, &picture, |ui, at| { + GradientOverlay::new("Gradient", value_at.bind(&mut *value)).style(GradientStyle::Reflected).show_at(ui, at).edit + }) } #[story(GradientOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::new(END).toward(vec2(0.0, 1.0))))] fn gradient_overlay_diamond(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("gradient", gradient()); + let (value, value_at) = data.value_at("gradient", gradient()); let picture = ramp(value, false); - on_canvas(ui, &picture, |ui, at| GradientOverlay::new("Gradient", Bind::bound(&mut *value)).style(GradientStyle::Diamond).show_at(ui, at).edit) + on_canvas(ui, &picture, |ui, at| GradientOverlay::new("Gradient", value_at.bind(&mut *value)).style(GradientStyle::Diamond).show_at(ui, at).edit) } #[story(GradientOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::new(END).toward(vec2(0.0, 1.0))))] diff --git a/crates/draw/src/ui/gradient/palette/stories.rs b/crates/draw/src/ui/gradient/palette/stories.rs index a5660ac6a..39928eab4 100644 --- a/crates/draw/src/ui/gradient/palette/stories.rs +++ b/crates/draw/src/ui/gradient/palette/stories.rs @@ -1,7 +1,6 @@ //! Stories of the gradient palette. use craft_theme::Srgba; -use craft_ui::contract::Bind; use craft_ui::patterns::presets::{PresetState, PresetView}; use craft_ui::testing::{StoryData, StoryOutput, story}; use egui::Ui; @@ -31,8 +30,8 @@ fn palette(ui: &mut Ui, data: &mut StoryData, view: PresetView) -> StoryOutput { let recent = [pair([0.2, 0.8, 0.4], [0.1, 0.2, 0.6])]; let mut initial = PresetState::new(); initial.view = view; - let state = data.value("state", initial); - let shown = GradientPalette::new("Gradients", &groups, Bind::bound(&mut *state)) + let (state, state_at) = data.value_at("state", initial); + let shown = GradientPalette::new("Gradients", &groups, state_at.bind(&mut *state)) .recent(&recent) .selected(GradientRef::Item { group: 0, item: 1 }) .show(ui); @@ -62,8 +61,8 @@ fn gradient_palette_tiles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { items.push(GradientItem::new("Focus, rectangle", stops.clone()).tile(GradientTile::Focus { outline: FocusOutline::Rect, focus })); items.push(GradientItem::new("Ramp", stops)); let groups = [GradientGroup::new("Tiles", items)]; - let state = data.value("state", PresetState::::new()); - let shown = GradientPalette::new("Gradient tiles", &groups, Bind::bound(&mut *state)).show(ui); + let (state, state_at) = data.value_at("state", PresetState::::new()); + let shown = GradientPalette::new("Gradient tiles", &groups, state_at.bind(&mut *state)).show(ui); StoryOutput::from(shown) } diff --git a/crates/draw/src/ui/measure/stories.rs b/crates/draw/src/ui/measure/stories.rs index 061922d49..b3ef96424 100644 --- a/crates/draw/src/ui/measure/stories.rs +++ b/crates/draw/src/ui/measure/stories.rs @@ -62,16 +62,16 @@ fn ruler_overlay_with_a_protractor_arm(ui: &mut Ui, data: &mut StoryData) -> Sto #[story(RulerBar<'static>, covers = [], drive = Drive::Never)] fn ruler_bar_with_a_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let use_scale = data.value("scale", false); + let (use_scale, use_scale_at) = data.value_at("scale", false); let mut output = None; - Bar::new("Options", BarKind::Options).show(ui, |ui, _| output = Some(RulerBar::new(Some(line()), Bind::bound(&mut *use_scale)).show(ui))); + Bar::new("Options", BarKind::Options).show(ui, |ui, _| output = Some(RulerBar::new(Some(line()), use_scale_at.bind(&mut *use_scale)).show(ui))); output.map(StoryOutput::from).unwrap_or_default() } #[story(RulerBar<'static>, covers = [], drive = Drive::Never)] fn ruler_bar_without_a_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let use_scale = data.value("none", false); + let (use_scale, use_scale_at) = data.value_at("none", false); let mut output = None; - Bar::new("Options", BarKind::Options).show(ui, |ui, _| output = Some(RulerBar::new(None, Bind::bound(&mut *use_scale)).show(ui))); + Bar::new("Options", BarKind::Options).show(ui, |ui, _| output = Some(RulerBar::new(None, use_scale_at.bind(&mut *use_scale)).show(ui))); output.map(StoryOutput::from).unwrap_or_default() } diff --git a/crates/draw/src/ui/pattern/stories.rs b/crates/draw/src/ui/pattern/stories.rs index 1ab671445..317b3e066 100644 --- a/crates/draw/src/ui/pattern/stories.rs +++ b/crates/draw/src/ui/pattern/stories.rs @@ -19,8 +19,8 @@ fn tile(cx: &ContentPainterCx<'_>, rect: Rect, _: &PatternSwatch) { } fn editor(ui: &mut Ui, data: &mut StoryData, start: PatternFillOptions, library: &[PatternSwatch]) -> StoryOutput { - let options = data.value("options", start); - let out = PatternFillEditor::new("Pattern fill", Bind::bound(options), library).thumbnails(tile).show(ui); + let (options, options_at) = data.value_at("options", start); + let out = PatternFillEditor::new("Pattern fill", options_at.bind(options), library).thumbnails(tile).show(ui); StoryOutput::from(out) } @@ -38,13 +38,10 @@ fn pattern_fill_preset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(PatternFillEditor<'static>, covers = [Default], drive = Drive::Never)] fn pattern_fill_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let library = swatches(); - let mut options = data.value("options", PatternFillOptions::bitmap("bubbles")).clone(); - let mut open = *data.value("open", true); - FormDialog::new("Pattern Fill", Bind::bound(&mut options)).opened(Bind::bound(&mut open)).show(ui, |ui, _, value| { + let ((options, options_at), (open, open_at)) = data.pair_at(("options", PatternFillOptions::bitmap("bubbles")), ("open", true)); + FormDialog::new("Pattern Fill", options_at.bind(options)).opened(open_at.bind(open)).show(ui, |ui, _, value| { PatternFillEditor::new("Pattern fill", Bind::bound(value), &library).thumbnails(tile).show(ui); true }); - *data.value("options", PatternFillOptions::bitmap("bubbles")) = options; - *data.value("open", true) = open; StoryOutput::default() } diff --git a/crates/draw/src/ui/pen/bezier/stories.rs b/crates/draw/src/ui/pen/bezier/stories.rs index 56cecf02d..ce9799c47 100644 --- a/crates/draw/src/ui/pen/bezier/stories.rs +++ b/crates/draw/src/ui/pen/bezier/stories.rs @@ -5,7 +5,7 @@ use super::{ }; use craft_behavior::kurbo::Point; use craft_theme::Srgba; -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::{Ui, Vec2}; @@ -30,52 +30,54 @@ fn selected() -> PathSelection { #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ANCHOR.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::X)))] fn direct_selection_with_a_selected_anchor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); - on_canvas(ui, |ui, at| BezierOverlay::new("Paths", Bind::bound(&mut *paths), &selected()).show_at(ui, at)) + let (paths, paths_at) = data.value_at("paths", paths()); + on_canvas(ui, |ui, at| BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &selected()).show_at(ui, at)) } #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ANCHOR.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::X)))] fn all_handles_shown(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); + let (paths, paths_at) = data.value_at("paths", paths()); on_canvas(ui, |ui, at| { - BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()).handles(HandlesShown::All).show_at(ui, at) + BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &PathSelection::default()).handles(HandlesShown::All).show_at(ui, at) }) } #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ANCHOR.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::X)))] fn curvature_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); - on_canvas(ui, |ui, at| BezierOverlay::new("Paths", Bind::bound(&mut *paths), &selected()).tool(BezierTool::Curvature).show_at(ui, at)) + let (paths, paths_at) = data.value_at("paths", paths()); + on_canvas(ui, |ui, at| BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &selected()).tool(BezierTool::Curvature).show_at(ui, at)) } /// Add Anchor takes a press on an anchor and moves nothing: the drag is `add_anchor_tool_dragged`'s, on a segment. #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Never)] fn add_anchor_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); + let (paths, paths_at) = data.value_at("paths", paths()); on_canvas(ui, |ui, at| { - BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()).tool(BezierTool::AddAnchor).show_at(ui, at) + BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &PathSelection::default()).tool(BezierTool::AddAnchor).show_at(ui, at) }) } #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(SEGMENT.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::Y)))] fn add_anchor_tool_dragged(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); + let (paths, paths_at) = data.value_at("paths", paths()); on_canvas(ui, |ui, at| { - BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()).tool(BezierTool::AddAnchor).show_at(ui, at) + BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &PathSelection::default()).tool(BezierTool::AddAnchor).show_at(ui, at) }) } #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Drag(Grip::part(SEGMENT.at(index(0, KnotRef { subpath: 0, knot: 0 }))).toward(Vec2::Y)))] fn convert_tool_straight_segment(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); - on_canvas(ui, |ui, at| BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()).tool(BezierTool::Convert).show_at(ui, at)) + let (paths, paths_at) = data.value_at("paths", paths()); + on_canvas(ui, |ui, at| { + BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &PathSelection::default()).tool(BezierTool::Convert).show_at(ui, at) + }) } #[story(BezierOverlay<'static>, covers = [Default], drive = Drive::Never)] fn outlines_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let paths = data.value("paths", paths()); + let (paths, paths_at) = data.value_at("paths", paths()); on_canvas(ui, |ui, at| { - BezierOverlay::new("Paths", Bind::bound(&mut *paths), &PathSelection::default()) + BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &PathSelection::default()) .tool(BezierTool::Anchors) .anchors(AnchorsShown::Hidden) .show_at(ui, at) @@ -89,6 +91,6 @@ fn a_path_in_its_own_colour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { paths[0].color = Some(Srgba::rgb(0.9, 0.43, 0.08)); paths }; - let paths = data.value("paths", coloured()); - on_canvas(ui, |ui, at| BezierOverlay::new("Paths", Bind::bound(&mut *paths), &selected()).show_at(ui, at)) + let (paths, paths_at) = data.value_at("paths", coloured()); + on_canvas(ui, |ui, at| BezierOverlay::new("Paths", paths_at.bind(&mut *paths), &selected()).show_at(ui, at)) } diff --git a/crates/draw/src/ui/pen/stories.rs b/crates/draw/src/ui/pen/stories.rs index 9a7267f23..bab6c996d 100644 --- a/crates/draw/src/ui/pen/stories.rs +++ b/crates/draw/src/ui/pen/stories.rs @@ -2,7 +2,6 @@ use super::{PathOptionsPopover, PathOptionsSettings}; use craft_theme::Srgba; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -14,8 +13,8 @@ fn line_color() -> Srgba { #[story(PathOptionsPopover<'static>, covers = [Default], drive = Drive::Never)] fn path_options_defaults(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut open = *data.value("open", false); - let settings = data.value("defaults", PathOptionsSettings::default()); - let shown = PathOptionsPopover::new("Path Options", Bind::bound(&mut *settings)).default_color(line_color()).show(ui, &mut open); + let (settings, settings_at) = data.value_at("defaults", PathOptionsSettings::default()); + let shown = PathOptionsPopover::new("Path Options", settings_at.bind(&mut *settings)).default_color(line_color()).show(ui, &mut open); *data.value("open", false) = open; shown.into() } @@ -23,8 +22,8 @@ fn path_options_defaults(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(PathOptionsPopover<'static>, covers = [], drive = Drive::Never)] fn path_options_with_a_color(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut open = *data.value("open-set", false); - let settings = data.value("set", PathOptionsSettings { rubber_band: true, color: Some([200, 40, 40]), thickness: Some(2.0) }); - let shown = PathOptionsPopover::new("Path Options", Bind::bound(&mut *settings)).show(ui, &mut open); + let (settings, settings_at) = data.value_at("set", PathOptionsSettings { rubber_band: true, color: Some([200, 40, 40]), thickness: Some(2.0) }); + let shown = PathOptionsPopover::new("Path Options", settings_at.bind(&mut *settings)).show(ui, &mut open); *data.value("open-set", false) = open; shown.into() } diff --git a/crates/draw/src/ui/picture_fill/stories.rs b/crates/draw/src/ui/picture_fill/stories.rs index d80c41f2c..96aec28fc 100644 --- a/crates/draw/src/ui/picture_fill/stories.rs +++ b/crates/draw/src/ui/picture_fill/stories.rs @@ -1,20 +1,19 @@ //! Stories of the picture fill editor: Stretch and Tile. use super::{PictureFill, PictureFillEditor, PictureMode, TileAlignment, TileMirror}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; #[story(PictureFillEditor<'static>, covers = [], drive = Drive::Never)] fn picture_fill_stretch(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let fill = data.value("stretch", PictureFill::new("sunrise.png")); - PictureFillEditor::new("Picture", Bind::bound(fill)).show(ui).into() + let (fill, fill_at) = data.value_at("stretch", PictureFill::new("sunrise.png")); + PictureFillEditor::new("Picture", fill_at.bind(fill)).show(ui).into() } #[story(PictureFillEditor<'static>, covers = [], drive = Drive::Never)] fn picture_fill_tile(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut start = PictureFill::new("sunrise.png"); start.mode = PictureMode::Tile { offset: [12.0, 0.0], scale: [50.0, 50.0], alignment: TileAlignment::Center, mirror: TileMirror::Horizontal }; - let fill = data.value("tile", start); - PictureFillEditor::new("Picture", Bind::bound(fill)).show(ui).into() + let (fill, fill_at) = data.value_at("tile", start); + PictureFillEditor::new("Picture", fill_at.bind(fill)).show(ui).into() } diff --git a/crates/draw/src/ui/stroke/stories.rs b/crates/draw/src/ui/stroke/stories.rs index 221031265..a4fce3cdc 100644 --- a/crates/draw/src/ui/stroke/stories.rs +++ b/crates/draw/src/ui/stroke/stories.rs @@ -54,51 +54,51 @@ fn with_readout(data: &mut StoryData, output: impl Into, latest: Op #[story(StrokeEditor<'static>, covers = [Default], drive = Drive::Never)] fn stroke_editor_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("panel", StrokeStyle::default()); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN).show(ui); + let (style, style_at) = data.value_at("panel", StrokeStyle::default()); + let out = StrokeEditor::new("Stroke", style_at.bind(style)).sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] fn stroke_editor_popover_dash_align(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("popover-align", StrokeStyle::default().with_line_style(super::LineStyle::Dashed)); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER | StrokeSections::DASH_ALIGN).show(ui); + let (style, style_at) = data.value_at("popover-align", StrokeStyle::default().with_line_style(super::LineStyle::Dashed)); + let out = StrokeEditor::new("Stroke", style_at.bind(style)).sections(StrokeSections::POPOVER | StrokeSections::DASH_ALIGN).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] fn stroke_editor_popover(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("popover", StrokeStyle::default()); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER).show(ui); + let (style, style_at) = data.value_at("popover", StrokeStyle::default()); + let out = StrokeEditor::new("Stroke", style_at.bind(style)).sections(StrokeSections::POPOVER).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] fn stroke_editor_open_path(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("open", StrokeStyle::default()); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER).closed(false).show(ui); + let (style, style_at) = data.value_at("open", StrokeStyle::default()); + let out = StrokeEditor::new("Stroke", style_at.bind(style)).sections(StrokeSections::POPOVER).closed(false).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] fn stroke_editor_dashed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("dashed", StrokeStyle::default().with_line_style(super::LineStyle::Dashed)); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER).show(ui); + let (style, style_at) = data.value_at("dashed", StrokeStyle::default().with_line_style(super::LineStyle::Dashed)); + let out = StrokeEditor::new("Stroke", style_at.bind(style)).sections(StrokeSections::POPOVER).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeEditor<'static>, covers = [Mixed], drive = Drive::Never)] fn stroke_editor_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (style, mixed) = data.value("mixed", { + let ((style, mixed), mixed_at) = data.value_at("mixed", { let base = StrokeStyle::default(); StrokeMixed::of([&base, &other_than(&base)]).expect("two styles") }); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER | StrokeSections::DASH_ALIGN).mixed(mixed).show(ui); + let out = StrokeEditor::new("Stroke", mixed_at.bind(style)).sections(StrokeSections::POPOVER | StrokeSections::DASH_ALIGN).mixed(mixed).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } @@ -158,8 +158,8 @@ struct Picks { #[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] fn stroke_editor_choice_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let picks = - data.value("rows", Picks { style: StrokeStyle::default(), start: "none".into(), end: "arrow".into(), profile: "uniform".into(), last: None }); + let (picks, picks_at) = data + .value_at("rows", Picks { style: StrokeStyle::default(), start: "none".into(), end: "arrow".into(), profile: "uniform".into(), last: None }); let heads = [ StrokeChoice::new("none", "None"), StrokeChoice::new("arrow", "Arrow"), @@ -179,7 +179,7 @@ fn stroke_editor_choice_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { .selected(Mixed::Same(picks.profile.as_str())) .paint(ChoicePainter::new(|cx, rect, choice| paint_profile(cx, rect, &choice.id))), ]; - let out = StrokeEditor::new("Stroke", Bind::bound(&mut picks.style)).rows(&rows).show(ui); + let out = StrokeEditor::new("Stroke", picks_at.bind(&mut picks.style)).rows(&rows).show(ui); let picked = out.choice.clone(); let story: StoryOutput = out.into(); if let Some((row, choice)) = &picked { @@ -206,25 +206,25 @@ fn stroke_editor_choice_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(StrokeButton<'static>, covers = [Default], drive = Drive::Never)] fn stroke_button(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (style, open) = data.value("button", (StrokeStyle::default(), false)); - let out = StrokeButton::new("Stroke Options", Bind::bound(style), Bind::bound(open)).show(ui); + let ((style, open), button_at) = data.value_at("button", (StrokeStyle::default(), false)); + let out = StrokeButton::new("Stroke Options", button_at.bind(style), button_at.bind(open)).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeButton<'static>, covers = [Mixed], drive = Drive::Never)] fn stroke_button_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (style, open) = data.value("button mixed", (Mixed::::Mixed, false)); - let out = StrokeButton::new("Stroke Options", Bind::bound_mixed(style), Bind::bound(open)).show(ui); + let ((style, open), style_open_at) = data.value_at("button mixed", (Mixed::::Mixed, false)); + let out = StrokeButton::new("Stroke Options", style_open_at.bind_mixed(style), style_open_at.bind(open)).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeButton<'static>, covers = [Invalid], drive = Drive::Never)] fn stroke_button_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let (style, open) = data.value("button refused", (StrokeStyle::default().with_line_style(super::LineStyle::Dashed), false)); + let ((style, open), style_open_at) = data.value_at("button refused", (StrokeStyle::default().with_line_style(super::LineStyle::Dashed), false)); let refuse_dashes = |style: &StrokeStyle| if style.dashes.is_empty() { Validity::Ok } else { Validity::Refuse(Message::new("Solid lines only")) }; - let out = StrokeButton::new("Stroke Options", Bind::bound(style).check(refuse_dashes), Bind::bound(open)).show(ui); + let out = StrokeButton::new("Stroke Options", style_open_at.bind(style).check(refuse_dashes), style_open_at.bind(open)).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } @@ -243,8 +243,8 @@ fn pick_dashed(fixture: &mut Fixture) { #[story(StrokeButton<'static>, covers = [Open], drive = Drive::Custom(pick_dashed))] fn stroke_button_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("button open", StrokeStyle::default()); - let out = StrokeButton::new("Stroke Options", Bind::bound(style), Bind::given(false)).show(ui); + let (style, style_at) = data.value_at("button open", StrokeStyle::default()); + let out = StrokeButton::new("Stroke Options", style_at.bind(style), Bind::given(false)).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } diff --git a/crates/draw/src/ui/symmetry/stories.rs b/crates/draw/src/ui/symmetry/stories.rs index 748d5ee1b..acd1ec0fd 100644 --- a/crates/draw/src/ui/symmetry/stories.rs +++ b/crates/draw/src/ui/symmetry/stories.rs @@ -98,14 +98,14 @@ fn editing_guides(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(SymmetryHandles<'static>, covers = [Default], drive = Drive::Drag(Grip::part(SYMMETRY.at(CENTRE))))] fn handles_on_a_canvas(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let symmetry = data.value("symmetry", sample(SymmetryMode::Vertical)); + let (symmetry, symmetry_at) = data.value_at("symmetry", sample(SymmetryMode::Vertical)); let room = craft_ui::testing::stage(ui); let view = view(ui, room); let shown = Canvas::new("Document").view(view).show_at(ui, room, |ui, body| { craft_ui::testing::canvas_story::show_document(ui, body.rect, &SHOWN); let drawn = *symmetry; SymmetryOverlay::new("Symmetry", &drawn, PAGE).editing(true).show_at(ui, body.rect); - SymmetryHandles::new("Symmetry", Bind::bound(&mut *symmetry), PAGE).show_at(ui, body.rect) + SymmetryHandles::new("Symmetry", symmetry_at.bind(&mut *symmetry), PAGE).show_at(ui, body.rect) }); let output = shown.inner.map(|output| StoryOutput::from(output.edit)).unwrap_or_default(); output.readout(axes(symmetry)) diff --git a/crates/draw/src/ui/transform/session_bar/stories.rs b/crates/draw/src/ui/transform/session_bar/stories.rs index 4ad81542c..eaa7716bf 100644 --- a/crates/draw/src/ui/transform/session_bar/stories.rs +++ b/crates/draw/src/ui/transform/session_bar/stories.rs @@ -3,7 +3,7 @@ use super::{BarSlot, TransformBar}; use super::{TransformEdit, TransformSession, TransformSettings}; use craft_behavior::kurbo::Rect; -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::display::Text; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -13,18 +13,18 @@ const START: Rect = Rect::new(0.0, 0.0, 200.0, 100.0); #[story(TransformBar<'static, ()>, covers = [], drive = Drive::Never)] fn box_phase(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", TransformSettings::default()); + let (settings, settings_at) = data.value_at("settings", TransformSettings::default()); let session = TransformSession::<()>::new(START); - TransformBar::new("Free Transform", &session, Bind::bound(settings)).show(ui).into() + TransformBar::new("Free Transform", &session, settings_at.bind(settings)).show(ui).into() } #[story(TransformBar<'static, ()>, covers = [], drive = Drive::Never)] fn warp_phase(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", TransformSettings::default()); + let (settings, settings_at) = data.value_at("settings", TransformSettings::default()); let mut session = TransformSession::<()>::new(START); let _ = session.apply(TransformEdit::Warp(()), 0.0); let fields = BarSlot::new(|ui: &mut Ui| { Text::new("Warp fields").show(ui); }); - TransformBar::new("Warp", &session, Bind::bound(settings)).warp_fields(fields).show(ui).into() + TransformBar::new("Warp", &session, settings_at.bind(settings)).warp_fields(fields).show(ui).into() } diff --git a/crates/draw/src/ui/transform/session_overlay/stories.rs b/crates/draw/src/ui/transform/session_overlay/stories.rs index 647577a90..6b72ef024 100644 --- a/crates/draw/src/ui/transform/session_overlay/stories.rs +++ b/crates/draw/src/ui/transform/session_overlay/stories.rs @@ -6,7 +6,7 @@ use craft_behavior::CanvasView; use craft_behavior::geometry::quad::BoxState; use craft_behavior::kurbo::{Line, Rect as DocRect}; use craft_ui::canvas::RasterSource as _; -use craft_ui::contract::{Bind, Entry}; +use craft_ui::contract::Entry; use craft_ui::runtime::env::Env; use craft_ui::runtime::pointer; use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, accent, paint_shapes}; @@ -100,9 +100,9 @@ fn run_session(ui: &mut Ui, data: &mut StoryData, with_rows: bool) -> StoryOutpu let rows = if with_rows { app_rows(&words) } else { Vec::new() }; let first = data.value("settings", sample_settings()).clone(); let kept = story_tool(data, || TransformKept::new(&first)); - let settings = data.value("settings", sample_settings()); + let (settings, settings_at) = data.value_at("settings", sample_settings()); // The bar shows before the canvas, as the app's options bar does: its edits reach the session on this pass. - let bar = TransformBar::new("Free Transform", &kept.borrow().session, Bind::bound(settings)).show(ui); + let bar = TransformBar::new("Free Transform", &kept.borrow().session, settings_at.bind(settings)).show(ui); let settings = settings.clone(); let document = StoryDocument::STANDARD; let line = accent(ui, 1.0); diff --git a/crates/draw/src/ui/transform/transform_box/stories.rs b/crates/draw/src/ui/transform/transform_box/stories.rs index 2a6796b77..04843c703 100644 --- a/crates/draw/src/ui/transform/transform_box/stories.rs +++ b/crates/draw/src/ui/transform/transform_box/stories.rs @@ -33,14 +33,14 @@ fn on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, B /// [`on_canvas`] with the box's whole output. fn shown_on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> Option { - let state = data.value("box", BoxState::from_rect(PICTURE)); + let (state, state_at) = data.value_at("box", BoxState::from_rect(PICTURE)); let room = craft_ui::testing::stage(ui); let view = craft_ui::testing::canvas_story::story_view(room, ui.pixels_per_point(), PICTURE.center(), 100.0); let layer = layer(); let shown = Canvas::new("Document").view(view).show_at(ui, room, |ui, body| { show_document(ui, body.rect, &StoryDocument::STANDARD); show_quad(ui, body.rect, "Layer", state.quad, &layer); - make(Bind::bound(&mut *state)).show_at(ui, body.rect) + make(state_at.bind(&mut *state)).show_at(ui, body.rect) }); shown.inner } diff --git a/crates/draw/src/ui/transform/transform_fields/stories.rs b/crates/draw/src/ui/transform/transform_fields/stories.rs index c4d919f70..6962bea36 100644 --- a/crates/draw/src/ui/transform/transform_fields/stories.rs +++ b/crates/draw/src/ui/transform/transform_fields/stories.rs @@ -6,7 +6,7 @@ use craft_behavior::kurbo::{Rect, Size}; use craft_behavior::{RulerUnits, Ticks}; use craft_ui::bars::{Bar, BarKind}; use craft_ui::canvas::RulerText; -use craft_ui::contract::{Bind, Entry, ShowContainer as _}; +use craft_ui::contract::{Entry, ShowContainer as _}; use craft_ui::runtime::env::UnitKind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -35,19 +35,19 @@ fn inches() -> RulerText { #[story(TransformFields<'static>, covers = [], drive = Drive::Never)] fn panel_form(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let state = data.value("state", sample()); - TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1)).show(ui).into() + let (state, state_at) = data.value_at("state", sample()); + TransformFields::new("Transform", state_at.bind(&mut state.0), START, state_at.bind(&mut state.1)).show(ui).into() } /// The panel form of a layer's properties: position and size only, percentages read against the document. #[story(TransformFields<'static>, covers = [], drive = Drive::Never)] fn panel_form_with_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let state = data.value("state", sample()); + let (state, state_at) = data.value_at("state", sample()); let mut groups = TransformGroups::NONE; groups.reference = true; groups.position = true; groups.size = true; - TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1)) + TransformFields::new("Transform", state_at.bind(&mut state.0), START, state_at.bind(&mut state.1)) .groups(groups) .document(Size::new(1000.0, 400.0)) .show(ui) @@ -57,12 +57,12 @@ fn panel_form_with_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// The bar form with the Δ toggle on: X and Y show the reference point's offset. #[story(TransformFields<'static>, covers = [], drive = Drive::Never)] fn bar_form_relative(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let state = data.value("state", (sample().0, true, true)); + let (state, state_at) = data.value_at("state", (sample().0, true, true)); Bar::new("Options", BarKind::Options) .show(ui, |ui, _| { - TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1)) + TransformFields::new("Transform", state_at.bind(&mut state.0), START, state_at.bind(&mut state.1)) .bar() - .relative(Bind::bound(&mut state.2)) + .relative(state_at.bind(&mut state.2)) .show(ui); }) .output @@ -71,10 +71,10 @@ fn bar_form_relative(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TransformFields<'static>, covers = [], drive = Drive::Never)] fn bar_form_in_percent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let state = data.value("state", sample()); + let (state, state_at) = data.value_at("state", sample()); Bar::new("Options", BarKind::Options) .show(ui, |ui, _| { - TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1)).bar().show(ui); + TransformFields::new("Transform", state_at.bind(&mut state.0), START, state_at.bind(&mut state.1)).bar().show(ui); }) .output .into() @@ -82,11 +82,11 @@ fn bar_form_in_percent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TransformFields<'static>, covers = [], drive = Drive::Never)] fn bar_form_in_a_length_unit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let state = data.value("state", sample()); + let (state, state_at) = data.value_at("state", sample()); let units = [Entry::new(UnitKind::Percent, "Percent"), Entry::new(UnitKind::Pixels, "Pixels"), Entry::new(UnitKind::Inches, "Inches")]; Bar::new("Options", BarKind::Options) .show(ui, |ui, _| { - TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1)) + TransformFields::new("Transform", state_at.bind(&mut state.0), START, state_at.bind(&mut state.1)) .bar() .units(inches(), inches()) .size_unit(size_unit_of(UnitKind::Inches, inches(), UnitKind::POINTS_PER_INCH)) diff --git a/crates/font-manager/src/axes/sliders/stories.rs b/crates/font-manager/src/axes/sliders/stories.rs index d5d426e97..d750b5dd0 100644 --- a/crates/font-manager/src/axes/sliders/stories.rs +++ b/crates/font-manager/src/axes/sliders/stories.rs @@ -1,7 +1,6 @@ //! Stories of `AxisSliders`: the Weight and Width axes of a variable face with three named instances. -use craft_ui::contract::Bind; -use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; +use craft_ui::testing::{Drive, StoryData, StoryOutput, ValueAt, story}; use egui::Ui; use super::{AxisSliders, AxisValues}; @@ -18,6 +17,6 @@ fn axis_sliders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ]; let instance = |name: &str, weight: f32, width: f32| NamedInstance { name: name.to_owned(), coordinates: vec![(WGHT, weight), (WDTH, width)] }; let instances = [instance("Light", 300.0, 100.0), instance("Regular", 400.0, 100.0), instance("Bold Condensed", 700.0, 75.0)]; - let values: &mut AxisValues = data.value("values", vec![(WGHT, 400.0), (WDTH, 100.0)]); - AxisSliders::new("Axes", &axes, Bind::bound(values)).instances(&instances).show(ui).into() + let (values, values_at): (&mut AxisValues, ValueAt<'_>) = data.value_at("values", vec![(WGHT, 400.0), (WDTH, 100.0)]); + AxisSliders::new("Axes", &axes, values_at.bind(values)).instances(&instances).show(ui).into() } diff --git a/crates/font-manager/src/picker/stories.rs b/crates/font-manager/src/picker/stories.rs index e729c2d9e..9971b0f94 100644 --- a/crates/font-manager/src/picker/stories.rs +++ b/crates/font-manager/src/picker/stories.rs @@ -212,23 +212,23 @@ fn font_picker_plain_missing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(FontPicker<'static>, covers = [Mixed], drive = Drive::Never)] fn font_picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let catalog = catalog(); - FontPicker::new("Font family", Bind::bound_mixed(data.value("family", Mixed::::Mixed)), &catalog).show(ui).into() + FontPicker::new("Font family", data.bind_mixed("family", Mixed::::Mixed), &catalog).show(ui).into() } /// A family the catalog does not hold, which the check refuses. #[story(FontPicker<'static>, covers = [Invalid], drive = Drive::Never)] fn font_picker_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let catalog = catalog(); - let known = catalog.clone(); - let check = move |family: &String| { - if known.styles(family).is_empty() { Validity::Refuse(Message::new("No such font is installed")) } else { Validity::Ok } - }; - FontPicker::new("Font family", Bind::bound(data.value("family", "Gotham".to_owned())).check(check), &catalog).show(ui).into() + // The story's catalog is built once for the process, so the check reads it rather than taking it as an input. + let family = data.bind("family", "Gotham".to_owned()).check(|family| { + if self::catalog().styles(family).is_empty() { Validity::Refuse(Message::new("No such font is installed")) } else { Validity::Ok } + }); + FontPicker::new("Font family", family, &catalog).show(ui).into() } /// A family name far longer than the field. #[story(FontPicker<'static>, covers = [LongText], drive = Drive::Never)] fn font_picker_long(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let catalog = catalog(); - FontPicker::new("Font family", Bind::bound(data.value("family", LONG_FAMILY.to_owned())), &catalog).show(ui).into() + FontPicker::new("Font family", data.bind("family", LONG_FAMILY.to_owned()), &catalog).show(ui).into() } diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index f3b5a8d53..15562e20a 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -30,6 +30,14 @@ pub struct Host { commands: Arc, jobs: Arc, files: Arc, + /// Unique per host built (`generation`). + generation: u64, +} + +/// A generation no host built before has. +fn next_generation() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } /// Collects a [`Host`]'s services; each one defaults when not set. @@ -49,6 +57,13 @@ impl Host { HostBuilder { app, i18n: None, lang: None, settings: None, commands: None, jobs: None, files: None } } + /// Which host this is: a host and its clones hold the same services and language, and one built anew + /// ([`HostBuilder::build`], [`Host::with_lang`], [`Host::with_files`]) gets a new generation. What the services + /// hold (settings sections, catalogs) changes inside them without changing the generation. + pub fn generation(&self) -> u64 { + self.generation + } + /// The app's name and version. pub fn app(&self) -> &AppInfo { &self.app @@ -97,12 +112,12 @@ impl Host { /// A copy in another language; install it to switch the interface. pub fn with_lang(&self, lang: Lang) -> Host { - Host { lang, ..self.clone() } + Host { lang, generation: next_generation(), ..self.clone() } } /// A copy with another file service; install it to switch the pickers. pub fn with_files(&self, files: Arc) -> Host { - Host { files, ..self.clone() } + Host { files, generation: next_generation(), ..self.clone() } } /// The stored value of section `S`, or `S::default()` when it is missing or does not fit `S`. @@ -166,6 +181,7 @@ impl HostBuilder { commands: self.commands.unwrap_or_else(|| Arc::new(NoCommands)), jobs: self.jobs.unwrap_or_else(default_jobs), files: self.files.unwrap_or_else(|| Arc::new(NoPickFiles::default())), + generation: next_generation(), } } diff --git a/crates/i18n/src/date.rs b/crates/i18n/src/date.rs index d554d66a3..0b1e33a9d 100644 --- a/crates/i18n/src/date.rs +++ b/crates/i18n/src/date.rs @@ -276,6 +276,8 @@ pub struct DateFormat { latin_digits: bool, /// Formatters and names, built on first use and shared by clones. cache: Arc, + /// Unique per format built; a clone keeps it (`generation`). + generation: u64, } /// One ICU formatter per field set the styles need. @@ -374,13 +376,25 @@ impl PartsWrite for Spliced { impl DateFormat { /// The format for `region`'s time locale and clock. pub fn new(region: &Region) -> DateFormat { - Self { locale: region.time.clone(), hour_cycle: region.hour_cycle, latin_digits: false, cache: Arc::default() } + Self { + locale: region.time.clone(), + hour_cycle: region.hour_cycle, + latin_digits: false, + cache: Arc::default(), + generation: crate::words::next_generation(), + } } /// This format writing `0`–`9` for [`Digits::Latin`], else the locale's own digits. Formatters /// are rebuilt on first use. pub fn with_digits(self, digits: Digits) -> DateFormat { - DateFormat { latin_digits: digits == Digits::Latin, cache: Arc::default(), ..self } + DateFormat { latin_digits: digits == Digits::Latin, cache: Arc::default(), generation: crate::words::next_generation(), ..self } + } + + /// Which format this is: a format and its clones write every date the same, and one built anew gets a new + /// generation. What keys on the dates a format writes keys on this. + pub fn generation(&self) -> u64 { + self.generation } /// The format for a locale tag (`de-CH`), with the locale's clock. diff --git a/crates/i18n/src/format.rs b/crates/i18n/src/format.rs index 163f5ed27..3b3cc78b7 100644 --- a/crates/i18n/src/format.rs +++ b/crates/i18n/src/format.rs @@ -38,6 +38,8 @@ pub struct Format { pub(crate) marks: Marks, /// The decimal and group marks of the written form, read once from a number that shows both. separators: (char, Option), + /// Unique per format built (`generation`). + generation: u64, } impl Format { @@ -50,7 +52,15 @@ impl Format { } let decimal = data::provider() .and_then(|p| DecimalFormatter::try_new_with_buffer_provider(p, (&locale).into(), DecimalFormatterOptions::default()).ok()); - let mut format = Format { decimal, group: None, point: None, percent: ("", "%"), marks: Marks::default(), separators: ('.', None) }; + let mut format = Format { + decimal, + group: None, + point: None, + percent: ("", "%"), + marks: Marks::default(), + separators: ('.', None), + generation: crate::words::next_generation(), + }; // The locale's own separators and digits, read from a number that shows them all. let probe = format.parts(&Decimal::try_from_str("-1234567.5").unwrap_or_default()); let latin = probe.integer.starts_with(|c: char| c.is_ascii_digit()); @@ -84,6 +94,12 @@ impl Format { format } + /// Which format this is: a format writes every number the same for its whole life, and one built anew gets a new + /// generation. What keys on the numbers a format writes keys on this. + pub fn generation(&self) -> u64 { + self.generation + } + /// The decimal and group marks numbers are written with, in the digits of the format. The group mark is /// `None` where the format writes none. pub fn separators(&self) -> (char, Option) { diff --git a/crates/i18n/src/words.rs b/crates/i18n/src/words.rs index 9a21368e9..706d01631 100644 --- a/crates/i18n/src/words.rs +++ b/crates/i18n/src/words.rs @@ -107,8 +107,8 @@ pub struct Words { generation: u64, } -/// A generation no `Words` built before has; English (the default) is 0. -fn next_generation() -> u64 { +/// A generation no `Words`, `Format` or `DateFormat` built before has; English (the default) is 0. +pub(crate) fn next_generation() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } diff --git a/crates/imaging/src/ui/adjust/basic/stories.rs b/crates/imaging/src/ui/adjust/basic/stories.rs index 647f43af7..47c78c6d3 100644 --- a/crates/imaging/src/ui/adjust/basic/stories.rs +++ b/crates/imaging/src/ui/adjust/basic/stories.rs @@ -15,8 +15,8 @@ use egui::Ui; #[story(BrightnessContrastEditor<'static>, covers = [Default], drive = Drive::Never)] fn brightness_contrast(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("value", BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: false }); - BrightnessContrastEditor::new("Brightness/Contrast", Bind::bound(value)).show(ui).into() + let (value, value_at) = data.value_at("value", BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: false }); + BrightnessContrastEditor::new("Brightness/Contrast", value_at.bind(value)).show(ui).into() } /// The editor in its Image › Adjustments dialog, opened from a button. @@ -35,16 +35,16 @@ fn brightness_contrast_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput #[story(ThresholdEditor<'static>, covers = [Default], drive = Drive::Never)] fn threshold(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let histogram = HistogramData::tone(&story_bins(0.0), ChannelColor::Neutral); - let level = data.value("level", 90.0); - ThresholdEditor::new("Threshold", Bind::bound(level)).histogram(&histogram).show(ui).into() + let (level, level_at) = data.value_at("level", 90.0); + ThresholdEditor::new("Threshold", level_at.bind(level)).histogram(&histogram).show(ui).into() } fn color_balance(ui: &mut Ui, data: &mut StoryData, start: ColorBalanceTone) -> StoryOutput { let shifts = ColorBalance { shadows: [-20.0, 0.0, 30.0], midtones: [10.0, -15.0, 0.0], highlights: [25.0, 10.0, -20.0], ..ColorBalance::default() }; // The host keeps the value and the tone shown. - let (value, tone) = data.value("value", (shifts, start)); - let shown = ColorBalanceEditor::new("Color Balance", Bind::bound(value)).tone(*tone).show(ui); + let ((value, tone), value_at) = data.value_at("value", (shifts, start)); + let shown = ColorBalanceEditor::new("Color Balance", value_at.bind(value)).tone(*tone).show(ui); *tone = shown.tone; shown.into() } @@ -67,13 +67,14 @@ fn color_balance_highlights(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// A filter preset: the Filter row is on. #[story(PhotoFilterEditor<'static>, covers = [Default], drive = Drive::Never, group = "Sources", title = "A filter preset")] fn photo_filter_preset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("preset", PhotoFilter { color: PhotoFilterPreset::Cooling80.color(), density: 25.0, preserve_luminosity: true }); - PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).show(ui).into() + let (value, value_at) = + data.value_at("preset", PhotoFilter { color: PhotoFilterPreset::Cooling80.color(), density: 25.0, preserve_luminosity: true }); + PhotoFilterEditor::new("Photo Filter", value_at.bind(value)).show(ui).into() } /// A colour of no preset: the Color row is on, and the select offers Custom. #[story(PhotoFilterEditor<'static>, covers = [], drive = Drive::Never, group = "Sources", title = "A custom color")] fn photo_filter_color(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("color", PhotoFilter { color: Srgba::rgb(0.4, 0.2, 0.6), density: 60.0, preserve_luminosity: false }); - PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).show(ui).into() + let (value, value_at) = data.value_at("color", PhotoFilter { color: Srgba::rgb(0.4, 0.2, 0.6), density: 60.0, preserve_luminosity: false }); + PhotoFilterEditor::new("Photo Filter", value_at.bind(value)).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/curves_panel/stories.rs b/crates/imaging/src/ui/adjust/curves_panel/stories.rs index 47cdbf216..d819a1ce1 100644 --- a/crates/imaging/src/ui/adjust/curves_panel/stories.rs +++ b/crates/imaging/src/ui/adjust/curves_panel/stories.rs @@ -6,7 +6,6 @@ use crate::ui::adjust::{ToneChannel, ToneChannels, TonePicker, ToneSpace}; use crate::ui::curve::Curve; use crate::ui::curve::stories::story_bins; use crate::ui::histogram::ChannelColor; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -36,22 +35,22 @@ fn curves_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut curves = ToneCurves::identity(&channels); curves.curves[0] = Curve::smooth(vec![[0.0, 0.0], [64.0, 80.0], [192.0, 170.0], [255.0, 255.0]]); curves.curves[1] = Curve::smooth(vec![[0.0, 10.0], [255.0, 245.0]]); - let rig = data.value("rig", Rig { curves, armed: None }); + let (rig, rig_at) = data.value_at("rig", Rig { curves, armed: None }); let histograms = [counts(0.0), counts(0.0), counts(12.0), counts(-12.0)]; - CurvesPanel::new("Curves", Bind::bound(&mut rig.curves), channels).histograms(&histograms).pickers(Bind::bound(&mut rig.armed)).show(ui).into() + CurvesPanel::new("Curves", rig_at.bind(&mut rig.curves), channels).histograms(&histograms).pickers(rig_at.bind(&mut rig.armed)).show(ui).into() } #[story(CurvesPanel<'static>, covers = [], drive = Drive::Never, group = "Modes", title = "Pencil, with Smooth")] fn curves_panel_pencil(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let channels = ToneChannels::of(ToneSpace::Rgb, false); let drawn = ToneCurves { curves: vec![Curve::Map(bumpy_map()); channels.len()], mode: CurvesMode::Pencil }; - let curves = data.value("drawn", drawn); - CurvesPanel::new("Curves", Bind::bound(curves), channels).histograms(&[counts(0.0), counts(0.0), counts(0.0), counts(0.0)]).show(ui).into() + let (curves, curves_at) = data.value_at("drawn", drawn); + CurvesPanel::new("Curves", curves_at.bind(curves), channels).histograms(&[counts(0.0), counts(0.0), counts(0.0), counts(0.0)]).show(ui).into() } #[story(CurvesPanel<'static>, covers = [], drive = Drive::Never, group = "Modes", title = "One isolated mask channel")] fn curves_panel_isolated_mask(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let channels = ToneChannels::isolated(ToneChannel::Named { name: "Layer mask".to_owned(), color: ChannelColor::Neutral }); - let curves = data.value("mask", ToneCurves::identity(&channels)); - CurvesPanel::new("Curves", Bind::bound(curves), channels).histograms(&[counts(0.0)]).show(ui).into() + let (curves, curves_at) = data.value_at("mask", ToneCurves::identity(&channels)); + CurvesPanel::new("Curves", curves_at.bind(curves), channels).histograms(&[counts(0.0)]).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/hue_saturation/stories.rs b/crates/imaging/src/ui/adjust/hue_saturation/stories.rs index 79aef78bc..ac45deb2c 100644 --- a/crates/imaging/src/ui/adjust/hue_saturation/stories.rs +++ b/crates/imaging/src/ui/adjust/hue_saturation/stories.rs @@ -2,7 +2,6 @@ use super::{HueRangeValue, HueSaturation, HueSaturationEditor}; use craft_theme::Srgba; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -22,8 +21,8 @@ fn shifted(degrees: f64) -> Srgba { #[story(HueSaturationEditor<'static>, covers = [Default], drive = Drive::Never)] fn hue_saturation_master(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("master", HueSaturation { hue: 40.0, saturation: 20.0, ..HueSaturation::default() }); - HueSaturationEditor::new("Hue/Saturation", Bind::bound(value)).adjusted_spectrum(&shifted).show(ui).into() + let (value, value_at) = data.value_at("master", HueSaturation { hue: 40.0, saturation: 20.0, ..HueSaturation::default() }); + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted_spectrum(&shifted).show(ui).into() } /// The Reds range with its four thumbs and the readout. @@ -31,13 +30,13 @@ fn hue_saturation_master(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn hue_saturation_range(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut start = HueSaturation::default(); start.ranges[0] = HueRangeValue { hue: 15.0, ..HueRangeValue::neutral(0) }; - let value = data.value("range", start); - HueSaturationEditor::new("Hue/Saturation", Bind::bound(value)).range(Some(0)).adjusted_spectrum(&shifted).show(ui).into() + let (value, value_at) = data.value_at("range", start); + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).range(Some(0)).adjusted_spectrum(&shifted).show(ui).into() } /// Colorize on: the range select is off and the Hue runs 0 to 360. #[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)] fn hue_saturation_colorize(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("colorize", HueSaturation { hue: 210.0, saturation: 40.0, colorize: true, ..HueSaturation::default() }); - HueSaturationEditor::new("Hue/Saturation", Bind::bound(value)).show(ui).into() + let (value, value_at) = data.value_at("colorize", HueSaturation { hue: 210.0, saturation: 40.0, colorize: true, ..HueSaturation::default() }); + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/levels_editor/stories.rs b/crates/imaging/src/ui/adjust/levels_editor/stories.rs index 680d4b1a6..d77eddf30 100644 --- a/crates/imaging/src/ui/adjust/levels_editor/stories.rs +++ b/crates/imaging/src/ui/adjust/levels_editor/stories.rs @@ -4,7 +4,7 @@ use super::{Levels, LevelsEditor}; use crate::ui::curve::stories::story_bins; use crate::ui::histogram::{ChannelColor, HistogramData}; use craft_behavior::Mixed; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::display::{Shade, Text}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; @@ -19,8 +19,8 @@ fn identity() -> Levels { fn levels_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let bins = story_bins(0.0); let histogram = HistogramData::tone(&bins, ChannelColor::Neutral); - let levels = data.value("levels", identity()); - let output = LevelsEditor::new("Levels", Bind::bound(&mut *levels)).histogram(&histogram).value("RGB channel").show(ui); + let (levels, levels_at) = data.value_at("levels", identity()); + let output = LevelsEditor::new("Levels", levels_at.bind(&mut *levels)).histogram(&histogram).value("RGB channel").show(ui); let facts = output.into(); let l = *levels; let readout = format!("Input {:.3} / {:.2} / {:.3}, output {:.3} / {:.3}", l.in_black, l.gamma, l.in_white, l.out_black, l.out_white); @@ -32,7 +32,7 @@ fn levels_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn levels_editor_stale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let bins = story_bins(12.0); let histogram = HistogramData::tone(&bins, ChannelColor::Red); - LevelsEditor::new("Levels", Bind::bound(data.value("stale", identity()))) + LevelsEditor::new("Levels", data.bind("stale", identity())) .channel(ChannelColor::Red) .histogram(&histogram) .stale(true) @@ -43,7 +43,7 @@ fn levels_editor_stale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(LevelsEditor<'static>, covers = [Mixed], drive = Drive::Never)] fn levels_editor_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - LevelsEditor::new("Levels", Bind::bound_mixed(data.value("mixed", Mixed::::Mixed))).show(ui).into() + LevelsEditor::new("Levels", data.bind_mixed("mixed", Mixed::::Mixed)).show(ui).into() } #[story(LevelsEditor<'static>, covers = [Invalid], drive = Drive::Never)] @@ -51,5 +51,5 @@ fn levels_editor_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse = |levels: &Levels| { if levels.in_black > 100.0 { Validity::Refuse(Message::new("Input black is above the limit")) } else { Validity::Ok } }; - LevelsEditor::new("Levels", Bind::bound(data.value("over", Levels::new(150.0, 1.0, 255.0, 0.0, 255.0))).check(refuse)).show(ui).into() + LevelsEditor::new("Levels", data.bind("over", Levels::new(150.0, 1.0, 255.0, 0.0, 255.0)).check(refuse)).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/levels_panel/stories.rs b/crates/imaging/src/ui/adjust/levels_panel/stories.rs index 976dfe003..eac768aed 100644 --- a/crates/imaging/src/ui/adjust/levels_panel/stories.rs +++ b/crates/imaging/src/ui/adjust/levels_panel/stories.rs @@ -5,7 +5,6 @@ use super::LevelsPanel; use crate::ui::adjust::{AdjustContext, Levels, ToneChannel, ToneChannels, TonePicker, ToneSpace}; use crate::ui::curve::stories::story_bins; use crate::ui::histogram::ChannelColor; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -26,10 +25,10 @@ fn counts(shift: f32) -> [u32; 256] { /// The panel over `channels` with the point pickers, in `context`. fn panel(ui: &mut Ui, data: &mut StoryData, channels: ToneChannels, context: AdjustContext, histograms: &[[u32; 256]], start: Rig) -> StoryOutput { - let rig = data.value("rig", start); - LevelsPanel::new("Levels", Bind::bound(&mut rig.levels), channels) + let (rig, rig_at) = data.value_at("rig", start); + LevelsPanel::new("Levels", rig_at.bind(&mut rig.levels), channels) .histograms(histograms) - .pickers(Bind::bound(&mut rig.armed)) + .pickers(rig_at.bind(&mut rig.armed)) .context(context) .show(ui) .into() @@ -65,7 +64,7 @@ fn levels_panel_gray(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(LevelsPanel<'static>, covers = [], drive = Drive::Never, group = "Channels", title = "One isolated mask channel")] fn levels_panel_isolated_mask(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let levels = data.value("mask", vec![Levels::identity(0.0..=255.0)]); + let (levels, levels_at) = data.value_at("mask", vec![Levels::identity(0.0..=255.0)]); let channels = ToneChannels::isolated(ToneChannel::Named { name: "Layer mask".to_owned(), color: ChannelColor::Neutral }); - LevelsPanel::new("Levels", Bind::bound(levels), channels).histograms(&[counts(0.0)]).show(ui).into() + LevelsPanel::new("Levels", levels_at.bind(levels), channels).histograms(&[counts(0.0)]).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/mixers/stories.rs b/crates/imaging/src/ui/adjust/mixers/stories.rs index 55b939fe3..3e8651bf0 100644 --- a/crates/imaging/src/ui/adjust/mixers/stories.rs +++ b/crates/imaging/src/ui/adjust/mixers/stories.rs @@ -1,13 +1,12 @@ //! Stories of Black & White, Channel Mixer and Selective Color: each editor's cases in one card. use super::{BlackWhite, BlackWhiteEditor, ChannelMixer, ChannelMixerEditor, SelectiveColor, SelectiveColorEditor, SelectiveMethod}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; fn black_white(ui: &mut Ui, data: &mut StoryData, start: BlackWhite) -> StoryOutput { - let value = data.value("value", start); - BlackWhiteEditor::new("Black & White", Bind::bound(value)).show(ui).into() + let (value, value_at) = data.value_at("value", start); + BlackWhiteEditor::new("Black & White", value_at.bind(value)).show(ui).into() } #[story(BlackWhiteEditor<'static>, covers = [Default], drive = Drive::Never, group = "Tint", title = "Default")] @@ -22,8 +21,8 @@ fn black_white_tinted(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { } fn channel_mixer(ui: &mut Ui, data: &mut StoryData, start: ChannelMixer) -> StoryOutput { - let value = data.value("value", start); - ChannelMixerEditor::new("Channel Mixer", Bind::bound(value)).show(ui).into() + let (value, value_at) = data.value_at("value", start); + ChannelMixerEditor::new("Channel Mixer", value_at.bind(value)).show(ui).into() } #[story(ChannelMixerEditor<'static>, covers = [Default], drive = Drive::Never, group = "Outputs", title = "Color")] @@ -44,8 +43,8 @@ fn channel_mixer_over(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { } fn selective_color(ui: &mut Ui, data: &mut StoryData, start: SelectiveColor) -> StoryOutput { - let value = data.value("value", start); - SelectiveColorEditor::new("Selective Color", Bind::bound(value)).show(ui).into() + let (value, value_at) = data.value_at("value", start); + SelectiveColorEditor::new("Selective Color", value_at.bind(value)).show(ui).into() } #[story(SelectiveColorEditor<'static>, covers = [Default], drive = Drive::Never, group = "Methods", title = "Relative")] diff --git a/crates/imaging/src/ui/adjust/session/stories.rs b/crates/imaging/src/ui/adjust/session/stories.rs index 2250cf143..c65a7efd5 100644 --- a/crates/imaging/src/ui/adjust/session/stories.rs +++ b/crates/imaging/src/ui/adjust/session/stories.rs @@ -2,7 +2,7 @@ use crate::ui::adjust::{AdjustContext, AdjustSession, ColorBalance, ColorBalanceEditor, ColorBalanceTone}; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Show as _, clicked}; +use craft_ui::contract::{Show as _, clicked}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -21,10 +21,11 @@ struct Panel { /// Reset returns to the settings the panel found while edited, and to the defaults the next time. #[story(ColorBalanceEditor<'static>, covers = [], drive = Drive::Never)] fn color_balance_properties(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let panel = data.value("panel", Panel { value: ColorBalance { shadows: [10.0, 0.0, -10.0], ..ColorBalance::default() }, ..Panel::default() }); + let (panel, panel_at) = + data.value_at("panel", Panel { value: ColorBalance { shadows: [10.0, 0.0, -10.0], ..ColorBalance::default() }, ..Panel::default() }); panel.pass += 1; panel.session.track(TARGET, panel.pass, &panel.value); - let mut editor = ColorBalanceEditor::new("Color Balance", Bind::bound(&mut panel.value)).context(AdjustContext::properties(true)); + let mut editor = ColorBalanceEditor::new("Color Balance", panel_at.bind(&mut panel.value)).context(AdjustContext::properties(true)); if let Some(tone) = panel.tone.take() { editor = editor.tone(tone); } diff --git a/crates/imaging/src/ui/adjust/sliders/stories.rs b/crates/imaging/src/ui/adjust/sliders/stories.rs index 5c767a474..9ea671b6a 100644 --- a/crates/imaging/src/ui/adjust/sliders/stories.rs +++ b/crates/imaging/src/ui/adjust/sliders/stories.rs @@ -3,7 +3,6 @@ use super::{AdjustField, AdjustSliders, AdjustTrack}; use crate::ui::adjust::AdjustWords; use crate::ui::adjust::style::{balance, mix, tones}; -use craft_ui::contract::Bind; use craft_ui::runtime::env::UnitKind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -12,8 +11,8 @@ use egui::Ui; #[story(AdjustSliders<'static>, covers = [Default], drive = Drive::Never)] fn adjust_sliders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let fields = AdjustField::exposure(&AdjustWords::default()); - let values = data.value("values", vec![0.0, 0.0, 1.0]); - AdjustSliders::new("Exposure", &fields, Bind::bound(values)).show(ui).into() + let (values, values_at) = data.value_at("values", vec![0.0, 0.0, 1.0]); + AdjustSliders::new("Exposure", &fields, values_at.bind(values)).show(ui).into() } /// A table with two-colour tracks. @@ -27,6 +26,6 @@ fn adjust_sliders_color_tracks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput .unit_kind(UnitKind::Percent) .track(AdjustTrack::Colors(vec![tones::BLACK, mix::RANGES[0]])), ]; - let values = data.value("colors", vec![0.0, 40.0]); - AdjustSliders::new("Colors", &fields, Bind::bound(values)).show(ui).into() + let (values, values_at) = data.value_at("colors", vec![0.0, 40.0]); + AdjustSliders::new("Colors", &fields, values_at.bind(values)).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/tone/stories.rs b/crates/imaging/src/ui/adjust/tone/stories.rs index 78283b664..ae26eb182 100644 --- a/crates/imaging/src/ui/adjust/tone/stories.rs +++ b/crates/imaging/src/ui/adjust/tone/stories.rs @@ -1,18 +1,17 @@ //! Stories of the point picker row: one picker armed, and the row in a colour mode without pickers. use super::{TonePicker, TonePickerRow}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; #[story(TonePickerRow<'static>, covers = [Default], drive = Drive::Never)] fn tone_picker_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let armed = data.value("armed", Some(TonePicker::Gray)); - TonePickerRow::new(Bind::bound(armed)).show(ui).into() + let (armed, armed_at) = data.value_at("armed", Some(TonePicker::Gray)); + TonePickerRow::new(armed_at.bind(armed)).show(ui).into() } #[story(TonePickerRow<'static>, covers = [], drive = Drive::Never)] fn tone_picker_row_unavailable(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let armed = data.value("armed", None::); - TonePickerRow::new(Bind::bound(armed)).unavailable().show(ui).into() + let (armed, armed_at) = data.value_at("armed", None::); + TonePickerRow::new(armed_at.bind(armed)).unavailable().show(ui).into() } diff --git a/crates/imaging/src/ui/blur_pins/stories.rs b/crates/imaging/src/ui/blur_pins/stories.rs index 5b6b9979f..d7df87118 100644 --- a/crates/imaging/src/ui/blur_pins/stories.rs +++ b/crates/imaging/src/ui/blur_pins/stories.rs @@ -1,7 +1,7 @@ //! Stories of the Blur Gallery's pins and the panel of the selected pin. use craft_ui::canvas::RasterSource as _; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::{Ui, vec2}; @@ -28,9 +28,9 @@ fn pin(x: f64, y: f64, amount: f64) -> BlurPin { /// The picture with the pins over it. fn on_picture(ui: &mut Ui, data: &mut StoryData, build: impl FnOnce(&MockImage) -> BlurPins) -> StoryOutput { let image = MockImage::default(); - let pins = data.value(PINS, build(&image)); + let (pins, pins_at) = data.value_at(PINS, build(&image)); story_canvas(ui, Some(&image), StoryView::Fit, |ui, at| { - StoryOutput::from(BlurPinsOverlay::new("Blur pins", Bind::bound(&mut *pins)).show_at(ui, at)) + StoryOutput::from(BlurPinsOverlay::new("Blur pins", pins_at.bind(&mut *pins)).show_at(ui, at)) }) } @@ -48,7 +48,7 @@ fn field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(BlurPinsOverlay<'static>, covers = [Invalid], drive = Drive::Never)] fn too_many_pins(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let image = MockImage::default(); - let pins = data.value(PINS, { + let (pins, pins_at) = data.value_at(PINS, { let mut pins = BlurPins::new(BlurKind::Field, bounds(&image), pin(0.5, 0.5, 30.0)); pins.pins = vec![pin(0.22, 0.55, 8.0), pin(0.5, 0.4, 30.0), pin(0.78, 0.62, 30.0)]; pins.selected = Some(1); @@ -57,7 +57,7 @@ fn too_many_pins(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { }); let few = |pins: &BlurPins| if pins.pins.len() > MOST_PINS { Validity::Refuse(Message::new("There are too many pins")) } else { Validity::Ok }; story_canvas(ui, Some(&image), StoryView::Fit, |ui, at| { - StoryOutput::from(BlurPinsOverlay::new("Blur pins", Bind::bound(&mut *pins).check(few)).show_at(ui, at)) + StoryOutput::from(BlurPinsOverlay::new("Blur pins", pins_at.bind(&mut *pins).check(few)).show_at(ui, at)) }) } diff --git a/crates/imaging/src/ui/color_range/stories.rs b/crates/imaging/src/ui/color_range/stories.rs index 90728d9a0..5407332e8 100644 --- a/crates/imaging/src/ui/color_range/stories.rs +++ b/crates/imaging/src/ui/color_range/stories.rs @@ -3,7 +3,6 @@ use std::sync::Arc; -use craft_ui::contract::Bind; use craft_ui::dialog::stories::hosted; use craft_ui::runtime::env::Label; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; @@ -29,22 +28,34 @@ fn document() -> [u32; 2] { #[story(ColorRangeDialog<'static>, covers = [Default], drive = Drive::Never)] fn color_range_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("value", sampled()); + let (value, value_at) = data.value_at("value", sampled()); let picture = MockImage::new(PROXY); - ColorRangeDialog::new("Color Range", Bind::bound(value)).mask(&picture).image(&picture).picture_scale(SCALE).document(document()).show(ui).into() + ColorRangeDialog::new("Color Range", value_at.bind(value)) + .mask(&picture) + .image(&picture) + .picture_scale(SCALE) + .document(document()) + .show(ui) + .into() } #[story(ColorRangeDialog<'static>, covers = [], drive = Drive::Never)] fn color_range_dialog_midtones(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("value", ColorRangeValue { select: ColorRangeSelect::Midtones, ..ColorRangeValue::default() }); + let (value, value_at) = data.value_at("value", ColorRangeValue { select: ColorRangeSelect::Midtones, ..ColorRangeValue::default() }); let picture = MockImage::new(PROXY); - ColorRangeDialog::new("Color Range", Bind::bound(value)).mask(&picture).image(&picture).picture_scale(SCALE).document(document()).show(ui).into() + ColorRangeDialog::new("Color Range", value_at.bind(value)) + .mask(&picture) + .image(&picture) + .picture_scale(SCALE) + .document(document()) + .show(ui) + .into() } #[story(ColorRangeDialog<'static>, covers = [], drive = Drive::Never)] fn color_range_dialog_failed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let value = data.value("value", ColorRangeValue::default()); - ColorRangeDialog::new("Color Range", Bind::bound(value)) + let (value, value_at) = data.value_at("value", ColorRangeValue::default()); + ColorRangeDialog::new("Color Range", value_at.bind(value)) .picture_scale(SCALE) .document(document()) .error(Label::from("The preview could not be rendered.")) diff --git a/crates/imaging/src/ui/curve/stories.rs b/crates/imaging/src/ui/curve/stories.rs index 81b90e1b4..61d55ac2b 100644 --- a/crates/imaging/src/ui/curve/stories.rs +++ b/crates/imaging/src/ui/curve/stories.rs @@ -4,7 +4,7 @@ use super::graph::{CurveGraph, PLOT}; use super::{Curve, CurveChannel, CurveEditor, CurvePreview, ToneRamp}; use crate::ui::histogram::{ChannelColor, HistogramData}; use craft_behavior::Mixed; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::style::DataColor; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; @@ -44,8 +44,8 @@ fn curve_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ) .clone(); let histogram = HistogramData::tone(&story_bins(0.0), ChannelColor::Neutral); - let curve = data.value("curve", bent()); - let output = CurveEditor::new("Curve", Bind::bound(curve)) + let (curve, curve_at) = data.value_at("curve", bent()); + let output = CurveEditor::new("Curve", curve_at.bind(curve)) .channels(&channels()) .overlays(&overlays) .histogram(&histogram) @@ -57,24 +57,24 @@ fn curve_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// Pencil mode: a drag draws one output per input level. #[story(CurveEditor<'static>, covers = [], drive = Drive::Drag(Grip::new(PLOT)))] fn curve_editor_pencil(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let curve = data.value("drawn", Curve::Map((0..=255).map(|k| k as f32).collect())); - CurveEditor::new("Curve", Bind::bound(curve)).pencil().show(ui).into() + let (curve, curve_at) = data.value_at("drawn", Curve::Map((0..=255).map(|k| k as f32).collect())); + CurveEditor::new("Curve", curve_at.bind(curve)).pencil().show(ui).into() } /// A contour: corner points and fields in percent; the Corner check box toggles the selected point. #[story(CurveEditor<'static>, covers = [], drive = Drive::Never)] fn curve_editor_corners(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let points = vec![[0.0, 0.0], [64.0, 160.0], [128.0, 96.0], [192.0, 224.0], [255.0, 255.0]]; - let curve = data.value("contour", Curve::from_parts(points, vec![false, false, true, false, false])); - CurveEditor::new("Contour", Bind::bound(curve)).corners().percent().show(ui).into() + let (curve, curve_at) = data.value_at("contour", Curve::from_parts(points, vec![false, false, true, false, false])); + CurveEditor::new("Contour", curve_at.bind(curve)).corners().percent().show(ui).into() } /// Fields in percent of the levels, with the selection kept by the host. #[story(CurveEditor<'static>, covers = [], drive = Drive::Never)] fn curve_editor_percent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let selected = *data.value("selected", Some(1usize)); - let curve = data.value("percent", bent()); - let output = CurveEditor::new("Curve", Bind::bound(curve)).percent().selection(selected).show(ui); + let (curve, curve_at) = data.value_at("percent", bent()); + let output = CurveEditor::new("Curve", curve_at.bind(curve)).percent().selection(selected).show(ui); *data.value("selected", Some(1usize)) = output.selected; output.into() } @@ -82,12 +82,12 @@ fn curve_editor_percent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// The plot of the curve editor alone. #[story(CurveGraph<'static>, covers = [Default], drive = Drive::Drag(Grip::new(PLOT)))] fn curve_graph(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - CurveGraph::new("Curve", Bind::bound(data.value("curve", bent()))).show(ui).into() + CurveGraph::new("Curve", data.bind("curve", bent())).show(ui).into() } #[story(CurveGraph<'static>, covers = [Mixed], drive = Drive::Never)] fn curve_graph_that_differs(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - CurveGraph::new("Curve", Bind::bound_mixed(data.value("mixed", Mixed::::Mixed))).show(ui).into() + CurveGraph::new("Curve", data.bind_mixed("mixed", Mixed::::Mixed)).show(ui).into() } /// A graph that refuses a curve of more than two points. @@ -96,7 +96,7 @@ fn curve_graph_that_is_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput let refuse = |curve: &Curve| { if curve.points().is_some_and(|points| points.len() > 2) { Validity::Refuse(Message::new("Too many points")) } else { Validity::Ok } }; - CurveGraph::new("Curve", Bind::bound(data.value("refused", bent())).check(refuse)).show(ui).into() + CurveGraph::new("Curve", data.bind("refused", bent()).check(refuse)).show(ui).into() } /// One curve, read-only. diff --git a/crates/imaging/src/ui/fill/stories.rs b/crates/imaging/src/ui/fill/stories.rs index d2c11a9be..d1de28716 100644 --- a/crates/imaging/src/ui/fill/stories.rs +++ b/crates/imaging/src/ui/fill/stories.rs @@ -12,7 +12,6 @@ use egui::Ui; use craft_behavior::kurbo::Rect; use craft_ui::canvas::RasterSource; -use craft_ui::contract::Bind; use craft_ui::dialog::stories::hosted; use craft_ui::dialog::{FullWindowView, HostedWorkspace}; use craft_ui::runtime::pending::{Job, Pending}; @@ -150,14 +149,14 @@ fn workspace_with_the_preview_failed(ui: &mut Ui, data: &mut StoryData) -> Story #[story(FillPanel<'static>, covers = [Default], drive = Drive::Never)] fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", FillSettings::default()); - FillPanel::new(Bind::bound(settings), SamplingMode::Auto).show(ui).into() + let (settings, settings_at) = data.value_at("settings", FillSettings::default()); + FillPanel::new(settings_at.bind(settings), SamplingMode::Auto).show(ui).into() } #[story(FillPanel<'static>, covers = [], drive = Drive::Never)] fn panel_with_an_error(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", FillSettings::default()); - FillPanel::new(Bind::bound(settings), SamplingMode::Custom) + let (settings, settings_at) = data.value_at("settings", FillSettings::default()); + FillPanel::new(settings_at.bind(settings), SamplingMode::Custom) .error(Some("at most 1000 sampling strokes: undo some, or reset the sampling area")) .show(ui) .into() diff --git a/crates/imaging/src/ui/fill/tool.rs b/crates/imaging/src/ui/fill/tool.rs index fd9b61e0a..cdf9d350f 100644 --- a/crates/imaging/src/ui/fill/tool.rs +++ b/crates/imaging/src/ui/fill/tool.rs @@ -18,7 +18,7 @@ use super::session::{FillLimit, FillLimits, FillSession, FillStrokeEvent, Sampli use crate::ui::select_mask::EditMode; /// The tools of Content-Aware Fill's strip: Sampling Brush (B), Lasso (L), Hand (H), Zoom (Z). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum FillTool { /// The Sampling Brush. diff --git a/crates/imaging/src/ui/filter_gallery/stories.rs b/crates/imaging/src/ui/filter_gallery/stories.rs index 70925be2c..012025430 100644 --- a/crates/imaging/src/ui/filter_gallery/stories.rs +++ b/crates/imaging/src/ui/filter_gallery/stories.rs @@ -8,7 +8,7 @@ use std::time::Duration; use craft_theme::Srgba; use craft_ui::canvas::{PixelRect, RasterSource}; -use craft_ui::contract::{Bind, Job}; +use craft_ui::contract::Job; use craft_ui::dialog::{FullWindowWorkspace as _, WorkspaceCx}; use craft_ui::patterns::form_dialogs::{Param, ParamKind}; use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource, ThumbnailOptions, Thumbnails}; @@ -153,7 +153,7 @@ fn workspace(ui: &mut Ui, data: &mut StoryData, rendering: bool) -> StoryOutput let session = data.value("session", start()).clone(); let mut workspace = FilterGalleryWorkspace::new(FilterGalleryOpen::new(image.size(), "Photo", session)); let source: &dyn FilterGallerySource = &MockSource { image, rendering, thumbs: FakeThumbSource::new() }; - let pass = workspace.show(ui, WorkspaceCx::new(source, Bind::bound(data.value("open", true)))); + let pass = workspace.show(ui, WorkspaceCx::new(source, data.bind("open", true))); // A swatch press asks the app for a color; the story has no picker. for event in &pass.events { if let FilterGalleryEvent::PickColor(request) = event { diff --git a/crates/imaging/src/ui/layer_style/blend_if/stories.rs b/crates/imaging/src/ui/layer_style/blend_if/stories.rs index 8c5b21549..e9d248858 100644 --- a/crates/imaging/src/ui/layer_style/blend_if/stories.rs +++ b/crates/imaging/src/ui/layer_style/blend_if/stories.rs @@ -1,6 +1,6 @@ //! Stories of `BlendIfBar`: halves together (one triangle per pair) and halves apart (split handles). -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::display::{Shade, Text}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -12,12 +12,12 @@ use crate::layer_style::BlendIfRange; fn blend_if_bar_unsplit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { // The card's hint over both bars: the first case shows it. Text::new("Tab to a handle. Arrows move one level, Shift ten, Alt one half.").shade(Shade::Muted).show(ui); - let range = data.value("range", BlendIfRange([30, 30, 220, 220])); - BlendIfBar::new("Underlying Layer", Bind::bound(range)).show(ui).into() + let (range, range_at) = data.value_at("range", BlendIfRange([30, 30, 220, 220])); + BlendIfBar::new("Underlying Layer", range_at.bind(range)).show(ui).into() } #[story(BlendIfBar<'static>, covers = [Default], drive = Drive::Never, group = "Handles", title = "Split pairs (Alt-drag splits a pair)")] fn blend_if_bar_split(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let range = data.value("range", BlendIfRange([10, 60, 190, 240])); - BlendIfBar::new("This Layer", Bind::bound(range)).show(ui).into() + let (range, range_at) = data.value_at("range", BlendIfRange([10, 60, 190, 240])); + BlendIfBar::new("This Layer", range_at.bind(range)).show(ui).into() } diff --git a/crates/imaging/src/ui/layer_style/contour/stories.rs b/crates/imaging/src/ui/layer_style/contour/stories.rs index 498ceb0f6..9215b3b50 100644 --- a/crates/imaging/src/ui/layer_style/contour/stories.rs +++ b/crates/imaging/src/ui/layer_style/contour/stories.rs @@ -1,6 +1,6 @@ //! Stories of the contour field: the built-in contours and a user's, under the host's "Contour" caption. -use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::contract::ShowContainer as _; use craft_ui::form::Field; use craft_ui::patterns::presets::PresetState; use craft_ui::runtime::env::Env; @@ -21,11 +21,11 @@ fn field(ui: &mut Ui, data: &mut StoryData, start: Contour, anti_alias: bool) -> let words = Env::of(ui).words::(); let user = user_contours(); let rows = contour_rows(&Contour::presets(), &user, &words, None); - let (contour, state, anti_alias) = data.value("field", (start, PresetState::::new(), Some(anti_alias))); + let ((contour, state, anti_alias), field_at) = data.value_at("field", (start, PresetState::::new(), Some(anti_alias))); let shown = Field::new("Contour").show(ui, |ui, _| { - ContourField::new("Contour", Bind::bound(&mut *contour), &rows, Bind::bound(&mut *state)) + ContourField::new("Contour", field_at.bind(&mut *contour), &rows, field_at.bind(&mut *state)) .user(&user) - .anti_alias(Bind::bound(&mut *anti_alias)) + .anti_alias(field_at.bind(&mut *anti_alias)) .show(ui) }); let output = shown.inner.map(StoryOutput::from).unwrap_or_default(); diff --git a/crates/imaging/src/ui/liquify/stories.rs b/crates/imaging/src/ui/liquify/stories.rs index 98aa45523..b264dc89e 100644 --- a/crates/imaging/src/ui/liquify/stories.rs +++ b/crates/imaging/src/ui/liquify/stories.rs @@ -12,7 +12,6 @@ use egui::{Color32, ColorImage, Ui}; use craft_behavior::PixelSize; use craft_behavior::kurbo::Point; use craft_ui::canvas::{PixelRect, RasterSource}; -use craft_ui::contract::Bind; use craft_ui::dialog::HostedWorkspace; use craft_ui::dialog::stories::hosted; use craft_ui::primitives::Revision; @@ -181,8 +180,8 @@ fn workspace_with_the_mesh_shown(ui: &mut Ui, data: &mut StoryData) -> StoryOutp #[story(LiquifyPanel<'static>, covers = [Default], drive = Drive::Never)] fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", LiquifySettings::default()); - LiquifyPanel::new(Bind::bound(settings)).show(ui).into() + let (settings, settings_at) = data.value_at("settings", LiquifySettings::default()); + LiquifyPanel::new(settings_at.bind(settings)).show(ui).into() } #[story(LiquifyPanel<'static>, covers = [], drive = Drive::Never)] @@ -194,7 +193,7 @@ fn panel_with_the_backdrop_shown(ui: &mut Ui, data: &mut StoryData) -> StoryOutp backdrop_opacity: BACKDROP_OPACITY, ..LiquifySettings::default() }; - let settings = data.value("settings", shown); + let (settings, settings_at) = data.value_at("settings", shown); let layers = [(LAYER_SKY, "Sky".to_owned()), (LAYER_HOUSE, "House".to_owned())]; - LiquifyPanel::new(Bind::bound(settings)).layers(&layers).show(ui).into() + LiquifyPanel::new(settings_at.bind(settings)).layers(&layers).show(ui).into() } diff --git a/crates/imaging/src/ui/liquify/tools.rs b/crates/imaging/src/ui/liquify/tools.rs index 73d43d5ed..d30b5c973 100644 --- a/crates/imaging/src/ui/liquify/tools.rs +++ b/crates/imaging/src/ui/liquify/tools.rs @@ -11,7 +11,7 @@ use super::session::{LiquifyStroke, StrokeEvent}; /// The tools of Liquify's strip, in strip order, with Photoshop's letters. Serialised with the /// engine's names (`forwardWarp`, `twirlCw`, `lassoMask`, …) so a [`LiquifyStroke`] passes to /// PhotoCraft's engine unchanged. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum LiquifyTool { diff --git a/crates/imaging/src/ui/raw_develop/stories.rs b/crates/imaging/src/ui/raw_develop/stories.rs index ba2143f3e..3c7dba759 100644 --- a/crates/imaging/src/ui/raw_develop/stories.rs +++ b/crates/imaging/src/ui/raw_develop/stories.rs @@ -164,14 +164,14 @@ fn floating_scope(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(RawDevelopPanel<'static>, covers = [Default], drive = Drive::Never)] fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", RawDevelopSettings::default()); - RawDevelopPanel::new(Bind::bound(settings)).show(ui).into() + let (settings, settings_at) = data.value_at("settings", RawDevelopSettings::default()); + RawDevelopPanel::new(settings_at.bind(settings)).show(ui).into() } #[story(RawDevelopPanel<'static>, covers = [], drive = Drive::Never)] fn panel_with_demosaic(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", RawDevelopSettings::default()); - RawDevelopPanel::new(Bind::bound(settings)).demosaic(Demosaic::Ahd).show(ui).into() + let (settings, settings_at) = data.value_at("settings", RawDevelopSettings::default()); + RawDevelopPanel::new(settings_at.bind(settings)).demosaic(Demosaic::Ahd).show(ui).into() } /// A click on the Color Mixer's Saturation tab, the second of its three. @@ -183,8 +183,8 @@ fn saturation_tab(fixture: &mut Fixture) { #[story(RawDevelopPanel<'static>, covers = [], drive = Drive::Custom(saturation_tab))] fn panel_with_color_mixer_saturation(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", RawDevelopSettings::default()); - RawDevelopPanel::new(Bind::bound(settings)).show(ui).into() + let (settings, settings_at) = data.value_at("settings", RawDevelopSettings::default()); + RawDevelopPanel::new(settings_at.bind(settings)).show(ui).into() } /// The scope state of the strip stories: Expanded, so the zone values and statistics show. @@ -225,7 +225,7 @@ fn floating_scope_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(RawFilmstrip<'static>, covers = [Default], drive = Drive::Never)] fn filmstrip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let items = raws(); - let current = data.value("current", 1_usize); - RawFilmstrip::new(&items, Bind::bound(current)).show(ui); + let (current, current_at) = data.value_at("current", 1_usize); + RawFilmstrip::new(&items, current_at.bind(current)).show(ui); StoryOutput::default() } diff --git a/crates/imaging/src/ui/scopes/stories.rs b/crates/imaging/src/ui/scopes/stories.rs index 235506d91..81f66fd24 100644 --- a/crates/imaging/src/ui/scopes/stories.rs +++ b/crates/imaging/src/ui/scopes/stories.rs @@ -208,12 +208,12 @@ fn first_values() -> ZoneValues { #[story(ScopePanel<'static>, covers = [Default], drive = Drive::Never)] fn tone_zones(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = (ScopePanelState { settings: view(ScopeView::Expanded), ..ScopePanelState::default() }, first_values()); - let (state, values) = data.value("zones", start); + let ((state, values), zones_at) = data.value_at("zones", start); let curves = curves(Mode::Rgb, 0.0); let channels = scope_channels(&curves); let frame = ScopeFrame::histogram(HistogramSet::new(&channels)); let (zones, scales, texts) = (ToneZone::CAMERA_RAW, zone_scales(), zone_texts(Some(&*values))); - ScopePanel::new(state).frame(&frame).zones(&zones, &scales, &texts, Bind::bound(values)).show(ui).into() + ScopePanel::new(state).frame(&frame).zones(&zones, &scales, &texts, zones_at.bind(values)).show(ui).into() } /// Generated pixels in a skin cluster, a sky and some foliage, with a few saturated ones. @@ -315,21 +315,21 @@ fn clipping_warnings_on(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(ClipWarning<'static>, covers = [Default], drive = Drive::Activate)] fn clip_warning(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let on = data.value("on", true); - ClipWarning::new("Highlight Clipping Warning (O)", Bind::bound(on), ChannelMask::R).show(ui).into() + let (on, on_at) = data.value_at("on", true); + ClipWarning::new("Highlight Clipping Warning (O)", on_at.bind(on), ChannelMask::R).show(ui).into() } #[story(ClipWarning<'static>, covers = [Mixed], drive = Drive::Never)] fn clip_warning_that_differs(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let on = data.value("mixed", Mixed::::Mixed); - ClipWarning::new("Highlight Clipping Warning (O)", Bind::bound_mixed(on), ChannelMask::R).show(ui).into() + let (on, on_at) = data.value_at("mixed", Mixed::::Mixed); + ClipWarning::new("Highlight Clipping Warning (O)", on_at.bind_mixed(on), ChannelMask::R).show(ui).into() } #[story(ClipWarning<'static>, covers = [Invalid], drive = Drive::Never)] fn clip_warning_that_is_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let on = data.value("refused", false); + let (on, on_at) = data.value_at("refused", false); let refuse = |_: &bool| Validity::Refuse(Message::new("Not available")); - ClipWarning::new("Highlight Clipping Warning (O)", Bind::bound(on).check(refuse), ChannelMask::R).show(ui).into() + ClipWarning::new("Highlight Clipping Warning (O)", on_at.bind(on).check(refuse), ChannelMask::R).show(ui).into() } /// The zones of a story over a picture, with each zone's scale and value text, and the story's canvas. @@ -343,23 +343,23 @@ fn zones_story(ui: &mut Ui, mut value: Bind<'_, ZoneValues>, texts: &[Label]) -> #[story(ToneZones<'static>, covers = [Default], drive = Drive::Drag(Grip::part(ZONE.at(1)).toward(vec2(1.0, 0.0))))] fn zones_over_a_plot(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", first_values()); + let (values, values_at) = data.value_at("values", first_values()); let texts = zone_texts(Some(&*values)); - zones_story(ui, Bind::bound(values), &texts) + zones_story(ui, values_at.bind(values), &texts) } #[story(ToneZones<'static>, covers = [Mixed], drive = Drive::Never)] fn zones_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("mixed", Mixed::::Mixed); - zones_story(ui, Bind::bound_mixed(values), &zone_texts(None)) + let (values, values_at) = data.value_at("mixed", Mixed::::Mixed); + zones_story(ui, values_at.bind_mixed(values), &zone_texts(None)) } #[story(ToneZones<'static>, covers = [Invalid], drive = Drive::Never)] fn zones_that_are_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("refused", first_values()); + let (values, values_at) = data.value_at("refused", first_values()); let texts = zone_texts(Some(&*values)); let refuse = |_: &ZoneValues| Validity::Refuse(Message::new("Not available")); - zones_story(ui, Bind::bound(values).check(refuse), &texts) + zones_story(ui, values_at.bind(values).check(refuse), &texts) } #[story(ClippingOverlay<'static>, covers = [Default], drive = Drive::Never)] diff --git a/crates/imaging/src/ui/select_mask/tools.rs b/crates/imaging/src/ui/select_mask/tools.rs index 89853e623..51e40d898 100644 --- a/crates/imaging/src/ui/select_mask/tools.rs +++ b/crates/imaging/src/ui/select_mask/tools.rs @@ -84,7 +84,7 @@ impl EditPhase { /// The tools of Select and Mask's strip, with Photoshop's letters. Quick Selection and Object /// Selection share the W slot, Lasso and Polygonal Lasso the L slot. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum SelectMaskTool { /// W. diff --git a/crates/imaging/src/ui/vanishing_point/commands.rs b/crates/imaging/src/ui/vanishing_point/commands.rs index d8d40231e..208a7c5a3 100644 --- a/crates/imaging/src/ui/vanishing_point/commands.rs +++ b/crates/imaging/src/ui/vanishing_point/commands.rs @@ -47,7 +47,7 @@ pub enum VanishingPointStripTool { } /// A slot of the strip. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] pub(super) enum Pick { EditPlane, CreatePlane, diff --git a/crates/imaging/src/ui/warp/perspective/stories.rs b/crates/imaging/src/ui/warp/perspective/stories.rs index 88dc9527a..3f18224cf 100644 --- a/crates/imaging/src/ui/warp/perspective/stories.rs +++ b/crates/imaging/src/ui/warp/perspective/stories.rs @@ -3,8 +3,8 @@ use craft_behavior::geometry::quad::Homography; use craft_behavior::kurbo::Point; -use craft_ui::contract::{Bind, Show as _}; -use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; +use craft_ui::contract::Show as _; +use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, ValueAt, story}; use egui::{Ui, vec2}; use super::overlay::CORNER; @@ -54,27 +54,27 @@ fn warped_by(planes: &[Plane]) -> impl Fn(Point) -> Point + use<> { /// Shows `planes` over the transform preview stage: the layer's picture drawn through the planes (in Layout the /// planes' targets are their sources, so it stays), the planes over it. -fn on_canvas(ui: &mut Ui, planes: &mut Vec, mode: PlaneMode) -> StoryOutput { +fn on_canvas(ui: &mut Ui, planes: &mut Vec, planes_at: ValueAt<'_>, mode: PlaneMode) -> StoryOutput { let doc = Document::standard(); let textures = doc.textures(); let layer = doc.layer(); doc.canvas(ui, Zoom::Fit, None, |ui, at| { let map = warped_by(planes); draw(ui, at, &doc, &textures, PreviewMap::function(layer, PreviewQuality::PLANE_CELLS, &map), 1.0, false); - StoryOutput::from(PerspectiveWarp::new("Planes", Bind::bound(&mut *planes), mode, 0).show_at(ui, at)) + StoryOutput::from(PerspectiveWarp::new("Planes", planes_at.bind(&mut *planes), mode, 0).show_at(ui, at)) }) } #[story(PerspectiveWarp<'static>, covers = [Default], drive = Drive::Drag(Grip::part(CORNER.at(1)).toward(vec2(1.0, -1.0))), group = "Planes", title = "Layout, two linked planes")] fn two_linked_planes_in_layout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let planes = data.value("planes", two_linked_planes(0.0)); - on_canvas(ui, planes, PlaneMode::Layout) + let (planes, planes_at) = data.value_at("planes", two_linked_planes(0.0)); + on_canvas(ui, planes, planes_at, PlaneMode::Layout) } #[story(PerspectiveWarp<'static>, covers = [Default], drive = Drive::Drag(Grip::part(CORNER.at(1)).toward(vec2(1.0, -1.0))), group = "Planes", title = "Warp, the picture follows")] fn two_linked_planes_in_warp(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let planes = data.value("warped", two_linked_planes(PULL)); - on_canvas(ui, planes, PlaneMode::Warp) + let (planes, planes_at) = data.value_at("warped", two_linked_planes(PULL)); + on_canvas(ui, planes, planes_at, PlaneMode::Warp) } /// A session over two linked planes, in `mode`. diff --git a/crates/imaging/src/ui/warp/pin/stories.rs b/crates/imaging/src/ui/warp/pin/stories.rs index 5b18f8741..94fec693f 100644 --- a/crates/imaging/src/ui/warp/pin/stories.rs +++ b/crates/imaging/src/ui/warp/pin/stories.rs @@ -2,8 +2,8 @@ //! deformation of a grid), and the options bar. use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; -use craft_ui::contract::{Bind, Show as _}; -use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; +use craft_ui::contract::Show as _; +use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, ValueAt, story}; use egui::{Ui, vec2}; use super::{Pin, PinDensity, PinEdit, PinMeshView, PinSolver, PinWarp, PinWarpBar, PinWarpOptions, PinWarpSession, PinWarpSettings}; @@ -107,9 +107,8 @@ pub(crate) fn sample_pins(layer: DocRect) -> Vec { } /// Shows `pins` over the transform preview stage: the layer's picture drawn by the real `TransformPreview` through -/// the solver's mesh as the pins deform it, the pins over it; the selection the pins report is kept. -fn on_canvas(ui: &mut Ui, data: &mut StoryData, pins: &mut Vec, show_mesh: bool) -> StoryOutput { - let selected = data.value("selected", vec![1usize]).clone(); +/// the solver's mesh as the pins deform it, the pins over it; the selection the pins report is kept in `selected`. +fn on_canvas(ui: &mut Ui, pins: &mut Vec, pins_at: ValueAt<'_>, selected: &mut Vec, show_mesh: bool) -> StoryOutput { let doc = Document::standard(); let textures = doc.textures(); let layer = layer(); @@ -117,12 +116,12 @@ fn on_canvas(ui: &mut Ui, data: &mut StoryData, pins: &mut Vec, show_mesh: let shown = doc.canvas(ui, Zoom::Fit, None, |ui, at| { let solver = IdwSolver::solved(layer, pins); draw(ui, at, &doc, &textures, PreviewMap::pins(solver.view(), layer), 1.0, false); - let output = PinWarp::new("Pins", Bind::bound(&mut *pins), solver.view()).selected_pins(&selected).show_mesh(show_mesh).show_at(ui, at); + let output = PinWarp::new("Pins", pins_at.bind(&mut *pins), solver.view()).selected_pins(selected).show_mesh(show_mesh).show_at(ui, at); reported = output.select.clone(); StoryOutput::from(output) }); if let Some(select) = reported { - *data.value("selected", vec![1usize]) = select; + *selected = select; } shown } @@ -135,10 +134,8 @@ fn pins_with_a_fixed_turn() -> Vec { #[story(PinWarp<'static>, covers = [Default], drive = Drive::Drag(Grip::part(super::overlay::PIN.at(1)).toward(vec2(1.0, 0.0))))] fn pins_with_a_fixed_rotation(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mut pins = data.value("pins", pins_with_a_fixed_turn()).clone(); - let output = on_canvas(ui, data, &mut pins, true); - *data.value("pins", pins_with_a_fixed_turn()) = pins; - output + let ((pins, pins_at), (selected, _)) = data.pair_at(("pins", pins_with_a_fixed_turn()), ("selected", vec![1usize])); + on_canvas(ui, pins, pins_at, selected, true) } /// A session on the sample pins with pin 1 selected and, when `fixed`, its rotation fixed. diff --git a/crates/imaging/src/ui/warp/stories.rs b/crates/imaging/src/ui/warp/stories.rs index a0098d70f..c5e241cde 100644 --- a/crates/imaging/src/ui/warp/stories.rs +++ b/crates/imaging/src/ui/warp/stories.rs @@ -2,7 +2,7 @@ use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_ui::bars::{Bar, BarKind}; -use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::contract::{Show as _, ShowContainer as _}; use craft_ui::testing::{Drive, Fixture, Grip, StoryData, StoryOutput, pointer, story}; use egui::{Ui, vec2}; @@ -38,26 +38,26 @@ fn hover_middle(fixture: &mut Fixture) { #[story(WarpGrid<'static>, covers = [Default])] fn one_patch_with_thirds(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mesh = data.value("mesh", WarpMesh::identity(picture(), 1, 1)); - on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", Bind::bound(mesh), picture()).show_at(ui, rect)) + let (mesh, mesh_at) = data.value_at("mesh", WarpMesh::identity(picture(), 1, 1)); + on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", mesh_at.bind(mesh), picture()).show_at(ui, rect)) } #[story(WarpGrid<'static>, covers = [Default], drive = Drive::Drag(Grip::part(POINT.at(0)).toward(vec2(24.0, 16.0))))] fn three_by_three_after_a_drag(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mesh = data.value("mesh", WarpMesh::identity(picture(), 3, 3)); - on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", Bind::bound(mesh), picture()).show_at(ui, rect)) + let (mesh, mesh_at) = data.value_at("mesh", WarpMesh::identity(picture(), 3, 3)); + on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", mesh_at.bind(mesh), picture()).show_at(ui, rect)) } #[story(WarpGrid<'static>, covers = [Default], drive = Drive::Custom(hover_middle))] fn cross_split_over_a_patch(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mesh = data.value("mesh", WarpMesh::identity(picture(), 3, 3)); - on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", Bind::bound(mesh), picture()).split(WarpSplit::Cross).show_at(ui, rect)) + let (mesh, mesh_at) = data.value_at("mesh", WarpMesh::identity(picture(), 3, 3)); + on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", mesh_at.bind(mesh), picture()).split(WarpSplit::Cross).show_at(ui, rect)) } #[story(WarpGrid<'static>, covers = [Default])] fn lines_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mesh = data.value("mesh", WarpMesh::identity(picture(), 3, 3)); - on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", Bind::bound(mesh), picture()).lines_only().show_at(ui, rect)) + let (mesh, mesh_at) = data.value_at("mesh", WarpMesh::identity(picture(), 3, 3)); + on_canvas(ui, mesh, |ui, rect, mesh| WarpGrid::new("Warp", mesh_at.bind(mesh), picture()).lines_only().show_at(ui, rect)) } /// The app's style list: None, four presets, Custom and Cylinder. diff --git a/crates/imaging/src/ui/wide_angle/mod.rs b/crates/imaging/src/ui/wide_angle/mod.rs index 34df37299..99593ec61 100644 --- a/crates/imaging/src/ui/wide_angle/mod.rs +++ b/crates/imaging/src/ui/wide_angle/mod.rs @@ -58,7 +58,7 @@ use serde_json::Value; use crate::ui::live_preview::settings_hash; /// The tools of the strip. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum WideAngleTool { /// A. diff --git a/crates/imaging/src/ui/wide_angle/stories.rs b/crates/imaging/src/ui/wide_angle/stories.rs index 69f2b0619..2d84a2c3f 100644 --- a/crates/imaging/src/ui/wide_angle/stories.rs +++ b/crates/imaging/src/ui/wide_angle/stories.rs @@ -9,7 +9,7 @@ use std::time::Duration; use craft_behavior::PixelSize; use craft_behavior::kurbo::Point; use craft_ui::canvas::RasterSource; -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::dialog::stories::hosted; use craft_ui::dialog::{FullWindowCanvas, FullWindowView, HostedWorkspace}; use craft_ui::runtime::pending::Job; @@ -119,9 +119,9 @@ fn workspace_corrected(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn lines(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let session = session(); let pictures = pictures(); - let view = data.value("view", FullWindowView::new()); + let (view, view_at) = data.value_at("view", FullWindowView::new()); let mut seen = None; - let canvas = FullWindowCanvas::new(Bind::bound(view), pictures.source()).controls(|ui, rect| { + let canvas = FullWindowCanvas::new(view_at.bind(view), pictures.source()).controls(|ui, rect| { seen = Some( ConstraintLines::new("Constraint lines", &session, &Bowed) .picture([IMAGE.width, IMAGE.height], [IMAGE.width, IMAGE.height]) @@ -135,6 +135,6 @@ fn lines(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(WideAnglePanel<'static>, covers = [Default], drive = Drive::Never)] fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let session = session(); - let preview = data.value("preview", true); - WideAnglePanel::new(&session, Bind::bound(preview)).show(ui).into() + let (preview, preview_at) = data.value_at("preview", true); + WideAnglePanel::new(&session, preview_at.bind(preview)).show(ui).into() } diff --git a/crates/imaging/tests/it/transform_preview.rs b/crates/imaging/tests/it/transform_preview.rs index 239c8aceb..882771cb6 100644 --- a/crates/imaging/tests/it/transform_preview.rs +++ b/crates/imaging/tests/it/transform_preview.rs @@ -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, 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, + #[plain_data(assume = "a display is replaced, never changed: its key follows its conversion")] + display: Option, +} + +/// What each painted preview shows: the texture and uv extent `PreviewTextures::pick` gives. +fn picks(ui: &egui::Ui, painting: &Painting) -> Vec> { + 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, +} + +fn previews(props: &mut Previews<'_>, ui: &mut egui::Ui) -> Vec> { + 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, - /// The previews the next frames paint, each at its scale. - painted: Rc>>, - /// The display every painted preview is converted for. - display: Rc>>, + /// What the next frames paint. + painting: Rc>>, /// What each painted preview showed in the last frame. shown: Rc>>>, /// 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, f32)>::new())); - let display = Rc::new(RefCell::new(None::)); + 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, 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])); diff --git a/crates/layers/src/ui/comps/stories.rs b/crates/layers/src/ui/comps/stories.rs index ba122e12c..818c7a447 100644 --- a/crates/layers/src/ui/comps/stories.rs +++ b/crates/layers/src/ui/comps/stories.rs @@ -1,6 +1,5 @@ //! Stories of `LayerCompsPanel`: no comps, two comps with one applied, a comp with a warning. -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -8,8 +7,8 @@ use super::{LayerCompRow, LayerCompsPanel}; #[story(LayerCompsPanel<'static>, covers = [Default], drive = Drive::Never)] fn layer_comps_panel_no_comps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let selected = data.value("selected", None::); - StoryOutput::from(LayerCompsPanel::new("Layer Comps", &[], Bind::bound(selected)).last_state_applied(true).show(ui)) + let (selected, selected_at) = data.value_at("selected", None::); + StoryOutput::from(LayerCompsPanel::new("Layer Comps", &[], selected_at.bind(selected)).last_state_applied(true).show(ui)) } #[story(LayerCompsPanel<'static>, covers = [], drive = Drive::Never)] @@ -18,13 +17,13 @@ fn layer_comps_panel_two_comps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput LayerCompRow::new(1, "Daylight").applied(true).visibility(true).position(true).appearance(true), LayerCompRow::new(2, "Night").comment("The scene with the lamps on").visibility(true), ]; - let selected = data.value("selected", Some(1_u64)); - StoryOutput::from(LayerCompsPanel::new("Layer Comps", &rows, Bind::bound(selected)).show(ui)) + let (selected, selected_at) = data.value_at("selected", Some(1_u64)); + StoryOutput::from(LayerCompsPanel::new("Layer Comps", &rows, selected_at.bind(selected)).show(ui)) } #[story(LayerCompsPanel<'static>, covers = [], drive = Drive::Never)] fn layer_comps_panel_warning(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rows = vec![LayerCompRow::new(1, "Draft").missing(3).visibility(true), LayerCompRow::new(2, "Final").missing(1).position(true)]; - let selected = data.value("selected", None::); - StoryOutput::from(LayerCompsPanel::new("Layer Comps", &rows, Bind::bound(selected)).show(ui)) + let (selected, selected_at) = data.value_at("selected", None::); + StoryOutput::from(LayerCompsPanel::new("Layer Comps", &rows, selected_at.bind(selected)).show(ui)) } diff --git a/crates/layers/src/ui/filter/stories.rs b/crates/layers/src/ui/filter/stories.rs index dd3658e33..f3754c7de 100644 --- a/crates/layers/src/ui/filter/stories.rs +++ b/crates/layers/src/ui/filter/stories.rs @@ -4,84 +4,85 @@ use super::{EffectKind, FilterBy, FilterKind, LayerAttribute, LayerFilter, Layer use crate::ui::mock::FakeLayers; use crate::ui::tree::LayerTree as _; use craft_theme::LabelColor; -use craft_ui::contract::Bind; -use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; +use craft_ui::testing::{Drive, StoryData, StoryOutput, ValueAt, story}; use egui::Ui; /// The bar over `filter`, with the count of `tree`'s layers the filter lists. -fn show_over(ui: &mut Ui, filter: &mut LayerFilter, tree: &FakeLayers) -> StoryOutput { +fn show_over(ui: &mut Ui, filter: &mut LayerFilter, filter_at: ValueAt<'_>, tree: &FakeLayers) -> StoryOutput { let modes = tree.blend_modes(false, "normal"); - let output = StoryOutput::from(LayerFilterBar::new(Bind::bound(&mut *filter)).blend_modes(&modes).show(ui)); + let output = StoryOutput::from(LayerFilterBar::new(filter_at.bind(&mut *filter)).blend_modes(&modes).show(ui)); let filter: &LayerFilter = filter; let shown = tree.layers.iter().filter(|layer| !filter.active() || tree.listed(&layer.id, filter)).count(); output.readout(format!("{shown} of {} layers match", tree.layers.len())) } /// The bar over `filter`, counted over the fifty-layer tree. -fn show(ui: &mut Ui, filter: &mut LayerFilter) -> StoryOutput { - show_over(ui, filter, &FakeLayers::fifty()) +fn show(ui: &mut Ui, filter: &mut LayerFilter, filter_at: ValueAt<'_>) -> StoryOutput { + show_over(ui, filter, filter_at, &FakeLayers::fifty()) } #[story(LayerFilterBar<'static>, covers = [Default], drive = Drive::Never, group = "Types", title = "Filter by Kind")] fn by_kind(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { kinds: vec![FilterKind::Pixel], ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = data.value_at("filter", LayerFilter { kinds: vec![FilterKind::Pixel], ..LayerFilter::default() }); + show(ui, filter, filter_at) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Name")] fn by_name(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Name, name: String::from("mask"), ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Name, name: String::from("mask"), ..LayerFilter::default() }); + show(ui, filter, filter_at) } /// An app that offers three of the nine types. #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Offering Kind, Name and Mode")] fn offered_types(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Mode, mode: String::from("multiply"), ..LayerFilter::default() }); + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Mode, mode: String::from("multiply"), ..LayerFilter::default() }); let tree = FakeLayers::fifty(); let modes = tree.blend_modes(false, "normal"); - let bar = LayerFilterBar::new(Bind::bound(filter)).filter_types([FilterBy::Kind, FilterBy::Name, FilterBy::Mode]).blend_modes(&modes); + let bar = LayerFilterBar::new(filter_at.bind(filter)).filter_types([FilterBy::Kind, FilterBy::Name, FilterBy::Mode]).blend_modes(&modes); StoryOutput::from(bar.show(ui)) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Effect")] fn by_effect(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Effect, effect: EffectKind::Stroke, ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Effect, effect: EffectKind::Stroke, ..LayerFilter::default() }); + show(ui, filter, filter_at) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Mode")] fn by_mode(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Mode, mode: String::from("multiply"), ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Mode, mode: String::from("multiply"), ..LayerFilter::default() }); + show(ui, filter, filter_at) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Attribute")] fn by_attribute(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Attribute, attribute: LayerAttribute::Clipped, ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = + data.value_at("filter", LayerFilter { by: FilterBy::Attribute, attribute: LayerAttribute::Clipped, ..LayerFilter::default() }); + show(ui, filter, filter_at) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Color")] fn by_color(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Color, color: Some(LabelColor::Blue), ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Color, color: Some(LabelColor::Blue), ..LayerFilter::default() }); + show(ui, filter, filter_at) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Smart Object")] fn by_smart_object(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::SmartObject, smart: vec![SmartKind::Missing], ..LayerFilter::default() }); - show_over(ui, filter, &FakeLayers::boards()) + let (filter, filter_at) = + data.value_at("filter", LayerFilter { by: FilterBy::SmartObject, smart: vec![SmartKind::Missing], ..LayerFilter::default() }); + show_over(ui, filter, filter_at, &FakeLayers::boards()) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Artboard")] fn by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() }); - show_over(ui, filter, &FakeLayers::boards()) + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() }); + show_over(ui, filter, filter_at, &FakeLayers::boards()) } #[story(LayerFilterBar<'static>, covers = [], drive = Drive::Never, group = "Types", title = "Filter by Group")] fn by_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let filter = data.value("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() }); - show(ui, filter) + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() }); + show(ui, filter, filter_at) } diff --git a/crates/layers/src/ui/panel/stories.rs b/crates/layers/src/ui/panel/stories.rs index 4ee0d6cd1..bbc228244 100644 --- a/crates/layers/src/ui/panel/stories.rs +++ b/crates/layers/src/ui/panel/stories.rs @@ -2,7 +2,6 @@ //! tree; extra columns; effects and Smart Filters open; filtered by Artboard and by Group, which keep each group open or //! closed. -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -50,8 +49,8 @@ fn layers_panel_no_active_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = selected(); - let filter = data.value("filter", LayerFilter { by: FilterBy::Name, name: String::from("o"), ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(Bind::bound(filter)).show(ui); + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Name, name: String::from("o"), ..LayerFilter::default() }); + let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } @@ -105,8 +104,8 @@ fn layers_panel_effects_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::boards(); - let filter = data.value("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(Bind::bound(filter)).show(ui); + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Artboard, ..LayerFilter::default() }); + let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } @@ -114,7 +113,7 @@ fn layers_panel_by_artboard(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)] fn layers_panel_by_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let tree = FakeLayers::fifty(); - let filter = data.value("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() }); - let shown = LayersPanel::new(&tree).filter(Bind::bound(filter)).show(ui); + let (filter, filter_at) = data.value_at("filter", LayerFilter { by: FilterBy::Group, ..LayerFilter::default() }); + let shown = LayersPanel::new(&tree).filter(filter_at.bind(filter)).show(ui); with_readout(data, shown) } diff --git a/crates/layers/tests/it/panel_input.rs b/crates/layers/tests/it/panel_input.rs index bf11f6a8f..ef21ce072 100644 --- a/crates/layers/tests/it/panel_input.rs +++ b/crates/layers/tests/it/panel_input.rs @@ -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, + events: Outbox<'a, LayersEvent>, +} + +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"); diff --git a/crates/layers/tests/it/panel_reveal.rs b/crates/layers/tests/it/panel_reveal.rs index ff8f90525..59d691d35 100644 --- a/crates/layers/tests/it/panel_reveal.rs +++ b/crates/layers/tests/it/panel_reveal.rs @@ -106,14 +106,21 @@ impl Rig { self.fixture.by_label(name).expect("the row is drawn").rect } - /// One frame that reveals `id`, with what it reported; asserts that the frame ran once and measured no row twice. + /// One frame that reveals `id`, with what it reported; asserts that the frame ran once and measured no row twice but + /// the rows the lead moves between. fn reveal(&mut self, id: u32, groups: Groups) -> Vec> { self.seen.borrow_mut().clear(); self.reveal.set(Some((id, groups))); self.fixture.idle(1); assert_eq!(self.fixture.passes(), 1, "a reveal runs its frame once"); let measures = craft_ui::runtime::measure::row_measures(self.fixture.ctx()); - assert!(measures.iter().all(|(_, count)| *count == 1), "a reveal measures no row twice: {measures:?}"); + // The lead moves to the revealed row: the row it leaves, measured before the move, is measured again with its + // new state, as is the revealed row when the pass measured it before the move. + let again = measures.iter().filter(|(_, count)| *count == 2).count(); + assert!( + measures.iter().all(|(_, count)| *count <= 2) && again <= 2, + "a reveal measures again only the rows the lead moves between: {measures:?}" + ); self.seen.borrow_mut().drain(..).collect() } diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 3907b35de..20effdb29 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -12,9 +12,9 @@ mod stories; use craft_keymap::{CommandRef, Platform}; -use craft_ui::contract::Show as _; +use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless}; use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle}; -use craft_ui::runtime::env::Env; +use craft_ui::runtime::env::{Env, Label}; use egui::{Rect, Ui}; use crate::context::Rows; @@ -56,8 +56,19 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform { } } +/// A replay at another place moves the titles' rect with the bar. +impl craft_ui::runtime::Shift for MenuBarOutput { + fn shifted(&self, by: &egui::RecordShift) -> Self { + MenuBarOutput { titles: by.rect(self.titles) } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within) } + } +} + /// What the bar did in a frame, from [`MenuBarUi::show`]. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct MenuBarOutput { /// The menu titles alone, without the room the bar leaves after them @@ -65,36 +76,57 @@ pub struct MenuBarOutput { pub titles: Rect, } +/// The English-label hook a bar takes by default: none is set, so this type only names the slot. +pub type EnglishFn = fn(Labeled<'_>) -> Option; + /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel. /// The commands chosen come back through the command queue, not from `show`. +/// +/// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing +/// reaches it (pointer, focus, keys, an open menu), it adds that run again in place of running. #[derive(craft_ui::contract::Pattern)] -pub struct MenuBarUi<'a> { +#[pattern(probe(MenuBarUi<'static, EnglishFn>))] +pub struct MenuBarUi<'a, E = EnglishFn> { bar: &'a MenuBar, /// The platform set with [`target`](Self::target); the shell's when none is. target: Option, - english: Option<&'a EnglishHook<'a>>, + english: Option>, preferred: &'a [(&'a str, char)], keyboard: Option, help_search: bool, } +/// Every input of the bar's view. +#[derive(MemoProps)] +struct BarProps<'a, #[memo_props(stateless)] E> { + bar: &'a MenuBar, + target: Target, + english: Option>, + preferred: &'a [(&'a str, char)], + keyboard: bool, + help: Option, + label: Label, +} + impl<'a> MenuBarUi<'a> { /// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]). pub fn new(bar: &'a MenuBar) -> MenuBarUi<'a> { MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false } } +} +impl<'a, E: Fn(Labeled<'_>) -> Option + Copy + 'static> MenuBarUi<'a, E> { /// The platform the bar is on, for the shortcut column ([`craft_keymap::Chord::display`]): ⌘ glyphs on /// [`Target::Mac`] and in a browser on a Mac, Ctrl names everywhere else. On [`Target::Mac`] the native bar /// has the keys, and this one takes none unless [`keyboard`](Self::keyboard) says so. - pub fn target(mut self, target: Target) -> MenuBarUi<'a> { + pub fn target(mut self, target: Target) -> MenuBarUi<'a, E> { self.target = Some(target); self } /// Whether the bar takes F10, Alt and Alt with a letter. By default it does, except on [`Target::Mac`]. The /// app turns it off while a modal dialog or the shortcut recorder has the keys. - pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a> { + pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a, E> { self.keyboard = Some(on); self } @@ -102,23 +134,24 @@ impl<'a> MenuBarUi<'a> { /// The English label of a row or title, for labels the keyboard can't type a letter of (Chinese, Japanese, /// Korean…): such a label shows its English label's mnemonic after it, "文件(F)", before a trailing ellipsis /// ("開く(O)…"), as Windows menus do. Without this hook (or when it returns `None`) such a label has no - /// mnemonic. The Help menu's search also matches the English labels, on every target. - pub fn english(mut self, english: &'a dyn Fn(Labeled<'_>) -> Option) -> MenuBarUi<'a> { - self.english = Some(english); - self + /// mnemonic. The Help menu's search also matches the English labels, on every target. The hook is a fn item or a + /// closure that captures nothing ([`Stateless`]): the bar's key follows its type. + pub fn english) -> Option + Copy + 'static>(self, english: F) -> MenuBarUi<'a, F> { + let MenuBarUi { bar, target, english: _, preferred, keyboard, help_search } = self; + MenuBarUi { bar, target, english: Some(Stateless::new(english)), preferred, keyboard, help_search } } /// Preferred mnemonics, each for a menu or submenu by its title as shown or for an item by its command id: /// the row takes that letter when its label has it and no row before it in its menu took it. Every other row /// takes the first unused letter of its label, word starts first. - pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a> { + pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a, E> { self.preferred = preferred; self } /// Start the [`MenuRole::Help`] menu with a search field over every command of the bar /// ([`MenuBar::help_entries`]). A bar with no Help menu has no field. - pub fn help_search(mut self, on: bool) -> MenuBarUi<'a> { + pub fn help_search(mut self, on: bool) -> MenuBarUi<'a, E> { self.help_search = on; self } @@ -129,20 +162,39 @@ impl<'a> MenuBarUi<'a> { pub fn show(self, ui: &mut Ui) -> MenuBarOutput { let env = Env::of(ui); let target = self.target.unwrap_or_else(|| Target::of_shell(env.view().shell())); - let rows = Rows::new(target).english(self.english).preferred(self.preferred); - let labels = - rows.labels(&self.bar.menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| rows.english_of(Labeled::Title(&menu.title))); - let shared = &rows; - let titles: Vec> = - self.bar.menus.iter().zip(labels).map(|(menu, label)| MenuTitle::new(label, move |ui| shared.show(ui, &menu.children))).collect(); let help = self.help_search.then(|| self.bar.menus.iter().position(|menu| menu.role == MenuRole::Help)).flatten(); - // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. - let (bar_model, english) = (self.bar, self.english); - let entries = move || entries_of(bar_model, english); - let mut bar = Bar::new(env.words::().label.clone(), titles).keyboard(self.keyboard.unwrap_or(target != Target::Mac)); - if let Some(menu) = help { - bar = bar.help(MenuHelp::new(menu, &entries)); - } - MenuBarOutput { titles: bar.show(ui).titles } + let props = BarProps { + bar: self.bar, + target, + english: self.english, + preferred: self.preferred, + keyboard: self.keyboard.unwrap_or(target != Target::Mac), + help, + label: env.words::().label.clone(), + }; + MemoView::new("menu-bar", props, show_bar::).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) } } + +/// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows. +fn show_bar) -> Option + Copy + 'static>(props: &mut BarProps<'_, E>, ui: &mut Ui) -> MenuBarOutput { + let hook = props.english.map(|english| { + let english = english.get(); + move |labeled: Labeled<'_>| english(labeled) + }); + let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>); + let rows = Rows::new(props.target).english(english).preferred(props.preferred); + let labels = + rows.labels(&props.bar.menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| rows.english_of(Labeled::Title(&menu.title))); + let shared = &rows; + let titles: Vec> = + props.bar.menus.iter().zip(labels).map(|(menu, label)| MenuTitle::new(label, move |ui| shared.show(ui, &menu.children))).collect(); + // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. + let bar_model = props.bar; + let entries = move || entries_of(bar_model, english); + let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard); + if let Some(menu) = props.help { + bar = bar.help(MenuHelp::new(menu, &entries)); + } + MenuBarOutput { titles: bar.show(ui).titles } +} diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index 7e1f20b13..8c5053f27 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -17,7 +17,7 @@ const CTRL_CMD_M: Chord = Chord::new(CTRL_CMD, Key::M); const CMD_COMMA: Chord = Chord::new(Mods::CMD, Key::Comma); /// The platform a layout is for. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum Target { #[allow(missing_docs)] diff --git a/crates/menu/src/modal.rs b/crates/menu/src/modal.rs index 821118fcb..9b51c0d30 100644 --- a/crates/menu/src/modal.rs +++ b/crates/menu/src/modal.rs @@ -12,7 +12,7 @@ use std::fmt; use std::sync::Arc; use craft_keymap::CommandRef; -use craft_ui::contract::{MemoKey, MemoProps}; +use craft_ui::contract::MemoProps; use crate::driver::Gate; use crate::model::{Builtin, Item}; @@ -37,7 +37,7 @@ pub type PendingRule = Arc bool + Send + Sync>; /// assert!(gate.allows_under(&rules, &"view.zoomIn".into())); /// assert!(!gate.allows_under(&rules, &"image.crop".into())); /// ``` -#[derive(Clone, Default)] +#[derive(Clone, Default, MemoProps)] #[non_exhaustive] pub struct ModalRules { /// Commands that still run while [`Gate::modal`] is set (a dialog or prompt is open), by @@ -48,6 +48,7 @@ pub struct ModalRules { pub workspace: bool, /// A pending operation is open (an uncommitted crop): only the commands this returns true for /// run. `None`: no pending operation. + #[memo_props(covered_by = "revision", reason = "the caller moves the revision with every rule change")] pub pending: Option, /// The caller's count of rule changes. A rule holds a closure and cannot be compared, so the /// caller says when the rules changed; the menu skips the resync, and the runtime's command gate keeps its answers, @@ -88,18 +89,6 @@ impl ModalRules { } } -/// As props of the runtime's command gate: the plain fields and [`ModalRules::revision`], which stands for the -/// [`ModalRules::pending`] closure. The derive cannot take the closure, and the revision is the caller's count of rule -/// changes, so equal keys mean equal rules as long as the caller moves it with every change. -impl MemoProps for ModalRules { - fn key(&self, key: &mut MemoKey) { - let ModalRules { in_dialogs, workspace, pending: _, revision } = self; - in_dialogs.key(key); - workspace.key(key); - revision.key(key); - } -} - impl fmt::Debug for ModalRules { // new: `PendingRule` is a closure; print whether one is set. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/menu/src/model.rs b/crates/menu/src/model.rs index d0955032b..164db097d 100644 --- a/crates/menu/src/model.rs +++ b/crates/menu/src/model.rs @@ -8,7 +8,7 @@ use craft_keymap::{Chord, CommandRef, Mods}; use craft_theme::Srgba; /// The app's menus, in order, and its open documents. -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct MenuBar { /// The top-level menus, left to right. @@ -18,7 +18,7 @@ pub struct MenuBar { } /// An open document, listed in the Window menu. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Document { /// What choosing it runs (bring the document to the front). @@ -51,7 +51,7 @@ impl Document { } /// A top-level menu. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Menu { /// The title in the bar. @@ -64,7 +64,7 @@ pub struct Menu { /// What a top-level menu is for, set by the app. macOS treats the app, Window and Help menus /// specially; File is where the system Close Window item goes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum MenuRole { /// Any menu without a fixed place. @@ -85,7 +85,7 @@ pub enum MenuRole { } /// The platforms an item or submenu is shown on. All of them by default. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] pub struct Platforms(u8); impl Platforms { @@ -132,7 +132,7 @@ impl BitOr for Platforms { } /// One entry of a menu. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum Node { /// An item the user can choose. @@ -162,7 +162,7 @@ pub enum Node { } /// One menu item: a command with its label, shortcut and state. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Item { /// What the item runs: the app's command (`file.open`), with its parameters @@ -198,7 +198,7 @@ pub struct Item { /// The command a row runs while `mods` are held as it is chosen (Alt on Merge Visible runs Stamp /// Visible). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Alternate { /// The modifiers that select the alternate. @@ -222,7 +222,7 @@ impl Alternate { } /// A plain item, or one with a checked state. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum ItemKind { /// An ordinary item. @@ -247,7 +247,7 @@ impl ItemKind { /// Items the layouts put in fixed places. The app tags its own About, Settings, Quit, Appearance /// and Language items; the Mac layout adds Hide and Minimize. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum ItemRole { /// The About item. @@ -268,7 +268,7 @@ pub enum ItemRole { } /// The items AppKit provides. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum Standard { #[allow(missing_docs)] @@ -307,7 +307,7 @@ pub(crate) fn label_or_system(label: &str, english: &str, system: impl FnOnce(&s /// The commands of the items the crate adds itself. The crate runs them; an app sees them only /// in a layout's result. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum Builtin { /// Hide the app: a custom item, because AppKit's own always takes ⌘H, which apps often bind. diff --git a/crates/menu/tests/it/main.rs b/crates/menu/tests/it/main.rs index 1d7371fd5..0a5fd90c0 100644 --- a/crates/menu/tests/it/main.rs +++ b/crates/menu/tests/it/main.rs @@ -4,6 +4,7 @@ mod appkit; mod keytips; mod layout; +mod memo; mod mnemonic; mod native; mod ribbon; diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs new file mode 100644 index 000000000..a07bc1b90 --- /dev/null +++ b/crates/menu/tests/it/memo.rs @@ -0,0 +1,83 @@ +//! The in-window bar is a memoized view: idle frames replay it, a title rename or Alt runs it once, and an open menu +//! runs it while it is open. + +use std::cell::RefCell; +use std::rc::Rc; + +use craft_host::target::Os; +use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items}; +use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_memo_runs, trial}; +use egui::{Event, Key, Modifiers}; + +fn model(title: &str) -> MenuBar { + from_items(&[title, "Edit"], &[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")]) +} + +fn fixture(bar: &Rc>) -> Fixture { + let bar = Rc::clone(bar); + let mut fixture = Fixture::new(move |ui| { + MenuBarUi::new(&bar.borrow()).target(Target::Linux).show(ui); + }); + fixture.os(Os::Linux); + fixture.settle(); + fixture +} + +/// The bar's runs and replays in the last frame. +fn counted(fixture: &Fixture) -> (usize, usize) { + let runs = last_frame_memo_runs(fixture.ctx()); + let of = |kind: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("BarProps") && *run == kind).count(); + (of(MemoRun::Ran), of(MemoRun::Replayed)) +} + +#[trial] +fn an_idle_menu_bar_replays_and_a_title_rename_runs_it_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + for _ in 0..4 { + fixture.frame(vec![]); + assert_eq!(counted(&fixture), (0, 1), "an idle frame replays the bar"); + } + assert!(fixture.by_label("File").is_some(), "a replayed bar keeps its titles' nodes"); + + *bar.borrow_mut() = model("Document"); + fixture.frame(vec![]); + assert_eq!(counted(&fixture).0, 1, "a model change runs the bar once in that frame"); + assert!(fixture.by_label("Document").is_some(), "and it shows the new title"); + fixture.frame(vec![]); + assert_eq!(counted(&fixture), (0, 1), "then it settles again"); +} + +/// Holding Alt underlines the titles' mnemonics: the bar runs once when Alt goes down and once when it goes up. +#[trial] +fn alt_runs_the_menu_bar_once_each_way() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + fixture.frame(vec![Event::ModifiersChanged(Modifiers::ALT)]); + assert_eq!(counted(&fixture).0, 1, "Alt down runs the bar once"); + fixture.frame(vec![]); + assert_eq!(counted(&fixture), (0, 1), "holding Alt replays it"); + fixture.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]); + assert_eq!(counted(&fixture).0, 1, "Alt up runs the bar once"); +} + +/// A menu the bar opens is an overlay inside its run, which keeps the run from being replayed while it is open. The +/// run in which the menu's fade ends is the last that shows it, so the replays after it match a real run (the audit). +#[trial] +fn an_open_menu_runs_the_bar_and_closing_it_replays_it() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + audit_replays(fixture.ctx(), true); + fixture.key(Key::F, Modifiers::ALT); + fixture.settle(); + assert!(fixture.by_label("New").is_some(), "Alt+F opened File"); + fixture.frame(vec![]); + assert!(counted(&fixture).0 > 0, "the bar runs while a menu is open"); + // The first Escape closes the menu; the bar keeps the keyboard until the second one hands it back. + fixture.key(Key::Escape, Modifiers::NONE); + fixture.settle(); + fixture.key(Key::Escape, Modifiers::NONE); + fixture.settle(); + fixture.frame(vec![]); + assert_eq!(counted(&fixture), (0, 1), "after the menu closes and the keyboard leaves, the bar replays"); +} diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index 83b065159..d8ecfd115 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -18,7 +18,7 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { _ => None, }; let mut fixture = Fixture::new(move |ui| { - MenuBarUi::new(&bar).english(&english).show(ui); + MenuBarUi::new(&bar).english(english).show(ui); }); // A Mac bar has no letters. fixture.os(Os::Linux); diff --git a/crates/pages/src/ui/column_bar/stories.rs b/crates/pages/src/ui/column_bar/stories.rs index 46ad88d2b..dc08af38f 100644 --- a/crates/pages/src/ui/column_bar/stories.rs +++ b/crates/pages/src/ui/column_bar/stories.rs @@ -1,7 +1,7 @@ //! Stories of the column bar. use super::ColumnBar; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; @@ -14,15 +14,15 @@ fn drag_first_divider(fixture: &mut Fixture) { #[story(ColumnBar<'static>, covers = [Default], drive = Drive::Custom(drag_first_divider))] fn three_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let widths = data.value("widths", vec![50.0, 30.0, 20.0]); - ColumnBar::new("Columns", Bind::bound(widths)).show(ui).into() + let (widths, widths_at) = data.value_at("widths", vec![50.0, 30.0, 20.0]); + ColumnBar::new("Columns", widths_at.bind(widths)).show(ui).into() } #[story(ColumnBar<'static>, covers = [Invalid], drive = Drive::Never)] fn a_column_without_width(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let widths = data.value("empty", vec![60.0, 0.0, 40.0]); + let (widths, widths_at) = data.value_at("empty", vec![60.0, 0.0, 40.0]); let refuse_empty = |widths: &Vec| { if widths.iter().any(|width| *width <= 0.0) { Validity::Refuse(Message::new("A column needs a width")) } else { Validity::Ok } }; - ColumnBar::new("Columns", Bind::bound(widths).check(refuse_empty)).show(ui).into() + ColumnBar::new("Columns", widths_at.bind(widths).check(refuse_empty)).show(ui).into() } diff --git a/crates/pages/src/ui/margins/stories.rs b/crates/pages/src/ui/margins/stories.rs index 4a6168325..4cd6d850c 100644 --- a/crates/pages/src/ui/margins/stories.rs +++ b/crates/pages/src/ui/margins/stories.rs @@ -39,15 +39,15 @@ fn handles(ui: &mut Ui, edges: Bind<'_, PageEdges>) -> StoryOutput { #[story(MarginHandles<'static>, covers = [Default], drive = Drive::Custom(drag_left_edge))] fn margin_handles_on_rulers(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let edges = data.value("state", PageEdges::new(Margins::uniform(72.0)).header_footer(36.0, 36.0)); - handles(ui, Bind::bound(edges)) + let (edges, edges_at) = data.value_at("state", PageEdges::new(Margins::uniform(72.0)).header_footer(36.0, 36.0)); + handles(ui, edges_at.bind(edges)) } #[story(MarginHandles<'static>, covers = [Invalid], drive = Drive::Never)] fn margin_handles_header_below_the_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let edges = data.value("reaching", PageEdges::new(Margins::uniform(72.0)).header_footer(96.0, 36.0)); + let (edges, edges_at) = data.value_at("reaching", PageEdges::new(Margins::uniform(72.0)).header_footer(96.0, 36.0)); let refuse_overlap = |edges: &PageEdges| { if edges.header > edges.margins.top { Validity::Refuse(Message::new("The header reaches the text")) } else { Validity::Ok } }; - handles(ui, Bind::bound(edges).check(refuse_overlap)) + handles(ui, edges_at.bind(edges).check(refuse_overlap)) } diff --git a/crates/pages/src/ui/preview/stories.rs b/crates/pages/src/ui/preview/stories.rs index 5733c0271..517b8b8e2 100644 --- a/crates/pages/src/ui/preview/stories.rs +++ b/crates/pages/src/ui/preview/stories.rs @@ -4,7 +4,7 @@ use super::{PagePicture, PagePreview, PagePreviewWords, PreviewLayer}; use crate::ui::fixtures::{DemoPages, PAPER}; use crate::ui::thumbnails::PageThumbnails; use craft_behavior::Selection; -use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer}; +use craft_ui::contract::{Props as _, Show as _, ShowContainer}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -53,7 +53,7 @@ fn preview_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let words = Env::of(ui).words::(); let step = Cell::new(0); let pages = DemoPages::new(5); - let layer = PreviewLayer::new(&words, Label::from("Page 2 of 5"), 1, 4, &step, Bind::bound(data.value("open", true))); + let layer = PreviewLayer::new(&words, Label::from("Page 2 of 5"), 1, 4, &step, data.bind("open", true)); ShowContainer::show(layer, ui, |ui, cx| { PagePicture::new(&pages, 1, "Page unavailable", PAPER).label("Page 2").show_at(ui, cx.rect); }) diff --git a/crates/pages/src/ui/range.rs b/crates/pages/src/ui/range.rs index 413656d2f..abfe9ae5e 100644 --- a/crates/pages/src/ui/range.rs +++ b/crates/pages/src/ui/range.rs @@ -164,19 +164,16 @@ impl<'a> PageRangeField<'a> { let env = Env::of(ui); let words = env.words::(); let units = env.units(); - let refuse = { - let (words, units) = (words.clone(), units.clone()); - move |value: &PageSelection| match &value.error { - Some(error) => Validity::Refuse(Message::new(words.error(error, &units))), - None => Validity::Ok, - } - }; let placeholder = units.number((current.min(count.saturating_sub(1)) + 1) as f64, 0..=0); let mut picked = None; let mut response = None; Field::new(label).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - let value = Bind::given(PageSelection::of(pages)).check(&refuse); + let value = + Bind::given(PageSelection::of(pages)).check_with((words.clone(), units.clone()), |(words, units), value| match &value.error { + Some(error) => Validity::Refuse(Message::new(words.error(error, units))), + None => Validity::Ok, + }); let field = TextField::with_codec(words.selected_pages.clone(), value, PageRangeCodec::new(count)) .placeholder(Label::from(placeholder.clone())) .show(ui); diff --git a/crates/pages/src/ui/setup/stories.rs b/crates/pages/src/ui/setup/stories.rs index 1961208b6..24389d639 100644 --- a/crates/pages/src/ui/setup/stories.rs +++ b/crates/pages/src/ui/setup/stories.rs @@ -12,16 +12,16 @@ use egui::Ui; #[story(PageSetupDialog<'static>, covers = [], drive = Drive::Never)] fn page_setup(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let setup = data.value("setup", PageSetup::default()); - PageSetupDialog::new(Bind::bound(setup)).layout().direction().opened(Bind::given(true)).show(ui); + let (setup, setup_at) = data.value_at("setup", PageSetup::default()); + PageSetupDialog::new(setup_at.bind(setup)).layout().direction().opened(Bind::given(true)).show(ui); StoryOutput::default() } #[story(PageSetupDialog<'static>, covers = [], drive = Drive::Never)] fn document_setup(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = PageSetup { pages: Some(8), mirrored: true, ..PageSetup::default() }; - let setup = data.value("setup", start); - PageSetupDialog::new(Bind::bound(setup)).document_setup().unit(UnitKind::Millimetres).opened(Bind::given(true)).show(ui); + let (setup, setup_at) = data.value_at("setup", start); + PageSetupDialog::new(setup_at.bind(setup)).document_setup().unit(UnitKind::Millimetres).opened(Bind::given(true)).show(ui); StoryOutput::default() } @@ -35,8 +35,8 @@ fn gridded() -> PageSetup { #[story(PageSetupDialog<'static>, covers = [], drive = Drive::Never)] fn page_setup_word(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = PageSetup { grid: Some(DocumentGrid::new(GridKind::None, 36, 39)), ..PageSetup::default() }; - let setup = data.value("setup", start); - PageSetupDialog::new(Bind::bound(setup)).layout().direction().opened(Bind::given(true)).show(ui); + let (setup, setup_at) = data.value_at("setup", start); + PageSetupDialog::new(setup_at.bind(setup)).layout().direction().opened(Bind::given(true)).show(ui); StoryOutput::default() } @@ -47,8 +47,8 @@ fn page_setup_grid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { if clicked(&Button::new("Page Setup\u{2026}").show(ui)) { open = true; } - let setup = data.value("setup", gridded()); - PageSetupDialog::new(Bind::bound(setup)).opened(Bind::bound(&mut open)).show(ui); + let (setup, setup_at) = data.value_at("setup", gridded()); + PageSetupDialog::new(setup_at.bind(setup)).opened(Bind::bound(&mut open)).show(ui); *data.value("open", false) = open; StoryOutput::default() } diff --git a/crates/pages/src/ui/table/stories.rs b/crates/pages/src/ui/table/stories.rs index 8339bc3b0..a06cf23a0 100644 --- a/crates/pages/src/ui/table/stories.rs +++ b/crates/pages/src/ui/table/stories.rs @@ -60,19 +60,19 @@ fn edge_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(EdgePicker<'static>, covers = [Mixed], drive = Drive::Never)] fn edge_picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - EdgePicker::new("Borders", Bind::bound_mixed(data.value("mixed", Mixed::Mixed))).show(ui).into() + EdgePicker::new("Borders", data.bind_mixed("mixed", Mixed::Mixed)).show(ui).into() } #[story(EdgePicker<'static>, covers = [Invalid], drive = Drive::Never)] fn edge_picker_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_none = |edges: &BorderEdges| if *edges == BorderEdges::default() { Validity::Refuse(Message::new("Choose a line")) } else { Validity::Ok }; - EdgePicker::new("Borders", Bind::bound(data.value("none", BorderEdges::default())).check(refuse_none)).show(ui).into() + EdgePicker::new("Borders", data.bind("none", BorderEdges::default()).check(refuse_none)).show(ui).into() } #[story(EdgePicker<'static>, covers = [], drive = Drive::Never)] fn edge_picker_paragraph(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - EdgePicker::new("Paragraph borders", Bind::bound(data.value("paragraph", mixed_edges()))).paragraph().show(ui).into() + EdgePicker::new("Paragraph borders", data.bind("paragraph", mixed_edges())).paragraph().show(ui).into() } /// The borders drawn as a sample on a text run, a paragraph (with a fill) and a page. diff --git a/crates/print/src/ui/stories.rs b/crates/print/src/ui/stories.rs index 8659985a8..0dc6a96a6 100644 --- a/crates/print/src/ui/stories.rs +++ b/crates/print/src/ui/stories.rs @@ -9,7 +9,7 @@ use craft_ui::runtime::env::Message; use craft_ui::testing::pictures::sample_picture; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::load::SizedTexture; -use egui::{Color32, ColorImage, Pos2, Rect, Ui, Vec2, pos2}; +use egui::{Color32, ColorImage, Rect, Ui, Vec2, pos2}; fn printers() -> Vec { vec![ @@ -23,12 +23,12 @@ fn printers() -> Vec { fn print_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = Settings { printer: "Office_1".to_owned(), duplex: Some(Duplex::LongEdge), ..Settings::default() }; let printers = printers(); - PrintPanel::new(Bind::bound(data.value("settings", start)), &printers).show(ui).into() + PrintPanel::new(data.bind("settings", start), &printers).show(ui).into() } #[story(PrintPanel<'static>, covers = [], drive = Drive::Never)] fn print_panel_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - PrintPanel::new(Bind::bound(data.value("settings", Settings::default())), &[]).discovering(true).show(ui).into() + PrintPanel::new(data.bind("settings", Settings::default()), &[]).discovering(true).show(ui).into() } const PICTURE: [usize; 2] = [240, 160]; @@ -58,8 +58,8 @@ fn preview_sheet(ui: &Ui) -> PrintSheet { #[story(PrintPreview<'static>, covers = [Default])] fn print_preview(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = preview_sheet(ui); - let position = data.value("position", sheet.image.min); - PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into() + let (position, position_at) = data.value_at("position", sheet.image.min); + PrintPreview::new("Print preview", &sheet, position_at.bind(position)).show(ui).into() } /// The image box hangs over the paper's right edge, a position the host refuses. @@ -68,11 +68,10 @@ fn print_preview_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = preview_sheet(ui); let paper = Rect::from_min_size(pos2(0.0, 0.0), sheet.paper); let size = sheet.image.size(); - let on_paper = move |at: &Pos2| { - if paper.contains_rect(Rect::from_min_size(*at, size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) } - }; - let position = data.value("position", pos2(400.0, 156.0)); - PrintPreview::new("Print preview", &sheet, Bind::bound(position).check(on_paper)).show(ui).into() + let position = data.bind("position", pos2(400.0, 156.0)).check_with((paper, size), |(paper, size), at| { + if paper.contains_rect(Rect::from_min_size(*at, *size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) } + }); + PrintPreview::new("Print preview", &sheet, position).show(ui).into() } #[story(PrintDialog<'static>, covers = [], drive = Drive::Never)] @@ -80,16 +79,13 @@ fn print_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = Settings { printer: "Office_1".to_owned(), duplex: Some(Duplex::LongEdge), ..Settings::default() }; let printers = printers(); let sheet = sheet(ui, true); - PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet).ready(true).show(ui).into() + PrintDialog::new(data.bind("settings", start), &printers, Bind::given(DialogFields::default()), &sheet).ready(true).show(ui).into() } #[story(PrintDialog<'static>, covers = [], drive = Drive::Never)] fn print_dialog_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = sheet(ui, false); - PrintDialog::new(Bind::bound(data.value("settings", Settings::default())), &[], Bind::given(DialogFields::default()), &sheet) - .discovering(true) - .show(ui) - .into() + PrintDialog::new(data.bind("settings", Settings::default()), &[], Bind::given(DialogFields::default()), &sheet).discovering(true).show(ui).into() } #[story(PrintDialog<'static>, covers = [], drive = Drive::Never)] @@ -97,5 +93,5 @@ fn print_dialog_busy(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = Settings { printer: "Office_1".to_owned(), ..Settings::default() }; let printers = printers(); let sheet = sheet(ui, false); - PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet).busy(true).show(ui).into() + PrintDialog::new(data.bind("settings", start), &printers, Bind::given(DialogFields::default()), &sheet).busy(true).show(ui).into() } diff --git a/crates/review/src/ui/signature/stories.rs b/crates/review/src/ui/signature/stories.rs index 4b56b36d0..c0b3b6356 100644 --- a/crates/review/src/ui/signature/stories.rs +++ b/crates/review/src/ui/signature/stories.rs @@ -2,7 +2,7 @@ use super::{DrawPad, SignaturePadDialog}; use crate::signature::SignatureDraft; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::dialog::StackDialog as _; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; @@ -10,16 +10,16 @@ use egui::Ui; #[story(DrawPad<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::PAD)))] fn draw_pad_with_strokes(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let strokes = data.value("strokes", vec![vec![[0.1, 0.5], [0.3, 0.2], [0.5, 0.7], [0.8, 0.4]]]); - DrawPad::new("Draw", Bind::bound(strokes)).show(ui).into() + let (strokes, strokes_at) = data.value_at("strokes", vec![vec![[0.1, 0.5], [0.3, 0.2], [0.5, 0.7], [0.8, 0.4]]]); + DrawPad::new("Draw", strokes_at.bind(strokes)).show(ui).into() } #[story(DrawPad<'static>, covers = [Invalid], drive = Drive::Never)] fn draw_pad_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_many = |strokes: &Vec>| if strokes.len() > 3 { Validity::Refuse(Message::new("Too many strokes")) } else { Validity::Ok }; - let strokes = data.value("strokes", vec![vec![[0.1, 0.2], [0.3, 0.4]]; 4]); - DrawPad::new("Draw", Bind::bound(strokes).check(refuse_many)).show(ui).into() + let (strokes, strokes_at) = data.value_at("strokes", vec![vec![[0.1, 0.2], [0.3, 0.4]]; 4]); + DrawPad::new("Draw", strokes_at.bind(strokes).check(refuse_many)).show(ui).into() } /// A dialog kept across passes. diff --git a/crates/story-render/src/main.rs b/crates/story-render/src/main.rs index b1cab6d45..b0e46c5a8 100644 --- a/crates/story-render/src/main.rs +++ b/crates/story-render/src/main.rs @@ -318,7 +318,7 @@ fn card(spec: &Arc, env: &RootEnv, options: &Options) -> (Fixture, Option< }); settle(&mut fixture); let mut opened = false; - for state in cells.borrow_mut().values_mut().filter(|state| state.dialog.hidden) { + for state in cells.borrow_mut().states_mut().filter(|state| state.dialog.hidden) { state.show_dialog(); opened = true; } diff --git a/crates/table/src/ui/conditions/stories.rs b/crates/table/src/ui/conditions/stories.rs index 82950ee59..491bc78c1 100644 --- a/crates/table/src/ui/conditions/stories.rs +++ b/crates/table/src/ui/conditions/stories.rs @@ -3,7 +3,6 @@ use super::{ Condition, ConditionBuilder, ConditionFields, ConditionGroup, ConditionItem, ConditionKind, ConditionLayout, ConditionValue, Join, Match, }; -use craft_ui::contract::Bind; use craft_ui::pickers::PickedDate; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -68,8 +67,8 @@ fn rules() -> ConditionGroup { #[story(ConditionBuilder<'static>, covers = [Default], drive = Drive::Never)] fn condition_builder(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let group = data.value("group", rules()); - ConditionBuilder::new("Rules", Bind::bound(group), &Photos).show(ui).into() + let (group, group_at) = data.value_at("group", rules()); + ConditionBuilder::new("Rules", group_at.bind(group), &Photos).show(ui).into() } /// Three rules in the joined layout, the third joined to the second by Or, at the rule limit so "+ Rule" is disabled. @@ -80,7 +79,7 @@ fn condition_builder_joined(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { rule.join = join; ConditionItem::Rule(rule) }; - let group = data.value( + let (group, group_at) = data.value_at( "joined", ConditionGroup::new( Match::All, @@ -91,5 +90,5 @@ fn condition_builder_joined(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ], ), ); - ConditionBuilder::new("Rules", Bind::bound(group), &Photos).layout(ConditionLayout::Joined).max_rules(3).show(ui).into() + ConditionBuilder::new("Rules", group_at.bind(group), &Photos).layout(ConditionLayout::Joined).max_rules(3).show(ui).into() } diff --git a/crates/table/src/ui/stats/stories.rs b/crates/table/src/ui/stats/stories.rs index 4ec2f730c..2459daa53 100644 --- a/crates/table/src/ui/stats/stories.rs +++ b/crates/table/src/ui/stats/stories.rs @@ -1,7 +1,7 @@ //! Stories of the selection statistics readout. use super::{SelectionStats, SelectionStatsReadout, StatsShown, StatsWords, stats_parts}; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::{Key, Modifiers, Ui}; @@ -13,7 +13,7 @@ fn stats() -> SelectionStats { fn readout(ui: &mut Ui, data: &mut StoryData, initial: StatsShown) -> StoryOutput { let shown = *data.value("shown", initial); let parts = stats_parts(&stats(), &shown, &StatsWords::default(), |value| format!("{value:.1}")); - SelectionStatsReadout::new("Selection statistics", &parts, Bind::bound(data.value("shown", initial))).show(ui).into() + SelectionStatsReadout::new("Selection statistics", &parts, data.bind("shown", initial)).show(ui).into() } #[story(SelectionStatsReadout<'static>, covers = [Default])] @@ -33,9 +33,7 @@ fn no_statistic_shown_is_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutp let refuse_none = |shown: &StatsShown| { if *shown == StatsShown::default() { Validity::Refuse(Message::new("Show at least one statistic")) } else { Validity::Ok } }; - SelectionStatsReadout::new("Selection statistics", &parts, Bind::bound(data.value("shown", StatsShown::default())).check(refuse_none)) - .show(ui) - .into() + SelectionStatsReadout::new("Selection statistics", &parts, data.bind("shown", StatsShown::default()).check(refuse_none)).show(ui).into() } fn open_menu(fixture: &mut Fixture) { diff --git a/crates/text/src/ui/columns.rs b/crates/text/src/ui/columns.rs index 838b45cb7..abff0e7f9 100644 --- a/crates/text/src/ui/columns.rs +++ b/crates/text/src/ui/columns.rs @@ -431,27 +431,30 @@ impl TextColumnsDialog { let codec = NumberCodec::new(units.reader(None), 0); let most = self.most_columns(); let message = Self::number_message(words, units, most); - let count_check = move |count: &Option| match count { - Some(n) if !(1.0..=f64::from(most)).contains(n) => Validity::Error(Message::new(message.clone())), + let count_check = |(most, message): &(u32, &str), count: &Option| match count { + Some(n) if !(1.0..=f64::from(*most)).contains(n) => Validity::Error(Message::new((*message).to_owned())), _ => Validity::Ok, }; let edit = Field::new(words.number.clone()) - .show(ui, |ui, _| NumberField::new(words.number.clone(), Bind::given(shown).check(&count_check)).codec(codec.clone()).show(ui)) + .show(ui, |ui, _| { + NumberField::new(words.number.clone(), Bind::given(shown).check_with((most, message.as_str()), count_check)) + .codec(codec.clone()) + .show(ui) + }) .inner; self.edit_count(edit.map(|out| out.edit.events).unwrap_or_default()); if self.word.is_none() { let points = self.edited.spacing.map_or(Mixed::Mixed, |p| Mixed::Same(Some(f64::from(p)))); let range = 0.0..=f64::from(MAX_SPACING); let message = self.spacing_message(words, units); - let in_range = range.clone(); - let spacing_check = move |spacing: &Option| match spacing { - Some(points) if !in_range.contains(points) => Validity::Error(Message::new(message.clone())), + let spacing_check = |(range, message): &(std::ops::RangeInclusive, &str), spacing: &Option| match spacing { + Some(points) if !range.contains(points) => Validity::Error(Message::new((*message).to_owned())), _ => Validity::Ok, }; let lengths = self.unit.lengths(); let edit = Field::new(words.spacing.clone()) .show(ui, |ui, _| { - let bind = Bind::given(points).check(&spacing_check); + let bind = Bind::given(points).check_with((range.clone(), message.as_str()), spacing_check); let field = NumberField::length(words.spacing.clone(), bind, lengths).range(range.clone()); field.show(ui).edit.events.map(|v| v.map(|p| p as f32)) }) diff --git a/crates/text/src/ui/editor/stories.rs b/crates/text/src/ui/editor/stories.rs index 3490eba1b..e8bcf4fc5 100644 --- a/crates/text/src/ui/editor/stories.rs +++ b/crates/text/src/ui/editor/stories.rs @@ -262,8 +262,8 @@ fn over_canvas(ui: &mut Ui, text: &mut String, mut bind: Bind<'_, TextSelection> /// The editor over `text` with `selection` on a canvas. fn on_canvas(ui: &mut Ui, data: &mut StoryData, text: &str, selection: TextSelection) -> StoryOutput { let mut host = data.value("text", text.to_owned()).clone(); - let selection = data.value("selection", selection); - let out = over_canvas(ui, &mut host, Bind::bound(&mut *selection)); + let (selection, selection_at) = data.value_at("selection", selection); + let out = over_canvas(ui, &mut host, selection_at.bind(&mut *selection)); *data.value("text", String::new()) = host; out } @@ -297,17 +297,17 @@ fn composing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TextEditor<'static>, covers = [Mixed], drive = Drive::Never)] fn selections_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut host = data.value("text", SAMPLE.to_owned()).clone(); - let selection = data.value("selection", Mixed::::Mixed); - over_canvas(ui, &mut host, Bind::bound_mixed(&mut *selection)) + let (selection, selection_at) = data.value_at("selection", Mixed::::Mixed); + over_canvas(ui, &mut host, selection_at.bind_mixed(&mut *selection)) } #[story(TextEditor<'static>, covers = [Invalid], drive = Drive::Never)] fn selection_past_the_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut host = data.value("text", SAMPLE.to_owned()).clone(); let end = host.chars().count(); - let selection = data.value("selection", TextSelection::caret_at(end + 1)); - let inside = move |selection: &TextSelection| { - if selection.caret > end { Validity::Refuse(Message::new("The selection is past the text")) } else { Validity::Ok } + let (selection, selection_at) = data.value_at("selection", TextSelection::caret_at(end + 1)); + let inside = |end: &usize, selection: &TextSelection| { + if selection.caret > *end { Validity::Refuse(Message::new("The selection is past the text")) } else { Validity::Ok } }; - over_canvas(ui, &mut host, Bind::bound(&mut *selection).check(inside)) + over_canvas(ui, &mut host, selection_at.bind(&mut *selection).check_with(end, inside)) } diff --git a/crates/text/src/ui/path_text/stories.rs b/crates/text/src/ui/path_text/stories.rs index 9c4556c37..56326ef41 100644 --- a/crates/text/src/ui/path_text/stories.rs +++ b/crates/text/src/ui/path_text/stories.rs @@ -2,7 +2,7 @@ use super::{MARK, PathRange, PathTextMarkers, PathTrack}; use craft_behavior::kurbo::{BezPath, Circle, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg, Point, Shape as _, Vec2 as PathVec}; -use craft_ui::contract::{Bind, Show as _}; +use craft_ui::contract::Show as _; use craft_ui::testing::canvas_story::{self, OUTLINE, StoryPicture, StoryShape, paint_shapes}; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::{Color32, Ui, vec2}; @@ -126,7 +126,7 @@ fn on_canvas( configure: impl for<'a> Fn(PathTextMarkers<'a>) -> PathTextMarkers<'a>, ) -> StoryOutput { const STEPS: usize = 120; - let range = data.value("range", initial); + let (range, range_at) = data.value_at("range", initial); let boxes = glyph_boxes(track, *range); let length = track.length(); let mut path = BezPath::new(); @@ -137,7 +137,7 @@ fn on_canvas( let shapes = [StoryShape::line(&path, OUTLINE, colour)]; let picture = StoryPicture::new(2 * CENTER.x as u32, 2 * CENTER.y as u32, move |p| paint_shapes(&shapes, Color32::TRANSPARENT, p)); canvas_story::on_picture(ui, &picture, |ui, at, _| { - StoryOutput::from(configure(PathTextMarkers::new("Text on path", Bind::bound(&mut *range), track).body(&boxes)).show_at(ui, at).range) + StoryOutput::from(configure(PathTextMarkers::new("Text on path", range_at.bind(&mut *range), track).body(&boxes)).show_at(ui, at).range) }) } diff --git a/crates/text/src/ui/ruler/stories.rs b/crates/text/src/ui/ruler/stories.rs index f91b539bb..5f4b3ed7a 100644 --- a/crates/text/src/ui/ruler/stories.rs +++ b/crates/text/src/ui/ruler/stories.rs @@ -6,7 +6,7 @@ use super::{RulerValues, TabAlign, TabLeader, TabStop, TextRuler}; use crate::ui::length::DocUnit; use craft_behavior::Mixed; use craft_ui::canvas::Rulers; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::primitives::RulerFace; use craft_ui::runtime::env::{Message, UnitKind}; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; @@ -47,8 +47,8 @@ fn inches() -> DocUnit { #[story(TextRuler<'static>, covers = [Default], drive = Drive::Drag(Grip::new(FIRST)))] fn with_stops_and_indents(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let kind = *data.value("kind", TabAlign::Left); - let values = data.value("values", word()); - let out = TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).kind(kind).show(ui); + let (values, values_at) = data.value_at("values", word()); + let out = TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).kind(kind).show(ui); if let Some(next) = out.kind { *data.value("kind", TabAlign::Left) = next; } @@ -57,23 +57,23 @@ fn with_stops_and_indents(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TextRuler<'static>, covers = [Mixed], drive = Drive::Never)] fn paragraphs_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", Mixed::::Mixed); - TextRuler::new("Ruler", Bind::bound_mixed(&mut *values), COLUMN).unit(inches()).show(ui).into() + let (values, values_at) = data.value_at("values", Mixed::::Mixed); + TextRuler::new("Ruler", values_at.bind_mixed(&mut *values), COLUMN).unit(inches()).show(ui).into() } #[story(TextRuler<'static>, covers = [Invalid], drive = Drive::Never)] fn indent_too_wide(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", RulerValues { left_indent: MOST_INDENT + 36.0, ..word() }); + let (values, values_at) = data.value_at("values", RulerValues { left_indent: MOST_INDENT + 36.0, ..word() }); let narrow = |values: &RulerValues| { if values.left_indent > MOST_INDENT { Validity::Refuse(Message::new("The indent leaves too little room")) } else { Validity::Ok } }; - TextRuler::new("Ruler", Bind::bound(&mut *values).check(narrow), COLUMN).unit(inches()).show(ui).into() + TextRuler::new("Ruler", values_at.bind(&mut *values).check(narrow), COLUMN).unit(inches()).show(ui).into() } #[story(TextRuler<'static>, covers = [], drive = Drive::Never)] fn tabs_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", RulerValues { stops: sample_stops(), ..RulerValues::default() }); - TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).picked_stop(PICKED).show(ui).into() + let (values, values_at) = data.value_at("values", RulerValues { stops: sample_stops(), ..RulerValues::default() }); + TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).picked_stop(PICKED).show(ui).into() } /// The page's width, points: 8.5 in. @@ -88,7 +88,7 @@ const THREE_GAPS: [(f32, f32); 3] = [(108.0, 126.0), (225.0, 243.0), (342.0, 360 /// Word's ruler over a page, its zero at the left margin, in `face` (unset: the component set's). fn over_a_page(ui: &mut Ui, data: &mut StoryData, face: Option) -> StoryOutput { - let values = data.value("values", word()); + let (values, values_at) = data.value_at("values", word()); let stage = craft_ui::testing::stage(ui); let (strip, _) = Rulers::strips(ui, stage); // The page starts at the strip's start edge: its right edge in a right-to-left interface. @@ -97,7 +97,7 @@ fn over_a_page(ui: &mut Ui, data: &mut StoryData, face: Option) -> St } else { (strip.min.x + PAGE_MARGIN, egui::Rangef::new(strip.min.x, strip.min.x + PAGE)) }; - let mut ruler = TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).origin(origin).extent(extent).scale(1.0); + let mut ruler = TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).origin(origin).extent(extent).scale(1.0); if let Some(face) = face { ruler = ruler.face(face); } @@ -124,26 +124,26 @@ fn centred_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TextRuler<'static>, covers = [], drive = Drive::Never)] fn two_column_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", RulerValues::default()); - TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).gaps(&TWO_GAPS).show(ui).into() + let (values, values_at) = data.value_at("values", RulerValues::default()); + TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).gaps(&TWO_GAPS).show(ui).into() } /// Fixed column gaps: shaded as on any ruler, with no grip and no resize cursor, where the document's column settings /// fix the gaps. #[story(TextRuler<'static>, covers = [], drive = Drive::Never)] fn fixed_column_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", RulerValues::default()); - TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).gaps(&TWO_GAPS).gaps_draggable(false).show(ui).into() + let (values, values_at) = data.value_at("values", RulerValues::default()); + TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).gaps(&TWO_GAPS).gaps_draggable(false).show(ui).into() } #[story(TextRuler<'static>, covers = [], drive = Drive::Never)] fn three_column_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", RulerValues::default()); - TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).gaps(&THREE_GAPS).show(ui).into() + let (values, values_at) = data.value_at("values", RulerValues::default()); + TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).gaps(&THREE_GAPS).show(ui).into() } #[story(TextRuler<'static>, covers = [], drive = Drive::Never)] fn table_column_borders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let values = data.value("values", RulerValues::default()); - TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).columns(&[0.0, 156.0, 312.0, COLUMN]).show(ui).into() + let (values, values_at) = data.value_at("values", RulerValues::default()); + TextRuler::new("Ruler", values_at.bind(&mut *values), COLUMN).unit(inches()).columns(&[0.0, 156.0, 312.0, COLUMN]).show(ui).into() } diff --git a/crates/text/src/ui/style_panel/stories.rs b/crates/text/src/ui/style_panel/stories.rs index 800173a3b..383793e19 100644 --- a/crates/text/src/ui/style_panel/stories.rs +++ b/crates/text/src/ui/style_panel/stories.rs @@ -2,7 +2,6 @@ use super::{NamedStyleRow, StylePreview, TextStyleKind, TextStyleRow, TextStylesPanel, style_rows}; use craft_behavior::{IconId, Mixed, Selection}; -use craft_ui::contract::Bind; use craft_ui::patterns::presets::{PresetKey, PresetPicker, PresetState}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -18,8 +17,8 @@ fn character_rows() -> Vec { #[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)] fn paragraph_styles_with_an_overridden_style(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rows = paragraph_rows(); - let selection = data.value("paragraph", Selection::::default()); - TextStylesPanel::new("Paragraph Styles", TextStyleKind::Paragraph, &rows, Bind::bound(selection)) + let (selection, selection_at) = data.value_at("paragraph", Selection::::default()); + TextStylesPanel::new("Paragraph Styles", TextStyleKind::Paragraph, &rows, selection_at.bind(selection)) .current(Some(1), true) .target(true) .show(ui) @@ -29,8 +28,8 @@ fn paragraph_styles_with_an_overridden_style(ui: &mut Ui, data: &mut StoryData) #[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)] fn character_styles_with_highlighted_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rows = character_rows(); - let selection = data.value("character", Selection::new(vec![1_u64, 2], Some(2), Some(1))); - TextStylesPanel::new("Character Styles", TextStyleKind::Character, &rows, Bind::bound(selection)) + let (selection, selection_at) = data.value_at("character", Selection::new(vec![1_u64, 2], Some(2), Some(1))); + TextStylesPanel::new("Character Styles", TextStyleKind::Character, &rows, selection_at.bind(selection)) .current(Some(0), false) .target(true) .highlighting(true) @@ -41,8 +40,8 @@ fn character_styles_with_highlighted_rows(ui: &mut Ui, data: &mut StoryData) -> #[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)] fn no_rows_with_empty_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rows: Vec = Vec::new(); - let selection = data.value("empty", Selection::::default()); - TextStylesPanel::new("Character Styles", TextStyleKind::Character, &rows, Bind::bound(selection)).empty("No document").show(ui).into() + let (selection, selection_at) = data.value_at("empty", Selection::::default()); + TextStylesPanel::new("Character Styles", TextStyleKind::Character, &rows, selection_at.bind(selection)).empty("No document").show(ui).into() } fn picker_styles() -> Vec { @@ -56,6 +55,6 @@ fn picker_styles() -> Vec { #[story(TextStylesPanel<'static>, covers = [], drive = Drive::Never)] fn style_picker_over_style_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rows = style_rows(&picker_styles()); - let (applied, state) = data.value("picker", (Mixed::Same(Some(PresetKey::Item(2_u64))), PresetState::>::new())); - PresetPicker::new("Style", Bind::bound_mixed(applied), &rows, Bind::bound(state)).show(ui).into() + let ((applied, state), picker_at) = data.value_at("picker", (Mixed::Same(Some(PresetKey::Item(2_u64))), PresetState::>::new())); + PresetPicker::new("Style", picker_at.bind_mixed(applied), &rows, picker_at.bind(state)).show(ui).into() } diff --git a/crates/theme-editor/src/stories.rs b/crates/theme-editor/src/stories.rs index 27b0f2e40..dcc43051c 100644 --- a/crates/theme-editor/src/stories.rs +++ b/crates/theme-editor/src/stories.rs @@ -3,7 +3,6 @@ use super::{AppLayerEditor, Pick, Problems, ThemeSubject, ThemeWorkspace, TokenBrowser, TokenDetail}; use craft_theme::report::ContrastReport; use craft_theme::{AppId, AppSizes, Appearance, Contrast, Explained, Mode, Size, TextSize, builtins}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use std::sync::LazyLock; @@ -25,7 +24,7 @@ fn explained() -> (&'static Explained, &'static ContrastReport) { #[story(TokenBrowser<'static>, covers = [])] fn token_browser(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TokenBrowser::new(explained().0, Bind::bound(data.value("pick", None::))).show(ui); + TokenBrowser::new(explained().0, data.bind("pick", None::)).show(ui); StoryOutput::default() } @@ -44,7 +43,7 @@ fn wordcraft_explained() -> &'static Explained { // The browser over the app layer: WordCraft's accent and chrome pins show as the roles' values. #[story(TokenBrowser<'static>, covers = [])] fn token_browser_with_wordcraft_pins(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TokenBrowser::new(wordcraft_explained(), Bind::bound(data.value("pins_pick", None::))).show(ui); + TokenBrowser::new(wordcraft_explained(), data.bind("pins_pick", None::)).show(ui); StoryOutput::default() } @@ -77,6 +76,6 @@ fn picked_size() -> &'static Pick { // The first size is picked, so the override editor and its controls show. #[story(AppLayerEditor<'static>, covers = [], drive = Drive::Activate)] fn app_layer_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - AppLayerEditor::new(Bind::bound(data.value("sizes", AppSizes::default())), explained().0).pick(picked_size()).show(ui); + AppLayerEditor::new(data.bind("sizes", AppSizes::default()), explained().0).pick(picked_size()).show(ui); StoryOutput::default() } diff --git a/crates/theme-store/src/ui/stories.rs b/crates/theme-store/src/ui/stories.rs index 3350b963a..fadb1346a 100644 --- a/crates/theme-store/src/ui/stories.rs +++ b/crates/theme-store/src/ui/stories.rs @@ -4,7 +4,7 @@ use super::{AppearancePage, ThemeChip}; use crate::{SelectionChange, SuiteClient}; use craft_theme::{ThemeId, builtins}; use craft_ui::choice::RadioGroup; -use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft_ui::layout_components::Row; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -18,13 +18,13 @@ fn favorites() -> Vec { fn appearance_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let client = SuiteClient::memory().view(); let favorites = favorites(); - AppearancePage::new(&client, Bind::bound(data.value("draft", SelectionChange::default()))).favorites(&favorites).show(ui).into() + AppearancePage::new(&client, data.bind("draft", SelectionChange::default())).favorites(&favorites).show(ui).into() } #[story(AppearancePage<'static>, covers = [], drive = Drive::Never)] fn appearance_page_without_text_size(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let client = SuiteClient::memory().view(); - AppearancePage::new(&client, Bind::bound(data.value("plain", SelectionChange::default()))).text_size(false).system_dark(true).show(ui).into() + AppearancePage::new(&client, data.bind("plain", SelectionChange::default())).text_size(false).system_dark(true).show(ui).into() } /// One theme's chips in a group: plain, chosen, favourite, and both. A click on a star toggles the chip's favourite. @@ -33,8 +33,8 @@ fn theme_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let themes = builtins(); let mut favorites = data.value("favorites", themes.iter().take(4).skip(2).map(|theme| theme.id.clone()).collect::>()).clone(); let mut flipped = None; - let chosen = data.value("chosen", Some(themes[1].id.clone())); - let shown = RadioGroup::new("Light Theme", Bind::bound(chosen)).show(ui, |ui, _| { + let (chosen, chosen_at) = data.value_at("chosen", Some(themes[1].id.clone())); + let shown = RadioGroup::new("Light Theme", chosen_at.bind(chosen)).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { for theme in themes.iter().take(4) { let chip = ThemeChip::new(theme, false).favorite(favorites.contains(&theme.id)).id_salt(theme.id.as_str()).show(ui); diff --git a/crates/timeline/src/ui/graph/stories.rs b/crates/timeline/src/ui/graph/stories.rs index c56283361..03c30ac2d 100644 --- a/crates/timeline/src/ui/graph/stories.rs +++ b/crates/timeline/src/ui/graph/stories.rs @@ -120,8 +120,8 @@ fn show_the_speed_graph(fixture: &mut Fixture) { #[story(GraphEditor<'static>, covers = [Default], drive = Drive::Custom(show_the_speed_graph))] fn position_curves(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut demo = data.value("demo", Demo::new()).clone(); - let range = data.value("range", GraphRange::default()); - let out = shown(ui, &mut demo, Bind::bound(range)); + let (range, range_at) = data.value_at("range", GraphRange::default()); + let out = shown(ui, &mut demo, range_at.bind(range)); *data.value("demo", Demo::new()) = demo; out } @@ -130,8 +130,8 @@ fn position_curves(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn speed_graph(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut demo = data.value("demo", Demo::new()).clone(); let start = GraphRange { mode: GraphMode::Speed, ..GraphRange::default() }; - let range = data.value("range", start); - let out = shown(ui, &mut demo, Bind::bound(range)); + let (range, range_at) = data.value_at("range", start); + let out = shown(ui, &mut demo, range_at.bind(range)); *data.value("demo", Demo::new()) = demo; out } @@ -139,8 +139,8 @@ fn speed_graph(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(GraphEditor<'static>, covers = [Mixed])] fn ranges_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut demo = data.value("demo", Demo::new()).clone(); - let range = data.value("range", Mixed::::Mixed); - let out = shown(ui, &mut demo, Bind::bound_mixed(range)); + let (range, range_at) = data.value_at("range", Mixed::::Mixed); + let out = shown(ui, &mut demo, range_at.bind_mixed(range)); *data.value("demo", Demo::new()) = demo; out } @@ -149,11 +149,11 @@ fn ranges_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn range_wider_than_the_limit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut demo = data.value("demo", Demo::new()).clone(); let wide = GraphRange { high: WIDEST + 1.0, ..GraphRange::default() }; - let range = data.value("range", wide); + let (range, range_at) = data.value_at("range", wide); let narrow = |range: &GraphRange| { if range.high - range.low > WIDEST { Validity::Refuse(Message::new("The range is wider than the graph shows")) } else { Validity::Ok } }; - let out = shown(ui, &mut demo, Bind::bound(range).check(narrow)); + let out = shown(ui, &mut demo, range_at.bind(range).check(narrow)); *data.value("demo", Demo::new()) = demo; out } diff --git a/crates/timeline/src/ui/keyframes/stories.rs b/crates/timeline/src/ui/keyframes/stories.rs index 82e326be3..28990258c 100644 --- a/crates/timeline/src/ui/keyframes/stories.rs +++ b/crates/timeline/src/ui/keyframes/stories.rs @@ -99,5 +99,5 @@ fn navigator_between_keys(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(AnimationToggle<'static>, covers = [Default])] fn stopwatch(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - AnimationToggle::new(Bind::bound(data.value("animated", false))).show(ui).into() + AnimationToggle::new(data.bind("animated", false)).show(ui).into() } diff --git a/crates/timeline/src/ui/mod.rs b/crates/timeline/src/ui/mod.rs index 1162ed909..bbc2981bb 100644 --- a/crates/timeline/src/ui/mod.rs +++ b/crates/timeline/src/ui/mod.rs @@ -92,7 +92,7 @@ impl DragEvent { /// The colours of the sixteen labels ([`MarkerColor`](crate::MarkerColor) indices), the app's Label preferences. The /// root value is Premiere's (FilmCraft `crates/project/src/label.rs:64`); an app sets its own through its app values. -#[derive(Clone, Debug, PartialEq, EnvValue)] +#[derive(Clone, Debug, PartialEq, EnvValue, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct LabelPalette(pub [egui::Color32; 16]); diff --git a/crates/timeline/src/ui/overview/stories.rs b/crates/timeline/src/ui/overview/stories.rs index 0c499c0b1..b19a2792c 100644 --- a/crates/timeline/src/ui/overview/stories.rs +++ b/crates/timeline/src/ui/overview/stories.rs @@ -62,7 +62,7 @@ fn shown(ui: &mut Ui, view: Bind<'_, TimeView>) -> StoryOutput { #[story(TimelineOverview<'static>, covers = [Default], drive = Drive::Custom(centre_the_window))] fn eight_tracks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - shown(ui, Bind::bound(data.value("view", TimeView::new(Tick::from_seconds_f64(VIEW_START), VIEW_ZOOM)))) + shown(ui, data.bind("view", TimeView::new(Tick::from_seconds_f64(VIEW_START), VIEW_ZOOM))) } #[story(TimelineOverview<'static>, covers = [Invalid], drive = Drive::Never)] @@ -70,5 +70,5 @@ fn window_closer_than_the_limit(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu let not_too_close = |view: &TimeView| { if view.points_per_second > CLOSEST_ZOOM { Validity::Refuse(Message::new("The window cannot be that narrow")) } else { Validity::Ok } }; - shown(ui, Bind::bound(data.value("close", TimeView::new(Tick::ZERO, CLOSEST_ZOOM * 2.0))).check(not_too_close)) + shown(ui, data.bind("close", TimeView::new(Tick::ZERO, CLOSEST_ZOOM * 2.0)).check(not_too_close)) } diff --git a/crates/timeline/src/ui/render_queue/stories.rs b/crates/timeline/src/ui/render_queue/stories.rs index 12d0ef620..33bae50aa 100644 --- a/crates/timeline/src/ui/render_queue/stories.rs +++ b/crates/timeline/src/ui/render_queue/stories.rs @@ -2,7 +2,6 @@ use super::{RenderItemId, RenderQueueItem, RenderQueueList, RenderStatus}; use craft_behavior::Selection; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use std::time::Duration; @@ -12,8 +11,8 @@ fn item(id: u64, status: RenderStatus) -> RenderQueueItem { } fn queue(ui: &mut Ui, data: &mut StoryData, items: &[RenderQueueItem], running: bool) -> StoryOutput { - let selection = data.value("selection", Selection::::default()); - RenderQueueList::new("Destinations", items, Bind::bound(selection)).running(running).show(ui).into() + let (selection, selection_at) = data.value_at("selection", Selection::::default()); + RenderQueueList::new("Destinations", items, selection_at.bind(selection)).running(running).show(ui).into() } #[story(RenderQueueList<'static>, covers = [Default, Many], drive = Drive::Never)] diff --git a/crates/timeline/src/ui/ruler/stories.rs b/crates/timeline/src/ui/ruler/stories.rs index 4da30f898..1c73b0543 100644 --- a/crates/timeline/src/ui/ruler/stories.rs +++ b/crates/timeline/src/ui/ruler/stories.rs @@ -134,8 +134,8 @@ fn ruler_at_minute_zoom(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TimelineRuler<'static>, covers = [Mixed])] fn playheads_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut view = *data.value("view", TimeView::new(Tick::ZERO, SECOND_ZOOM)); - let playhead = data.value("playhead", Mixed::::Mixed); - let shown = in_view(ui, &mut view, |ui| Some(TimelineRuler::new("Time ruler", Bind::bound_mixed(&mut *playhead)).show(ui))); + let (playhead, playhead_at) = data.value_at("playhead", Mixed::::Mixed); + let shown = in_view(ui, &mut view, |ui| Some(TimelineRuler::new("Time ruler", playhead_at.bind_mixed(&mut *playhead)).show(ui))); *data.value("view", TimeView::new(Tick::ZERO, SECOND_ZOOM)) = view; shown } @@ -143,12 +143,12 @@ fn playheads_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(TimelineRuler<'static>, covers = [Invalid])] fn playhead_after_the_limit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut view = *data.value("view", TimeView::new(Tick::ZERO, SECOND_ZOOM)); - let playhead = data.value("playhead", secs(LATEST_SECONDS + 1.0)); + let (playhead, playhead_at) = data.value_at("playhead", secs(LATEST_SECONDS + 1.0)); let shown = in_view(ui, &mut view, |ui| { let before_the_limit = |t: &Tick| { if *t > secs(LATEST_SECONDS) { Validity::Refuse(Message::new("The playhead is past the limit")) } else { Validity::Ok } }; - Some(TimelineRuler::new("Time ruler", Bind::bound(&mut *playhead).check(before_the_limit)).show(ui)) + Some(TimelineRuler::new("Time ruler", playhead_at.bind(&mut *playhead).check(before_the_limit)).show(ui)) }); *data.value("view", TimeView::new(Tick::ZERO, SECOND_ZOOM)) = view; shown diff --git a/crates/timeline/src/ui/timecode/stories.rs b/crates/timeline/src/ui/timecode/stories.rs index 3e810f330..73fd2b924 100644 --- a/crates/timeline/src/ui/timecode/stories.rs +++ b/crates/timeline/src/ui/timecode/stories.rs @@ -6,7 +6,7 @@ use crate::rates::FrameRate; use crate::time::Tick; use crate::timecode::{TimeDisplay, TimeFormat}; use craft_behavior::Mixed; -use craft_ui::contract::{Bind, Show as _, Validity}; +use craft_ui::contract::{Show as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -28,12 +28,12 @@ const LONG_SECONDS: f64 = 1.0e9; #[story(TimecodeField<'static>, covers = [Default], drive = Drive::Type(TYPED_TIME))] fn timecode_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = Tick::from_seconds_f64(3_723.5); - TimecodeField::new("Current time", Bind::bound(data.value("time", start)), drop_frame()).show(ui).edit.into() + TimecodeField::new("Current time", data.bind("time", start), drop_frame()).show(ui).edit.into() } #[story(TimecodeField<'static>, covers = [Mixed], drive = Drive::Never)] fn timecode_field_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TimecodeField::new("Current time", Bind::bound_mixed(data.value("mixed", Mixed::::Mixed)), drop_frame()).show(ui).edit.into() + TimecodeField::new("Current time", data.bind_mixed("mixed", Mixed::::Mixed), drop_frame()).show(ui).edit.into() } #[story(TimecodeField<'static>, covers = [Invalid], drive = Drive::Never)] @@ -41,19 +41,19 @@ fn timecode_field_past_the_limit(ui: &mut Ui, data: &mut StoryData) -> StoryOutp let before_the_limit = |time: &Tick| { if *time > Tick::from_seconds_f64(LATEST_SECONDS) { Validity::Refuse(Message::new("The time is past the limit")) } else { Validity::Ok } }; - let time = data.value("late", Tick::from_seconds_f64(LATEST_SECONDS + 60.0)); - TimecodeField::new("Current time", Bind::bound(time).check(before_the_limit), drop_frame()).show(ui).edit.into() + let (time, time_at) = data.value_at("late", Tick::from_seconds_f64(LATEST_SECONDS + 60.0)); + TimecodeField::new("Current time", time_at.bind(time).check(before_the_limit), drop_frame()).show(ui).edit.into() } #[story(TimecodeField<'static>, covers = [LongText], drive = Drive::Never)] fn timecode_field_long(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TimecodeField::new("Current time", Bind::bound(data.value("long", Tick::from_seconds_f64(LONG_SECONDS))), drop_frame()).show(ui).edit.into() + TimecodeField::new("Current time", data.bind("long", Tick::from_seconds_f64(LONG_SECONDS)), drop_frame()).show(ui).edit.into() } #[story(TimecodeField<'static>, covers = [], drive = Drive::Type(TYPED_TIME))] fn timecode_field_from_sequence_start(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = Tick::from_seconds_f64(3_600.0); - TimecodeField::new("In point", Bind::bound(data.value("time", start)), drop_frame()).min(start).show(ui).edit.into() + TimecodeField::new("In point", data.bind("time", start), drop_frame()).min(start).show(ui).edit.into() } #[story(TimecodePanel<'static>, covers = [Default], drive = Drive::Never)] @@ -68,5 +68,5 @@ fn timecode_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { TimecodeRowKind::Duration => "00:05:00:00".to_owned(), _ => "17,940".to_owned(), }); - TimecodePanel::new("Timecode", Bind::bound(data.value("settings", TimecodePanelSettings::new(rows))), text).show(ui).into() + TimecodePanel::new("Timecode", data.bind("settings", TimecodePanelSettings::new(rows)), text).show(ui).into() } diff --git a/crates/timeline/src/ui/transport/stories.rs b/crates/timeline/src/ui/transport/stories.rs index 1856a8720..267603189 100644 --- a/crates/timeline/src/ui/transport/stories.rs +++ b/crates/timeline/src/ui/transport/stories.rs @@ -1,14 +1,13 @@ //! Stories of the transport bar and the media controls. use super::{MediaControls, TransportBar, TransportBarSettings, TransportButton}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; #[story(TransportBar<'static>, covers = [Default], drive = Drive::Never)] fn transport_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let settings = data.value("settings", TransportBarSettings::default()); - TransportBar::new("Program transport", &TransportButton::PROGRAM).playing(true).looping(true).settings(Bind::bound(settings)).show(ui).into() + let (settings, settings_at) = data.value_at("settings", TransportBarSettings::default()); + TransportBar::new("Program transport", &TransportButton::PROGRAM).playing(true).looping(true).settings(settings_at.bind(settings)).show(ui).into() } #[story(MediaControls, covers = [Default], drive = Drive::Never)] diff --git a/crates/timeline/src/ui/view.rs b/crates/timeline/src/ui/view.rs index d3420d63d..611e4b352 100644 --- a/crates/timeline/src/ui/view.rs +++ b/crates/timeline/src/ui/view.rs @@ -127,7 +127,8 @@ impl TimeAxis { } /// The env value that carries the axis of the innermost [`TimelineView`]; `None` outside one. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] +#[memo_props(every_pass = "the axis the timeline rebuilds each pass from its view")] struct InTimeline(Option); impl EnvValue for InTimeline { diff --git a/crates/timeline/src/ui/view/stories.rs b/crates/timeline/src/ui/view/stories.rs index 045ff24da..56da06418 100644 --- a/crates/timeline/src/ui/view/stories.rs +++ b/crates/timeline/src/ui/view/stories.rs @@ -4,7 +4,7 @@ use super::TimelineView; use crate::rates::FrameRate; use crate::time::{Tick, TimeView}; use crate::timecode::TimeFormat; -use craft_ui::contract::{Bind, ShowContainer as _, Validity}; +use craft_ui::contract::{ShowContainer as _, Validity}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, pointer, story}; use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, TouchPhase, Ui, Vec2}; @@ -39,17 +39,17 @@ pub(crate) fn zoom_the_time_area(fixture: &mut Fixture) { #[story(TimelineView<'static>, covers = [Default], drive = Drive::Custom(zoom_the_time_area))] fn timeline_view(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", TimeView::new(Tick::ZERO, POINTS_PER_SECOND)); - let out = TimelineView::new("Time", Bind::bound(view), format(), Tick::from_seconds_f64(END_SECONDS)).show(ui, |_, _| {}); + let (view, view_at) = data.value_at("view", TimeView::new(Tick::ZERO, POINTS_PER_SECOND)); + let out = TimelineView::new("Time", view_at.bind(view), format(), Tick::from_seconds_f64(END_SECONDS)).show(ui, |_, _| {}); out.output.into() } #[story(TimelineView<'static>, covers = [Invalid], drive = Drive::Never)] fn view_closer_than_the_limit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("close", TimeView::new(Tick::ZERO, CLOSEST_ZOOM * 2.0)); + let (view, view_at) = data.value_at("close", TimeView::new(Tick::ZERO, CLOSEST_ZOOM * 2.0)); let not_too_close = |view: &TimeView| { if view.points_per_second > CLOSEST_ZOOM { Validity::Refuse(Message::new("The time area cannot zoom in that far")) } else { Validity::Ok } }; - let out = TimelineView::new("Time", Bind::bound(view).check(not_too_close), format(), Tick::from_seconds_f64(END_SECONDS)).show(ui, |_, _| {}); + let out = TimelineView::new("Time", view_at.bind(view).check(not_too_close), format(), Tick::from_seconds_f64(END_SECONDS)).show(ui, |_, _| {}); out.output.into() } diff --git a/crates/timeline/tests/it/timecode.rs b/crates/timeline/tests/it/timecode.rs index 6dbacd630..4215aaf99 100644 --- a/crates/timeline/tests/it/timecode.rs +++ b/crates/timeline/tests/it/timecode.rs @@ -4,7 +4,7 @@ use craft_keymap::Platform; use craft_timeline::ui::{TimecodeField, TimecodePanel, TimecodePanelSettings, TimecodeRow, TimecodeRowKind, TimecodeSource, TimecodeText}; use craft_timeline::{FrameRate, Tick, TimeFormat}; -use craft_ui::contract::{Bind, Role, Show as _}; +use craft_ui::contract::{Role, Show as _}; use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, pointer, trial}; use egui::{Key, Modifiers, Ui, Vec2}; @@ -14,7 +14,7 @@ fn start() -> Tick { } fn field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TimecodeField::new("Time", Bind::bound(data.value("time", start())), TimeFormat::timecode(FrameRate::FPS_30)).show(ui).edit.into() + TimecodeField::new("Time", data.bind("time", start()), TimeFormat::timecode(FrameRate::FPS_30)).show(ui).edit.into() } fn fixture() -> Fixture { @@ -60,7 +60,7 @@ fn rows() -> TimecodePanelSettings { fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let text = TimecodeText::new(|row| format!("{:?}", row.kind)); - TimecodePanel::new("Timecode", Bind::bound(data.value("settings", rows())), text).show(ui).into() + TimecodePanel::new("Timecode", data.bind("settings", rows()), text).show(ui).into() } fn kinds(fixture: &mut Fixture) -> Vec { diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs index 17f12e09a..a56ddbe4f 100644 --- a/crates/tracked/src/lib.rs +++ b/crates/tracked/src/lib.rs @@ -305,13 +305,13 @@ impl Tracked { f(&mut **self) } - /// Called by craft-ui's `bind_tracked!` only: the value without moving the revision, and the write count. The - /// macro borrows each bound field from the value through a field path and gives the binding the count, which it - /// moves on every write that changes the field. A direct call can write any part of the value without moving the + /// Called by craft-ui's `bind_tracked!` only: the value without moving the revision, the write count and the + /// source id. The macro borrows each bound field from the value through a field path and gives the binding the + /// count, which it moves on every write that changes the field, and the source, which names the field's reads. A direct call can write any part of the value without moving the /// revision, so readers keyed by it would miss the write; design-lint rejects direct calls in UI crates. #[doc(hidden)] - pub fn __split_for_bind(&mut self) -> (&mut T, &Cell) { - (&mut self.value, Cell::from_mut(&mut self.revision.count)) + pub fn __split_for_bind(&mut self) -> (&mut T, &Cell, u64) { + (&mut self.value, Cell::from_mut(&mut self.revision.count), self.revision.source) } /// The value, leaving the tracking. @@ -326,6 +326,13 @@ impl Clone for Tracked { } } +/// Two values are equal when what they hold is: the revision says which writes a value saw, not what it is. +impl PartialEq for Tracked { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + impl Deref for Tracked { type Target = T; diff --git a/crates/ui-canvas/src/canvas/crop/stories.rs b/crates/ui-canvas/src/canvas/crop/stories.rs index 0d43c21da..a9436092d 100644 --- a/crates/ui-canvas/src/canvas/crop/stories.rs +++ b/crates/ui-canvas/src/canvas/crop/stories.rs @@ -3,7 +3,7 @@ use super::{CropOverlay, CropOverlayOutput, CropScope, FRAME}; use crate::canvas::RasterSource as _; use crate::canvas::testing::canvas_story::{self, StoryDocument, StoryPicture, StoryShape, paint_shapes}; -use crate::contract::{Bind, Show as _, Validity}; +use crate::contract::{Show as _, Validity}; use crate::runtime::env::Message; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use craft_behavior::Mixed; @@ -70,73 +70,73 @@ fn drag_top_left(fixture: &mut Fixture) { #[story(CropOverlay<'static>, covers = [Default], drive = Drive::Custom(drag_top_left))] fn upright(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", crop()); - on_canvas(ui, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", crop()); + on_canvas(ui, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).show_at(ui, at)) } #[story(CropOverlay<'static>, covers = [Default], drive = Drive::Custom(drag_top_left))] fn object_scope(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { // One placed picture's crop: the frame stays inside its source, and the shield dims only the source. let source = DocRect::new(180.0, 110.0, 460.0, 290.0); - let rect = data.value("crop", crop()); - on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).scope(CropScope::Object { source }).show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", crop()); + on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).scope(CropScope::Object { source }).show_at(ui, at)) } #[story(CropOverlay<'static>, covers = [Mixed], drive = Drive::Custom(drag_top_left))] fn crops_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", Mixed::::Mixed); - on_canvas(ui, |ui, at| CropOverlay::new("Crop", Bind::bound_mixed(&mut *rect)).show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", Mixed::::Mixed); + on_canvas(ui, |ui, at| CropOverlay::new("Crop", rect_at.bind_mixed(&mut *rect)).show_at(ui, at)) } #[story(CropOverlay<'static>, covers = [Invalid], drive = Drive::Custom(drag_top_left))] fn too_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", CropBox::upright(DocRect::new(240.0, 145.0, 240.0 + LEAST_WIDTH / 2.0, 225.0))); + let (rect, rect_at) = data.value_at("crop", CropBox::upright(DocRect::new(240.0, 145.0, 240.0 + LEAST_WIDTH / 2.0, 225.0))); on_canvas(ui, |ui, at| { let narrow = |crop: &CropBox| { if crop.rect.width() < LEAST_WIDTH { Validity::Refuse(Message::new("The crop is too narrow")) } else { Validity::Ok } }; - CropOverlay::new("Crop", Bind::bound(&mut *rect).check(narrow)).show_at(ui, at) + CropOverlay::new("Crop", rect_at.bind(&mut *rect).check(narrow)).show_at(ui, at) }) } #[story(CropOverlay<'static>, covers = [Default])] fn turned(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", CropBox::new(DocRect::new(260.0, 165.0, 380.0, 235.0), 15.0)); - on_canvas(ui, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", CropBox::new(DocRect::new(260.0, 165.0, 380.0, 235.0), 15.0)); + on_canvas(ui, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).show_at(ui, at)) } #[story(CropOverlay<'static>, covers = [Default])] fn ratio_held(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", CropBox::upright(DocRect::new(240.0, 145.0, 400.0, 235.0))); - on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).ratio(16.0 / 9.0).show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", CropBox::upright(DocRect::new(240.0, 145.0, 400.0, 235.0))); + on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).ratio(16.0 / 9.0).show_at(ui, at)) } #[story(CropOverlay<'static>, covers = [Default])] fn guide_shown(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", crop()); + let (rect, rect_at) = data.value_at("crop", crop()); on_canvas(ui, |ui, at| { - CropOverlay::new("Crop", Bind::bound(&mut *rect)).guide((CropGuide::Thirds, 0)).guide_show(GuideShow::Always).show_at(ui, at) + CropOverlay::new("Crop", rect_at.bind(&mut *rect)).guide((CropGuide::Thirds, 0)).guide_show(GuideShow::Always).show_at(ui, at) }) } #[story(CropOverlay<'static>, covers = [Default])] fn straighten_armed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", crop()); - on_landscape(ui, STRAIGHTEN_TILT, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).straighten().show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", crop()); + on_landscape(ui, STRAIGHTEN_TILT, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).straighten().show_at(ui, at)) } #[story(CropOverlay<'static>, covers = [Default])] fn image_mode(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", crop()); - on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).image_mode().auto_center().show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", crop()); + on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).image_mode().auto_center().show_at(ui, at)) } /// The default frame over the whole picture before any drag changed it: a dashed outline, no shield, no guide. #[story(CropOverlay<'static>, covers = [Default], drive = Drive::Custom(drag_top_left))] fn untouched(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", CropBox::upright(StoryDocument::STANDARD.rect())); + let (rect, rect_at) = data.value_at("crop", CropBox::upright(StoryDocument::STANDARD.rect())); on_landscape(ui, 0.0, |ui, at| { - CropOverlay::new("Crop", Bind::bound(&mut *rect)) + CropOverlay::new("Crop", rect_at.bind(&mut *rect)) .default_frame() .image_mode() .guide((CropGuide::Thirds, 0)) @@ -148,6 +148,6 @@ fn untouched(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// The frame hidden: nothing shows over the picture, and a press anywhere draws a new frame. #[story(CropOverlay<'static>, covers = [Default])] fn hidden(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let rect = data.value("crop", CropBox::upright(StoryDocument::STANDARD.rect())); - on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", Bind::bound(&mut *rect)).default_frame().image_mode().hidden().show_at(ui, at)) + let (rect, rect_at) = data.value_at("crop", CropBox::upright(StoryDocument::STANDARD.rect())); + on_landscape(ui, 0.0, |ui, at| CropOverlay::new("Crop", rect_at.bind(&mut *rect)).default_frame().image_mode().hidden().show_at(ui, at)) } diff --git a/crates/ui-canvas/src/canvas/full_window/stories.rs b/crates/ui-canvas/src/canvas/full_window/stories.rs index 4c52972af..9fa9c5052 100644 --- a/crates/ui-canvas/src/canvas/full_window/stories.rs +++ b/crates/ui-canvas/src/canvas/full_window/stories.rs @@ -55,7 +55,7 @@ fn liquify_shell(ui: &mut Ui, data: &mut StoryData, own_window: bool) -> StoryOu dialog = dialog.own_window(WindowSpec::dialog()); } let shown: StoryOutput = dialog - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .buttons(buttons) .sides(|ui, _| { FullWindowSide::new("Properties").show(ui, |ui, _| { diff --git a/crates/ui-canvas/src/canvas/full_window_parts/stories.rs b/crates/ui-canvas/src/canvas/full_window_parts/stories.rs index dc8fe5de4..22529e21c 100644 --- a/crates/ui-canvas/src/canvas/full_window_parts/stories.rs +++ b/crates/ui-canvas/src/canvas/full_window_parts/stories.rs @@ -2,7 +2,7 @@ use super::{FullWindowCanvas, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowZoomBar, RasterOverlay}; use crate::canvas::{PixelRect, RasterSource}; -use crate::contract::{Bind, Show as _, ShowContainer as _}; +use crate::contract::{Show as _, ShowContainer as _}; use crate::display::Text; use crate::layout_components::Stack; use crate::primitives::{Checker, Revision}; @@ -72,8 +72,8 @@ const PREVIEWS: [(&str, Option>); 3] = [("Idle", None), ("Pending", #[story(FullWindowZoomBar, covers = [], drive = Drive::Never)] fn zoom_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let note = *data.value("note", true); - let view = data.value("view", FullWindowView::new()); - let bar = FullWindowZoomBar::new(Bind::bound(view)); + let (view, view_at) = data.value_at("view", FullWindowView::new()); + let bar = FullWindowZoomBar::new(view_at.bind(view)); let bar = if note { bar.note("Preview 120 ms") } else { bar }; bar.show(ui).into() } @@ -81,8 +81,8 @@ fn zoom_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(FullWindowZoomBar, covers = [], drive = Drive::Never)] fn zoom_bar_with_progress(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let progress = *data.choice("preview", Some(Some(0.4)), &PREVIEWS); - let view = data.value("view", FullWindowView::new()); - FullWindowZoomBar::new(Bind::bound(view)).progress(progress).show(ui).into() + let (view, view_at) = data.value_at("view", FullWindowView::new()); + FullWindowZoomBar::new(view_at.bind(view)).progress(progress).show(ui).into() } #[story(FullWindowTitle, covers = [], drive = Drive::Never)] @@ -109,8 +109,8 @@ fn canvas(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let checkerboard = *data.value("checkerboard", true); let overlay = *data.value("overlay", true); let tint = *data.value("tint", true); - let view = data.value("view", FullWindowView::new()); - let mut canvas = FullWindowCanvas::new(Bind::bound(view), &IMAGE_SOURCE); + let (view, view_at) = data.value_at("view", FullWindowView::new()); + let mut canvas = FullWindowCanvas::new(view_at.bind(view), &IMAGE_SOURCE); if checkerboard { canvas = canvas.checkerboard(Checker::new()); } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index f8c7da9ca..453cad77a 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -589,7 +589,7 @@ impl<'a> Canvas<'a> { let Some(pointer) = input.pos.filter(|_| run.mark().is_some()) else { break 'pass false }; let step = run.step(pointer, crate::runtime::frame::clock(&ctx)); crate::runtime::cursor::request(&ctx, run.cursor(Some(pointer)).into(), CursorPriority::Drag); - crate::runtime::frame::request_own_repaint(&ctx); + crate::runtime::frame::request_repaint(&ctx); Autoscroll::scroll(view, step, size).is_some() }; (moved, swallowing || run.swallowing()) diff --git a/crates/ui-canvas/src/canvas/navigate/stories.rs b/crates/ui-canvas/src/canvas/navigate/stories.rs index 4f40d15b8..783d9c146 100644 --- a/crates/ui-canvas/src/canvas/navigate/stories.rs +++ b/crates/ui-canvas/src/canvas/navigate/stories.rs @@ -39,23 +39,23 @@ fn drag_rim(fixture: &mut Fixture) { #[story(RotateView<'static>, covers = [Default], drive = Drive::Custom(drag_rim))] fn compass(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let angle = data.value("angle", TURNED); - in_corner(ui, *angle, |ui, at| RotateView::new("Rotation", Bind::bound(&mut *angle), false).show_at(ui, at)) + let (angle, angle_at) = data.value_at("angle", TURNED); + in_corner(ui, *angle, |ui, at| RotateView::new("Rotation", angle_at.bind(&mut *angle), false).show_at(ui, at)) } #[story(RotateView<'static>, covers = [Mixed], drive = Drive::Custom(drag_rim))] fn views_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let angle = data.value("angle", Mixed::::Mixed); - in_corner(ui, 0.0, |ui, at| RotateView::new("Rotation", Bind::bound_mixed(&mut *angle), false).show_at(ui, at)) + let (angle, angle_at) = data.value_at("angle", Mixed::::Mixed); + in_corner(ui, 0.0, |ui, at| RotateView::new("Rotation", angle_at.bind_mixed(&mut *angle), false).show_at(ui, at)) } #[story(RotateView<'static>, covers = [Invalid], drive = Drive::Custom(drag_rim))] fn too_far(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let angle = data.value("angle", MOST + TURNED); + let (angle, angle_at) = data.value_at("angle", MOST + TURNED); in_corner(ui, *angle, |ui, at| { let near = |angle: &f64| if angle.abs() > MOST { Validity::Refuse(Message::new("The view turns at most a quarter turn")) } else { Validity::Ok }; - RotateView::new("Rotation", Bind::bound(&mut *angle).check(near), false).show_at(ui, at) + RotateView::new("Rotation", angle_at.bind(&mut *angle).check(near), false).show_at(ui, at) }) } diff --git a/crates/ui-canvas/src/canvas/navigator/stories.rs b/crates/ui-canvas/src/canvas/navigator/stories.rs index 902bd1dac..34e1dde7e 100644 --- a/crates/ui-canvas/src/canvas/navigator/stories.rs +++ b/crates/ui-canvas/src/canvas/navigator/stories.rs @@ -3,7 +3,7 @@ use super::preview::WELL; use super::{Navigator, NavigatorPreview, NavigatorZoomRow}; use crate::canvas::AppPaint; -use crate::contract::{Bind, Show as _, Validity}; +use crate::contract::{Show as _, Validity}; use crate::runtime::env::Message; use crate::testing::{Drive, Grip, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{Point, Size}; @@ -24,39 +24,39 @@ const CAP: f64 = 1200.0; #[story(NavigatorZoomRow<'static>, covers = [], drive = Drive::Never)] fn zoom_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); - NavigatorZoomRow::new(Bind::bound(view), DOCUMENT).show(ui).into() + let (view, view_at) = data.value_at("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); + NavigatorZoomRow::new(view_at.bind(view), DOCUMENT).show(ui).into() } #[story(Navigator<'static>, covers = [Default], drive = Drive::Step)] fn navigator(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); - Navigator::new("Navigator", Bind::bound(view), DOCUMENT).show(ui).into() + let (view, view_at) = data.value_at("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); + Navigator::new("Navigator", view_at.bind(view), DOCUMENT).show(ui).into() } #[story(Navigator<'static>, covers = [], drive = Drive::Drag(Grip::new(WELL)))] fn navigator_drag(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); - Navigator::new("Navigator", Bind::bound(view), DOCUMENT).show(ui).into() + let (view, view_at) = data.value_at("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); + Navigator::new("Navigator", view_at.bind(view), DOCUMENT).show(ui).into() } #[story(Navigator<'static>, covers = [Invalid], drive = Drive::Never)] fn view_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_right = |view: &CanvasView| if view.center.x > CAP { Validity::Refuse(Message::new("Too far right")) } else { Validity::Ok }; - let view = data.value("over", CanvasView::new(CANVAS, Point::new(1500.0, 750.0), 1.0)); - Navigator::new("Navigator", Bind::bound(view).check(refuse_right), DOCUMENT).show(ui).into() + let (view, view_at) = data.value_at("over", CanvasView::new(CANVAS, Point::new(1500.0, 750.0), 1.0)); + Navigator::new("Navigator", view_at.bind(view).check(refuse_right), DOCUMENT).show(ui).into() } #[story(Navigator<'static>, covers = [Mixed], drive = Drive::Never)] fn views_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", Mixed::::Mixed); - Navigator::new("Navigator", Bind::bound_mixed(view), DOCUMENT).show(ui).into() + let (view, view_at) = data.value_at("view", Mixed::::Mixed); + Navigator::new("Navigator", view_at.bind_mixed(view), DOCUMENT).show(ui).into() } #[story(Navigator<'static>, covers = [], drive = Drive::Never)] fn painted_by_the_app(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); - Navigator::new("Navigator", Bind::bound(view), DOCUMENT) + let (view, view_at) = data.value_at("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); + Navigator::new("Navigator", view_at.bind(view), DOCUMENT) .preview(NavigatorPreview::Paint(AppPaint::new(|painter, rect| { painter.painter.rect_filled(rect, 0.0, Color32::from_gray(PICTURE_GRAY)); }))) diff --git a/crates/ui-canvas/src/canvas/navigator_panel/stories.rs b/crates/ui-canvas/src/canvas/navigator_panel/stories.rs index d359a8676..3f8c6f800 100644 --- a/crates/ui-canvas/src/canvas/navigator_panel/stories.rs +++ b/crates/ui-canvas/src/canvas/navigator_panel/stories.rs @@ -1,7 +1,6 @@ //! Stories of the Navigator panel. use super::NavigatorPanel; -use crate::contract::Bind; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Size}; @@ -15,12 +14,12 @@ const CANVAS: Rect = Rect::from_min_max(Pos2::new(0.0, 0.0), Pos2::new(800.0, 60 #[story(NavigatorPanel<'static>, covers = [], drive = Drive::Never)] fn navigator_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); - NavigatorPanel::new("Navigator", Bind::bound(view), DOCUMENT).show(ui).into() + let (view, view_at) = data.value_at("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); + NavigatorPanel::new("Navigator", view_at.bind(view), DOCUMENT).show(ui).into() } #[story(NavigatorPanel<'static>, covers = [], drive = Drive::Never)] fn navigator_panel_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let view = data.value("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); - NavigatorPanel::new("Navigator", Bind::bound(view), DOCUMENT).enabled(false).show(ui).into() + let (view, view_at) = data.value_at("view", CanvasView::new(CANVAS, Point::new(1000.0, 750.0), 1.0)); + NavigatorPanel::new("Navigator", view_at.bind(view), DOCUMENT).enabled(false).show(ui).into() } diff --git a/crates/ui-canvas/src/canvas/readout.rs b/crates/ui-canvas/src/canvas/readout.rs index 103aa4274..ec36f1e0c 100644 --- a/crates/ui-canvas/src/canvas/readout.rs +++ b/crates/ui-canvas/src/canvas/readout.rs @@ -6,7 +6,7 @@ use egui::{Context, Pos2}; /// The one Show Transformation Values gate: while it holds `false` in the root env, [`readout`] and the tool host's /// paint of a tool's readout rows paint nothing. [`hud`] is never gated. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] pub struct ShowReadouts(pub bool); impl EnvValue for ShowReadouts { diff --git a/crates/ui-canvas/src/canvas/rulers/stories.rs b/crates/ui-canvas/src/canvas/rulers/stories.rs index 0570035ff..fda918b50 100644 --- a/crates/ui-canvas/src/canvas/rulers/stories.rs +++ b/crates/ui-canvas/src/canvas/rulers/stories.rs @@ -3,7 +3,7 @@ use super::{CORNER, RulerMargins, Rulers}; use crate::canvas::testing::canvas_story::{StoryDocument, on_ruled_canvas}; use crate::canvas::{Canvas, RasterSource as _, RulerText}; -use crate::contract::{Bind, Validity}; +use crate::contract::Validity; use crate::primitives::RulerFace; use crate::runtime::env::{Message, UnitKind}; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -85,50 +85,50 @@ fn rulers_canvas<'a>(room: Rect, pixels_per_point: f32, settings: Settings, rule #[story(Rulers<'static>, covers = [Default], drive = Drive::Custom(drag_corner))] fn zero_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); - let zero = data.value("zero", Point::ZERO); + let (zero, zero_at) = data.value_at("zero", Point::ZERO); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", Bind::bound(&mut *zero))); + let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind(&mut *zero))); on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } #[story(Rulers<'static>, covers = [Open], drive = Drive::Custom(open_units_menu))] fn units_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); - let zero = data.value("zero", Point::ZERO); + let (zero, zero_at) = data.value_at("zero", Point::ZERO); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", Bind::bound(&mut *zero)).units(&UNITS)); + let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind(&mut *zero)).units(&UNITS)); on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } #[story(Rulers<'static>, covers = [Mixed], drive = Drive::Custom(drag_corner))] fn zero_points_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); - let zero = data.value("zero", Mixed::::Mixed); + let (zero, zero_at) = data.value_at("zero", Mixed::::Mixed); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", Bind::bound_mixed(&mut *zero))); + let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind_mixed(&mut *zero))); on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } #[story(Rulers<'static>, covers = [Invalid], drive = Drive::Custom(drag_corner))] fn zero_point_left_of_the_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); - let zero = data.value("zero", Point::new(LEAST_X - 1.0, 0.0)); + let (zero, zero_at) = data.value_at("zero", Point::new(LEAST_X - 1.0, 0.0)); let room = stage(ui); let inside = |zero: &Point| if zero.x < LEAST_X { Validity::Refuse(Message::new("The zero point is left of the document")) } else { Validity::Ok }; - let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", Bind::bound(&mut *zero).check(inside))); + let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", zero_at.bind(&mut *zero).check(inside))); on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } /// The rulers in `face` with the document's margins shaded. fn in_face(ui: &mut Ui, data: &mut StoryData, face: RulerFace) -> StoryOutput { let settings = settings(data); - let zero = data.value("zero", Point::ZERO); + let (zero, zero_at) = data.value_at("zero", Point::ZERO); let room = stage(ui); let size = StoryDocument::STANDARD.size(); let (width, height) = (f64::from(size.width), f64::from(size.height)); let margins = RulerMargins::new([0.0..MARGIN, width - MARGIN..width], [0.0..MARGIN, height - MARGIN..height]); - let rulers = Rulers::new("Rulers", Bind::bound(&mut *zero)).margins(margins).face(face); + let rulers = Rulers::new("Rulers", zero_at.bind(&mut *zero)).margins(margins).face(face); let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, rulers); on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } diff --git a/crates/ui-canvas/src/canvas/scrollbars/stories.rs b/crates/ui-canvas/src/canvas/scrollbars/stories.rs index 63b7a5c71..cfc809265 100644 --- a/crates/ui-canvas/src/canvas/scrollbars/stories.rs +++ b/crates/ui-canvas/src/canvas/scrollbars/stories.rs @@ -3,7 +3,7 @@ use super::{CanvasScrollbars, HORIZONTAL, VERTICAL}; use crate::canvas::Canvas; use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with, story_view}; -use crate::contract::{Bind, Show as _, Validity}; +use crate::contract::{Show as _, Validity}; use crate::runtime::env::{Label, Message}; use crate::testing::stage; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, Target, story}; @@ -59,10 +59,10 @@ fn drag_vertical_thumb(fixture: &mut Fixture) { fn tip_while_dragging(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let full = stage(ui); let shown = view_over(ui, full); - let view = data.value("view", shown); + let (view, view_at) = data.value_at("view", shown); on_canvas_with(ui, full, Canvas::new("Document").view(shown), Some(&SHOWN), |ui, at| { let page = |_: &CanvasView| Label::from("Page 2 of 6"); - CanvasScrollbars::new("Scroll bars", Bind::bound(&mut *view), DOCUMENT).tip(&page).show_at(ui, at) + CanvasScrollbars::new("Scroll bars", view_at.bind(&mut *view), DOCUMENT).tip(&page).show_at(ui, at) }) } @@ -71,9 +71,9 @@ fn scrolled_view(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let full = stage(ui); let shown = view_over(ui, full); let overscroll = *data.value("overscroll", false); - let view = data.value("view", shown); + let (view, view_at) = data.value_at("view", shown); on_canvas_with(ui, full, Canvas::new("Document").view(shown), Some(&SHOWN), |ui, at| { - CanvasScrollbars::new("Scroll bars", Bind::bound(&mut *view), DOCUMENT).overscroll(overscroll).show_at(ui, at) + CanvasScrollbars::new("Scroll bars", view_at.bind(&mut *view), DOCUMENT).overscroll(overscroll).show_at(ui, at) }) } @@ -82,9 +82,9 @@ fn views_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let full = stage(ui); let shown = view_over(ui, full); let overscroll = *data.value("overscroll", false); - let view = data.value("view", Mixed::::Mixed); + let (view, view_at) = data.value_at("view", Mixed::::Mixed); on_canvas_with(ui, full, Canvas::new("Document").view(shown), Some(&SHOWN), |ui, at| { - CanvasScrollbars::new("Scroll bars", Bind::bound_mixed(&mut *view), DOCUMENT).overscroll(overscroll).show_at(ui, at) + CanvasScrollbars::new("Scroll bars", view_at.bind_mixed(&mut *view), DOCUMENT).overscroll(overscroll).show_at(ui, at) }) } @@ -93,11 +93,11 @@ fn view_scrolled_too_far(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let full = stage(ui); let shown = view_over(ui, full); let overscroll = *data.value("overscroll", false); - let view = data.value("view", shown); + let (view, view_at) = data.value_at("view", shown); on_canvas_with(ui, full, Canvas::new("Document").view(shown), Some(&SHOWN), |ui, at| { let kept = |view: &CanvasView| { if view.center.x > LAST_CENTRE_X { Validity::Refuse(Message::new("The view cannot scroll further right")) } else { Validity::Ok } }; - CanvasScrollbars::new("Scroll bars", Bind::bound(&mut *view).check(kept), DOCUMENT).overscroll(overscroll).show_at(ui, at) + CanvasScrollbars::new("Scroll bars", view_at.bind(&mut *view).check(kept), DOCUMENT).overscroll(overscroll).show_at(ui, at) }) } diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index c280527a5..82b3cfd4d 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -158,7 +158,8 @@ pub fn snap_tolerance(view: &CanvasView, mods: Mods, os: Platform, suspend: Snap (!snap_suspended(mods, os, suspend, gesture_reads_key)).then(|| view.doc_len(SNAP_PX as f32)) } -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, crate::contract::MemoProps)] +#[memo_props(every_pass = "a context the canvas rebuilds each pass")] struct InCanvasSnap(Option); impl EnvValue for InCanvasSnap { diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 381b45686..88d5848a2 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -364,7 +364,8 @@ pub(crate) fn context_menu(cx: &mut Cx<'_, C>, part: impl Into); impl EnvValue for InCanvas { @@ -373,8 +374,9 @@ impl EnvValue for InCanvas { } } -/// The env value that carries the guide a drag out of the canvas's rulers is placing in this pass. -#[derive(Clone, Copy, Debug, PartialEq)] +/// The env value that carries the guide a drag out of the canvas's rulers is placing in this pass: a view under the +/// canvas runs in every pass of the drag (`GuideDrag` keys in every pass), and replays when no drag is placing one. +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] struct InRulerGuide(Option); impl EnvValue for InRulerGuide { diff --git a/crates/ui-canvas/src/canvas/split/stories.rs b/crates/ui-canvas/src/canvas/split/stories.rs index e798ba1f9..358e160df 100644 --- a/crates/ui-canvas/src/canvas/split/stories.rs +++ b/crates/ui-canvas/src/canvas/split/stories.rs @@ -71,51 +71,51 @@ fn click_inactive_pane(fixture: &mut Fixture) { #[story(SplitViews<'static>, covers = [Default], drive = Drive::Custom(drag_divider))] fn two_views(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", SplitAt::default()); + let (at, at_at) = data.value_at("split", SplitAt::default()); let shown = at.clone(); - split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, Bind::bound(at), shown) + split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, at_at.bind(at), shown) } #[story(SplitViews<'static>, covers = [Default], drive = Drive::Custom(drag_divider))] fn four_views(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", SplitAt::default()); + let (at, at_at) = data.value_at("split", SplitAt::default()); let shown = at.clone(); - split(ui, SplitLayout::FourUp, 4, MAIN_OF_FOUR, Bind::bound(at), shown) + split(ui, SplitLayout::FourUp, 4, MAIN_OF_FOUR, at_at.bind(at), shown) } #[story(SplitViews<'static>, covers = [Default], drive = Drive::Custom(drag_divider))] fn grid_views(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", SplitAt::default()); + let (at, at_at) = data.value_at("split", SplitAt::default()); let shown = at.clone(); - split(ui, SplitLayout::Tile, 5, 0, Bind::bound(at), shown) + split(ui, SplitLayout::Tile, 5, 0, at_at.bind(at), shown) } #[story(SplitViews<'static>, covers = [Default], drive = Drive::Custom(drag_row_divider))] fn stacked_views(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", SplitAt::default()); + let (at, at_at) = data.value_at("split", SplitAt::default()); let shown = at.clone(); - split(ui, SplitLayout::ThreeUpStacked, 3, 0, Bind::bound(at), shown) + split(ui, SplitLayout::ThreeUpStacked, 3, 0, at_at.bind(at), shown) } #[story(SplitViews<'static>, covers = [Default], drive = Drive::Custom(click_inactive_pane))] fn another_view_clicked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", SplitAt::default()); + let (at, at_at) = data.value_at("split", SplitAt::default()); let shown = at.clone(); - split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, Bind::bound(at), shown) + split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, at_at.bind(at), shown) } #[story(SplitViews<'static>, covers = [Mixed], drive = Drive::Custom(drag_divider))] fn splits_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", Mixed::::Mixed); - split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, Bind::bound_mixed(at), SplitAt::default()) + let (at, at_at) = data.value_at("split", Mixed::::Mixed); + split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, at_at.bind_mixed(at), SplitAt::default()) } #[story(SplitViews<'static>, covers = [Invalid], drive = Drive::Custom(drag_divider))] fn views_too_far_left(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let at = data.value("split", SplitAt::new(MOST_LEFT + 0.1, 0.5)); + let (at, at_at) = data.value_at("split", SplitAt::new(MOST_LEFT + 0.1, 0.5)); let shown = at.clone(); let too_wide = |at: &SplitAt| { if at.columns.first().is_some_and(|&x| x > MOST_LEFT) { Validity::Refuse(Message::new("The left view is too wide")) } else { Validity::Ok } }; - split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, Bind::bound(at).check(too_wide), shown) + split(ui, SplitLayout::TwoUpVertical, 2, MAIN_OF_TWO, at_at.bind(at).check(too_wide), shown) } diff --git a/crates/ui-canvas/src/canvas/stories.rs b/crates/ui-canvas/src/canvas/stories.rs index dc068f2bf..b74e93529 100644 --- a/crates/ui-canvas/src/canvas/stories.rs +++ b/crates/ui-canvas/src/canvas/stories.rs @@ -72,9 +72,9 @@ fn under_a_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { } }; let stage = Stack::new().fill().footer(row).footer_gap(Gap::Stack).show_at(ui, room, |ui, stack| { - let view = data.value("view", StoryDocument::STANDARD.view(stack.rect, pixels_per_point, 100.0)); + let (view, view_at) = data.value_at("view", StoryDocument::STANDARD.view(stack.rect, pixels_per_point, 100.0)); Canvas::new("Document") - .view(Bind::bound(view)) + .view(view_at.bind(view)) .show_at(ui, stack.rect, |ui, body| show_document(ui, body.rect, &StoryDocument::STANDARD)) .output }); @@ -121,10 +121,10 @@ fn press_menu_key(fixture: &mut Fixture) { fn document_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let room = stage(ui); let navigation = NavigationOptions { wheel: WheelScheme::Document, ..NavigationOptions::default() }; - let view = data.value("view", scrolled_view(room, ui.pixels_per_point())); + let (view, view_at) = data.value_at("view", scrolled_view(room, ui.pixels_per_point())); Canvas::new("Document") .navigation(navigation) - .view(Bind::bound(&mut *view)) + .view(view_at.bind(&mut *view)) .show_at(ui, room, |ui, body| show_document(ui, body.rect, &StoryDocument::STANDARD)) .output .into() @@ -143,10 +143,10 @@ fn scrolled_view(room: Rect, pixels_per_point: f32) -> craft_behavior::CanvasVie fn middle_autoscroll(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let room = stage(ui); let navigation = NavigationOptions { middle_button: MiddleButton::Autoscroll, ..NavigationOptions::default() }; - let view = data.value("view", scrolled_view(room, ui.pixels_per_point())); + let (view, view_at) = data.value_at("view", scrolled_view(room, ui.pixels_per_point())); let shown = Canvas::new("Document") .navigation(navigation) - .view(Bind::bound(&mut *view)) + .view(view_at.bind(&mut *view)) .show_at(ui, room, |ui, body| show_document(ui, body.rect, &StoryDocument::STANDARD)); shown.output.into() } diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index be418022c..3e6f00681 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -411,7 +411,8 @@ fn keys_down(ctx: &Context, holds: &[Key]) -> Vec { } /// The tool input a canvas publishes to its body. -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq, crate::contract::MemoProps)] +#[memo_props(every_pass = "a context the canvas rebuilds each pass")] struct InToolPass(Option); impl EnvValue for InToolPass { @@ -676,7 +677,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); @@ -751,7 +752,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 } diff --git a/crates/ui-canvas/src/canvas/zoom_motion.rs b/crates/ui-canvas/src/canvas/zoom_motion.rs index d8429fea2..94781ef9b 100644 --- a/crates/ui-canvas/src/canvas/zoom_motion.rs +++ b/crates/ui-canvas/src/canvas/zoom_motion.rs @@ -165,7 +165,7 @@ pub fn easing_view(ctx: &Context, canvas: Id) -> Option { /// tool host for a tool's view, the Navigator for a preview zoom. The canvas applies it in its next pass. pub(crate) fn steer(ctx: &Context, canvas: Id, steer: Steer) { with_session(ctx, ViewMotion::id(canvas), |slot: &mut ViewMotion| slot.steer = Some(steer)); - frame::request_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 diff --git a/crates/ui-canvas/src/canvas_controls/guides/stories.rs b/crates/ui-canvas/src/canvas_controls/guides/stories.rs index d86738ce4..02fdeb99c 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/stories.rs @@ -52,7 +52,7 @@ fn drag_out_of_the_top_ruler(fixture: &mut Fixture) { #[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_out_of_the_top_ruler))] fn guide_dragged_out_of_a_ruler(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", guides()); + let (guides, guides_at) = data.value_at("guides", guides()); let mut zero = Point::ZERO; let canvas = ui.scope_id().with("guides story canvas"); let room = stage(ui); @@ -63,7 +63,7 @@ fn guide_dragged_out_of_a_ruler(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu let strips = Rulers::new("Rulers", Bind::bound(&mut zero)).interactive(true); let shown = Canvas::new("Document").id(canvas).view(view).with_rulers(Some(strips)).rulers(text, text).show_at(ui, room, |ui, body| { show_document(ui, body.rect, &StoryDocument::STANDARD); - Guides::new("Guides", canvas, Bind::bound(&mut *guides)).interactive(true).show_at(ui, body.rect) + Guides::new("Guides", canvas, guides_at.bind(&mut *guides)).interactive(true).show_at(ui, body.rect) }); let mut output: StoryOutput = shown.inner.map(Into::into).unwrap_or_default(); // A click on a strip is the rulers' to report. @@ -73,36 +73,36 @@ fn guide_dragged_out_of_a_ruler(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu #[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_first))] fn guides_over_a_canvas(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", guides()); + let (guides, guides_at) = data.value_at("guides", guides()); on_guides_canvas(ui, |ui, at, canvas| { - Guides::new("Guides", canvas, Bind::bound(&mut *guides)).interactive(true).selected_guide(GuideKey::new(2)).show_at(ui, at) + Guides::new("Guides", canvas, guides_at.bind(&mut *guides)).interactive(true).selected_guide(GuideKey::new(2)).show_at(ui, at) }) } #[story(Guides<'static>, covers = [Mixed], drive = Drive::Custom(drag_first))] fn guides_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", Mixed::>::Mixed); - on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, Bind::bound_mixed(&mut *guides)).interactive(true).show_at(ui, at)) + let (guides, guides_at) = data.value_at("guides", Mixed::>::Mixed); + on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, guides_at.bind_mixed(&mut *guides)).interactive(true).show_at(ui, at)) } #[story(Guides<'static>, covers = [Invalid], drive = Drive::Custom(drag_first))] fn too_many_guides(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", guides()); + let (guides, guides_at) = data.value_at("guides", guides()); let few = |guides: &Vec| { if guides.len() > MOST_GUIDES { Validity::Refuse(Message::new("There are too many guides")) } else { Validity::Ok } }; - on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, Bind::bound(&mut *guides).check(few)).interactive(true).show_at(ui, at)) + on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, guides_at.bind(&mut *guides).check(few)).interactive(true).show_at(ui, at)) } #[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_first))] fn guides_that_only_draw(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", guides()); - on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, Bind::bound(&mut *guides)).show_at(ui, at)) + let (guides, guides_at) = data.value_at("guides", guides()); + on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, guides_at.bind(&mut *guides)).show_at(ui, at)) } #[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_first))] fn bounded_guides(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", guides()); + let (guides, guides_at) = data.value_at("guides", guides()); let page = DocRect::new(120.0, 80.0, 520.0, 320.0); - on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, Bind::bound(&mut *guides)).interactive(true).bounds(page).show_at(ui, at)) + on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, guides_at.bind(&mut *guides)).interactive(true).bounds(page).show_at(ui, at)) } diff --git a/crates/ui-canvas/src/canvas_controls/task_bar/stories.rs b/crates/ui-canvas/src/canvas_controls/task_bar/stories.rs index 0a7893134..b695d99dc 100644 --- a/crates/ui-canvas/src/canvas_controls/task_bar/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/task_bar/stories.rs @@ -3,7 +3,7 @@ use super::{TaskBar, TaskBarDismiss, TaskBarPlace}; use crate::buttons::{Button, IconButton}; use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas}; -use crate::contract::{Bind, Props as _, Show as _}; +use crate::contract::{Props as _, Show as _}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::IconId; use craft_behavior::kurbo::{Point, Vec2}; @@ -69,8 +69,8 @@ fn selection_bar_kept_while_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOut fn crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let corners = turned_frame(); on_canvas(ui, |ui, area, _| { - let place = data.value("place", TaskBarPlace::default()); - TaskBar::new("Crop", &corners, Bind::bound(place)) + let (place, place_at) = data.value_at("place", TaskBarPlace::default()); + TaskBar::new("Crop", &corners, place_at.bind(place)) .show(ui, area, |ui, cx| { for (icon, name) in [("rotate_ccw", "Rotate left"), ("rotate_cw", "Rotate right"), ("grid", "Overlay")] { let _ = IconButton::new(IconId::new(icon)).label(name).show(ui); @@ -88,8 +88,8 @@ fn crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn placed_and_pinned(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let corners = turned_frame(); on_canvas(ui, |ui, area, _| { - let place = data.value("place", TaskBarPlace { pinned: true, at: Some([24.0, 24.0]) }); - TaskBar::new("Crop", &corners, Bind::bound(place)) + let (place, place_at) = data.value_at("place", TaskBarPlace { pinned: true, at: Some([24.0, 24.0]) }); + TaskBar::new("Crop", &corners, place_at.bind(place)) .show(ui, area, |ui, _| { let _ = Button::new("Done").show(ui); }) diff --git a/crates/ui-canvas/tests/it/canvas/split.rs b/crates/ui-canvas/tests/it/canvas/split.rs index a12c8e744..b90507f92 100644 --- a/crates/ui-canvas/tests/it/canvas/split.rs +++ b/crates/ui-canvas/tests/it/canvas/split.rs @@ -3,7 +3,7 @@ use craft_behavior::PartKey; use craft_ui::canvas::{SplitAt, SplitLayout, SplitViews}; -use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::contract::ShowContainer as _; use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial}; use egui::{Pos2, Rect, Vec2}; @@ -41,8 +41,8 @@ fn widths(panes: &[Rect]) -> Vec { } fn show(ui: &mut egui::Ui, data: &mut StoryData, layout: SplitLayout, count: usize) -> StoryOutput { - let at = data.value("split", SplitAt::default()); - SplitViews::new("Views", layout, Bind::bound(at)).count(count).show(ui, |_, _| ()).output.into() + let (at, at_at) = data.value_at("split", SplitAt::default()); + SplitViews::new("Views", layout, at_at.bind(at)).count(count).show(ui, |_, _| ()).output.into() } fn tiled(ui: &mut egui::Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index 01d3a740c..ec8d7c310 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -11,7 +11,7 @@ use craft_ui::canvas::{ canvas_space, tool_pass, }; use craft_ui::contract::tooltip::DELAY; -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; @@ -22,7 +22,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}; @@ -907,23 +907,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; 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| { @@ -947,12 +953,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:?}"); } diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 33c775c3f..38b98b400 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -38,6 +38,8 @@ craft-ui-macros = { workspace = true } craft-tracked = { workspace = true } # `MemoKey`: SipHash-1-3 with a 128-bit output. siphasher = "1" +# `MemoProps::identity`: the `TypeId` of a props type with its lifetimes erased. +typeid = { workspace = true } # `CommandRef.params`, which a memo key walks. serde_json = { workspace = true } craft-settings = { workspace = true } diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index ab1d798f2..0ebaf221d 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -103,7 +103,9 @@ pub(super) struct BodyHooks<'b> { scroll_bound: bool, moved: bool, last: BodyView, - /// The content's extent from the last run that laid it out, kept with the offset it bounds (`ScrollState`). + /// The content's extent. Step 4 reads the last pass's, kept with the offset it bounds (`ScrollState`): the moves + /// it applies act on the content that pass showed. A measuring run lays the content out for the extent it sets + /// (`measure_run`); from step 5 the real run takes what this pass's measuring run found. last_extent: (f32, f32), /// The height of a scroll strip (`ScrollIndicator::Strips`). strip: f32, @@ -126,6 +128,9 @@ pub(super) struct BodyHooks<'b> { settle: Option, unsettled: Option, extent: Option, + /// The content extent a measuring run found that leaves another view than the one the run laid the content out + /// for: the run lays it out again at that view. + view_moves: Option<(f32, f32)>, view: Option, save: Option, layer: bool, @@ -220,6 +225,7 @@ impl<'b> BodyHooks<'b> { settle: None, unsettled: None, extent: None, + view_moves: None, view: None, save: None, layer: false, diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 5d0f8087d..5f95a19e4 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -38,6 +38,7 @@ use crate::style::{StyleCx, SurfaceKind, band_color, scroll_bar_look, surface_st use craft_behavior::layout_memory::measure_tolerance; use craft_behavior::{CancelRule, CursorIcon, EditEvent, KeyRole, Mixed, Roving, ScrollPos, ScrollSpan, WheelRoom, WheelTaker}; use craft_theme::variant::Tone; +use egui::emath::GuiRounding as _; use egui::layers::ShapeIdx; use egui::{Context, CornerRadius, Id, Pos2, Rect, Shape, Ui, UiBuilder, Vec2}; use std::any::Any; @@ -344,12 +345,13 @@ impl ShapeHooks for BodyHooks<'_> { let mut stage = MemoryStage::open_peek(&ctx, id); let mut fresh = self.measuring_hooks(fading); crate::contract::run::measured_extent(comp, &mut fresh, at, &mut stage, style, shown); - // The strips show in the pass whose content first overflows: the measuring run's content decides them. - if let Some(extent) = fresh.extent.filter(|_| scroll_of(&props).is_some_and(|scroll| scroll.has_strips())) { - self.last_extent = (extent.x, extent.y); - } } let took = |key: Id| layout_memory::measured(&ctx, key).map(|measured| measured.took); + // The real run decides the scroll from the content this pass measured: whether it overflows (the wheel, the + // bars, the strips) and how far it scrolls. + if let Some(extent) = took(sub(id, "extent")).filter(|_| scroll_of(&props).is_some()) { + self.last_extent = (extent.x, extent.y); + } self.measured_body = took(id); self.measured_header = props.header.and_then(|_| took(sub(id, "header"))); self.measured_footer = props.footer.as_ref().and_then(|_| took(sub(id, "footer"))).unwrap_or(Vec2::ZERO); @@ -438,7 +440,7 @@ impl ShapeHooks for BodyHooks<'_> { let tokens = cx.tokens; let pad = self.pads(&props, tokens); let inner = content.shrink2(pad); - let regions = self.regions(&props, inner, pad, self.room_size(rect, inner), rtl, self.measured_sizes()); + let regions = self.regions(&props, inner, pad, self.room_size(rect, inner), rtl, self.measured_sizes(), !cx.ui.is_sizing_pass()); let (_, slots) = self.header_line(regions.header, pad_of(tokens, header.inset), parts, rtl); Some(std::rc::Rc::new(slots)) } @@ -451,7 +453,7 @@ impl ShapeHooks for BodyHooks<'_> { let pad = self.pads(&props, tokens); let inner = pcx.content_rect.shrink2(pad); let room = self.room_size(rect, inner); - let regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes()); + let regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes(), !pcx.ui.is_sizing_pass()); let scroll = scroll_of(&props); if self.open && scroll.is_some() { let at = regions.body; @@ -746,6 +748,42 @@ impl BodyHooks<'_> { let (layer, rect) = self.begin_measure_run(at, cx.core, cx.style.metrics().padding); let mut values = AppValues::default(); comp.content_env(cx, &mut values); + // A scrolling body's view (a bar that takes room, the strips) follows from its content's overflow. The content is + // laid out as overflowing along every axis it scrolls, beside the bars; when its overflow leaves another view + // (content that fits), the sweep is taken back and the content runs once more at that view. Content that + // overflows, whose children are the costly ones to run twice, runs once. + let overflows = crate::contract::MAX_EXTENT; + (self.last_extent, self.view_moves) = ((overflows, overflows), None); + if scroll_of(&self.props).is_some() { + let ctx = at.ui.ctx().clone(); + let (overflow, _) = crate::contract::draft( + &ctx, + || { + self.sweeps(comp, at, cx, (layer, rect), &values); + self.view_moves.take() + }, + Option::is_none, + ); + if let Some(extent) = overflow { + self.last_extent = extent; + self.sweeps(comp, at, cx, (layer, rect), &values); + self.view_moves = None; + } + } else { + self.sweeps(comp, at, cx, (layer, rect), &values); + } + self.end_measure_run(at, cx.core.id, key, content) + } + + /// The measuring run's sweeps of the regions at the view it lays the content out for. + fn sweeps( + &mut self, + comp: &mut C, + at: &Measuring<'_, '_>, + cx: &mut Cx<'_, C>, + (layer, rect): (areas::LayerKey, Rect), + values: &AppValues, + ) { // A label group settles its columns before a measure inside stands: when a row of a body that shows at its // measured width read a column narrower than the group's widest, the sweep is taken back and the content runs // once more with the group opened at the widths the first sweep found. @@ -754,20 +792,19 @@ impl BodyHooks<'_> { let (unsettled, _) = crate::contract::draft( &ctx, || { - self.sweep(comp, at, cx, (layer, rect), &values); + self.sweep(comp, at, cx, (layer, rect), values); self.unsettled.take() }, Option::is_none, ); if let Some(widths) = unsettled { (self.settle, self.reached) = (Some(widths), None); - self.sweep(comp, at, cx, (layer, rect), &values); + self.sweep(comp, at, cx, (layer, rect), values); (self.settle, self.unsettled) = (None, None); } } else { - self.sweep(comp, at, cx, (layer, rect), &values); + self.sweep(comp, at, cx, (layer, rect), values); } - self.end_measure_run(at, cx.core.id, key, content) } /// Opens the measuring run of `cx`'s container: its rect at the room's start edge, which `cx` takes, and the layer @@ -836,6 +873,10 @@ impl BodyHooks<'_> { if let Some(content) = content { record(sub(id, "content"), content); } + // What a scrolling body's content took, for the real run's scroll (`pass_extent`). + if let Some(extent) = self.extent.filter(|_| scroll_of(&props).is_some()) { + record(sub(id, "extent"), extent); + } // The rows of a content-sized body reach past the columns of the group around by as much more as the // container does: a box's padding, or a row's members after its labelled one. The group measures its extent // from these, at its widest columns. @@ -953,6 +994,8 @@ struct ScrollRegion { bar: f32, /// The run lays the content out for the view. lays_out: bool, + /// The bars' inset and the part of the body the content shows in, as the extent the run starts from gives them. + laid_for: (Vec2, Rect), } /// The `Ui` a measuring run lays a transformed body out in: on the body layer the real run shows it on. @@ -1029,12 +1072,12 @@ impl BodyHooks<'_> { let pad = self.pads(props, &env.tokens); let inner = core.content_rect.shrink2(pad); let room = self.room_size(rect, inner); - let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes()); - let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_))); - let band_slot = ui.painter().add(Shape::Noop); // A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer, // and claims no room in a parent flow. let real = !ui.is_sizing_pass(); + let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes(), real); + let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_))); + let band_slot = ui.painter().add(Shape::Noop); let window = window_instance(props, id).filter(|window| *window != id); if real { register_instances(&ctx, props, id, window); @@ -1211,7 +1254,7 @@ impl BodyHooks<'_> { let beside = if real { self.measured_sizes() } else { RegionSizes { header: self.header_size, footer: self.measured_footer, end: self.end_size } }; if !real { - let placed = self.regions(props, plan.inner, plan.pad, plan.room, plan.rtl, beside); + let placed = self.regions(props, plan.inner, plan.pad, plan.room, plan.rtl, beside, real); (plan.regions.body, plan.regions.beside) = (placed.body, placed.beside); } let line = shared_line(props, beside); @@ -1442,9 +1485,14 @@ impl BodyHooks<'_> { Pos2::new(if rtl { shows.max.x } else { shows.max.x - inset.x }, shows.max.y - inset.y), ); let (width, height) = (if scroll.horizontal_on() { big } else { seen.width() }, if scroll.vertical_on() { big } else { seen.height() }); - let x = if scroll.horizontal_on() { off.x as f32 } else { 0.0 }; + // The content moves by whole physical pixels on steps of egui's UI rounding, the grids widget rects and paint + // are rounded to: a settled run moved with the content then replays where a run would be + // (`lazy::keeps_placement`). + let ppp = ctx.pixels_per_point(); + let (x, y) = ((off.x as f32).round_to_pixels(ppp).round_ui(), (off.y as f32).round_to_pixels(ppp).round_ui()); + let x = if scroll.horizontal_on() { x } else { 0.0 }; let min_x = if rtl { seen.max.x - width + x } else { seen.min.x - x }; - let max = Rect::from_min_size(Pos2::new(min_x, seen.min.y - off.y as f32), Vec2::new(width, height)); + let max = Rect::from_min_size(Pos2::new(min_x, seen.min.y - y), Vec2::new(width, height)); let layout_of = *body_ui.layout(); let mut region_ui = alloc::child(body_ui, UiBuilder::new().scope_id(sub(id, "scroll_region")).layout(layout_of).max_rect(max)); region_ui.set_clip_rect(shows.intersect(body_ui.clip_rect())); @@ -1460,25 +1508,23 @@ impl BodyHooks<'_> { content: max, axes: (scroll.horizontal_on(), scroll.vertical_on()), rtl, - anchor: self.anchor.map(|anchor| anchor.child), - reveal: self.glide.map(|glide| glide.child), }; // Only the run that lays the content out for the view places its children; a measure lays it out for its // own question. let lays_out = run.real && !crate::runtime::measure::active(ctx); if lays_out { - crate::runtime::lazy::begin(ctx, id); + crate::runtime::lazy::begin(ctx, view, self.anchor.map(|anchor| anchor.child), self.glide.map(|glide| glide.child)); } let env = run.env.derive_local(|scoped| scoped.lazy = Some(view)); let installed = Env::install_for(®ion_ui, env.clone()); - ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out } + ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out, laid_for: (inset, shows) } } /// After a scrolling body's content ran: the anchor and glide follow what it placed, and the body takes what the /// view shows of it. fn scrolled(&mut self, run: &BodyRun<'_>, scroll: Scroll, at: Rect, region: ScrollRegion, bars: &mut Vec2) -> Option { let (ctx, id) = (run.ctx, run.id); - let ScrollRegion { ui: region_ui, installed, seen, max, shown, bar, lays_out, .. } = region; + let ScrollRegion { ui: region_ui, installed, seen, max, shown, bar, lays_out, laid_for, .. } = region; Env::restore(ctx, installed); if lays_out { crate::contract::run::close_bar_line(ctx, id); @@ -1497,6 +1543,11 @@ impl BodyHooks<'_> { crate::runtime::egui::widgets::note_scroll_region(ctx, region_ui.clip_rect(), region_ui.min_rect().intersect(max)); } self.extent = Some(extent); + // A measuring run whose content leaves another view than the one it laid the content out for runs again there. + let leaves = (overflow_inset(scroll, extent, at.size(), bar), view_within(scroll, extent, at, self.strip)); + if !run.real && leaves != laid_for { + self.view_moves = Some((extent.x, extent.y)); + } // Along an axis it scrolls the body took what the view shows; along the other it took its content. *bars = overflow_inset(scroll, extent, at.size(), bar); // Strips take their height from the view: a body that overflows takes all of its room. diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 208849286..001b98ca9 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -1,6 +1,7 @@ //! Where the header, body, footer and end regions sit inside the container, and the rules between them. use super::BodyHooks; +use super::scroll::scroll_of; use crate::contract::cx::BodyCx; use crate::contract::{Container, ContainerProps, FooterPlace, Gap, HeaderParts, LeastWidth, Mount, Pad, PadEdges, Sizing}; use crate::layout::{ColumnGroup, Columns, Reached}; @@ -355,9 +356,11 @@ impl<'b> BodyHooks<'b> { self.rules.under + if header_h > 0.0 { self.header_gap * self.presence.t } else { 0.0 } } - /// The regions inside `inner` (the rect minus padding and the padding tier), placed from `sizes`. A header with a - /// band spreads over the `bleed` the padding leaves around `inner` at the top and the sides. - pub(super) fn regions(&self, props: &ContainerProps, inner: Rect, bleed: Vec2, room: Vec2, rtl: bool, sizes: RegionSizes) -> Regions { + /// The regions inside `inner` (the rect minus padding and the padding tier), placed from `sizes`, in a real run when + /// `real` (not a measuring run: the `Ui` is no sizing pass). A header with a band spreads over the `bleed` the + /// padding leaves around `inner` at the top and the sides. + #[allow(clippy::too_many_arguments, reason = "the regions' rect, room and sizes beside the run they are placed for")] + pub(super) fn regions(&self, props: &ContainerProps, inner: Rect, bleed: Vec2, room: Vec2, rtl: bool, sizes: RegionSizes, real: bool) -> Regions { let inline = props.header.is_some_and(|header| header.inline); let (in_end, full) = (footer_in_end(props), end_full_height(props)); let header_h = if props.header.is_some() { sizes.header.unwrap_or(Vec2::ZERO).y } else { 0.0 }; @@ -382,7 +385,13 @@ impl<'b> BodyHooks<'b> { let line_h = if inline { body_h.max(header_h) } else { body_h }; // A full-height end region stands beside the footer too, so only the part of it under the line counts. let end_line = if full { (end_h - across_h).max(0.0) } else { end_h }; - (top + body_room, top + line_h.max(end_line).min(body_room)) + let line_bottom = top + line_h.max(end_line).min(body_room); + // A scrolling body offered no bound (a content-sized container in a body that scrolls) shows all of its + // content: in the real run its view is the line this pass measured, never an unbounded band. Its measuring + // run keeps the unbounded band, in which the content takes its whole extent. + let unbounded_view = real && !body_room.is_finite() && scroll_of(props).is_some(); + let bottom = if unbounded_view { line_bottom } else { top + body_room }; + (bottom, line_bottom) } else { // A fill-width body is offered the room the parent gives this pass, never the height its content took last // pass: a collection that scrolls takes its rows up to that room, and from zero it would stay at zero. diff --git a/crates/ui-contract/src/contract/body/scroll.rs b/crates/ui-contract/src/contract/body/scroll.rs index d83bb4afb..8a527a030 100644 --- a/crates/ui-contract/src/contract/body/scroll.rs +++ b/crates/ui-contract/src/contract/body/scroll.rs @@ -31,6 +31,14 @@ pub const STRIP_FORWARD: PartKey = PartKey::new("body_scroll_strip_forward"); /// Rows per second a region scrolls at while the pointer rests on one of its strips, in rows a control high. const STRIP_ROWS_PER_SECOND: f32 = 24.0; +/// The child the scroll position of the scrolling body `body` is named by (`lazy::Anchor`), for trials. +#[cfg(feature = "testing")] +pub(crate) fn anchor_of(ctx: &Context, body: Id) -> Option { + crate::runtime::memory::with_session::(ctx, crate::runtime::memory::sub(body, "scroll"), |state| { + state.anchor.map(|anchor| anchor.child) + }) +} + /// The height of a scroll strip. pub(super) fn scroll_strip_height(tokens: &UiTokens) -> f32 { tokens.size.control.sm diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 70607efd8..bf05efae3 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -28,8 +28,6 @@ pub(super) struct MeasureKey { width: Option, /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), - /// The content extent the view keeps, which decides the scroll bars' inset. - extent: (f32, f32), env: EnvFacts, } @@ -93,7 +91,6 @@ impl<'b> BodyHooks<'b> { wide: self.wide(), width, shows: (self.open, self.presence.t), - extent: self.last_extent, env: EnvFacts::of(env), } } diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index 081ae575b..3c464e0b4 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -595,26 +595,27 @@ impl CollectionProps { } } -/// What an item reads of its place in the collection; the item step joins it to the item's flags at step 12. +/// What an item reads of its place in the collection; the item step joins it to the item's flags at step 12. The +/// fields marked "Measured" are the ones an auto row's measure reads (the row-hook contract on `ItemCx`). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct RowState { - /// The row is selected. + /// The row is selected. Measured. pub selected: bool, - /// The row holds the lead. + /// The row holds the lead. Measured. pub lead: bool, /// A drag would drop on the row. pub drop_target: bool, /// The row is being dragged. pub dragging: bool, - /// The row's name is being edited. + /// The row's name is being edited. Measured. pub renaming: bool, /// The app marks the row. pub emphasized: bool, - /// The collection's current item (`CollectionProps::current`). + /// The collection's current item (`CollectionProps::current`). Measured. pub current: bool, - /// An odd row of a striped list. + /// An odd row of a striped list. Measured. pub striped: bool, - /// A tree row whose children show. + /// A tree row whose children show. Measured. pub open: bool, /// The pointer is over the row and a press there would reach it. pub hovered: bool, @@ -627,11 +628,11 @@ pub struct RowState { /// button shown. pub menu_open: bool, /// `Some(steps)` for a sub-row of a row above (`ItemSource::sub_row`): compact, its toggles `steps` indent steps - /// into its content. + /// into its content. Measured. pub sub_row: Option, - /// The next row is a sub-row, which continues this row: no divider between them. + /// The next row is a sub-row, which continues this row: no divider between them. Measured. pub continued: bool, - /// The row is the collection's last: dividers fall between rows, so none under it. + /// The row is the collection's last: dividers fall between rows, so none under it. Measured. pub last: bool, /// The activation key (Enter) activated the row this pass: a row with controls of its own may move focus into one. pub activated_by_key: bool, diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index da27a3368..142677f22 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -123,7 +123,7 @@ impl ShellPane { } /// The padding tier of a body. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub enum Pad { /// No padding. @@ -717,7 +717,7 @@ pub enum Gap { /// Set by a menu for its body: a horizontal divider takes `space.gap.inline` above and below its line, since the rows /// of a menu touch. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct InMenu(pub bool); diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index c1eaafc5d..72ddd0283 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -167,6 +167,8 @@ pub struct CxCore<'a> { pub(crate) roving_arrival: Option, /// The member of the container's roving group that moves start from, set by `Cx::roving_lead`. pub(crate) roving_lead: Option, + /// The component joined the roving group of the body it is shown in this pass (`Cx::join_roving`). + pub(crate) roving_member: bool, /// The collection's selection (a `Selection`) and lead as the item step holds them, for `Cx::collection_selection`. pub(crate) collection_selection: Option>, /// The events and visible range the item step left for `collection_response`. @@ -236,13 +238,11 @@ impl Cx<'_, C> { crate::runtime::egui::output::open_url(&self.core.ctx, url, new_tab); } - /// Makes this component a member of the roving group of the body it is shown in: its stop joins the group and - /// Tab visits the group once. A component that never calls it keeps its own Tab stop. + /// Makes this component a member of the roving group of the body it is shown in: its stop and its focusable parts + /// join the group, and Tab visits the group once. Called from `update`: the stops register after it, in the same + /// pass. A component that does not call it in a pass keeps its own Tab stop in that pass. pub fn join_roving(&mut self) { - if let Some(group) = self.core.env.roving() { - crate::contract::steps::join_group(&self.core.ctx, group, self.core.id); - focus::registration::join_part_group(&self.core.ctx, group, self.core.id, crate::runtime::memory::sub(self.core.id, "roving")); - } + self.core.roving_member = true; } /// Runs `command` as this component's own activation would, for a command that is not the component's bound diff --git a/crates/ui-contract/src/contract/cx/item.rs b/crates/ui-contract/src/contract/cx/item.rs index 3d4ccfe7a..c36fb5460 100644 --- a/crates/ui-contract/src/contract/cx/item.rs +++ b/crates/ui-contract/src/contract/cx/item.rs @@ -17,6 +17,16 @@ pub struct ItemOpener { } /// What the item closure reads for one item: a view over the pipeline's memory stage keyed by the item. +/// +/// The row-hook contract. The collection measures an auto row (auto height or auto widths) at step 5, before it +/// places its rows, from the item this closure and `Collection::dress` make with the row state known before the pass +/// senses input: the `RowState` fields marked "measured" as step 4 read them, the depth and the set position, under +/// the collection's env. The size of an auto row depends only on those. It must not depend on app values the body +/// adds at step 13, the surface, focus, or the pointer and gesture state (`hovered`, `pointer_over`, `pressed`, +/// `dragging`, `drop_target`, `menu_open`, `activated_by_key`): only the build that shows the row has them. A row +/// whose measured state this pass's input changes (a click that selects it, a press that starts its rename) is +/// measured again when it is built; a size other than the one the pass placed it by makes the pass run again, so +/// the frame shows the row at its new size. #[non_exhaustive] pub struct ItemCx<'a, 'r, K> { /// The item's key. diff --git a/crates/ui-contract/src/contract/ghost.rs b/crates/ui-contract/src/contract/ghost.rs index 5933c9851..89e8db46a 100644 --- a/crates/ui-contract/src/contract/ghost.rs +++ b/crates/ui-contract/src/contract/ghost.rs @@ -107,7 +107,7 @@ fn paint_pointer(ctx: &Context, env: &Env, painter: &egui::Painter) { use craft_behavior::{Cursor, PaintedCursor}; let Some(at) = areas::pointer_pos(ctx) else { return }; let Some(Cursor::Painted(cursor)) = cursor::current(ctx) else { return }; - let closed = pointer::frame(ctx).buttons.contains(craft_behavior::Buttons::PRIMARY); + let closed = pointer::frame_raw(ctx).buttons.contains(craft_behavior::Buttons::PRIMARY); let tip = matches!(cursor, PaintedCursor::Circle { .. } | PaintedCursor::Outline { .. }); let whole = pointer_art(env, &cursor, closed, false); let confined = cursor::current_region(ctx).filter(|region| tip && !shows_whole(ctx, region, &whole, at)); @@ -160,7 +160,7 @@ fn paint_drag(ctx: &Context, env: &Env, painter: &egui::Painter, session: &drag: } let record = RefCell::new(PaintRecord::default()); let draw = &Draw::new(painter, &record, DrawEnv { tokens: &env.tokens, direction: env.direction, ink: Ink::OnPanel }); - let Some(at) = pointer::frame(ctx).pos else { return }; + let Some(at) = pointer::frame_raw(ctx).pos else { return }; match &session.preview { DragPreview::Badge(label) => { let label = env.view().resolve(label); diff --git a/crates/ui-contract/src/contract/group.rs b/crates/ui-contract/src/contract/group.rs index c82f4be8a..72a725788 100644 --- a/crates/ui-contract/src/contract/group.rs +++ b/crates/ui-contract/src/contract/group.rs @@ -32,6 +32,8 @@ impl Default for GroupState { /// A group form's handle, put into its body's env with `content_env`. Members and body code read it with /// `cx.env.get::>()`; a member outside any group gets the inert root handle. +#[derive(crate::contract::MemoProps)] +#[memo_props(every_pass = "a handle to group state its members write during the pass: a key cannot follow it")] pub struct GroupHandle { state: Option>>>, kind: PhantomData G>, diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 08746b3d1..0b0255421 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -229,6 +229,10 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { /// The bound column layout as the read step found it; `None` while the header keeps its own memory. column_layout_at_read: Option, lead: Lead, + /// The lead row and the renaming row as step 4 read them: a row's measure at step 5 reads them + /// (`known_row`). + lead_at_read: Option, + renaming_at_read: Option, renaming: Renaming, ended_rename: bool, /// The editor of the rename that ended still held focus, so focus goes back to the collection. @@ -241,8 +245,6 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { page_reveal: Option, /// The row this pass scrolls into view, placed before the rows are built (`place_reveal`). revealing: Option, - /// The rows `place_reveal` built and measured this pass: the build places them by that measure. - measured_for_reveal: Vec, /// The row the collection's own press is held on this pass, and where on it. pressed: Option<(usize, crate::contract::collection::RowPressed)>, /// The rows above and below the edge-press band declared this pass. @@ -306,7 +308,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { drags: Drags::default(), page_reveal: None, revealing: None, - measured_for_reveal: Vec::new(), + lead_at_read: None, + renaming_at_read: None, pressed: None, edge: None, } diff --git a/crates/ui-contract/src/contract/items/drag.rs b/crates/ui-contract/src/contract/items/drag.rs index fff7c7028..3ffb3d5b8 100644 --- a/crates/ui-contract/src/contract/items/drag.rs +++ b/crates/ui-contract/src/contract/items/drag.rs @@ -447,7 +447,7 @@ impl ItemsHooks<'_, '_, C> { /// does nothing and starts no sweep. pub(super) fn begin_toggle(&mut self, cx: &mut Cx<'_, C>, at: usize, (column, toggle, cell): (ColumnKey, ToggleColumn, Rect)) { if toggle.sweepable { - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; self.drags.sweep = Some(Sweep { column: column.clone(), on: false, mods, crossed: vec![at], span: cell.x_range(), open: Vec::new() }); } match self.flip_toggle(cx, at, column, toggle) { @@ -467,7 +467,7 @@ impl ItemsHooks<'_, '_, C> { return None; } let on = !self.source.toggled(at, &column); - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; self.emit_toggle(cx, at, &column, on, mods); if toggle.exclusive && on { for other in (0..self.source.len()).filter(|&other| other != at && self.source.toggled(other, &column)) { diff --git a/crates/ui-contract/src/contract/items/edge.rs b/crates/ui-contract/src/contract/items/edge.rs index baf704692..b3c6da9be 100644 --- a/crates/ui-contract/src/contract/items/edge.rs +++ b/crates/ui-contract/src/contract/items/edge.rs @@ -16,7 +16,7 @@ impl ItemsHooks<'_, '_, C> { pub(super) fn edge_parts(&mut self, comp: &C, pcx: &mut PartsCx<'_, C>) { self.edge = None; let Some(rule) = comp.edge_press() else { return }; - let frame = crate::runtime::pointer::frame(pcx.measure.ui.ctx()); + let frame = crate::runtime::pointer::frame_raw(pcx.measure.ui.ctx()); let (Some(pos), true) = (frame.pos, frame.mods == rule.mods()) else { return }; let Some(layout) = self.layout.clone() else { return }; let view = self.below_header(pcx.content_rect); @@ -59,7 +59,7 @@ impl ItemsHooks<'_, '_, C> { pub(super) fn edge_step(&mut self, cx: &mut Cx<'_, C>) { let Some((above, below)) = self.edge.clone() else { return }; if cx.part_activated(EDGE).is_some() { - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; self.events.push(CollectionEvent::EdgePressed { above, below, mods }); } } diff --git a/crates/ui-contract/src/contract/items/header.rs b/crates/ui-contract/src/contract/items/header.rs index 5b5d51436..fe640469d 100644 --- a/crates/ui-contract/src/contract/items/header.rs +++ b/crates/ui-contract/src/contract/items/header.rs @@ -602,7 +602,7 @@ impl Header { self.events.push(ColumnEvent::Removed { key: key.clone() }); } } - if cx.part(HEADER.at(hash)).hovered && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) { + if cx.part(HEADER.at(hash)).hovered && crate::runtime::pointer::frame_raw(&ctx).release == Some(PointerButton::Secondary) { self.ask_menu(&ctx, Some(key.clone()), ctx.pointer_latest_pos().unwrap_or(rect.left_bottom())); } if movable && primary && matches!(phase, PressPhase::DragStart { .. }) { @@ -648,7 +648,7 @@ impl Header { } if let Some(room) = self.room && cx.part(ROOM).hovered - && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) + && crate::runtime::pointer::frame_raw(&ctx).release == Some(PointerButton::Secondary) { self.ask_menu(&ctx, None, ctx.pointer_latest_pos().unwrap_or(room.left_bottom())); } @@ -797,7 +797,7 @@ impl Header { /// where the `PaintUi` the hosting needs exists. pub(super) fn paint(&self, ui: &mut Ui, cx: &Cx<'_, C>, comp: &mut C, env: &Env, id: Id, rtl: bool) { let ctx = ui.ctx().clone(); - let group = crate::contract::steps::parts_group(&ctx, id); + let group = crate::contract::steps::parts_group(id, env.roving.filter(|_| cx.core.roving_member)); for cell in &self.cells { let spec = &self.specs[cell.spec]; let hosted = self.hosted.contains(&spec.key); diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 1f8f7507c..a3b6225fd 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -15,13 +15,13 @@ use crate::contract::run::{Measuring, ShapeHooks, ShowAt}; use crate::contract::steps::ShapeKind; use crate::contract::{Bind, Collection, Cx, Internal, ItemCx, ItemOutput as _, PartsCx, Props, Show as _, Sizing}; use crate::primitives::{HiddenContent, ScrollBar, SurfaceSlot}; -use crate::runtime::access::{self, Role, SetPosition}; +use crate::runtime::access::{self, Role}; use crate::runtime::egui::{alloc, areas, child, response}; use crate::runtime::env::WheelScope; use crate::runtime::env::{AppValues, ArenaId, Env, ItemFacts, ThemeScope}; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::{focus, keys, layout_memory, lazy, overlay, wheel}; -use crate::style::{ComponentStyle as _, StyleCx, SurfaceKind, UiTokens, scroll_bar_look, surface_style}; +use crate::style::{ComponentStyle as _, SurfaceKind, UiTokens, scroll_bar_look, surface_style}; use craft_behavior::{ Axis, CancelReason, EditEvent, Intent, ItemLayout, Mixed, Proposal, ScrollPos, ScrollSpan, SelectionModel, Sense, WheelRoom, WheelTaker, }; @@ -129,6 +129,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.lead.key = self.selection.lead().filter(|key| self.index_of(key).is_some()).cloned(); } self.renaming = stage.session::>(sub(id, "rename")).clone(); + (self.lead_at_read, self.renaming_at_read) = (self.lead.key.clone(), self.renaming.key.clone()); let scrolled = match comp.scroll() { Some(bind) => match bind.get() { Some(Mixed::Same(pos)) => Scrolled { y: pos.y, x: pos.x, anchor: None }, @@ -165,105 +166,13 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { fn measured_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Vec2 { let id = cx.core.id; self.record_largest(comp, at, id); - self.extent(comp, at.ui, at.at, id, at.scx) + self.items_extent(comp, at, id) } fn pass_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, _style: &C::Style, _shown: Option>>) -> Vec2 { let id = at.resolved.id; self.record_largest(comp, at, id); - self.extent(comp, at.ui, at.at, id, at.scx) - } - - fn extent(&mut self, comp: &C, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { - let room = match at { - ShowAt::Rect(rect) => rect.size(), - ShowAt::Flow => crate::layout::flow_room(ui), - }; - let env = Env::of(ui); - // The layout reads the component's own motion memory (`StyleCx::exiting`): an item leaving its source keeps - // its room until its exit ends. - let scx = &scx.measured_by(ui).owned_by(id, env.motion); - self.room = room; - self.indent_step = scx.control().icon; - let room = Self::inner_room(comp, scx.tokens, room); - // Where the enclosing body does not give the width, the collection takes its width from its content, whether - // it fills or fills the width, as a container does. Held in a content-sized column it measures so, and shows - // across the width the column settles on. - let held = env.content_column || crate::layout::in_grid_content_column(ui); - self.from_content = (!env.gives_width() && (crate::runtime::measure::active(ui.ctx()) || !held), env.content.1); - self.header.measure(scx); - self.header.read_content(ui.ctx(), id); - let bounded = room.x.is_finite(); - let item = comp.measures_items().then(|| layout_memory::measured(ui.ctx(), sub(id, "largest")).map(|measured| measured.took)).flatten(); - // Under a body that does not give the width, the measuring run lays the rows out at the width the collection - // asks for, so the height it reports is the one it has at that width (a grid's rows at its columns). - let from_content = self.from_content.0 && !self.content_sized(comp); - let asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, ui, id, room, item, scx)); - let width = match (bounded, self.content_sized(comp)) { - (true, false) => asked.unwrap_or(room.x), - // No rows: the empty state has no ideal width, so it takes the room, or none where the room is unbounded. - (_, _) if self.source.is_empty() => { - if bounded { - room.x - } else { - 0.0 - } - } - // An unbounded room (a horizontally scrolling body) takes the widest row, as a content-sized collection does. - (_, _) => { - let floor = env.get::().0; - let widest = layout_memory::measured(ui.ctx(), sub(id, "largest")).map_or(0.0, |measured| measured.took.x); - // Columns side by side at their own widths: a `Content` column takes its widest cell, not the share of - // the widest row it would get. - let columns = if self.header.has_columns() { self.header.content_width() } else { 0.0 }; - widest.max(columns).max(comp.ideal_width(item, self.source.len(), scx)).max(floor).min(room.x) - } - }; - let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone())); - let mut layout = comp.item_layout_from(previous, self.source, width, item, scx); - if self.header.has_columns() { - layout.set_columns(&self.header.columns(width)); - } - let ctx = ui.ctx(); - rows::measured_heights(ctx, id, |height| layout.measured(&|at| height(rows::measured_id(id, &self.source.key(at))))); - if layout.auto_widths() { - rows::measured_widths(ctx, id, |width| { - for at in 0..self.source.len() { - if let Some((ideal, min)) = width(rows::measured_width_id(id, &self.source.key(at))) { - layout.set_width(at, ideal, min); - } - } - }); - } - let content = layout.content_size(); - self.content = Vec2::new(content.x as f32, content.y as f32); - let props = comp.items(); - let row = props.row_height.of(scx); - let floor = rows_height(&layout, self.source.len(), props.min_rows, row); - let cap = props.max_rows.map(|rows| rows_height(&layout, self.source.len(), rows, row).max(floor)); - self.columns = layout.column_count() as u32; - self.layout = Some(Arc::new(layout)); - let empty = if self.source.is_empty() { comp.empty_height(width, ui, scx) } else { 0.0 }; - let rows = self.content.y.max(empty).max(floor); - let height = cap.map_or(rows, |cap| rows.min(cap)) + self.header.height; - if !(self.scrolls && room.y.is_finite()) { - let wide = if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) } else { self.content.x }; - return Vec2::new(wide, height); - } - // A scrolling collection in a bounded room: `Content` takes its rows up to the room, `Fill` the room. - let wide = if self.content_sized(comp) { - self.content.x - } else if from_content { - asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) - } else { - 0.0 - }; - match comp.props(Internal::new()).sizing { - // Under a body sized from its content along the height, the rows take up to the room, as a content-sized - // collection's do: the body has no room of its own to hand it. - Sizing::Fill | Sizing::FillHeight => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }), - Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)), - } + self.items_extent(comp, at, id) } fn pad(&self, comp: &C, tokens: &UiTokens) -> f32 { @@ -423,22 +332,12 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } let rtl = env.direction.is_rtl(); let node = matches!(C::ROLE, Role::Node(_)); - let (child_size, child_glyphs) = (comp.props(Internal::new()).child_size, comp.props(Internal::new()).child_glyphs); // The rows sit on the surface the collection paints, else on the one the collection sits on. let own = surface.or_else(|| cx.style.surface().and_then(|look| look.kind_in(&cx.core.state))); - let base_env = env.derive(|scoped| { - scoped.extend_values(values); - scoped.arena = Some(ArenaId::new(id)); - scoped.size = child_size.unwrap_or(cx.core.resolved.size); - if let Some(role) = child_glyphs { - scoped.glyphs = role; - } - scoped.surface = SurfaceKind::under(own, scoped.surface); - // The rows lay out their own content: no line or first line of the body around reaches them. - scoped.row_line = None; - scoped.first_line = None; - }); - self.place_reveal(comp, ui, (id, cx.core.env, &base_env), &mut layout, rect); + let base_env = Self::rows_env(comp, env, id, cx.core.resolved.size, own).derive(|scoped| scoped.extend_values(values)); + let known = self.known(comp, false); + let known_at_read = self.known(comp, true); + let revealed = self.place_reveal(comp, ui, (id, cx.core.env, &base_env), (&mut layout, &known), rect); let offset = ScrollPos { x: self.offset_x, y: self.offset }; Arc::make_mut(&mut layout).set_view(rect.size(), offset); if self.scrolls { @@ -464,12 +363,22 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let lead = self.lead.key.clone(); let mut lead_child = None; let striped = comp.items().striped; - let current: Option = comp.items().current.as_deref().and_then(|key| key.downcast_ref::()).cloned(); let mut stripe: Option<(usize, usize)> = None; let transform = comp.props(Internal::new()).transform; let (parent, clip) = (ui.layer_id(), rect.intersect(ui.clip_rect())); let forward = areas::Forward { root: id, sense: response::to_egui(cx.core.root_sense), rect: cx.core.rect.intersect(ui.clip_rect()) }; - let placed = self.selection.placed(self.source); + let placed = known.placed.clone(); + let tolerance = craft_behavior::layout_memory::measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); + // What this pass measured of the rows it builds, before any of them is built: (width and height, widths). + let fresh: Vec<(Option, Option)> = rows::measured_this_pass(&ctx, id, |fresh| { + order + .iter() + .map(|&at| { + let key = self.source.key(at); + (fresh(rows::measured_id(id, &key)), fresh(rows::measured_width_id(id, &key))) + }) + .collect() + }); let mut row_groups = Vec::with_capacity(order.len()); let mut shown_rows: Vec> = Vec::with_capacity(order.len()); // A section row the component declares as its own `section_part` reports its own node; any other one is the @@ -500,7 +409,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { (members_ui, installed) }); let mut members = Vec::new(); - for at in order.into_iter() { + for (place, at) in order.into_iter().enumerate() { if self.source.section_stop(at) { continue; } @@ -509,45 +418,31 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let row_group = rows::row_group(item_id); row_groups.push(row_group); let mut row = self.screen(&layout, rect, at, offset, rtl); + let odd = striped && { + let run = self.stripe_run(stripe, at); + stripe = Some((at, run)); + run.is_multiple_of(2) && !self.source.is_section(at) + }; + let (known_state, mut flags) = self.known_row(at, &known, odd); + // A row step 5 measured whose measured state this pass's input changed since is measured again. + let restated = !revealed.contains(&at) && self.known_row(at, &known_at_read, odd).0 != known_state; let state = RowState { - selected: placed.holds_row(at), - lead: lead.as_ref() == Some(&key), - renaming: self.renaming.key.as_ref() == Some(&key), - striped: striped && { - let run = self.stripe_run(stripe, at); - stripe = Some((at, run)); - run.is_multiple_of(2) && !self.source.is_section(at) - }, dragging: self.drags.grabbed.as_ref() == Some(&key), drop_target: matches!(&self.drags.pending, Some(PendingDrop::Drop(DropAt::Onto(over))) if *over == key), - current: current.as_ref() == Some(&key), - open: self.source.has_children(at) && self.source.open(at), hovered: hover_at.is_some_and(|pos| row.contains(pos)), pointer_over: over_at.is_some_and(|pos| row.contains(pos)), pressed: self.pressed.as_ref().filter(|(held, _)| *held == at).map(|(_, pressed)| pressed.clone()), menu_open: self.drags.menu.as_ref() == Some(&key) && menu_open, - sub_row: self.source.sub_row(at), - continued: at + 1 < len && self.source.sub_row(at + 1).is_some(), - last: at + 1 == len, activated_by_key: self.keyed_activation.as_ref() == Some(&key), - ..RowState::default() + ..known_state }; - let mut flags = crate::style::Flags::empty(); - flags.set(crate::style::Flags::SELECTED, state.selected); let child = if state.lead { rows::child_focus(&ctx, row_group) } else { None }; lead_child = lead_child.or(child); // A list that never takes key focus (a popup list: the host forwards its keys) shows its lead always. flags.set(crate::style::Flags::LEAD, state.lead && (focused || child.is_some() || !comp.items().focus_on_press)); - flags.set(crate::style::Flags::EXPANDED, state.open); flags.set(crate::style::Flags::DRAGGING, state.dragging); flags.set(crate::style::Flags::DROP_TARGET, state.drop_target); - flags.set(crate::style::Flags::CURRENT, state.current); - let mut position = SetPosition::new(at - self.source.section_stops_before(at)) - .of(len - self.source.section_stops_before(len)) - .columns(columns.len()); - if tree { - position = position.level(self.source.depth(at) + 1); - } + let position = self.row_position(at, columns.len(), tree); let mut cells = Vec::new(); layout.cells(at, offset, &mut cells); for (_, cell) in &mut cells { @@ -579,6 +474,8 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { memory: &mut *cx.core.memory, }; icx.memory.claim(icx.id); + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_build(&ctx, item_id); let item = (self.item)(&key, &mut icx); let mut item = comp.dress(item, &state); let tip = icx.tip.take(); @@ -618,11 +515,29 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { }; // A row is a run or a member, so one of the two is there. if let Some((measure_ui, _)) = row_ui.as_ref().or(members_ui.as_ref()) { - if layout.is_auto(at) && !self.measured_for_reveal.contains(&at) { + // A row this pass measured is placed by that measure. A row it did not measure (one the reveal's + // scroll or a kept lead brings in) is measured here. A restated row is measured again with its new + // state; a size other than the one the pass placed by asks for the frame's discard pass, so the + // rerun places it from step 5. + let (measured_size, measured_widths) = fresh[place]; + if layout.auto_widths() && (measured_widths.is_none() || restated) { + let widths = Vec2::new(item.measure_in(measure_ui, Proposal::Ideal).x, item.measure_in(measure_ui, Proposal::Min).x); + rows::record_measure(&ctx, id, rows::measured_width_id(id, &key), widths); + if measured_widths.is_some_and(|before| (before - widths).abs().max_elem() > tolerance) { + layout_memory::ask_discard(&ctx); + } + Arc::make_mut(&mut layout).set_width(at, widths.x, widths.y); + row = self.screen(&layout, rect, at, offset, rtl); + } + let measured_size = measured_size.filter(|size| (size.x - row.width()).abs() <= tolerance); + if layout.is_auto(at) && (measured_size.is_none() || restated) { let measured = item.measure_in(measure_ui, Proposal::Width(row.width())).y; #[cfg(feature = "testing")] crate::runtime::measure::count_row_measure(&ctx, rows::measured_id(id, &key)); rows::record_measure(&ctx, id, rows::measured_id(id, &key), Vec2::new(row.width(), measured)); + if measured_size.is_some_and(|before| (before.y - measured).abs() > tolerance) { + layout_memory::ask_discard(&ctx); + } if measured != row.height() { Arc::make_mut(&mut layout).set_height(at, measured); row = self.screen(&layout, rect, at, offset, rtl); @@ -634,13 +549,6 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { fit_widest = fit_widest.max(*width); } } - if layout.auto_widths() { - let ideal = item.measure_in(measure_ui, Proposal::Ideal).x; - let min = item.measure_in(measure_ui, Proposal::Min).x; - rows::record_measure(&ctx, id, rows::measured_width_id(id, &key), Vec2::new(ideal, min)); - Arc::make_mut(&mut layout).set_width(at, ideal, min); - row = self.screen(&layout, rect, at, offset, rtl); - } } // A member has no node of its own: it reports as a sub-node of the collection's. let row_node = if C::MEMBERS { super::members::lead_node(id, &key) } else { item_id }; @@ -824,13 +732,13 @@ impl ItemsHooks<'_, '_, C> { } let offset = ScrollPos { x: self.offset_x, y: self.offset }; let named = self.anchor.map(|anchor| anchor.child); - let mut placed = lazy::Placed::default(); + let mut placed = lazy::Placed::named(named, None, (false, true)); // Frozen rows and section rows can stay put while the rows scroll: only a row that scrolls names the position. let first = layout.first_navigable(); for at in self.visible.clone().filter(|&at| at >= first && layout.shown(at) && !self.source.section_stop(at)) { let row = layout.rect(at, offset); let item = sub(id, ("key", key_hash(&self.source.key(at)))); - placed.note((named, (false, true)), item, Vec2::new(0.0, row.min.y), row.size()); + placed.note(item, Vec2::new(0.0, row.min.y), row.size()); } let moved = Vec2::new(0.0, (self.offset - self.offset_at_read) as f32); let room = (Vec2::new(0.0, self.offset as f32), Vec2::new(0.0, (self.max_offset(view.y) - self.offset) as f32)); @@ -971,10 +879,108 @@ fn rename_input( /// The height of the first `rows` rows of `layout` over `len` items: the rows it lays out, and the row height `row` for /// each one it does not have. -fn rows_height(layout: &impl ItemLayout, len: usize, rows: u16, row: f32) -> f32 { +pub(super) fn rows_height(layout: &impl ItemLayout, len: usize, rows: u16, row: f32) -> f32 { let rows = usize::from(rows); let laid = rows.min(len); let top = if len == 0 { 0.0 } else { layout.rect(0, ScrollPos::default()).min.y }; let built = if laid == 0 { 0.0 } else { layout.rect(laid - 1, ScrollPos::default()).max.y - top }; built + (rows - laid) as f32 * row } + +impl ItemsHooks<'_, '_, C> { + /// Step 5 in both runs: what the rows take in the room `measuring` gives. The auto rows in view are measured + /// first (`measure_ahead`), so the collection takes its size, and places its rows, by this pass's measure. + fn items_extent(&mut self, comp: &C, measuring: &Measuring<'_, '_>, id: Id) -> Vec2 { + let (ui, scx) = (measuring.ui, measuring.scx); + let room = match measuring.at { + ShowAt::Rect(rect) => rect.size(), + ShowAt::Flow => crate::layout::flow_room(ui), + }; + let env = Env::of(ui); + // The layout reads the component's own motion memory (`StyleCx::exiting`): an item leaving its source keeps + // its room until its exit ends. + let scx = &scx.measured_by(ui).owned_by(id, env.motion); + self.room = room; + self.indent_step = scx.control().icon; + let room = Self::inner_room(comp, scx.tokens, room); + // Where the enclosing body does not give the width, the collection takes its width from its content, whether + // it fills or fills the width, as a container does. Held in a content-sized column it measures so, and shows + // across the width the column settles on. + let held = env.content_column || crate::layout::in_grid_content_column(ui); + self.from_content = (!env.gives_width() && (crate::runtime::measure::active(ui.ctx()) || !held), env.content.1); + self.header.measure(scx); + self.header.read_content(ui.ctx(), id); + let bounded = room.x.is_finite(); + let item = comp.measures_items().then(|| layout_memory::measured(ui.ctx(), sub(id, "largest")).map(|measured| measured.took)).flatten(); + // Under a body that does not give the width, the measuring run lays the rows out at the width the collection + // asks for, so the height it reports is the one it has at that width (a grid's rows at its columns). + let from_content = self.from_content.0 && !self.content_sized(comp); + let asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, ui, id, room, item, scx)); + let width = match (bounded, self.content_sized(comp)) { + (true, false) => asked.unwrap_or(room.x), + // No rows: the empty state has no ideal width, so it takes the room, or none where the room is unbounded. + (_, _) if self.source.is_empty() => { + if bounded { + room.x + } else { + 0.0 + } + } + // An unbounded room (a horizontally scrolling body) takes the widest row, as a content-sized collection does. + (_, _) => { + let floor = env.get::().0; + let widest = layout_memory::measured(ui.ctx(), sub(id, "largest")).map_or(0.0, |measured| measured.took.x); + // Columns side by side at their own widths: a `Content` column takes its widest cell, not the share of + // the widest row it would get. + let columns = if self.header.has_columns() { self.header.content_width() } else { 0.0 }; + widest.max(columns).max(comp.ideal_width(item, self.source.len(), scx)).max(floor).min(room.x) + } + }; + let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone())); + let mut layout = comp.item_layout_from(previous, self.source, width, item, scx); + if self.header.has_columns() { + layout.set_columns(&self.header.columns(width)); + } + let ctx = ui.ctx(); + rows::measured_heights(ctx, id, |height| layout.measured(&|at| height(rows::measured_id(id, &self.source.key(at))))); + if layout.auto_widths() { + rows::measured_widths(ctx, id, |width| { + for at in 0..self.source.len() { + if let Some((ideal, min)) = width(rows::measured_width_id(id, &self.source.key(at))) { + layout.set_width(at, ideal, min); + } + } + }); + } + self.measure_ahead(comp, measuring, id, &mut layout, (width, room)); + let content = layout.content_size(); + self.content = Vec2::new(content.x as f32, content.y as f32); + let props = comp.items(); + let row = props.row_height.of(scx); + let floor = rows_height(&layout, self.source.len(), props.min_rows, row); + let cap = props.max_rows.map(|rows| rows_height(&layout, self.source.len(), rows, row).max(floor)); + self.columns = layout.column_count() as u32; + self.layout = Some(Arc::new(layout)); + let empty = if self.source.is_empty() { comp.empty_height(width, ui, scx) } else { 0.0 }; + let rows = self.content.y.max(empty).max(floor); + let height = cap.map_or(rows, |cap| rows.min(cap)) + self.header.height; + if !(self.scrolls && room.y.is_finite()) { + let wide = if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) } else { self.content.x }; + return Vec2::new(wide, height); + } + // A scrolling collection in a bounded room: `Content` takes its rows up to the room, `Fill` the room. + let wide = if self.content_sized(comp) { + self.content.x + } else if from_content { + asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) + } else { + 0.0 + }; + match comp.props(Internal::new()).sizing { + // Under a body sized from its content along the height, the rows take up to the room, as a content-sized + // collection's do: the body has no room of its own to hand it. + Sizing::Fill | Sizing::FillHeight => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }), + Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)), + } + } +} diff --git a/crates/ui-contract/src/contract/items/lead.rs b/crates/ui-contract/src/contract/items/lead.rs index d78d489ef..88e069872 100644 --- a/crates/ui-contract/src/contract/items/lead.rs +++ b/crates/ui-contract/src/contract/items/lead.rs @@ -115,7 +115,7 @@ impl ItemsHooks<'_, '_, C> { /// The pointer's position, in screen space, while it is over the collection. fn hovered_pos(cx: &Cx<'_, C>) -> Option { - crate::runtime::pointer::frame(&cx.core.ctx).pos.filter(|_| cx.core.response.hovered()) + crate::runtime::pointer::frame_raw(&cx.core.ctx).pos.filter(|_| cx.core.response.hovered()) } /// The row under `pos` (screen space) in the rows' placement `at`: the pointer-to-row mapping of `hover_lead`, @@ -139,9 +139,8 @@ impl ItemsHooks<'_, '_, C> { /// arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead /// with no movement to measure, and a modifier change under a resting pointer leaves the lead where the keys put it. pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { - let moved = crate::runtime::pointer::with_pass_pointer(&cx.core.ctx, |pass| { - pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. })) - }); + let moved = + crate::runtime::pointer::with_pass_raw(&cx.core.ctx, |pass| pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. }))); if !moved { return; } @@ -177,7 +176,7 @@ impl ItemsHooks<'_, '_, C> { { return; } - let Some(row) = crate::runtime::pointer::frame(ctx).pos.and_then(|pos| self.row_under(layout, at, pos)) else { return }; + let Some(row) = crate::runtime::pointer::frame_raw(ctx).pos.and_then(|pos| self.row_under(layout, at, pos)) else { return }; if self.holds(row) { return; } diff --git a/crates/ui-contract/src/contract/items/marquee.rs b/crates/ui-contract/src/contract/items/marquee.rs index ab7139dcb..02342ac3b 100644 --- a/crates/ui-contract/src/contract/items/marquee.rs +++ b/crates/ui-contract/src/contract/items/marquee.rs @@ -47,7 +47,7 @@ impl ItemsHooks<'_, '_, C> { let local = Self::logical(layout, rect, rtl, origin); if rect.contains(origin) && layout.hit(local, seen).is_none() { let selected: Vec = self.selected_keys(&self.selection_at_read); - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; let select = MarqueeSelect::begin(content_point(local, seen), mods, selected.clone()); self.drags.marquee = Some(MarqueeDrag { select, last: selected, live: false }); } diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index 3b85a4639..7934c7026 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -8,12 +8,14 @@ use crate::contract::collection::RowState; use crate::contract::run::{Measuring, ShowAt}; use crate::contract::{Collection, Internal, ItemCx, Props, Show as _}; use crate::runtime::access::SetPosition; +use crate::runtime::env::ArenaId; use crate::runtime::env::{Env, EnvView, ItemFacts}; use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; +use crate::style::{Flags, SurfaceKind}; use crate::style::{StyleCx, UiTokens}; -use craft_behavior::Proposal; use craft_behavior::layout_memory::measure_tolerance; +use craft_behavior::{ItemLayout as _, Proposal, ScrollPos, SelectionModel as _}; use egui::{Id, Pos2, Rect, Ui, Vec2}; impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { @@ -138,8 +140,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { if self.source.section_stop(at) { continue; } - let row = RowMeasure { at, rect: Rect::ZERO, cells: cells.clone(), proposal: Proposal::Ideal }; - let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row); + let row = RowMeasure::new(at, Rect::ZERO, cells.clone()); + let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row, |measure| measure(Proposal::Ideal)); largest = largest.max(size); for (column, width) in cells { match widest.iter_mut().find(|(held, _)| *held == column) { @@ -151,31 +153,32 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { (largest, widest) } - /// Builds the item of `row.at` as the collection `id` builds it, with the default row state, under `installed` - /// (`view` is what the item builder sees), and measures it at `row.proposal` without allocating: its size and the - /// widths its column cells reported. Item memory goes to `memory`. - pub(super) fn measure_row( + /// Builds the item of `row.at` as the collection `id` builds it, with the row state `row.state` and flags + /// `row.flags`, under `installed` (`view` is what the item builder sees), and hands `measure` a measure of it that + /// does not allocate: its size at a proposal and the widths its column cells reported. The item is built once + /// however many proposals `measure` asks. Item memory goes to `memory`. + pub(super) fn measure_row( &mut self, comp: &C, ui: &Ui, (id, view, installed): (Id, EnvView<'_>, &Env), memory: &mut MemoryStage, row: RowMeasure, - ) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) { + measure: impl FnOnce(&mut dyn FnMut(Proposal) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>)) -> R, + ) -> R { let ctx = ui.ctx().clone(); - let RowMeasure { at, rect, cells, proposal } = row; + let RowMeasure { at, rect, cells, state, flags, tree } = row; let len = self.source.len(); let key = self.source.key(at); let item_id = sub(id, ("key", key_hash(&key))); - let position = - SetPosition::new(at - self.source.section_stops_before(at)).of(len - self.source.section_stops_before(len)).columns(cells.len()); + let position = self.row_position(at, cells.len(), tree); let columns: Vec = cells.iter().map(|(key, _)| key.clone()).collect(); let column_count = cells.len(); let mut icx = ItemCx { key: &key, at, rect, - row: RowState::default(), + row: state.clone(), depth: self.source.depth(at), set: position, row_index: at, @@ -190,11 +193,13 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { item: item_id, memory, }; + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_build(&ctx, item_id); let item = (self.item)(&key, &mut icx); - let mut item = Props::id(comp.dress(item, &RowState::default()), item_id); + let mut item = Props::id(comp.dress(item, &state), item_id); let facts = ItemFacts { item: item_id, - flags: crate::style::Flags::empty(), + flags, position, columns, toggles: self.header.toggle_columns().map(|(key, _)| key).collect(), @@ -211,18 +216,202 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { scoped.item_facts = Some(std::sync::Arc::new(facts)); }), ); - let measured = crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal)); + let measured = measure(&mut |proposal| crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal))); Env::restore(&ctx, env); measured } + + /// Measures the auto rows in the view the collection takes that this pass has not measured, before step 5 sizes + /// the collection from its layout: their ideal and minimum widths in a layout of auto widths, then their heights at + /// their widths. Each measure is recorded (`rows::record_measure`) and set in `layout`, so this pass places every + /// row in view by its measure, and the other runs of the pass take it without measuring again. The view is the + /// one step 5 sizes: `width` wide, as high as the rows (capped by `max_rows`), and no higher than `room` less the + /// header when the rows scroll in a bounded room, at the offset step 4 read. It repeats while measured rows bring + /// other unmeasured rows into view; each row is measured at most once. + pub(super) fn measure_ahead(&mut self, comp: &C, measuring: &Measuring<'_, '_>, id: Id, layout: &mut C::ItemLayout, (width, room): (f32, Vec2)) { + if self.source.is_empty() { + return; + } + let ctx = measuring.ui.ctx().clone(); + let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); + let props = comp.items(); + let (row, max_rows, striped) = (props.row_height.of(measuring.scx), props.max_rows, props.striped); + let tree = matches!(layout.nav(), craft_behavior::NavShape::Tree); + let known = self.known(comp, true); + let env = Self::rows_env(comp, measuring.env, id, measuring.resolved.size, comp.props(Internal::new()).surface); + let widths = layout.auto_widths(); + let mut memory = None; + // How many times each row was measured here: its widths once, its height again only at a width the later rows' + // widths moved it to. + let mut done: Vec<(usize, u8)> = Vec::new(); + loop { + let content = layout.content_size().y as f32; + let mut high = max_rows.map_or(content, |rows| content.min(super::hooks::rows_height(&*layout, self.source.len(), rows, row))); + if self.scrolls && room.y.is_finite() { + high = high.min((room.y - self.header.height).max(0.0)); + } + let mut in_view = Vec::new(); + layout.visible(ScrollPos { x: self.offset_x, y: self.offset.max(0.0) }, Vec2::new(width, high), &mut in_view); + in_view.sort_unstable(); + let source = self.source; + // The rows of the view this pass has not measured: (row, its widths, its height). + let todo: Vec<(usize, bool, bool)> = rows::measured_this_pass(&ctx, id, |fresh| { + in_view + .into_iter() + .filter(|&at| layout.is_auto(at) && !source.section_stop(at) && done.iter().all(|&(held, times)| held != at || times < 2)) + .filter_map(|at| { + let key = source.key(at); + let wide = widths && fresh(rows::measured_width_id(id, &key)).is_none(); + let row_width = layout.rect(at, ScrollPos::default()).width(); + let high = fresh(rows::measured_id(id, &key)).is_none_or(|size| (size.x - row_width).abs() > tolerance); + (wide || high).then_some((at, wide, high)) + }) + .collect() + }); + if todo.is_empty() { + return; + } + let memory = memory.get_or_insert_with(|| MemoryStage::open_peek(&ctx, id)); + let mut stripe: Option<(usize, usize)> = None; + for (at, wide, high) in todo { + match done.iter_mut().find(|(held, _)| *held == at) { + Some((_, times)) => *times += 1, + None => done.push((at, 1)), + } + let odd = striped && { + let run = self.stripe_run(stripe, at); + stripe = Some((at, run)); + run.is_multiple_of(2) && !self.source.is_section(at) + }; + let (state, flags) = self.known_row(at, &known, odd); + let mut cells = Vec::new(); + layout.cells(at, ScrollPos::default(), &mut cells); + let row_measure = RowMeasure { at, rect: layout.rect(at, ScrollPos::default()), cells, state, flags, tree }; + let key = self.source.key(at); + let (width_id, height_id) = (rows::measured_width_id(id, &key), rows::measured_id(id, &key)); + let installed = (id, env.view(), &env); + // The rows' measure is the collection's own, as its largest-row probe is: no transcript around takes it. + // It runs as a measure; the layout takes its results in the run that called it, so the run's own + // placement (a strip's report of its tabs) follows them. + let row_width = layout.rect(at, ScrollPos::default()).width(); + let (widths, height) = layout_memory::boundary(&ctx, true, || { + crate::contract::steps::measuring(&ctx, || { + self.measure_row(comp, measuring.ui, installed, memory, row_measure, |measure| { + // A row of auto widths takes its ideal width unless the fit over every row's widths shrinks it: + // its height is measured there, and again only where the fit settles on another width. + let widths = wide.then(|| Vec2::new(measure(Proposal::Ideal).0.x, measure(Proposal::Min).0.x)); + let row_width = widths.map_or(row_width, |widths| widths.x); + let height = (high || wide).then(|| Vec2::new(row_width, measure(Proposal::Width(row_width)).0.y)); + (widths, height) + }) + }) + }); + if let Some(widths) = widths { + rows::record_measure(&ctx, id, width_id, widths); + layout.set_width(at, widths.x, widths.y); + } + if let Some(height) = height { + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_measure(&ctx, height_id); + rows::record_measure(&ctx, id, height_id, height); + layout.set_height(at, height.y); + } + } + } + } + + /// The place of the row `at` in the collection's set, among `columns` columns, with its level in a tree. + pub(super) fn row_position(&self, at: usize, columns: usize, tree: bool) -> SetPosition { + let len = self.source.len(); + let position = SetPosition::new(at - self.source.section_stops_before(at)).of(len - self.source.section_stops_before(len)).columns(columns); + if tree { position.level(self.source.depth(at) + 1) } else { position } + } + + /// The env the rows lay out under, from the collection's env `env`: the collection's arena, the child size (else + /// the collection's `size`), the child glyph role, and the surface the rows sit on (`own`, else the one the + /// collection sits on). The rows lay out their own content: no line or first line of the body around reaches them. + /// The content step adds the app values its body gives (the row-hook contract on `ItemCx`). + pub(super) fn rows_env(comp: &C, env: &Env, id: Id, size: craft_theme::ControlSize, own: Option) -> Env { + let (child_size, child_glyphs) = (comp.props(Internal::new()).child_size, comp.props(Internal::new()).child_glyphs); + env.derive(|scoped| { + scoped.arena = Some(ArenaId::new(id)); + scoped.size = child_size.unwrap_or(size); + if let Some(role) = child_glyphs { + scoped.glyphs = role; + } + scoped.surface = SurfaceKind::under(own, scoped.surface); + scoped.row_line = None; + scoped.first_line = None; + }) + } + + /// The state of the row `at` its measure reads, from `known` (the row-hook contract on `ItemCx`): selected, lead, + /// renaming, current, open, striped (`striped`, which the caller runs along the rows), and its place among + /// sub-rows and the last row; with the `SELECTED`, `EXPANDED` and `CURRENT` flags. The content step adds the + /// pointer, gesture and focus state. + pub(super) fn known_row(&self, at: usize, known: &Known, striped: bool) -> (RowState, Flags) { + let key = self.source.key(at); + let len = self.source.len(); + let state = RowState { + selected: known.placed.holds_row(at), + lead: known.lead.as_ref() == Some(&key), + renaming: known.renaming.as_ref() == Some(&key), + striped, + current: known.current.as_ref() == Some(&key), + open: self.source.has_children(at) && self.source.open(at), + sub_row: self.source.sub_row(at), + continued: at + 1 < len && self.source.sub_row(at + 1).is_some(), + last: at + 1 == len, + ..RowState::default() + }; + let mut flags = Flags::empty(); + flags.set(Flags::SELECTED, state.selected); + flags.set(Flags::EXPANDED, state.open); + flags.set(Flags::CURRENT, state.current); + (state, flags) + } + + /// The facts `known_row` reads: the selection, lead and renaming row as step 4 read them (`at_read`), or as the + /// pass leaves them. + pub(super) fn known(&self, comp: &C, at_read: bool) -> Known { + let current = comp.items().current.as_deref().and_then(|key| key.downcast_ref::()).cloned(); + if at_read { + Known { + placed: self.selection_at_read.placed(self.source), + lead: self.lead_at_read.clone(), + renaming: self.renaming_at_read.clone(), + current, + } + } else { + Known { placed: self.selection.placed(self.source), lead: self.lead.key.clone(), renaming: self.renaming.key.clone(), current } + } + } } -/// A row to build and measure (`measure_row`): its position, rect and column cells, and the proposal it is measured at. +/// What the state of a row known before the pass senses input comes from (`ItemsHooks::known_row`). +pub(super) struct Known { + pub(super) placed: craft_behavior::PlacedSelection, + pub(super) lead: Option, + pub(super) renaming: Option, + pub(super) current: Option, +} + +/// A row to build and measure (`measure_row`): its position, rect and column cells, its state and flags, and whether +/// the collection is a tree. pub(super) struct RowMeasure { pub(super) at: usize, pub(super) rect: Rect, pub(super) cells: Vec<(craft_behavior::ColumnKey, Rect)>, - pub(super) proposal: Proposal, + pub(super) state: RowState, + pub(super) flags: Flags, + pub(super) tree: bool, +} + +impl RowMeasure { + /// The row `at` at `rect` with `cells`, in the default state. + pub(super) fn new(at: usize, rect: Rect, cells: Vec<(craft_behavior::ColumnKey, Rect)>) -> Self { + RowMeasure { at, rect, cells, state: RowState::default(), flags: Flags::empty(), tree: false } + } } /// The inputs a kept measure of the items serves under. diff --git a/crates/ui-contract/src/contract/items/press.rs b/crates/ui-contract/src/contract/items/press.rs index d2ed33973..362340ecb 100644 --- a/crates/ui-contract/src/contract/items/press.rs +++ b/crates/ui-contract/src/contract/items/press.rs @@ -56,11 +56,11 @@ impl ItemsHooks<'_, '_, C> { let at = xf.map_or(at, |map| map.to_layer(at)) - rect.min.to_vec2(); if layout.mirrors() && rtl { flow.to_physical(Rect::from_min_size(at, Vec2::ZERO)).min } else { at } }; - let mods_now = crate::runtime::pointer::frame(&ctx).mods; + let mods_now = crate::runtime::pointer::frame_raw(&ctx).mods; // A click on a row the collection does not take (a caption, a disabled row) is no pick: the layers around the // collection (a dropdown's list) stay open. if cx.core.activation.as_ref().is_some_and(|activation| !activation.by_key) - && let Some(pos) = crate::runtime::pointer::frame(&ctx).pos + && let Some(pos) = crate::runtime::pointer::frame_raw(&ctx).pos && local(pos).y >= 0.0 && layout .hit(local(pos), offset) @@ -100,7 +100,7 @@ impl ItemsHooks<'_, '_, C> { self.drags.command = Some(self.source.key(at)); self.move_lead(at, LeadSource::Pointer); } else if !secondary_on_toggle { - let mods = crate::runtime::pointer::frame(&ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&ctx).mods; let key = self.source.key(at); let column = if Self::selects_cells(comp) { layout.column_at(local(start.origin), offset) } else { None }; // A plain press on a selected row of a multiple selection leaves the selection whole, so a drag @@ -206,7 +206,7 @@ impl ItemsHooks<'_, '_, C> { && let Some(at) = layout.hit(local(start.origin), offset).filter(|&at| self.source.enabled(at) && layout.shown(at)) { // A modified click is a command on the thumbnail (load as selection, and so on), not a pick. - let mods = crate::runtime::pointer::frame(&ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&ctx).mods; if !(mods.shift || mods.cmd || mods.alt) { if !self.keeps_pick(at, start.clicks) { self.pick(comp, at, false, false); @@ -277,7 +277,7 @@ impl ItemsHooks<'_, '_, C> { // Something over the collection, or a part of a row or of the collection that takes presses and is under the // pointer, keeps the request away; a part that picks its item (a thumbnail) is the row's, and the request names // it. - let released = crate::runtime::pointer::frame(&ctx); + let released = crate::runtime::pointer::frame_raw(&ctx); let hover = crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)).hover; let menu_at = if released.release == Some(craft_behavior::PointerButton::Secondary) && cx.core.response.hovered() diff --git a/crates/ui-contract/src/contract/items/reveal.rs b/crates/ui-contract/src/contract/items/reveal.rs index 94be7096e..27059aa53 100644 --- a/crates/ui-contract/src/contract/items/reveal.rs +++ b/crates/ui-contract/src/contract/items/reveal.rs @@ -1,6 +1,6 @@ //! Bringing a row into view: a requested reveal and the scroll that does it. -use super::measure::RowMeasure; +use super::measure::{Known, RowMeasure}; use super::{ItemsHooks, rows}; use crate::contract::Collection; use crate::contract::collection::LeadSource; @@ -37,17 +37,20 @@ impl ItemsHooks<'_, '_, C> { /// for the first time takes its measured height when built and moves the rows after it, so the auto rows that /// share the view with the revealed row, up to it, and have no kept height are built and measured first, under the /// rows' env `installed`, until the scroll that shows the row places it by measured heights only. The build takes - /// those heights (`measured_for_reveal`) and does not measure the rows again. + /// those heights (they are this pass's measure) and does not measure the rows again. The rows are measured with + /// the state `known` the pass leaves them in; returns them. pub(super) fn place_reveal( &mut self, comp: &C, ui: &Ui, (id, view_env, installed): (Id, EnvView<'_>, &Env), - layout: &mut Arc, + (layout, known): (&mut Arc, &Known), view: Rect, - ) { - let Some(at) = self.revealing.take().filter(|&at| layout.shown(at)) else { return }; + ) -> Vec { + let mut measured = Vec::new(); + let Some(at) = self.revealing.take().filter(|&at| layout.shown(at)) else { return measured }; let ctx = ui.ctx().clone(); + let (striped, tree) = (comp.items().striped, matches!(layout.nav(), craft_behavior::NavShape::Tree)); loop { self.aim_reveal(layout, at, view.height()); let mut in_view = Vec::new(); @@ -58,29 +61,32 @@ impl ItemsHooks<'_, '_, C> { .into_iter() .chain([at]) .filter(|&row| row <= at && layout.is_auto(row) && !source.section_stop(row)) - .filter(|row| !self.measured_for_reveal.contains(row) && height(rows::measured_id(id, &source.key(*row))).is_none()) + .filter(|row| !measured.contains(row) && height(rows::measured_id(id, &source.key(*row))).is_none()) .collect() }); if unmeasured.is_empty() { - return; + return measured; } let mut memory = MemoryStage::open_peek(&ctx, id); for row in unmeasured { - if self.measured_for_reveal.contains(&row) { + if measured.contains(&row) { continue; } let rect = layout.rect(row, ScrollPos::default()); let mut cells = Vec::new(); layout.cells(row, ScrollPos::default(), &mut cells); - let measure = RowMeasure { at: row, rect, cells, proposal: Proposal::Width(rect.width()) }; - let (size, _) = - crate::contract::steps::measuring(&ctx, || self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure)); - let measured = rows::measured_id(id, &self.source.key(row)); + let odd = striped && self.stripe_run(None, row).is_multiple_of(2) && !self.source.is_section(row); + let (state, flags) = self.known_row(row, known, odd); + let measure = RowMeasure { at: row, rect, cells, state, flags, tree }; + let (size, _) = crate::contract::steps::measuring(&ctx, || { + self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure, |measure| measure(Proposal::Width(rect.width()))) + }); + let height_id = rows::measured_id(id, &self.source.key(row)); #[cfg(feature = "testing")] - crate::runtime::measure::count_row_measure(&ctx, measured); - rows::record_measure(&ctx, id, measured, Vec2::new(rect.width(), size.y)); + crate::runtime::measure::count_row_measure(&ctx, height_id); + rows::record_measure(&ctx, id, height_id, Vec2::new(rect.width(), size.y)); Arc::make_mut(layout).set_height(row, size.y); - self.measured_for_reveal.push(row); + measured.push(row); } let content = layout.content_size(); self.content = Vec2::new(content.x as f32, content.y as f32); diff --git a/crates/ui-contract/src/contract/items/rows.rs b/crates/ui-contract/src/contract/items/rows.rs index b8cc620d7..bcde9f9a2 100644 --- a/crates/ui-contract/src/contract/items/rows.rs +++ b/crates/ui-contract/src/contract/items/rows.rs @@ -46,7 +46,14 @@ pub(super) fn measured_id(collection: Id, key: &K) -> Id { /// Runs `f` with a reader of the heights the auto rows of the collection `collection` had in the last pass that built /// them: the rows the pass does not build, out of view, are placed by them (`runtime::lazy`). pub(super) fn measured_heights(ctx: &Context, collection: Id, f: impl FnOnce(&dyn Fn(Id) -> Option) -> R) -> R { - lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|size| size.y))) + lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|(size, _)| size.y))) +} + +/// Runs `f` with a reader of what this pass measured of the rows of the collection `collection`, by the ids +/// `measured_id` and `measured_width_id` give: the row's width and height, or its ideal and minimum widths; `None` for +/// a row this pass has not measured. A row measured this pass is not measured again in it. +pub(super) fn measured_this_pass(ctx: &Context, collection: Id, f: impl FnOnce(&dyn Fn(Id) -> Option) -> R) -> R { + lazy::reading(ctx, collection, |read| f(&|id| read(id).and_then(|(size, now)| now.then_some(size)))) } /// The id an auto-width item's measured widths (ideal, then minimum) are kept under. @@ -57,11 +64,11 @@ pub(super) fn measured_width_id(collection: Id, key: &K) -> /// Runs `f` with a reader of the `(ideal, min)` widths the auto-width items of the collection `collection` had in the /// last pass that built them. pub(super) fn measured_widths(ctx: &Context, collection: Id, f: impl FnOnce(&dyn Fn(Id) -> Option<(f32, f32)>) -> R) -> R { - lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|size| (size.x, size.y)))) + lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|(size, _)| (size.x, size.y)))) } -/// Records the size an auto row of the collection `collection` measured this pass; the row is placed by it in the same -/// pass. +/// Records the size an auto row of the collection `collection` measured this pass (its width and height, or its ideal +/// and minimum widths); the row is placed by it in the same pass. pub(super) fn record_measure(ctx: &Context, collection: Id, id: Id, size: Vec2) { lazy::remember(ctx, collection, id, size); } diff --git a/crates/ui-contract/src/contract/label/props.rs b/crates/ui-contract/src/contract/label/props.rs index 5f80ba2a3..e1b357c84 100644 --- a/crates/ui-contract/src/contract/label/props.rs +++ b/crates/ui-contract/src/contract/label/props.rs @@ -72,7 +72,7 @@ impl GlyphLabel { /// How the labelled rows under a container show their labels: set once on the container (`ContainerProps::labels`), /// read by every label step under it until another container sets its own. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub enum LabelScheme { /// A dialog or a form: a beside label sits against its control and ends with a colon; the control keeps its own diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 4f2d00f8e..d0db84761 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -1,13 +1,14 @@ -//! `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_in_flow}; +use crate::layout::{flow_region, take_cell, take_in_flow}; use crate::runtime::egui::alloc; -use crate::runtime::egui::areas::Layer; use crate::runtime::env::Env; use crate::runtime::focus; use crate::runtime::layout_memory; -use crate::runtime::lazy::{self, Decision, Place}; +use crate::runtime::lazy::{self, Decision, Key, Place}; +#[cfg(feature = "testing")] +use crate::runtime::measure::{MemoRun, count_memo_run}; use crate::runtime::memory::sub; use crate::runtime::replay; use egui::{Pos2, Rect, Ui, UiBuilder, Vec2}; @@ -29,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, - settles: bool, - content: Option, } impl Lazy { @@ -47,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 @@ -58,71 +58,18 @@ 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`): 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 or an edit - /// of a given value, either of 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 or for an edit of a given value elsewhere: what - /// either changes in the data it shows moves the version, or reaches it as a command or app repaint request. - pub fn content(mut self, version: u64) -> Lazy { - self.content = Some(version); - self - } - /// Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not /// run. pub fn show(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option { - self.run(ui, |ui, _| add(ui)) + match self.run_keyed(ui, "Lazy", Key::None, |ui, _| add(ui)) { + Shown::Ran(out) => Some(out), + Shown::Replayed(..) | Shown::OutOfView => None, + } } - /// [`show`](Self::show) for a child that may leave its room to other content: `add` runs first and settles; when - /// it returns `None`, `otherwise` runs in the same child `Ui` and the run is not kept, so a settling child runs - /// again in the next pass rather than replay it. A dock group's host view is one: where the host leaves the group - /// to the dock, the dock's group shows in its place and settles by its own rules. `None` when the child did not - /// run: it replayed a run of `add`, or was out of view. - /// - /// `add` runs in a `Ui` that takes room in the child only when it returns `Some`: an `add` that leaves its room - /// leaves the child as it found it, so `otherwise` takes the same place whether it runs or replays, and the child's - /// extent does not change between them (a change would cost the frame a discard pass). - pub fn show_or(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> Option, otherwise: impl FnOnce(&mut Ui) -> U) -> Option> { - self.run(ui, |ui, run| { - let mut first = alloc::child(ui, UiBuilder::new().max_rect(flow_region(ui)).layout(*ui.layout())); - match add(&mut first) { - Some(shown) => { - alloc::advance_past(ui, first.min_rect()); - Ok(shown) - } - None => { - drop(first); - run.unkept(ui.ctx()); - Err(otherwise(ui)) - } - } - }) - } - - fn run(self, ui: &mut Ui, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Option { + /// 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 memoized view keyed `key`, or takes the extent of a child out of view. + pub(super) fn run_keyed(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { let ctx = ui.ctx().clone(); let view = Env::of(ui).view().lazy_view(); let id = match view { @@ -139,10 +86,9 @@ impl Lazy { // A run around this one that is replayed later keeps the child's entry. replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); if let Some(view) = view { - let at = |size: Vec2| { - let x = if rtl { available.max.x - size.x } else { available.min.x }; - Rect::from_min_size(Pos2::new(x, available.min.y), size) - }; + // A run around this child decides it by the scroll view: it replays only while the view is the same. + replay::note_input(&ctx, crate::runtime::inputs::Input::Scroll); + let at = |size: Vec2| Rect::from_min_size(at_start(available, rtl, size), size); let estimate = view.estimate(self.estimate); if self.reveal { crate::contract::queue_child_reveal(&ctx, view.owner, id); @@ -154,7 +100,9 @@ impl Lazy { lazy::replay(&ctx, id); lazy::place(&ctx, &view, id, took); } - return None; + #[cfg(feature = "testing")] + count_memo_run(&ctx, name, id, MemoRun::OutOfView, real); + return Shown::OutOfView; } } let layout = *ui.layout(); @@ -164,25 +112,47 @@ impl Lazy { layer: ui.layer_id(), layout, pixels_per_point: ctx.pixels_per_point(), + atlas: ctx.fonts(|fonts| fonts.atlas_generation()), env: Env::of(ui).key, }; - if self.settles - && let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place), self.content) + let memo = matches!(key, Key::Memo(_)); + if real && memo { + crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); + } + let settled = if memo { lazy::settled(&ctx, owner, id, sizing.then_some(available), real.then_some(place), view, key) } else { None }; + // The replay audit runs a view that would replay for real in place of the replay, and compares the two. + let audited = settled.as_ref().filter(|_| audits(&ctx, real)).map(|(_, _, shift)| *shift); + if let Some((size, ran_at, shift)) = settled + && audited.is_none() { - let (took, _) = take_in_flow(ui, size); - if real { + // 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); - lazy::replay_settled(&ctx, id); + let kept = lazy::replay_settled(&ctx, id, &shift); if let Some(view) = view { lazy::place(&ctx, &view, id, took); } - } - return None; + 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, kept: true, layer: place.layer }; + let mut run = Run { + recording: memo && real, + output: None, + #[cfg(feature = "testing")] + same_output: None, + }; + let edits = if run.recording { lazy::edits(&ctx) } else { 0 }; + let seen = if run.recording { crate::runtime::inputs::seen(&ctx) } else { Default::default() }; if run.recording { - replay::open(&ctx); + open_record(&ctx, audited.is_some()); } let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id)); // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. @@ -191,16 +161,26 @@ impl Lazy { // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); let record = run.recording.then(|| replay::close(&ctx, place.layer)); - if !run.kept { - lazy::forget(&ctx, id); + if let Some(shift) = audited { + return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); + } + #[cfg(feature = "testing")] + if let Some(record) = &record + && crate::runtime::audit::on(&ctx) + { + crate::runtime::audit::name_callback(&ctx, name, record); } if real { layout_memory::backstop(&ctx, id, rect.size()); } - alloc::advance_past(ui, rect); - if view.is_some() || self.settles { + if memo { + place_view(ui, rect); + } else { + alloc::advance_past(ui, rect); + } + 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, rect.size(), sizing, registered); + lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available }, registered); } if let Some(view) = view && real @@ -208,27 +188,108 @@ impl Lazy { lazy::place(&ctx, &view, id, rect); } if let Some(record) = record { - lazy::ran(&ctx, id, record, place, rect, self.content); + // The key from before the run: a run that wrote through its props moved the key, so the view runs once more, + // from the written value, before it replays. + lazy::ran(&ctx, id, record, place, rect, lazy::Ran { key, edits, seen, view, output: run.output.take() }); } - Some(out) + #[cfg(feature = "testing")] + if memo { + count_memo_run(&ctx, name, id, MemoRun::Ran, real); + } + // The name is read by the count trials only. + let _ = name; + Shown::Ran(out) } } -/// The run of a child: whether it records what it adds for a replay, and whether it is kept. -struct Run { +/// Places the audit run of a view that would have replayed, as a replay places it, and compares the run with the kept +/// run replayed at the place `shift` names (`runtime::audit`). It keeps the kept run: every later pass compares with +/// what a replay adds. +fn place_audit_run(ui: &mut Ui, audited: Audited<'_>, out: R, run: &Run) -> Shown { + let Audited { name, id, view, rect, record, shift } = audited; + let ctx = ui.ctx().clone(); + layout_memory::backstop(&ctx, id, rect.size()); + place_view(ui, rect); + if let Some(view) = view { + lazy::place(&ctx, &view, id, rect); + } + #[cfg(feature = "testing")] + { + if let Some(record) = record { + lazy::audit(&ctx, name, id, crate::runtime::audit::Shown { record, rect, output: run.output.as_ref() }, run.same_output, &shift); + } + count_memo_run(&ctx, name, id, MemoRun::Replayed, true); + } + let _ = (name, record, run, shift); + Shown::Ran(out) +} + +/// What the runner hands its audit step. +struct Audited<'a> { + name: &'static str, + id: egui::Id, + view: Option, + rect: Rect, + record: Option<&'a replay::Record>, + /// Where the replay would have added the kept run. + shift: egui::RecordShift, +} + +/// Whether the replay audit runs a child that would replay in a pass whose runs are `real` (test builds only). A pass +/// egui will discard paints nothing, so a run there is no shown run to compare with: the child replays. +fn audits(ctx: &egui::Context, real: bool) -> bool { + #[cfg(feature = "testing")] + return real && !ctx.will_discard() && crate::runtime::audit::runs(ctx); + #[cfg(not(feature = "testing"))] + { + let _ = (ctx, real); + false + } +} + +/// Opens the record around a recording run, an audit run's when `audited`. +fn open_record(ctx: &egui::Context, audited: bool) { + #[cfg(feature = "testing")] + if audited { + replay::open_audit(ctx); + return; + } + let _ = audited; + replay::open(ctx); +} + +/// Where content of `size` starts in `region`: at its start edge, the right one in a right-to-left layout. +fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 { + Pos2::new(if rtl { region.max.x - size.x } else { region.min.x }, region.min.y) +} + +/// Places a memoized view's extent `rect` in flow in `ui`, as its run and its replay both do, and returns `rect`: in the +/// `Grid` or spread `Row` body that encloses `ui` directly the view takes the next cell at its extent, as its content +/// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`. +fn place_view(ui: &mut Ui, rect: Rect) -> Rect { + if take_cell(ui, rect.size()).is_none() { + alloc::advance_past(ui, rect); + } + rect +} + +/// What a child came to in a pass. +pub(super) enum Shown { + /// It ran and returned this. + Ran(R), + /// It took the extent of its kept run, and added that run again in a real run; with what a memoized view's run + /// returned, as the run left it, and the shift the replay moved the run by (none in a measuring run). + Replayed(Option, egui::RecordShift), + /// It is out of view in its scroll area. + OutOfView, +} + +/// The run of a child: whether it records what it adds for a replay. +pub(super) struct Run { recording: bool, - kept: bool, - layer: Layer, -} - -impl Run { - /// Ends the run's record here and keeps it from settling: what the child adds from here on is not what it settles - /// on. - fn unkept(&mut self, ctx: &egui::Context) { - if self.recording { - replay::close(ctx, self.layer); - self.recording = false; - } - self.kept = false; - } + /// What a memoized view's run returned, which its replays return. + pub(super) output: Option, + /// Whether two outputs of a memoized view are equal, for the replay audit. + #[cfg(feature = "testing")] + pub(super) same_output: Option, } diff --git a/crates/ui-contract/src/contract/level.rs b/crates/ui-contract/src/contract/level.rs index f084f4e92..fa45435a6 100644 --- a/crates/ui-contract/src/contract/level.rs +++ b/crates/ui-contract/src/contract/level.rs @@ -17,7 +17,7 @@ use super::{Probe, ShapeKind}; use std::collections::BTreeMap; /// Where a type sits in the design system, in the order a viewer lists them. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, craft_ui_macros::PlainData)] #[non_exhaustive] pub enum Level { /// Colours, the edit lifecycle, stock egui. @@ -56,7 +56,7 @@ impl Level { } /// The surface a type's stories sit on in an app; a viewer draws a story on it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub enum Surface { /// A dock panel (`surface.panel`): most types. @@ -71,7 +71,7 @@ pub enum Surface { } /// How a viewer lays out the stories of one type together, as the old gallery's story of the type laid out its cases. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub enum StoryLayout { /// One under the other, each under its caption. diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 3fe67ad42..9b9bacdda 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -204,6 +204,102 @@ //! } //! ``` //! +//! A field another field stands for feeds nothing: `#[memo_props(covered_by = "", reason = "why")]`. The named +//! field must be one of the same struct or variant that feeds the key itself, and the reason is required. A closure the +//! caller's revision covers: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps}; +//! use std::sync::Arc; +//! #[derive(MemoProps)] +//! struct Rules { +//! #[memo_props(covered_by = "revision", reason = "the caller moves the revision with every rule change")] +//! allows: Arc bool + Send + Sync>, +//! revision: u64, +//! } +//! let rules = |revision, allows: fn(&str) -> bool| Rules { allows: Arc::new(allows), revision }; +//! assert_eq!(MemoKey::of(&rules(1, |_| true)), MemoKey::of(&rules(1, |_| false))); +//! assert_ne!(MemoKey::of(&rules(1, |_| true)), MemoKey::of(&rules(2, |_| true))); +//! ``` +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Rules { +//! #[memo_props(covered_by = "generation", reason = "no such field")] +//! allows: std::sync::Arc bool + Send + Sync>, +//! revision: u64, +//! } +//! ``` +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Rules { +//! #[memo_props(covered_by = "revision")] +//! allows: std::sync::Arc bool + Send + Sync>, +//! revision: u64, +//! } +//! ``` +//! +//! A `&'static` reference to a static item feeds where it points: `#[memo_props(address = "why")]`. Any other field +//! type is an error: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps}; +//! struct Registration(&'static str); +//! // Equal registrations at two places: two items. +//! static FIRST: Registration = Registration("Button"); +//! static SECOND: Registration = Registration("Button"); +//! #[derive(MemoProps)] +//! struct Card { +//! #[memo_props(address = "registrations are static items")] +//! story: &'static Registration, +//! } +//! assert_eq!(MemoKey::of(&Card { story: &FIRST }), MemoKey::of(&Card { story: &FIRST })); +//! assert_ne!(MemoKey::of(&Card { story: &FIRST }), MemoKey::of(&Card { story: &SECOND })); +//! ``` +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! struct Card<'a> { +//! #[memo_props(address = "a borrowed value")] +//! story: &'a u32, +//! } +//! ``` +//! +//! A handle to state written during the pass, or a context rebuilt each pass, is keyed in every pass: +//! `#[memo_props(every_pass = "why")]` on the type. It feeds no field (a field attribute there is an error), and a view +//! whose key holds it runs in every pass; outside a view's key it feeds nothing: +//! +//! ``` +//! # extern crate craft_ui_contract as craft_ui; +//! use craft_ui::contract::{MemoKey, MemoProps}; +//! use std::sync::{Arc, Mutex}; +//! #[derive(MemoProps)] +//! #[memo_props(every_pass = "its members write the shared state during the pass")] +//! struct Handle(Arc>>); +//! let handle = Handle(Arc::default()); +//! assert_eq!(MemoKey::of(&handle), MemoKey::of(&handle)); +//! ``` +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! #[memo_props(every_pass = "")] +//! struct Handle(std::sync::Arc>>); +//! ``` +//! +//! ```compile_fail +//! # extern crate craft_ui_contract as craft_ui; +//! #[derive(craft_ui::contract::MemoProps)] +//! #[memo_props(every_pass = "rebuilt each pass")] +//! struct Handle(#[memo_props(hash = "a number")] u32); +//! ``` +//! //! Plain props derive, recursive types included: //! //! ``` @@ -259,15 +355,33 @@ pub use craft_ui_macros::MemoProps; pub trait MemoProps { /// Feeds every input the view reads into `key`. fn key(&self, key: &mut MemoKey); + + /// The props type with its lifetimes erased (`Props<'a>` and `Props<'b>` are one type): a memoized view seeds its + /// key with it, so two views at one id whose props feed the same bytes, such as two empty props types, key apart. + fn identity() -> TypeId + where + Self: Sized, + { + typeid::of::() + } } /// A 128-bit hash of a memoized view's props (SipHash-1-3 with a 128-bit output, a fixed key). A collision has a chance /// of about 2⁻¹²⁸ per compare. A [`Stateless`] callback feeds the 64 bits its `TypeId` hashes, so two callbacks key /// apart unless those collide. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Default)] pub struct MemoKey { hasher: SipHasher13, bytes: usize, + /// The context of the view that takes the key: framework values whose writes the context counts (kept and saved + /// bindings) feed that count. + context: Option, +} + +impl std::fmt::Debug for MemoKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MemoKey").field("bytes", &self.bytes).finish_non_exhaustive() + } } impl MemoKey { @@ -276,6 +390,21 @@ impl MemoKey { MemoKey::default() } + /// An empty key of a view shown in `ctx`. + pub(crate) fn of_view(ctx: &egui::Context) -> MemoKey { + MemoKey { context: Some(ctx.clone()), ..MemoKey::default() } + } + + /// An empty key of the same view as this one. + pub(crate) fn child(&self) -> MemoKey { + MemoKey { context: self.context.clone(), ..MemoKey::default() } + } + + /// The context of the view that takes the key; `None` for a key taken outside a view (`MemoKey::of`). + pub(crate) fn context(&self) -> Option<&egui::Context> { + self.context.as_ref() + } + /// The key of `props`. pub fn of(props: &P) -> u128 { let mut key = MemoKey::new(); @@ -283,6 +412,16 @@ impl MemoKey { key.finish() } + /// Feeds an input whose value a key cannot follow (a handle to state shared and written elsewhere, a context a + /// container rebuilds each pass): a view whose key holds it runs in every pass. Outside a view's key it feeds + /// nothing. + pub fn changes_every_pass(&mut self) { + if let Some(ctx) = &self.context { + let pass = ctx.cumulative_pass_nr(); + self.write(&pass.to_le_bytes()); + } + } + /// Feeds `bytes`. pub fn write(&mut self, bytes: &[u8]) { self.hasher.write(bytes); @@ -604,6 +743,15 @@ impl MemoProps for Tracked { } } +/// A view's write access to a model: by revision, as `Tracked`. A write the view makes moves the key, so the view +/// runs once more, from the written value, and replays from then on. `&mut` of any other type is not props: a write to +/// it would not move a key. +impl MemoProps for &mut Tracked { + fn key(&self, key: &mut MemoKey) { + self.revision().key(key); + } +} + /// A callback in props: a fn item or a capture-free closure, which is zero-sized, so its type alone says what it /// does, and its `TypeId` keys it. A capturing closure is not zero-sized and fails to build where `Stateless::new` is /// called (not at `cargo check`: the assertion is evaluated when the call is compiled): @@ -682,6 +830,46 @@ impl MemoProps for craft_i18n::Word { } } +impl MemoProps for craft_behavior::Mixed { + fn key(&self, key: &mut MemoKey) { + match self { + craft_behavior::Mixed::Same(value) => { + key.write_u32(0); + value.key(key); + } + craft_behavior::Mixed::Mixed => key.write_u32(1), + } + } +} + +/// The translator (`Words::generation`): words with the same generation read every word the same. +impl MemoProps for craft_i18n::Words { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + +/// The format (`Format::generation`): a format writes every number the same for its whole life. +impl MemoProps for craft_i18n::Format { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + +/// The format (`DateFormat::generation`): a format and its clones write every date the same. +impl MemoProps for craft_i18n::DateFormat { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + +/// The host (`Host::generation`): a host and its clones hold the same services and language. +impl MemoProps for craft_host::Host { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + impl MemoProps for craft_keymap::CommandRef { fn key(&self, key: &mut MemoKey) { let craft_keymap::CommandRef { id, params } = self; @@ -770,6 +958,13 @@ impl MemoProps for craft_theme::variant::Tone { } } +/// Derived `Hash`. +impl MemoProps for craft_theme::ComponentSet { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + impl MemoProps for craft_behavior::IconId { fn key(&self, key: &mut MemoKey) { // The name is the whole id. @@ -778,6 +973,47 @@ impl MemoProps for craft_behavior::IconId { } /// Derived `Hash` (`#[non_exhaustive]`). +/// Every field (`#[non_exhaustive]`, so a field added later is listed here by hand): the screen rect, the document +/// point at its centre, the zoom, the turn, the mirror and the pixel aspect. +impl MemoProps for craft_behavior::canvas::CanvasView { + fn key(&self, key: &mut MemoKey) { + self.rect.key(key); + for value in [self.center.x, self.center.y, self.zoom, self.rotation, self.aspect] { + value.key(key); + } + self.flip_x.key(key); + } +} + +/// The width and the height. +impl MemoProps for craft_behavior::kurbo::Size { + fn key(&self, key: &mut MemoKey) { + self.width.key(key); + self.height.key(key); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_behavior::Axis { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_behavior::overlay::Side { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_behavior::PixelSize { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + impl MemoProps for craft_behavior::fit::FitKeep { fn key(&self, key: &mut MemoKey) { key.feed_hash(self); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs new file mode 100644 index 000000000..d866926f6 --- /dev/null +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -0,0 +1,191 @@ +//! `MemoView`: a view the framework runs only when one of its inputs changed, and otherwise adds again as its last run +//! left it. + +use super::lazy::{Lazy, Shown}; +use super::memo::{MemoKey, MemoProps}; +use crate::runtime::env::{Env, Scoped}; +use crate::runtime::shift::Shift; +use egui::Ui; +use std::fmt; +use std::hash::Hash; +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 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 +/// that did not change. +/// +/// The key is the props type, the `fn` and every input the props feed. What a run paints and returns comes from its +/// own state, the props as the run found them and wrote them on its way. A run that writes through its props (a +/// `&mut Tracked` model, a [`Bind`](super::Bind)) moves its key: its record keeps the key from before the run, so the +/// view runs once more, reads the written value, and replays from then on. A write costs one more run, never a stale +/// replay. +/// +/// Its other inputs are the framework's, and each reaches the key or the settled test: +/// - its place: the room it is given, the clip, the layer, the layout, the scale and the scope's style inputs (tokens, +/// theme, density, direction, language, window active), compared for every view; +/// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every +/// app value, and the rest of `Scoped::scope_key`), in the key; +/// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the +/// window facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the scroll view of a nested +/// `Lazy`): a change of one runs only the views that read it; +/// - the clock, read through `frame::stepped_clock`: the view runs at the next step; +/// - commands sent to a command scope instance inside it: it runs while one waits. +/// +/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a row's shrink, a column's +/// sweep, a grid's cursor) does not reach in, so the room it is given reaches it only through its place. To the body +/// around it the view is one unit, sized by its content's measure. +/// +/// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept +/// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once +/// per pass. Events leave a view through an [`Outbox`] in its +/// props (picks, closes, drags: what its components report in the pass), its bindings, its `Tracked` writes or +/// commands. A measuring pass that takes the kept extent returns the kept value of the real run. +/// +/// `show` is a `fn`: a closure that captures does not build. +/// +/// ```compile_fail,E0308 +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::MemoView; +/// fn view(ui: &mut egui::Ui, count: u32) { +/// MemoView::new("count", (), move |_: &mut (), ui: &mut egui::Ui| { +/// ui.label(count.to_string()); +/// }) +/// .show(ui); +/// } +/// ``` +/// +/// ``` +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::MemoView; +/// fn view(ui: &mut egui::Ui, count: u32) -> Option { +/// MemoView::new("count", count, |count: &mut u32, ui: &mut egui::Ui| ui.label(count.to_string()).rect.width()).show(ui) +/// } +/// ``` +#[must_use] +pub struct MemoView { + lazy: Lazy, + props: P, + show: fn(&mut P, &mut Ui) -> R, +} + +impl MemoView { + /// The view `id` showing `props` through `show`. The id is unique as a `Lazy` key is: among the memoized views and + /// `Lazy` children of the scroll area the view is in, nested containers included, or among those of its parent `Ui` + /// 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 { + 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, + /// the kept value when it replayed; `None` only when it is out of view in a scroll area. + pub fn show(self, ui: &mut Ui) -> Option { + let MemoView { lazy, mut props, show } = self; + let ctx = ui.ctx().clone(); + let env = Env::of(ui); + let key = Self::key(&ctx, &env, &props, show); + let shown = lazy.run_keyed(ui, std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { + // The content is a layout room of its own: the flow of the body around it does not reach in. + let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + let out = show(&mut props, ui); + Env::restore(&ctx, installed); + run.output = Some(Arc::new(out.clone())); + #[cfg(feature = "testing")] + { + run.same_output = Some(crate::runtime::audit::same::); + } + out + }); + match shown { + Shown::Ran(out) => Some(out), + // A replay at another place moves what the run returned with its record. + Shown::Replayed(kept, shift) => { + kept.and_then(|kept| kept.downcast_ref::().map(|out| if shift.is_none() { out.clone() } else { out.shifted(&shift) })) + } + Shown::OutOfView => None, + } + } + + /// The key of `props` shown through `show` in the scope `env`: the props type, the `fn`'s address, the props' inputs + /// and what the scope hands down beyond its style inputs (`Scoped::scope_key`). Two `fn`s the compiler merged into + /// one address differ in their props type or show the same. + fn key(ctx: &egui::Context, env: &Env, props: &P, show: fn(&mut P, &mut Ui) -> R) -> u128 { + let mut key = MemoKey::of_view(ctx); + key.feed_hash(&P::identity()); + key.write(&(show as usize).to_le_bytes()); + key.write(&env.scope_key().to_le_bytes()); + props.key(&mut key); + #[cfg(feature = "testing")] + crate::runtime::measure::count_memo_key_bytes(ctx, key.bytes()); + key.finish() + } +} + +/// The events a memoized view's run sends to the code around it, in the pass it runs: what its components reported (a +/// pick, a close, a drag that started). A run sends; a replay sends nothing. That is complete, because input reaches +/// only a view it engages (the pointer over it, focus in it, a held press, an intent routed to it), and an engaged view +/// runs. The view cannot read what it sent, so an outbox is no input and feeds nothing into the key. +/// +/// ``` +/// # extern crate craft_ui_contract as craft_ui; +/// use craft_ui::contract::{MemoProps, MemoView, Outbox}; +/// #[derive(MemoProps)] +/// struct Row<'a> { +/// title: &'a str, +/// clicked: Outbox<'a, ()>, +/// } +/// fn row(props: &mut Row<'_>, ui: &mut egui::Ui) { +/// if ui.button(props.title).clicked() { +/// props.clicked.send(()); +/// } +/// } +/// fn view(ui: &mut egui::Ui) -> bool { +/// let mut clicked = Vec::new(); +/// let _ = MemoView::new("row", Row { title: "Open", clicked: Outbox::new(&mut clicked) }, row).show(ui); +/// !clicked.is_empty() +/// } +/// ``` +pub struct Outbox<'a, E> { + sent: &'a mut Vec, +} + +impl<'a, E> Outbox<'a, E> { + /// An outbox whose events go into `sent`, after what it holds. + pub fn new(sent: &'a mut Vec) -> Outbox<'a, E> { + Outbox { sent } + } + + /// Sends `event`. + pub fn send(&mut self, event: E) { + self.sent.push(event); + } +} + +impl fmt::Debug for Outbox<'_, E> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Outbox").field("sent", &self.sent.len()).finish() + } +} + +/// An outbox feeds nothing: the view only writes it. +impl MemoProps for Outbox<'_, E> { + fn key(&self, _: &mut MemoKey) {} +} diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 92a9cba84..3c8f80cc2 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -22,6 +22,7 @@ mod level; mod level_table; mod looks; mod memo; +mod memo_view; mod mount; pub mod overlay; mod pages; @@ -96,6 +97,7 @@ pub use lazy::Lazy; pub use level::{Catalog, CatalogEntry, Level, StoryLayout, Surface, catalog, stale_table_rows, story_title}; pub use looks::Looks; pub use memo::{MemoKey, MemoProps, Stateless}; +pub use memo_view::{MemoView, Outbox}; pub use overlay::{Overlay, OverlayUi, Overlays, Popup, PopupHandle, SizeLimits, Trigger}; pub use pages::Pages; pub use paint_ui::PaintUi; @@ -108,7 +110,7 @@ pub use registry::{CollectionEntry, ContainerEntry, Exemption, LeafEntry, Patter pub use sampler::{CanvasGesture, Sampler}; pub use settle::SettleCx; pub use text::EDIT_MENU; -pub use values::{Bind, BindMut, EditResponse, Hover, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed}; +pub use values::{Bind, BindCheck, BindMut, EditResponse, Hover, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed}; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; @@ -653,7 +655,8 @@ pub trait Collection: Component + HasProps + Meta { None } - /// Adjusts the item the closure built for a row, from the row's state. + /// Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this + /// makes, under the row-hook contract on `ItemCx`. fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r> { item } diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 8e349c3f1..b6790cd12 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -75,7 +75,7 @@ pub(super) fn dismissal( /// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { - let Some(press) = pointer::frame(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) + let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) else { return false; }; @@ -120,10 +120,9 @@ impl Cx<'_, C> { self.core.injected = Some(source); } - /// The modifiers held this frame, Alt alone included. The read is recorded like a value's: a settled component - /// that read them runs again in the frame they change (a menu title underlines its mnemonic while Alt is held). + /// The modifiers held this frame, Alt alone included. A tracked input: a memoized view that reads them runs when + /// they change. pub fn modifiers(&self) -> Mods { - crate::runtime::replay::note_read(&self.core.ctx, crate::runtime::reads::BindKey::Modifiers); - pointer::frame(&self.core.ctx).mods + pointer::mods(&self.core.ctx) } } diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index 57ac11405..d00d8c6fd 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -68,7 +68,7 @@ impl Opener { // arena member alike: whether the open press is on it and whether a click released on it. let pressed_on = response::is_pressed(anchor); let request = keys::context_request(&anchor.ctx, anchor.id); - let (fired, opening, pressed, clicked) = pointer::with_pass_pointer(&anchor.ctx, |pass| { + let (fired, opening, pressed, clicked) = pointer::with_pass_raw(&anchor.ctx, |pass| { let Some(frame) = pass.frame.as_ref() else { return (false, Opening::Plain, false, false) }; let inside = frame .pos @@ -125,14 +125,14 @@ impl Opener { } } -/// Whether a secondary-button release lands inside `response`'s rect in this pass: the secondary click a +/// Whether a secondary-button release lands inside `response`'s rect, where its clip shows it, in this pass: the secondary click a /// `Trigger::Press` opener opens on. pub(super) fn secondary_release_in(response: &Response) -> bool { - pointer::with_pass_pointer(&response.ctx, |pass| { + pointer::with_pass_raw(&response.ctx, |pass| { pass.frame.as_ref().is_some_and(|frame| { frame.release == Some(PointerButton::Secondary) && frame.pos.is_some_and(|pos| { - response.rect.contains(areas::layer_map(&response.ctx, response.layer_id).map_or(pos, |map| map.to_layer(pos))) + response.interact_rect.contains(areas::layer_map(&response.ctx, response.layer_id).map_or(pos, |map| map.to_layer(pos))) }) }) }) @@ -169,7 +169,7 @@ pub(crate) fn anchor_floor(overlay: &Overlay) -> f32 { /// The least width of the layer the content runs in ([`anchor_floor`]), which a layer's container gives its regions: /// a content-sized collection in the layer is at least this wide, so its rows fill the layer. 0 outside a layer. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] pub(crate) struct LayerFloor(pub(crate) f32); impl crate::runtime::env::EnvValue for LayerFloor { diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index abe127806..c4100569e 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -59,7 +59,7 @@ fn stored_opening(ctx: &Context, id: Id) -> Option { /// The screen rect the popups opened in an env are contained in, and the popups opened from those: the menus of a menu /// bar stay below the bar ([`OverlayUi::contain_popups_below`](super::OverlayUi::contain_popups_below)). `None`, the /// root's, lets popups take the whole safe rect. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub struct PopupRegion(pub Option); diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs index ba6fd7bd7..28c7b0916 100644 --- a/crates/ui-contract/src/contract/pages.rs +++ b/crates/ui-contract/src/contract/pages.rs @@ -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, &[]); @@ -61,7 +52,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { size }); let size = kept.unwrap_or_else(|| { - replay::open(&ctx); + replay::open_in_pass(&ctx); let size = measure::run(&ctx, || { // What the hidden page measures joins no transcript around it: the run that shows the pages does // not show it, so nothing there checks it. @@ -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) diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index fa05cd5e8..f7e3aab2d 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -390,6 +390,7 @@ fn blank_core<'a>( reveal: None, member_tip: None, header_stops: Vec::new(), + roving_member: false, press_cancel: None, scroll_moves: Vec::new(), value_parts: Default::default(), @@ -700,7 +701,6 @@ struct StopsStep<'a> { rtl: bool, env: &'a Env, resolved: &'a Resolved<'a>, - inert: bool, holder_widget: Option, member: Option, own: Sense, @@ -709,7 +709,7 @@ struct StopsStep<'a> { /// Registers the focus stops of a component that has any; one that sets `STOPS = false` has none, which a debug build checks. fn stops_step(at: StopsStep<'_>, e: &mut dyn ErasedPass<'_>, facts: &TypeFacts, parts: &PartsStep) { - let StopsStep { ctx, id, rtl, env, resolved, inert, holder_widget, member, own, text_keys } = at; + let StopsStep { ctx, id, rtl, env, resolved, holder_widget, member, own, text_keys } = at; let body_roving = e.roving(); if !facts.stops && body_roving.is_none() { debug_assert!( @@ -734,15 +734,15 @@ fn stops_step(at: StopsStep<'_>, e: &mut dyn ErasedPass<'_>, facts: &TypeFacts, ctx, id, holder: holder_widget.unwrap_or_else(|| member.map_or(id, |arena| arena.0)), - focusable: !inert && steps::takes_focus(resolved) && own.contains(Sense::FOCUS) && env.item != Some(id), - parts_focus: !inert && steps::takes_focus(resolved), + focusable: steps::takes_focus(resolved) && own.contains(Sense::FOCUS) && env.item != Some(id), + parts_focus: steps::takes_focus(resolved), text, press_only: text && resolved.read_only && !facts.holds_cells(), keys, role: role.resettable(resettable).value(value).text(text).moves(role.moves || keys.moves).deletes(role.deletes || keys.deletes || text), rtl, parts, - group: steps::member_group(ctx, env.roving, id), + group: env.roving.filter(|_| e.core_ref().roving_member), body: env.roving, row: env.row, item: env.item == Some(id), @@ -854,7 +854,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h let scope = enter_scope(p, ui); let env = host_env.unwrap_or(p.env); if let Some(mut h) = sense_steps(p, ui, host_at, env) { - update_steps(p, &h); + update_steps(p, env, &h); overlay_step(p, ui, env, &h); state_steps(p, ui, env, &h); paint_step(p, ui, env, &mut h); @@ -884,8 +884,10 @@ struct HostStep { /// The component's own direction: right to left unless its axis keeps its order. rtl: bool, rect: Rect, - /// The parts step 7 declared. - decls: super::cx::Decls, + /// What step 7 declared: the parts, roving groups and text parts. The stops register from it after `update`. + parts: PartsStep, + /// The egui widget of the component's text part or editor, which holds key focus for it. + holder_widget: Option, text_keys: Option, own: Sense, member: Option, @@ -969,7 +971,6 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e let own = if env.item == Some(id) { own.difference(Sense::CLICK | Sense::FOCUS) | Sense::HOVER } else { own }; let arena = e.arena(); let member = if arena || facts.text() { None } else { env.arena }; - stops_step(StopsStep { ctx: &ctx, id, rtl, env, resolved, inert, holder_widget, member, own, text_keys }, e, facts, &parts); // A body's wheel share is its scroll taker (body step, step 7); the gate value does not take the wheel. A body root that // senses the wheel itself (a canvas) registers like any other component. A collection that senses the wheel itself // registers in the item step, with its notch. @@ -1088,7 +1089,8 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e id, rtl, rect, - decls: parts.decls, + parts, + holder_widget, text_keys, own, member, @@ -1106,7 +1108,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e /// Step 9, update, with the body's roving group, which registers after `update`. // Kept out of the recursive frame above it: opt-level 2 inlines it there, so its locals stay on the stack while children run. #[inline(never)] -fn update_steps(p: &mut Pass<'_, '_, '_>, h: &HostStep) { +fn update_steps(p: &mut Pass<'_, '_, '_>, env: &Env, h: &HostStep) { let (facts, ctx, id, rtl) = (p.facts, &h.ctx, h.id, h.rtl); let e = &mut *p.p; // 9 update @@ -1132,6 +1134,10 @@ fn update_steps(p: &mut Pass<'_, '_, '_>, h: &HostStep) { } e.updated(); steps::record_context(e.core_ref()); + // The stops register after `update`, which says whether the component joins its body's roving group. + let at = + StopsStep { ctx, id, rtl, env, resolved: p.resolved, holder_widget: h.holder_widget, member: h.member, own: h.own, text_keys: h.text_keys }; + stops_step(at, e, facts, &h.parts); // The body's group registers after `update`, which may change its rules from what the component knows now. if let Some(roving) = e.roving() { let core = e.core_ref(); @@ -1249,13 +1255,17 @@ fn content_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) /// `paint_over`, after the `over` parts are placed, so the children it shows stack above them (8.3). fn paint_over_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) { ui.set_clip_rect(h.outer_clip); - sensing::place_over_widgets(ui, h.id, h.member, h.decls.parts()); + sensing::place_over_widgets(ui, h.id, h.member, h.parts.decls.parts()); ui.set_clip_rect(h.inside); let e = &mut *p.p; let fade = steps::fade(ui, env, e.core()); e.paint_over(ui, env); steps::unfade(ui, e.core(), fade); ui.set_clip_rect(h.outer_clip); + // Every member of the root's arena has joined: its widgets take their senses. + if h.member.is_none() { + sensing::widen_root(&h.ctx, h.id, p.facts.role == Role::None); + } } /// Steps 15 (settle) and 16 (report, then the tooltip), and the activation step 17 fires. @@ -1278,17 +1288,19 @@ fn report_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) facts, &steps::ReportIn { node: h.node, - decls: &h.decls, + decls: &h.parts.decls, sense: h.own, live: e.live(), scrolls: e.scrolls(), expanded: e.expanded(), position: e.position(), - group: steps::member_group(ctx, env.roving, id), + group: env.roving.filter(|_| e.core_ref().roving_member), + owns: e.roving().map(|_| steps::body_group(id)), }, ); let shows_label = e.shows_label(); - let tip_in = tooltip::TipIn { ui: &*ui, env, rich: p.tip.take(), parts: &h.decls, shows_label, canvas_control: facts.canvas_control, message }; + let tip_in = + tooltip::TipIn { ui: &*ui, env, rich: p.tip.take(), parts: &h.parts.decls, shows_label, canvas_control: facts.canvas_control, message }; tooltip::run(e.core_ref(), tip_in); // Activations accumulate across the passes of a viewport mount; step 17 fires the bound command once, with the // injected source when there is one. @@ -1361,7 +1373,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(); diff --git a/crates/ui-contract/src/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 650138e5c..b424f2a7d 100644 --- a/crates/ui-contract/src/contract/steps.rs +++ b/crates/ui-contract/src/contract/steps.rs @@ -43,7 +43,7 @@ pub(crate) use scroll_owner::{child_reveal, peek_reveal, queue_child_reveal, rev pub(crate) use sense::{part_state, register_wheel}; pub(crate) use settle::settle; pub(crate) use state::{register_reset, state, value_flags}; -pub(crate) use stops::{StopsIn, body_group, join_group, member_group, parts_group, register_stops, takes_focus}; +pub(crate) use stops::{StopsIn, body_group, parts_group, register_stops, takes_focus}; pub(crate) use style::{style, style_cx}; pub(crate) use update::{after_update, edit_intents, gesture_gate, key_activation, record_context, secondary_click, takes_activation, update_inputs}; pub(crate) use value::{Shown, ShownState, peek_value, value}; diff --git a/crates/ui-contract/src/contract/steps/apply.rs b/crates/ui-contract/src/contract/steps/apply.rs index 22f18aed1..58183e4da 100644 --- a/crates/ui-contract/src/contract/steps/apply.rs +++ b/crates/ui-contract/src/contract/steps/apply.rs @@ -170,7 +170,8 @@ fn apply_binding( /// 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, @@ -180,9 +181,7 @@ pub(crate) fn rerun_after_edit( leaf: bool, ) { if edit.given { - let ctx = &p.core_ref().ctx; - crate::runtime::lazy::note_given_edit(ctx); - ctx.request_repaint(); + p.core_ref().ctx.request_repaint(); return; } let Some(key) = edit.key.filter(|_| edit.written || edit.shown) else { return }; diff --git a/crates/ui-contract/src/contract/steps/label.rs b/crates/ui-contract/src/contract/steps/label.rs index 9df60e8ef..735180b28 100644 --- a/crates/ui-contract/src/contract/steps/label.rs +++ b/crates/ui-contract/src/contract/steps/label.rs @@ -53,7 +53,7 @@ fn scrub_warp(core: &mut CxCore<'_>, drag: &ValueDrag, pos: Pos2) -> Vec2 { if warp.pending() { return shift; } - let Some(screen) = crate::runtime::pointer::frame(&ctx).pos else { return shift }; + let Some(screen) = crate::runtime::pointer::frame_raw(&ctx).pos else { return shift }; let hosts = WindowHost::of(&ctx); if let (Some(by), Some(desktop)) = (drag.warp_by(screen, ctx.content_rect()), hosts.desktop_pointer()) && hosts.warp_pointer(desktop + by) diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index 2328d5aa6..9effbc8ec 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -27,8 +27,8 @@ pub(crate) struct Fade { /// The layer whose open veil the components shown here lie under: set by `PaintUi` for the children a faded /// component shows while its paint runs, which its veil covers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct UnderVeil(pub Option); +#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] +pub(crate) struct UnderVeil(#[memo_props(hash = "an egui layer id is its order and id")] pub Option); impl EnvValue for UnderVeil { fn root() -> Self { @@ -55,7 +55,7 @@ pub(crate) fn fade(ui: &Ui, env: &Env, core: &mut CxCore<'_>) -> Option { /// 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) { core.fade = None; diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 122d14070..c53047145 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -26,6 +26,8 @@ pub(crate) struct ReportIn<'a> { pub scrolls: (bool, bool), /// The roving group the component's own stop is in. pub group: Option, + /// The roving group of the component's body, which it owns: its report writes its members' places in the set. + pub owns: Option, /// The expanded state of a collapsible container, unless `Component::access` says otherwise. pub expanded: Option, /// The position the component reports itself, ahead of its group's and its item facts'. @@ -59,6 +61,14 @@ pub(crate) fn validity_of(validity: &Validity) -> Option<(&Message, bool)> pub(crate) fn report(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_>) -> Option { let validity = register_validity(p); report_access(p, facts, input, validity.as_ref().map(|(text, _)| text.clone())); + // The body's members have run and reported: each that left its place to the group takes it among this pass's + // members. + if let Some(group) = input.owns { + let ctx = &p.core_ref().ctx; + for (member, position) in focus::group_positions(ctx, group) { + access::write_set_position(ctx, member, position); + } + } crate::contract::cx::write_cursor(p.core_ref()); validity.filter(|(_, shown)| !shown).map(|(text, _)| text) } @@ -144,9 +154,11 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> if access.position.is_none() { access.position = input.position; } + // A member of a roving group that gives no place of its own takes it from the group's owner, which knows the + // members of the pass only after they all ran; its item facts' place stands until then. + let group_place = input.group.filter(|_| access.position.is_none()); if access.position.is_none() { - access.position = - input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); + access.position = core.env.facts_of(id).map(|facts| facts.position); } let inner_of = access::fold::owner_of(ctx, id); let folded = access::fold::take(ctx, id); @@ -190,6 +202,9 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> } } else { access::report(ctx, &own); + if let Some(group) = group_place { + focus::takes_group_position(ctx, id, group); + } } if let Some(folded) = &folded { keys::register_node(ctx, id, folded.inner, None, focusable); diff --git a/crates/ui-contract/src/contract/steps/stops.rs b/crates/ui-contract/src/contract/steps/stops.rs index f156af64d..696f5728f 100644 --- a/crates/ui-contract/src/contract/steps/stops.rs +++ b/crates/ui-contract/src/contract/steps/stops.rs @@ -1,15 +1,13 @@ -//! Step 7's tail: the focus stops and the roving groups they join. +//! After step 9: the focus stops and the roving groups they join. use super::parts::PartsStep; use crate::contract::Resolved; -use crate::runtime::egui::memory as store; use crate::runtime::focus::{self, Group, Stop}; use crate::runtime::memory::sub; use craft_behavior::{DocKey, KeyRole, PartRef}; use egui::{Context, Id}; -/// The parts of last pass's complete set in which this pass's results are read; first-frame parts read idle. -/// Step 7's tail: the focus stops. The root's interest when the component or any part is focusable, its +/// The focus stops, registered after `update`: the root's interest when the component or any part is focusable, its /// `(id, part)` stops, and its roving groups. pub(crate) struct StopsIn<'a> { pub ctx: &'a Context, @@ -27,7 +25,8 @@ pub(crate) struct StopsIn<'a> { pub role: KeyRole, pub rtl: bool, pub parts: &'a PartsStep, - /// The roving group of the body this component is shown in: its own stop joins it. + /// The roving group of the body this component is shown in, when it joined it in this pass (`Cx::join_roving`): its + /// own stop and its focusable parts join it. pub group: Option, /// The roving group of the innermost body this component is shown in, whether or not it joined it. pub body: Option, @@ -42,34 +41,17 @@ pub(crate) struct StopsIn<'a> { } /// The id of the roving group a container's body forms. -/// Records that `id` is a member of the roving `group` in this pass. -pub(crate) fn join_group(ctx: &Context, group: Id, id: Id) { - let slot = sub(group, ("member", id)); - store::put(ctx, slot, crate::runtime::pointer::pass_of(ctx)); - crate::runtime::memory::adopt::(ctx, id, slot); -} - /// The roving group of a component's own parts. fn roving_group(id: Id) -> Id { sub(id, "roving") } -/// The roving group a stop shown among a component's parts joins: the group of the component's own parts, or the body -/// group they joined. The one source for the parts' registration and for a component the header hosts in its cells. -pub(crate) fn parts_group(ctx: &Context, id: Id) -> Id { - let own = roving_group(id); - focus::registration::part_group(ctx, own).unwrap_or(own) +/// The roving group a stop shown among a component's parts joins: the body group `joined` when the component joined it +/// in this pass (`Cx::join_roving`), else the group of the component's own parts. The one source for the parts' +/// registration and for a component the header hosts in its cells. +pub(crate) fn parts_group(id: Id, joined: Option) -> Id { + joined.unwrap_or_else(|| roving_group(id)) } - -/// `group` when `id` joined it in this pass or the one before, else `None`: a component that is no member keeps its -/// own Tab stop. -pub(crate) fn member_group(ctx: &Context, group: Option, id: Id) -> Option { - let group = group?; - let pass = crate::runtime::pointer::pass_of(ctx); - let joined = store::peek_clone::(ctx, sub(group, ("member", id)))?; - (joined.saturating_add(1) >= pass).then_some(group) -} - pub(crate) fn body_group(id: Id) -> Id { sub(id, "body_roving") } @@ -115,8 +97,8 @@ pub(crate) fn register_stops(input: &StopsIn<'_>) -> Vec { let stop = if extras.nudges { stop.role(input.role.nudge(true)) } else { stop }; let stop = if extras.default_stop { stop.default_stop() } else { stop }; // A part group that joined the body's roving group has its parts registered there. - let joined = group.and_then(|parts| focus::registration::part_group(ctx, parts)); - let stop = if let Some(group) = row_parts.or(joined).or(group).or(input.row) { stop.in_group(group) } else { stop }; + let joined = group.map(|_| parts_group(input.id, input.group)); + let stop = if let Some(group) = row_parts.or(joined).or(input.row) { stop.in_group(group) } else { stop }; if extras.after_header { after_header.push(stop); } else { diff --git a/crates/ui-contract/src/contract/steps/update.rs b/crates/ui-contract/src/contract/steps/update.rs index 0c78589a6..ebaa68552 100644 --- a/crates/ui-contract/src/contract/steps/update.rs +++ b/crates/ui-contract/src/contract/steps/update.rs @@ -18,7 +18,7 @@ pub(crate) fn takes_activation(resolved: &Resolved<'_>) -> bool { /// `Intent::Activate` carries them, and the pass's pointer frame reads them from the same input a pointer activation's /// modifiers come from (Alt+Enter adds the way Alt+click does). pub(crate) fn key_activation(ctx: &egui::Context) -> crate::contract::Activation { - crate::contract::Activation { by_key: true, mods: crate::runtime::pointer::frame(ctx).mods } + crate::contract::Activation { by_key: true, mods: crate::runtime::pointer::frame_raw(ctx).mods } } /// Step 9, update, the part the library writes: the keyboard activation. @@ -104,7 +104,7 @@ fn double_click(core: &CxCore<'_>) -> Option> { /// Whether this pass releases the secondary button over the component, its text part included (a widget of its own /// over it): a right click on it. pub(crate) fn secondary_click(core: &CxCore<'_>) -> bool { - crate::runtime::pointer::frame(&core.ctx).release == Some(craft_behavior::PointerButton::Secondary) + crate::runtime::pointer::frame_raw(&core.ctx).release == Some(craft_behavior::PointerButton::Secondary) && (core.response.hovered() || core.texts.as_ref().is_some_and(|(key, _)| { core.ctx.read_response(crate::primitives::text_adapter::text_id(core.id, *key)).is_some_and(|text| text.hovered()) diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index d8a0d90ab..4bc7910c0 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -526,7 +526,7 @@ pub(crate) fn run( } if part.options.holds_drafts { // A window deactivation leaves the draft for the next Enter or a press elsewhere (L-52). - if state.end == Some(End::Blur) && crate::runtime::pointer::with_pass_pointer(&ctx, |pointer| pointer.focus_lost) { + if state.end == Some(End::Blur) && crate::runtime::pointer::with_pass_raw(&ctx, |pointer| pointer.focus_lost) { state.end = None; } // A press the focus service held for this part keeps focus; the draft shows as its value would. diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index 4fb832a43..91390e6b1 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -1,6 +1,7 @@ //! Values and edits (chapter 10): the binding, the output of a value component and the types that carry a value //! between the app and the pipeline. +use crate::contract::{MemoKey, MemoProps}; use crate::runtime::env::Message; use crate::runtime::memory::{MemoryStage, Savable, SaveKey, StageAccess}; use crate::runtime::reads::{self, BindKey}; @@ -97,7 +98,42 @@ impl Clone for SaveSpec { } } -type Check<'a, T> = dyn Fn(&T) -> Validity + 'a; +/// A binding's check: its verdict on a value, and the key of its inputs and its `fn`, which only a memoized view that +/// holds the binding takes. +trait Checker { + fn validity(&self, value: &T) -> Validity; + fn key(&self, key: &mut MemoKey); +} + +/// A check `fn` and the inputs it reads (`Bind::check_with`). +struct WithInputs { + inputs: I, + check: fn(&I, &T) -> Validity, +} + +impl Checker for WithInputs { + fn validity(&self, value: &T) -> Validity { + (self.check)(&self.inputs, value) + } + + fn key(&self, key: &mut MemoKey) { + self.inputs.key(key); + key.write(&(self.check as usize).to_le_bytes()); + } +} + +/// A borrowed check, for a reborrowed binding. +impl + ?Sized> Checker for &C { + fn validity(&self, value: &T) -> Validity { + (**self).validity(value) + } + + fn key(&self, key: &mut MemoKey) { + (**self).key(key); + } +} + +type Check<'a, T> = dyn Checker + 'a; /// Where a binding's value lives. enum Source<'a, T> { @@ -109,16 +145,27 @@ enum Source<'a, T> { MutMixed(&'a mut Mixed), /// Write-through to a field of a `Tracked` (`bind_tracked!`), whose write count moves only when an edit changes /// the field. - Tracked { value: &'a mut T, count: &'a Cell }, + Tracked { value: &'a mut T, count: &'a Cell, at: TrackedAt }, + /// `Tracked` for a field that may be mixed; an edit makes it concrete. + TrackedMixed { value: &'a mut Mixed, count: &'a Cell, at: TrackedAt }, /// No caller value: session memory under the component id, or the saved tier. Kept, } +/// Where a `bind_tracked!` binding's field is: the source id of the `Tracked` that holds it and the field's offset in +/// bytes from the start of that value. It names the field in every pass, wherever the value lives. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct TrackedAt { + source: u64, + offset: usize, +} + /// The binding of a value component: a value the app owns, the check on it and the value a reset restores. The same /// binding produces the same events whichever source it has. pub struct Bind<'a, T> { source: Source<'a, T>, policy: EditPolicy, + /// The check and the inputs it reads (`check_with`). check: Option>>, save: Option>, reset: Option, @@ -140,11 +187,18 @@ impl<'a, T: Value> Bind<'a, T> { Self::from_source(Source::MutMixed(v)) } - /// Called by [`bind_tracked!`](crate::bind_tracked) only: edits write through to `value`, and an edit that - /// changes it moves `count`, the write count of the `Tracked` that holds it. + /// Called by [`bind_tracked!`](crate::bind_tracked) only: edits write through to `value`, a field `offset` bytes + /// into the value of the `Tracked` with source id `source`, and an edit that changes it moves `count`, that + /// `Tracked`'s write count. #[doc(hidden)] - pub fn __tracked(value: &'a mut T, count: &'a Cell) -> Self { - Self::from_source(Source::Tracked { value, count }) + pub fn __tracked(value: &'a mut T, count: &'a Cell, source: u64, offset: usize) -> Self { + Self::from_source(Source::Tracked { value, count, at: TrackedAt { source, offset } }) + } + + /// `Bind::__tracked` for a field that may be mixed: an edit makes it concrete. + #[doc(hidden)] + pub fn __tracked_mixed(value: &'a mut Mixed, count: &'a Cell, source: u64, offset: usize) -> Self { + Self::from_source(Source::TrackedMixed { value, count, at: TrackedAt { source, offset } }) } /// No caller value: the component keeps it in session memory under its id. Until something is stored, it reads @@ -179,9 +233,23 @@ impl<'a, T: Value> Bind<'a, T> { } /// The check on a value: `Fix` replaces it; `Warn`, `Refuse` and `Error` set the component's state, and `Refuse` - /// also refuses a commit. - pub fn check(mut self, check: impl Fn(&T) -> Validity + 'a) -> Self { - self.check = Some(Box::new(check)); + /// also refuses a commit. `check` is a `fn`, which captures nothing; a check that reads other values takes them as + /// inputs ([`check_with`](Self::check_with)). + pub fn check(self, check: fn(&T) -> Validity) -> Self + where + T: 'a, + { + self.check_with(CheckFn(check), |check, value| (check.0)(value)) + } + + /// The check `check` on a value, reading `inputs` beside it (a limit, the names already taken). The inputs are + /// props ([`MemoProps`]) and `check` is a `fn`, which captures nothing, so a memoized view that holds the binding + /// sees every input of its check. + pub fn check_with(mut self, inputs: I, check: fn(&I, &T) -> Validity) -> Self + where + T: 'a, + { + self.check = Some(Box::new(WithInputs { inputs, check })); self } @@ -199,10 +267,11 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => Source::Given(value.clone()), Source::Mut(value) => Source::Mut(&mut **value), Source::MutMixed(value) => Source::MutMixed(&mut **value), - Source::Tracked { value, count } => Source::Tracked { value: &mut **value, count }, + Source::Tracked { value, count, at } => Source::Tracked { value: &mut **value, count, at: *at }, + Source::TrackedMixed { value, count, at } => Source::TrackedMixed { value: &mut **value, count, at: *at }, Source::Kept => Source::Kept, }; - let check = self.check.as_deref().map(|check| Box::new(move |value: &T| check(value)) as Box>); + let check = self.check.as_deref().map(|check| Box::new(check) as Box>); Bind { source, policy: self.policy, check, save: self.save.clone(), reset: self.reset.clone() } } @@ -232,7 +301,7 @@ impl<'a, T: Value> Bind<'a, T> { match &self.source { Source::Given(Mixed::Same(value)) => value == shown, Source::Mut(value) => **value == *shown, - Source::MutMixed(Mixed::Same(value)) => value == shown, + Source::MutMixed(Mixed::Same(value)) | Source::TrackedMixed { value: Mixed::Same(value), .. } => value == shown, Source::Tracked { value, .. } => **value == *shown, _ => false, } @@ -244,13 +313,101 @@ impl<'a, T: Value> Bind<'a, T> { Source::Given(value) => SourceMut::Given(value), Source::Mut(value) => SourceMut::Mut(&mut **value), Source::MutMixed(value) => SourceMut::MutMixed(&mut **value), - Source::Tracked { value, count } => SourceMut::Tracked { value: &mut **value, count }, + Source::Tracked { value, count, at } => SourceMut::Tracked { value: &mut **value, count, at: *at }, + Source::TrackedMixed { value, count, at } => SourceMut::TrackedMixed { value: &mut **value, count, at: *at }, Source::Kept => SourceMut::Kept, }; BindMut { source, policy: self.policy, check: self.check.as_deref(), save: self.save.as_ref(), reset: self.reset.as_ref() } } } +/// A binding's check as props (`BindMut::check_of`): by the key of its inputs and its `fn`. +pub struct BindCheck<'c, T> { + check: Option<&'c Check<'c, T>>, +} + +impl BindCheck<'_, T> { + /// The check's verdict on `value`. + pub fn validity(&self, value: &T) -> Validity { + self.check.map_or(Validity::Ok, |check| check.validity(value)) + } +} + +impl MemoProps for BindCheck<'_, T> { + fn key(&self, key: &mut MemoKey) { + key_check(self.check, key); + } +} + +/// Feeds a binding's check, or its absence. +fn key_check(check: Option<&Check<'_, T>>, key: &mut MemoKey) { + match check { + None => key.write_u32(0), + Some(check) => { + key.write_u32(1); + check.key(key); + } + } +} + +/// A check with no inputs, as the inputs of the one mechanism (`Bind::check_with`): keyed by the `fn`'s address. +struct CheckFn(fn(&T) -> Validity); + +impl MemoProps for CheckFn { + fn key(&self, key: &mut MemoKey) { + key.write(&(self.0 as usize).to_le_bytes()); + } +} + +/// A binding in a memoized view's props: by what the view reads through it. A given value keys by value; a +/// write-through source by its value and its address, the place the framework knows its reads by (a large value is +/// bound through `bind_tracked!` or held as `&Tracked` instead: its value is hashed for each key); a `Tracked` field +/// (`bind_tracked!`) by its `Tracked`'s source, the field's place in the value and the write count; a kept value by the writes the context counts +/// outside a component's edit: of its saved value (`set_saved_value`, `forget_saved`), or of session memory +/// (`forget`). The framework tracks the component's own reads and edits. The policy, the reset value, the save key and +/// the check's inputs and `fn` (`check_with`) feed too. +impl MemoProps for Bind<'_, T> { + fn key(&self, key: &mut MemoKey) { + let Bind { source, policy, check, save, reset } = self; + let address = |value: &T| std::ptr::from_ref(value).addr(); + match source { + Source::Given(value) => { + key.write_u32(0); + Mixed::::key(value, key); + } + Source::Mut(value) => { + key.write_u32(1); + T::key(value, key); + address(value).key(key); + } + Source::MutMixed(value) => { + key.write_u32(2); + Mixed::::key(value, key); + std::ptr::from_ref::>(value).addr().key(key); + } + Source::Tracked { count, at, .. } | Source::TrackedMixed { count, at, .. } => { + key.write_u32(3); + at.source.key(key); + at.offset.key(key); + count.get().key(key); + } + Source::Kept => { + key.write_u32(4); + let writes = key.context().map(|ctx| crate::runtime::memory::writes(ctx, save.as_ref().map(|save| &save.key))); + match (writes, save) { + (Some((saved, _)), Some(_)) => saved.key(key), + (Some((_, session)), None) => session.key(key), + (None, _) => {} + } + } + } + key.feed_hash(policy); + reset.key(key); + save.as_ref().map(|save| save.key.as_str()).key(key); + key_check(check.as_deref(), key); + } +} + impl<'a> From for Bind<'a, CanvasView> { fn from(view: CanvasView) -> Self { Bind::given(view) @@ -261,7 +418,8 @@ enum SourceMut<'a, T> { Given(&'a Mixed), Mut(&'a mut T), MutMixed(&'a mut Mixed), - Tracked { value: &'a mut T, count: &'a Cell }, + Tracked { value: &'a mut T, count: &'a Cell, at: TrackedAt }, + TrackedMixed { value: &'a mut Mixed, count: &'a Cell, at: TrackedAt }, Kept, } @@ -284,6 +442,7 @@ impl BindMut<'_, T> { SourceMut::Mut(value) => Some(Mixed::Same((**value).clone())), SourceMut::MutMixed(value) => Some((**value).clone()), SourceMut::Tracked { value, .. } => Some(Mixed::Same((**value).clone())), + SourceMut::TrackedMixed { value, .. } => Some((**value).clone()), SourceMut::Kept => None, } } @@ -295,7 +454,8 @@ impl BindMut<'_, T> { SourceMut::Given(_) => None, SourceMut::Mut(value) => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), SourceMut::MutMixed(value) => Some(BindKey::Place(std::ptr::from_ref::>(value) as usize, TypeId::of::>())), - SourceMut::Tracked { value, .. } => Some(BindKey::Place(std::ptr::from_ref::(value) as usize, TypeId::of::())), + SourceMut::Tracked { at, .. } => Some(BindKey::Tracked(at.source, at.offset, size_of::(), TypeId::of::())), + SourceMut::TrackedMixed { at, .. } => Some(BindKey::Tracked(at.source, at.offset, size_of::>(), TypeId::of::>())), SourceMut::Kept => Some(match self.save { Some(save) => BindKey::Saved(Id::NULL.with(&save.key)), None => BindKey::Kept(id), @@ -315,7 +475,9 @@ impl BindMut<'_, T> { /// when it changed. pub(crate) fn shown_matches(&self, shown: &T) -> bool { match &self.source { - SourceMut::Given(Mixed::Same(value)) | SourceMut::MutMixed(Mixed::Same(value)) => value == shown, + SourceMut::Given(Mixed::Same(value)) + | SourceMut::MutMixed(Mixed::Same(value)) + | SourceMut::TrackedMixed { value: Mixed::Same(value), .. } => value == shown, SourceMut::Mut(value) => **value == *shown, SourceMut::Tracked { value, .. } => **value == *shown, _ => false, @@ -325,7 +487,13 @@ impl BindMut<'_, T> { /// The check's verdict on `value`. #[doc(hidden)] pub fn validity(&self, value: &T) -> Validity { - self.check.map_or(Validity::Ok, |check| check(value)) + self.check.map_or(Validity::Ok, |check| check.validity(value)) + } + + /// The binding's check, as the inputs of a child's check (`Bind::check_with`): a composite hands its own check to + /// the children that edit its value. + pub fn check_of(&self) -> BindCheck<'_, T> { + BindCheck { check: self.check } } /// The value of a kept binding: the saved tier when it has a `SaveKey`, else session memory under `id`, else the @@ -416,7 +584,7 @@ impl BindMut<'_, T> { pub(crate) fn writes(&self, event: &EditEvent) -> bool { match self.source { SourceMut::Given(_) | SourceMut::Kept => false, - SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked { .. } => { + SourceMut::Mut(_) | SourceMut::MutMixed(_) | SourceMut::Tracked { .. } | SourceMut::TrackedMixed { .. } => { self.policy == EditPolicy::WriteThrough || !matches!(event, EditEvent::Update { .. }) } } @@ -431,22 +599,26 @@ impl BindMut<'_, T> { match &mut self.source { SourceMut::Mut(value) => event.apply(&mut **value), SourceMut::MutMixed(value) => event.apply_mixed(&mut **value), - SourceMut::Tracked { value, count } => { - // A gesture's start and a cancel with nothing to restore never write. - if matches!(event, EditEvent::Begin { .. } | EditEvent::Cancel { before: None, .. }) { - return Applied::Unchanged; - } - let applied = event.apply(&mut **value); - if applied != Applied::Unchanged { - count.set(count.get().wrapping_add(1)); - } - applied - } + SourceMut::Tracked { value, count, .. } => write_tracked(event, count, |event| event.apply(&mut **value)), + SourceMut::TrackedMixed { value, count, .. } => write_tracked(event, count, |event| event.apply_mixed(&mut **value)), SourceMut::Given(_) | SourceMut::Kept => Applied::Unchanged, } } } +/// Applies `event` to a `Tracked` field through `apply`: a gesture's start and a cancel with nothing to restore never +/// write, and a write that changes the field moves the `Tracked`'s write count. +fn write_tracked(event: &EditEvent, count: &Cell, apply: impl FnOnce(&EditEvent) -> Applied) -> Applied { + if matches!(event, EditEvent::Begin { .. } | EditEvent::Cancel { before: None, .. }) { + return Applied::Unchanged; + } + let applied = apply(event); + if applied != Applied::Unchanged { + count.set(count.get().wrapping_add(1)); + } + applied +} + /// The output of a component that edits a value. Only `cx.edit_response()` builds it. #[derive(Debug)] #[non_exhaustive] @@ -640,9 +812,9 @@ pub(crate) enum Checked { /// Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` /// gives one [`Bind`], `bind_tracked!(doc => title, style.size)` a tuple with one per field path (field names and -/// tuple indices only). Making and reading the bindings leaves the revision; an edit that changes a field moves it at -/// the write, so bindings made every pass don't invalidate the value's readers. Each binding borrows its own field, -/// so the paths must not overlap. +/// tuple indices only), and `bind_tracked!(name)` one binding to the whole value. Making and reading the bindings +/// leaves the revision; an edit that changes the bound value moves it at the write, so bindings made every pass don't +/// invalidate the value's readers. Each binding borrows its own field, so the paths must not overlap. /// /// ``` /// # extern crate craft_ui_contract as craft_ui; @@ -657,6 +829,12 @@ pub(crate) enum Checked { /// let mut doc = Tracked::new(Doc { title: "a".into(), style: (12.0, false) }); /// let (title, size) = bind_tracked!(doc => title, style.0); /// # let _ = (title, size); +/// +/// let mut name = Tracked::new(String::from("a")); +/// let before = name.revision(); +/// let whole = bind_tracked!(name); +/// # drop(whole); +/// assert_eq!(name.revision(), before, "binding leaves the revision"); /// ``` /// /// Overlapping paths don't compile: @@ -681,11 +859,23 @@ pub(crate) enum Checked { #[macro_export] macro_rules! bind_tracked { ($tracked:expr => $first:tt $(. $rest:tt)*) => {{ - let (model, count) = $tracked.__split_for_bind(); - $crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count) + let (model, count, source) = $tracked.__split_for_bind(); + let base = ::std::ptr::from_ref(&*model).addr(); + let field = &mut model.$first $(.$rest)*; + let offset = ::std::ptr::from_ref(&*field).addr() - base; + $crate::contract::Bind::__tracked(field, count, source, offset) }}; ($tracked:expr => $($first:tt $(. $rest:tt)*),+ $(,)?) => {{ - let (model, count) = $tracked.__split_for_bind(); - ($($crate::contract::Bind::__tracked(&mut model.$first $(.$rest)*, count),)+) + let (model, count, source) = $tracked.__split_for_bind(); + let base = ::std::ptr::from_ref(&*model).addr(); + ($({ + let field = &mut model.$first $(.$rest)*; + let offset = ::std::ptr::from_ref(&*field).addr() - base; + $crate::contract::Bind::__tracked(field, count, source, offset) + },)+) + }}; + ($tracked:expr) => {{ + let (model, count, source) = $tracked.__split_for_bind(); + $crate::contract::Bind::__tracked(model, count, source, 0) }}; } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index f12cde91f..c32bee2cb 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1164,16 +1164,24 @@ pub fn empty_cell(ui: &mut Ui) { /// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself. fn take_in(ui: &mut Ui, grid: Option, size: Vec2) -> (Rect, bool) { - let cell = grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get_mut(&body).map(|cursor| cursor.cell(size)))); - match cell { - Some(cell) => { - alloc::advance_past(ui, cell); - (cell, true) - } + match cell_in(ui, grid, size) { + Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } } +/// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns +/// it; `None`, taking nothing, outside such a body. +pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { + cell_in(ui, Env::of(ui).grid, size) +} + +fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { + let cell = grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get_mut(&body).map(|cursor| cursor.cell(size))))?; + alloc::advance_past(ui, cell); + Some(cell) +} + /// The region the next child shown in flow in `ui` measures and is placed in: that of the next cell of the `Grid` or /// spread `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. pub(crate) fn flow_region(ui: &Ui) -> Rect { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index d95a7a7d6..4f2654e97 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -26,5 +26,5 @@ pub(crate) use body::run_body; pub(crate) use body::{ InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured, - shares_y, shrink_cap, take_in_flow, view_room, + shares_y, shrink_cap, take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 3d32019bf..af372d7ba 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -30,7 +30,7 @@ pub enum PaintShape { } /// A line width from the theme, so content never picks a literal one. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub enum StrokeWidth { /// One physical pixel. diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 4b744974b..57e414720 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -2,12 +2,14 @@ use super::svg_set; use super::textures::TextureCache; +use crate::contract::{MemoKey, MemoProps}; use crate::style::{DataColor, Ink, StyleColor, UiTokens, ink_color, log_once}; use craft_behavior::IconId; use craft_i18n::Direction; use craft_theme::{IconPackId, Srgba}; use egui::emath::GuiRounding as _; use egui::{Color32, Painter, Rect, pos2, vec2}; +use std::any::Any; pub use super::svg_set::IconSet; @@ -23,8 +25,9 @@ pub enum Mirror { } /// A value glyph: an icon drawn from a value. It is `Sync` because container props that show one are kept with a -/// body's measurement in layout memory. -pub trait Glyph: Sync { +/// body's measurement in layout memory. It is props ([`MemoProps`]): an icon keys a memoized view by the glyph's type, +/// then by what the glyph feeds, so a glyph owns what it draws from (`'static`). +pub trait Glyph: Any + MemoProps + Sync { /// Whether the glyph has a reading direction (an arrow) and so flips under right-to-left. fn directional(&self) -> bool { false @@ -42,7 +45,7 @@ pub enum IconSource<'a> { /// An SVG-set or tool icon, by its egui-free key. Svg(IconId), /// A value glyph. - Glyph(&'a dyn Glyph), + Glyph(&'a (dyn Glyph + 'static)), /// A colour from data, painted as a swatch (a guide colour, a matte colour); `None` paints the empty swatch of a /// colour the theme decides. Swatch(Option), @@ -56,6 +59,37 @@ pub enum IconSource<'a> { Mark(craft_behavior::CursorBadge), } +/// By variant, then what it draws: a glyph by its type, then by what it feeds. +impl MemoProps for IconSource<'_> { + fn key(&self, key: &mut MemoKey) { + match self { + IconSource::Svg(id) => { + key.write_u32(0); + id.key(key); + } + IconSource::Glyph(glyph) => { + key.write_u32(1); + let any: &dyn Any = *glyph; + key.feed_hash(&any.type_id()); + glyph.key(key); + } + IconSource::Swatch(color) => { + key.write_u32(2); + color.key(key); + } + IconSource::Disc => key.write_u32(3), + IconSource::Initial(letter) => { + key.write_u32(4); + letter.key(key); + } + IconSource::Mark(badge) => { + key.write_u32(5); + key.feed_hash(badge); + } + } + } +} + impl std::fmt::Debug for IconSource<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -85,7 +119,7 @@ impl PartialEq for IconSource<'_> { } /// An icon to paint. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] pub struct IconSpec<'a> { /// The drawing. pub source: IconSource<'a>, @@ -101,7 +135,7 @@ pub struct IconSpec<'a> { } /// A data-colour mark on an icon. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub enum IconMark { /// A dot at the icon's bottom-trailing corner, ringed in the icon's colour. @@ -141,7 +175,7 @@ impl<'a> IconSpec<'a> { } /// An icon of `glyph` in the panel ink. - pub fn glyph(glyph: &'a dyn Glyph) -> Self { + pub fn glyph(glyph: &'a (dyn Glyph + 'static)) -> Self { IconSpec { source: IconSource::Glyph(glyph), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, badge: None } } diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 7cce1927b..ab1bc0b6e 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -252,13 +252,14 @@ struct ArenaState { /// The stack position of the root's own `over` parts: above the members its body showed and below the ones /// `paint_over` shows (`place_over_widgets`). Above everything until the owner has placed them. own_over_at: u32, - /// The senses and bounds of the members that joined this pass and last pass. + /// The senses of the members that joined this pass: the root's widgets take them once its body has run + /// (`widen_root`). union_sense: Sense, - previous_union_sense: Sense, + /// The root takes its members' senses: it was enabled at its step 8 this pass. + widens: bool, layer: Option, - /// The layer and the egui sense the root's widgets had at its last step 8, for `sense_early`. + /// The layer the root's widgets had at its last step 8, for `sense_early`. last_layer: Option, - last_sense: Sense, /// The pass whose outcome `sense_early` stepped before the root's step 8. early: u64, root: Option, @@ -305,7 +306,8 @@ fn rotate(state: &mut ArenaState, pass_nr: u64) { std::mem::swap(&mut state.previous_own, &mut state.own); state.own.clear(); state.own_over_at = u32::MAX; - state.previous_union_sense = std::mem::take(&mut state.union_sense); + state.union_sense = Sense::empty(); + state.widens = false; state.pass = pass_nr; } } @@ -401,34 +403,76 @@ 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. -/// What a root registers in its arena at step 8, kept for a replay. +crate::stays!(ArenaId); + +impl crate::runtime::Shift for PartDecl { + fn shifted(&self, by: &egui::RecordShift) -> Self { + PartDecl { shape: self.shape.shifted(by), ..self.clone() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + PartDecl { shape: self.shape.snapped(&to.shape, within), ..self.clone() } + } +} + +impl crate::runtime::Shift for MemberDecl { + fn shifted(&self, by: &egui::RecordShift) -> Self { + MemberDecl { rect: by.rect(self.rect), parts: self.parts.shifted(by), ..self.clone() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + MemberDecl { rect: self.rect.snapped(&to.rect, within), parts: self.parts.snapped(&to.parts, within), ..self.clone() } + } +} + +impl crate::runtime::Shift for RootInfo { + fn shifted(&self, by: &egui::RecordShift) -> Self { + RootInfo { rect: by.rect(self.rect), ..*self } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + RootInfo { rect: self.rect.snapped(&to.rect, within), ..*self } + } +} + +impl crate::runtime::Shift for RootRegistration { + fn shifted(&self, by: &egui::RecordShift) -> Self { + RootRegistration { info: self.info.shifted(by), own: self.own.shifted(by), ..self.clone() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + RootRegistration { info: self.info.snapped(&to.info, within), own: self.own.snapped(&to.own, within), ..self.clone() } + } +} + +/// What a root registers in its arena at step 8, kept for a replay. The egui widgets, with the senses they take, +/// are in egui's pass records. #[derive(Clone, Debug, PartialEq)] struct RootRegistration { info: RootInfo, own: Vec, widgets: Vec, layer: Layer, - sense: Sense, } /// Notes a root's step-8 registration in the open records. -fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], widgets: &[Id], (layer, sense): (Layer, Sense)) { +fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], widgets: &[Id], layer: Layer) { crate::runtime::replay::journal( ctx, - || (arena, RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer, sense }), + || (arena, RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer }), |ctx, (arena, registration)| register_root_again(ctx, *arena, registration.clone()), ); } -/// A replayed root's step-8 registration: its own parts, rect, widgets, layer and sense, with no press run. +/// A replayed root's step-8 registration: its own parts, rect, widgets and layer, with no press run. fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistration) { - journal_root(ctx, arena, registration.info, ®istration.own, ®istration.widgets, (registration.layer, registration.sense)); + journal_root(ctx, arena, registration.info, ®istration.own, ®istration.widgets, registration.layer); let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); with_arena(ctx, arena, pass_nr, |state| { rotate(state, pass_nr); @@ -436,7 +480,6 @@ fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistra state.root = Some(registration.info); state.widgets = registration.widgets; state.last_layer = Some(registration.layer); - state.last_sense = registration.sense; }); } @@ -445,8 +488,8 @@ fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistra fn journal_join(ctx: &Context, arena: ArenaId, layer: Layer, clip: Rect, joined: &[MemberDecl]) { crate::runtime::replay::journal( ctx, - || (arena, layer, clip, joined.to_vec()), - |ctx, (arena, layer, clip, joined)| join_again(ctx, *arena, *layer, *clip, joined), + || (arena, layer, crate::runtime::Clip::new(clip), joined.to_vec()), + |ctx, (arena, layer, clip, joined)| join_again(ctx, *arena, *layer, clip.rect(), joined), ); } @@ -479,7 +522,11 @@ fn join_member(state: &mut ArenaState, mut decl: MemberDecl, layer: Layer, targe /// so far, as `place_over_widgets` does, and records their shapes on `layer` through `clip`; journaled, so a replay /// places them above the members joined in the replaying pass. fn place_over(ctx: &Context, (arena, id, member, layer, clip): (ArenaId, Id, bool, Layer, Rect)) { - crate::runtime::replay::journal(ctx, || (arena, id, member, layer, clip), |ctx, &args| place_over(ctx, args)); + crate::runtime::replay::journal( + ctx, + || (arena, id, member, layer, crate::runtime::Clip::new(clip)), + |ctx, &(arena, id, member, layer, clip)| place_over(ctx, (arena, id, member, layer, clip.rect())), + ); let read = PassRead::of(ctx); let shapes = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { rotate(state, read.pass_nr); @@ -523,7 +570,7 @@ impl PassRead { } /// Steps the press machine of the root `id` before its measuring run, from what last pass registered: the root rect, -/// widgets, layer and sense. A body reads the parts' presses of this pass in both of its runs through +/// widgets and layer. A body reads the parts' presses of this pass in both of its runs through /// [`part_press`]; step 8 finds the memoised outcome. Does nothing on a root's first pass and when the root was not /// drawn last pass. `enabled` is what is known before the root's step 5; step 8 ends a press of a root that turns out /// to be inert. @@ -537,11 +584,10 @@ pub(crate) fn sense_early(ctx: &Context, id: Id, enabled: bool) { rotate(state, read.pass_nr); let root = state.root?; let layer = state.last_layer?; - (root.rect.is_positive() && root.rect.is_finite() && !state.previous_own.is_empty()) - .then_some((layer, state.last_sense | state.previous_union_sense)) + (root.rect.is_positive() && root.rect.is_finite() && !state.previous_own.is_empty()).then_some(layer) }); - let Some((layer, sense)) = last else { return }; - outcome_in(ctx, &read, arena, layer, enabled, sense); + let Some(layer) = last else { return }; + outcome_in(ctx, &read, arena, layer, enabled); with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| state.early = read.pass_nr); } @@ -584,7 +630,8 @@ pub(crate) struct RootResult { pub activation: bool, /// The member a click activated. pub activated_member: Option, - /// The sense the root's egui widget carries. + /// The sense the root's egui widget carries at step 8: its own and its parts', and focus while it holds key focus + /// for a member. Its members' senses join it once its body has run (`widen_root`). pub sense: Sense, } @@ -596,24 +643,20 @@ pub(crate) fn sense_root(ui: &Ui, spec: RootSpec<'_>) -> RootResult { let arena = ArenaId::new(spec.id); let read = PassRead::of(ctx); let (clip, layer) = (ui.clip_rect(), ui.layer_id()); - let last_union = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { - rotate(state, read.pass_nr); - state.previous_union_sense - }); // A disabled root only hovers, whatever its parts and members sense; it keeps the focus stop its own sense or a part's grants. - let sense = if spec.enabled { - spec.own.iter().fold(spec.own_sense | last_union, |sense, part| sense | part.sense) - } else { - Sense::HOVER | spec.own.iter().fold(spec.own_sense, |sense, part| sense | part.sense).intersection(Sense::FOCUS) - }; - // A root outside its clip gets an empty response rect at its corner, never an inverted one. - let shown = spec.rect.intersect(clip); - let response = response::widget(ui, spec.id, Rect::from_min_max(shown.min, shown.max.max(shown.min)), sense); + let own = spec.own.iter().fold(spec.own_sense, |sense, part| sense | part.sense); + let sense = if spec.enabled { own } else { Sense::HOVER | own.intersection(Sense::FOCUS) }; + // A root that holds key focus for a member's stop senses focus now: egui drops the focus of a widget registered + // without it, before the members, which read it, run and join their senses (`widen_root`). + let sense = if crate::runtime::focus::held_for_member(ctx, spec.id) { sense | Sense::FOCUS } else { sense }; + // The response rect is the root's whole rect and egui's hit test uses its part inside the clip (`interact_rect`), + // as for any egui widget: a root the clip cuts reports and reveals where it is, not where it shows. + let response = response::widget(ui, spec.id, spec.rect, sense); // Each edge or handle part that reaches outside the root rect gets its own widget, resolved as the root. let mut widgets = vec![spec.id, sub(spec.id, "transform")]; for part in spec.own.iter().filter(|part| reaches_out(spec.rect, part)) { let id = sub(spec.id, ("edge", part.key, part.index)); - response::widget(ui, id, part.shape.bounds().intersect(clip), part.sense); + response::widget(ui, id, part.shape.bounds(), part.sense); crate::runtime::egui::access::hide(ctx, id); widgets.push(id); } @@ -623,15 +666,16 @@ pub(crate) fn sense_root(ui: &Ui, spec: RootSpec<'_>) -> RootResult { let background = background_shape(spec.id, spec.rect, spec.own_sense | Sense::HOVER); pointer::record_widgets_in(ctx, read.viewport, layer, spec.id, &widgets, sense.contains(Sense::CLICK)); let info = RootInfo { id: spec.id, rect: spec.rect }; - journal_root(ctx, arena, info, spec.own, &widgets, (layer, sense)); + journal_root(ctx, arena, info, spec.own, &widgets, layer); // The parts last pass registered, which this pass's results read. let known = with_arena_in(ctx, read.viewport, arena, read.pass_nr, |state| { + rotate(state, read.pass_nr); + state.widens = spec.enabled; state.own.clear(); state.own.extend_from_slice(spec.own); state.root = Some(info); state.widgets = widgets; state.last_layer = Some(layer); - state.last_sense = sense; // A root that stepped early while it was not yet known to be inert: an open press ends as the disabled root's // would, by stepping again with the cancel. if !spec.enabled && state.early == read.pass_nr && state.outcome.is_some_and(|outcome| outcome.pass == read.pass_nr) { @@ -648,7 +692,7 @@ pub(crate) fn sense_root(ui: &Ui, spec: RootSpec<'_>) -> RootResult { std::iter::once(background).chain(own_shapes(spec.own, spec.id, read.target())), ); let mut response = response; - let outcome = outcome_in(ctx, &read, arena, layer, spec.enabled, sense); + let outcome = outcome_in(ctx, &read, arena, layer, spec.enabled); // The root is hovered while a shape of its arena shows hover (`pointer::Under`): its background, a part or a member; // it contains the pointer while any shape of the arena lies under it. response::hover_flags(&mut response, outcome.hover.any(), outcome.contains); @@ -699,7 +743,7 @@ pub(crate) fn place_over_widgets(ui: &Ui, id: Id, member: Option, decls let widgets: Vec = over_parts(decls) .map(|part| { let widget = over_widget(id, part); - response::widget(ui, widget, part.shape.bounds().intersect(clip), part.sense); + response::widget(ui, widget, part.shape.bounds(), part.sense); crate::runtime::egui::access::hide(ctx, widget); widget }) @@ -716,11 +760,38 @@ pub(crate) fn place_over_widgets(ui: &Ui, id: Id, member: Option, decls } } +/// The root `id`, once its body and `paint_over` have run, takes the senses of the members that joined its arena this +/// pass into its egui widget and its transformed body's forwarding widget (egui adds the sense of a widget registered +/// again in a pass), so egui's hit test in the next pass names the root wherever a member takes a press. A root whose +/// widget has no node (`hidden`) keeps it hidden. Nothing for a disabled root, which only hovers, or a root with no +/// arena this pass. +pub(crate) fn widen_root(ctx: &Context, id: Id, hidden: bool) { + let read = PassRead::of(ctx); + let found = PerViewport::::with(ctx, read.viewport, |arenas| { + arenas.by_root.get(&id).filter(|state| state.pass == read.pass_nr && state.widens).map(|state| (state.union_sense, state.last_layer)) + }); + let Some((union, Some(layer))) = found else { return }; + if union.is_empty() { + return; + } + let sense = response::to_egui(union); + if response::widen(ctx, id, sense) && hidden { + crate::runtime::egui::access::hide(ctx, id); + } + let forward = sub(id, "transform"); + if response::widen(ctx, forward, sense) { + crate::runtime::egui::access::hide(ctx, forward); + } + if union.contains(Sense::CLICK) { + pointer::record_widgets_in(ctx, read.viewport, layer, id, &[], true); + } +} + /// Step 8 for a root with no sense, no parts and no members: nothing can hit it, so it has no arena entry, shape /// record or press lifecycle, only its egui widget and its entry in the widget record. pub(crate) fn sense_none(ui: &Ui, id: Id, rect: Rect) -> RootResult { let ctx = ui.ctx(); - let response = response::widget(ui, id, rect.intersect(ui.clip_rect()), Sense::empty()); + let response = response::widget(ui, id, rect, Sense::empty()); pointer::record_widgets(ctx, ui.layer_id(), id, &[id, sub(id, "transform")], false); RootResult { response, parts: PartResults::new(), press: PressState::IDLE, activation: false, activated_member: None, sense: Sense::empty() } } @@ -815,9 +886,8 @@ fn press_view(outcome: &Outcome, holds: impl Fn(&Hit) -> bool, clicks: impl Fn(& } /// Runs the press lifecycle for this pass, once: later calls in the pass return the same outcome. A repeated -/// pass has no events, so phases hold and a release, click or activation does not repeat. `union_sense` is -/// what the root's egui widgets sense. -fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enabled: bool, union_sense: Sense) -> Outcome { +/// pass has no events, so phases hold and a release, click or activation does not repeat. +fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enabled: bool) -> Outcome { let pass_nr = read.pass_nr; let done = with_arena_in(ctx, read.viewport, arena, pass_nr, |state| state.outcome.filter(|outcome| outcome.pass == pass_nr)); if let Some(outcome) = done { @@ -863,12 +933,13 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab // is on top under it for that kind (`pointer::press_winners`); the root starts it for the kinds it won. A // root under a modal layer starts none; where egui names no target of the root's kind (its click target, // its drag target for a drag-only root; a root whose widgets sense neither is never named), only a root the - // modal's canvas admits does. + // modal's canvas admits does. The root's kind is what its widget sensed in the pass egui's targets come from. let root = state.root.map(|root| root.id); let targets = pass_pointer.press_targets; - let untargeted = if union_sense.contains(Sense::CLICK) { + let sensed = crate::runtime::egui::widgets::sensed_last_pass(ctx, arena.0); + let untargeted = if sensed.senses_click() { targets.click.is_none() - } else if union_sense.contains(Sense::DRAG) { + } else if sensed.senses_drag() { targets.drag.is_none() } else { true diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 275f41b19..248c09145 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -555,7 +555,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut }; // A secondary press inside the selection keeps the selection for the edit menu it opens, as native fields do; // egui's widget moves the caret to any press, so the selection from before the press is put back. - let secondary = crate::runtime::pointer::frame(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary); + let secondary = crate::runtime::pointer::frame_raw(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary); let kept = selection(ctx, widget).filter(|(caret, anchor)| secondary && caret != anchor); let shown = text_edit::show(input.ui, edit); crate::runtime::pointer::record_text_widget(ctx, widget, input.id); diff --git a/crates/ui-contract/src/primitives/textures/loader.rs b/crates/ui-contract/src/primitives/textures/loader.rs index 3b98ff466..8e05cf0ab 100644 --- a/crates/ui-contract/src/primitives/textures/loader.rs +++ b/crates/ui-contract/src/primitives/textures/loader.rs @@ -161,9 +161,9 @@ impl Default for Pools { /// 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 { store: TextureStore, diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 9957ba63d..1f80642c2 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -52,12 +52,17 @@ pub(crate) fn hide(ctx: &egui::Context, id: Id) { adapter::hide(ctx, id); } +/// Writes `position` into the node of `id`, which reported itself in this pass: the place its roving group's owner +/// gives it among the group's members of the pass. +pub(crate) fn write_set_position(ctx: &egui::Context, id: Id, position: SetPosition) { + adapter::write_set_position(ctx, id, position.index, position.size); +} + /// Takes the node of `id` out of what assistive technology reports and keeps its children in their place: a /// component whose type has a node and that reports none this pass (`Access::role`), with children that have theirs. pub(crate) fn pass_through(ctx: &egui::Context, id: Id) { adapter::pass_through(ctx, id); } - /// Reports `id` as the focused node of this pass. pub(crate) fn set_focus(ctx: &egui::Context, id: Id) { adapter::set_focus(ctx, id); diff --git a/crates/ui-contract/src/runtime/audit.rs b/crates/ui-contract/src/runtime/audit.rs new file mode 100644 index 000000000..a270f2654 --- /dev/null +++ b/crates/ui-contract/src/runtime/audit.rs @@ -0,0 +1,103 @@ +//! The replay audit (`CRAFT_UI_AUDIT_REPLAY=1`, test builds only): in a real pass, a memoized view that would replay +//! its kept run runs for real, and that run is compared with what the replay would have added. A difference panics, +//! naming the view and the first difference of each kind: a replay that differs from a real run is a view whose props +//! miss an input, or a registration the journal misses. +//! +//! A pass egui will discard paints nothing and keeps no record (`lazy::ran`): the audit skips it, and a view there +//! replays. +//! +//! The audit run keeps the kept run as it was, so every later pass compares with what a replay adds, and every decision +//! is the one the pass makes with the audit off. Only the outermost view that would replay runs: a view that would +//! replay inside an audit run replays, and the outer comparison covers that replay. The count trials' counters count +//! nothing inside an audit run (`runtime::measure`). + +use crate::runtime::egui::memory as store; +use crate::runtime::lazy::Output; +use crate::runtime::replay::{self, Record}; +use crate::runtime::shift::Shift; +use egui::{Context, Id, RecordShift, Rect}; +use std::collections::HashSet; + +/// How far apart, in points, the audit lets a coordinate of a replay and of the real run lie +/// (`Shift::snapped`, `PassRecords::first_difference`): a record moved by a whole pixel from positions off the float +/// grid differs from the run at the new place by rounding only, far less than this; ids, counts, colours, text and +/// every other float compare exactly. +pub(crate) const WITHIN: f32 = 1.0 / 256.0; + +/// Whether two outputs of a memoized view are equal: both of its output type, and `==` within `WITHIN`. +pub(crate) type SameOutput = fn(&Output, &Output, &RecordShift) -> bool; + +/// The audit's switch for one context and the views it named. +#[derive(Default)] +struct Audit { + /// `None` until read: then `CRAFT_UI_AUDIT_REPLAY=1`, unless a test set it (`testing::audit_replays`). + on: Option, + /// The views named for painting a paint callback. + named: HashSet<&'static str>, +} + +/// Whether the audit runs in `ctx`. +pub(crate) fn on(ctx: &Context) -> bool { + store::with::(ctx, |audit| *audit.on.get_or_insert_with(|| std::env::var("CRAFT_UI_AUDIT_REPLAY").is_ok_and(|value| value == "1"))) +} + +/// Turns the audit on or off in `ctx`, in place of `CRAFT_UI_AUDIT_REPLAY`. +pub fn set(ctx: &Context, on: bool) { + store::with::(ctx, |audit| audit.on = Some(on)); +} + +/// Whether the code running in `ctx` is a run of the audit: a test that counts its own runs of a view counts none in +/// it, as the framework's counters do. +pub fn in_run(ctx: &Context) -> bool { + replay::in_audit_run(ctx) +} + +/// Whether a view that would replay here runs for the audit: the audit is on, and no audit run is around it. +pub(crate) fn runs(ctx: &Context) -> bool { + on(ctx) && !replay::in_audit_run(ctx) +} + +/// Whether the kept output `kept`, as a replay at the place `shift` names returns it, equals `run`'s, as `R`. +pub(crate) fn same(kept: &Output, run: &Output, shift: &RecordShift) -> bool { + match (kept.downcast_ref::(), run.downcast_ref::()) { + (Some(kept), Some(run)) => kept.shifted(shift).snapped(run, WITHIN) == *run, + _ => false, + } +} + +/// What a view's kept run, or its audit run, added and returned. +pub(crate) struct Shown<'a> { + pub(crate) record: &'a Record, + pub(crate) rect: Rect, + pub(crate) output: Option<&'a Output>, +} + +/// Compares the audit run `run` of the view `name` (`id`) with its kept run `kept` replayed at the place `shift` names, +/// and panics on a difference. +pub(crate) fn compare(name: &'static str, id: Id, (kept, shift): (Shown<'_>, &RecordShift), run: Shown<'_>, same: Option) { + let mut found = Vec::new(); + let kept_rect = shift.rect(kept.rect).snapped(&run.rect, WITHIN); + if kept_rect != run.rect { + found.push(format!("rect: left {:?} / right {:?}", kept_rect, run.rect)); + } + found.extend(kept.record.differences(run.record, shift)); + let output = match (kept.output, run.output, same) { + (Some(kept), Some(run), Some(same)) => same(kept, run, shift), + (kept, run, _) => kept.is_none() == run.is_none(), + }; + if !output { + found.push("output: the run returned another output than the kept one".to_owned()); + } + assert!( + found.is_empty(), + "replay audit: memoized view `{name}` ({id:?}) differs from its real run (left: the replay, right: the run):\n {}", + found.join("\n ") + ); +} + +/// Names the view `name` once in `ctx` when its real run `record` painted a paint callback: it runs every pass. +pub(crate) fn name_callback(ctx: &Context, name: &'static str, record: &Record) { + if record.paints_callback() && store::with::(ctx, |audit| audit.named.insert(name)) { + eprintln!("replay audit: memoized view `{name}` paints a paint callback, so it runs every pass"); + } +} diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 0d7f58fbb..e80cfddde 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -123,6 +123,8 @@ pub(crate) struct Board { /// The commands the app defines at run time, from this frame's input. app: Option, keymap: Option, + /// How many keymaps the board built: the keymap's generation (`runtime::inputs::Input::Keymap`). + keymaps: u64, gate: Option, /// The gate's answers under its current key, by command key (`CommandRef::key`). The gate is a `fn` of its props, /// so the board asks it once per command until the key moves, whichever readers, passes and frames resolve it. @@ -143,8 +145,6 @@ pub(crate) struct Board { state_log: Vec<(u64, StateKey)>, /// The generations of the inputs every resolution reads and of the focus vantage. gens: Gens, - /// 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, /// App-scope commands for the next `FrameOutput`. @@ -183,14 +183,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() @@ -470,7 +462,7 @@ fn focused_edits(ctx: &Context, viewport: ViewportId) -> Option<(EditSet, EditSe } /// Notes, in the read record, that the running code showed a resolution under `key` (a state's, or the focused stop's -/// answer): a settled region that showed it runs when `begin` resolves the command from the same reader to something +/// answer): a 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, an instance or the stop's edits changed), and a change published after it in /// the pass runs the pass again. fn note_read(ctx: &Context, key: Option) { @@ -1049,7 +1041,6 @@ fn platform(ctx: &Context) -> Platform { /// 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| { // A published state resolves from this frame's, else the last frame's: one published last frame and not again @@ -1102,13 +1093,13 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text }); board.gens.shared += 1; + board.keymaps += 1; for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); } } } - board.changed = (frame, InputChanges { keymap: stale }); shadowed }); for id in shadowed { @@ -1122,13 +1113,25 @@ pub(crate) fn edit_chords(ctx: &Context) -> Arc<[(EditCommand, Chord)]> { with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.edit_chords)).unwrap_or_default()) } +/// The generation of the window's keymap: it moves each time a new keymap is built. +pub(crate) fn keymap_generation(ctx: &Context) -> u64 { + with(ctx, |board| board.keymaps) +} + +/// Whether the queue holds a command for one of `instances`: only a run of the view they registered in takes it. +pub(crate) fn queued_for(ctx: &Context, instances: &[Id]) -> bool { + !instances.is_empty() && with(ctx, |board| board.queue.iter().any(|fired| fired.target.is_some_and(|target| instances.contains(&target)))) +} + /// The bindings the window's keymap gives `command`; none before the first frame builds one. pub(crate) fn bindings(ctx: &Context, command: &CommandRef) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); with(ctx, |board| board.keymap.as_ref().map(|cache| cache.keymap.bindings(command)).unwrap_or_default()) } /// The chord the window's keymap shows for `command` (`Keymap::shown_chord`); none before the first frame builds one. pub(crate) fn chord(ctx: &Context, command: &CommandRef) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); with(ctx, |board| board.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command))) } @@ -1140,6 +1143,7 @@ pub fn keymap(ctx: &Context) -> Option> { /// The command that holds `chord` in the window's keymap (`Keymap::holder`); none before the first frame builds one. pub(crate) fn holder(ctx: &Context, chord: &Chord) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); with(ctx, |board| board.keymap.as_ref().and_then(|cache| cache.keymap.holder(chord))) } @@ -1168,6 +1172,7 @@ pub(crate) fn take_delivered(ctx: &Context) -> Vec { /// Whether the component that holds key focus sits inside the instance `id`. #[doc(hidden)] pub fn focus_within(ctx: &Context, id: Id) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Focus); with(ctx, |board| board.here.focused.iter().any(|(_, chain)| chain.contains(&id))) } @@ -1179,6 +1184,7 @@ pub(crate) fn register_instance(ctx: &Context, scope: CommandScope, id: Id) { /// `register_instance` in the layer `layer`, which a replay of the registration keeps. fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| register_in(ctx, scope, id, layer)); + crate::runtime::replay::note_instance(ctx, id); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); with(ctx, |board| { @@ -1346,6 +1352,8 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma /// `command` as `reader` is shown it, noted as its read: the kept resolution while its inputs are unchanged, else a new /// one, kept. fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> Arc { + // The resolved command carries the chord the keymap shows, kept or made now. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); let viewport = pass::current_viewport(ctx); let vantage = vantage_of(ctx, &reader); let edits = focused_edits(ctx, viewport); @@ -1422,8 +1430,8 @@ fn resolve_once(ctx: &Context, command: &CommandRef, instance: Option, reach /// fx.F23: resolves again what a reader of `viewport` was shown when an input of it changed since the viewport's last /// wake, from that reader's own vantage under this pass's gate, states, modal facts and instances, and notes an edit of /// the key each was read under when its 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 walks only the entries whose inputs +/// 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 walks only the entries whose inputs /// moved, through the table's indexes: every entry when a generation all of them read moved (the shared one, the /// viewport's keys, the gate), else the readers of the focus, of the focused stop's edits and of each changed state, /// and the readers under a layer or in a menu, whose vantage it reads again. A second pass of a frame compares against @@ -1614,7 +1622,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 @@ -1783,10 +1791,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); diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 30ba60754..c53e067da 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -34,6 +34,7 @@ pub use board::{bound_around, take_around}; #[doc(hidden)] pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; +pub(crate) use board::{keymap_generation, queued_for}; use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked}; use craft_behavior::CommandFlags; @@ -450,6 +451,8 @@ impl CommandInput { #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct CommandChain(Arc<[(CommandScope, Id)]>); +crate::stays!(CommandChain, CommandState, CommandRef, CommandScope); + impl CommandChain { pub(crate) fn pushed(&self, scope: CommandScope, id: Id) -> Self { CommandChain(self.0.iter().copied().chain([(scope, id)]).collect()) @@ -565,6 +568,16 @@ pub fn resolve(ctx: &Context, command: impl Into) -> Arc impl Fn(CommandRef) -> Option> + 'static { + let ctx = ui.ctx().clone(); + let chain = crate::runtime::env::Env::of(ui).view().command_chain().clone(); + move |command| board::resolve_scoped(&ctx, &chain, &command) +} + /// The keys `command` has in the runtime's keymap: its defaults under the user's overrides (`CommandInput`), on the /// window's platform, double presses included. Empty before the first frame. pub fn bindings(ctx: &Context, command: &CommandRef) -> Vec { diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index fdfea4948..0f109e029 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -74,6 +74,33 @@ pub enum DropMark { }, } +crate::stays!(Arc); + +impl crate::runtime::Shift for DropMark { + fn shifted(&self, by: &egui::RecordShift) -> Self { + self.mapped(|point| by.pos(point)) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + let pos = |value: Pos2, to: Pos2| crate::runtime::Shift::snapped(&value, &to, within); + let rect = |value: Rect, to: Rect| Rect::from_min_max(pos(value.min, to.min), pos(value.max, to.max)); + match (self, to) { + (DropMark::Line { from, to: end }, DropMark::Line { from: to_from, to: to_end }) => { + DropMark::Line { from: pos(*from, *to_from), to: pos(*end, *to_end) } + } + (DropMark::Into(target), DropMark::Into(to_target)) => DropMark::Into(rect(*target, *to_target)), + (DropMark::Region { area, line }, DropMark::Region { area: to_area, line: to_line }) => DropMark::Region { + area: rect(*area, *to_area), + line: match (line, to_line) { + (Some([a, b]), Some([to_a, to_b])) => Some([pos(*a, *to_a), pos(*b, *to_b)]), + _ => *line, + }, + }, + _ => *self, + } + } +} + impl DropMark { /// An insertion line from `from` to `to`. pub const fn line(from: Pos2, to: Pos2) -> Self { @@ -328,12 +355,14 @@ pub fn amend(ctx: &Context, change: impl FnOnc /// The active drag payload of type `P`, from any viewport. For code without a `Cx`. pub fn active(ctx: &Context) -> Option> { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Drag); active_of(ctx, TypeId::of::

())?.downcast::

().ok() } /// The active drag payload whose type is `payload`: the session's own payload, else its `also`. For a target that /// picks the payload types it takes at run time. pub(crate) fn active_of(ctx: &Context, payload: TypeId) -> Option> { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Drag); let (own, also) = board(ctx, |board| board.session.as_ref().map(|session| (session.payload.clone(), session.also.clone())))?; if Any::type_id(&*own) == payload { return Some(own); @@ -344,9 +373,21 @@ pub(crate) fn active_of(ctx: &Context, payload: TypeId) -> Option u64 { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Drag); board(ctx, |board| board.started) } +/// What a drag reader sees of the session, as the tracked input `Drag` compares it: the sessions started, and the +/// payloads of the running one. +pub(crate) fn state(ctx: &Context) -> (u64, Option<(usize, Option)>) { + board(ctx, |board| { + let payloads = board.session.as_ref().map(|session| { + (Arc::as_ptr(&session.payload) as *const () as usize, session.also.as_ref().map(|also| Arc::as_ptr(also) as *const () as usize)) + }); + (board.started, payloads) + }) +} + /// The mark of the target that would take a drop now. #[doc(hidden)] pub fn mark(ctx: &Context) -> Option { @@ -374,7 +415,7 @@ pub fn cancel(ctx: &Context, reason: CancelReason) { /// The begin hook: the window losing focus ends the session. pub(crate) fn begin(ctx: &Context) { - if source_viewport(ctx) == Some(pass::current_viewport(ctx)) && pointer::with_pass_pointer(ctx, |pointer| pointer.focus_lost) { + if source_viewport(ctx) == Some(pass::current_viewport(ctx)) && pointer::with_pass_raw(ctx, |pointer| pointer.focus_lost) { cancel(ctx, CancelReason::Blur); } os_files(ctx); @@ -460,7 +501,7 @@ pub fn cross_window_pointer(ctx: &Context, viewport: ViewportId) -> Option pub(crate) fn dragging_of(ctx: &Context, payload: TypeId) -> Option<(Arc, Pos2)> { let payload = active_of(ctx, payload)?; let os = board(ctx, |board| board.session.as_ref().is_some_and(|session| session.os)); - let frame = pointer::frame(ctx).pos; + let frame = pointer::frame_raw(ctx).pos; let host = WindowHost::of(ctx); let pointer = if os && host.desktop_pointer().is_some() { host.pointer_in(pass::current_viewport(ctx)) } else { frame }; Some((payload, pointer?)) @@ -537,7 +578,7 @@ pub fn next_ordinal(ctx: &Context, owner: Id) -> u32 { /// The operation the held modifiers pick now. pub(crate) fn current_operation(ctx: &Context) -> DropOperation { - operation(ctx, pointer::frame(ctx).mods) + operation(ctx, pointer::frame_raw(ctx).mods) } /// Whether the session's button was released in this pass. @@ -549,7 +590,7 @@ fn released(ctx: &Context) -> bool { if os { return board(ctx, |board| board.session.as_ref().is_some_and(|session| session.dropped == Some(frame))); } - pointer::frame(ctx).release == Some(button) + pointer::frame_raw(ctx).release == Some(button) || board(ctx, |board| board.session.as_ref().is_some_and(|session| session.released.is_some() && session.viewport != viewport)) } @@ -667,9 +708,9 @@ pub(crate) fn end_pass(ctx: &Context) { best.map(|(_, mark)| mark) }); let op = current_operation(ctx); - let over_this_window = pointer::frame(ctx).pos.is_some(); - let primary_down = pointer::with_pass_pointer(ctx, |pointer| pointer.primary_down); - let buttons = pointer::frame(ctx).buttons; + let over_this_window = pointer::frame_raw(ctx).pos.is_some(); + let primary_down = pointer::with_pass_raw(ctx, |pointer| pointer.primary_down); + let buttons = pointer::frame_raw(ctx).buttons; let frame = pass::root_frame_nr(ctx); let held = board(ctx, |board| board.session.as_ref().map(|session| (session.os, session.button, session.dropped))).is_none_or( |(os, button, dropped)| match (os, button) { @@ -681,7 +722,7 @@ pub(crate) fn end_pass(ctx: &Context) { let source = source_viewport(ctx); let is_source = source == Some(viewport); if is_source { - windows::note_source_pointer(ctx, viewport, pointer::frame(ctx).pos); + windows::note_source_pointer(ctx, viewport, pointer::frame_raw(ctx).pos); } let foreign_target = is_source && !held && foreign_winner(ctx, viewport); let running = board(ctx, |board| { diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 29a36ecf4..4b482d982 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -17,7 +17,7 @@ use super::{memory, pass}; pub use accesskit::TreeUpdate; pub(crate) use node::{NodeAction, NodeSpec, Toggle, write_node}; -pub(crate) use patch::{write_label_patch, write_merge_patch, write_status}; +pub(crate) use patch::{write_label_patch, write_merge_patch, write_set_position, write_status}; pub(crate) use text::{ NodeEnd, RunLink, RunNode, TextNode, fold_widget, is_text_request, requested_selection, requested_value, write_run, write_selection, write_text, }; diff --git a/crates/ui-contract/src/runtime/egui/access/patch.rs b/crates/ui-contract/src/runtime/egui/access/patch.rs index b820ae389..64fcf0533 100644 --- a/crates/ui-contract/src/runtime/egui/access/patch.rs +++ b/crates/ui-contract/src/runtime/egui/access/patch.rs @@ -78,6 +78,17 @@ pub(crate) fn write_merge_patch(ctx: &Context, patch: &MergePatch) { }); } +/// Writes the place in its set of the node `id`, which the node's own report left to its roving group. +pub(crate) fn write_set_position(ctx: &Context, id: Id, index: usize, size: Option) { + ctx.accesskit_node_builder(id, |node| { + node.set_position_in_set(index); + match size { + Some(size) => node.set_size_of_set(size), + None => node.clear_size_of_set(), + } + }); +} + /// The status node `id`: one live node holding `text`, none while there is nothing to say. pub(crate) fn write_status(ctx: &Context, id: Id, text: &str, assertive: bool) { crate::runtime::egui::widgets::note_node(ctx, id); diff --git a/crates/ui-contract/src/runtime/egui/response.rs b/crates/ui-contract/src/runtime/egui/response.rs index 70685a79f..3a4a3bedc 100644 --- a/crates/ui-contract/src/runtime/egui/response.rs +++ b/crates/ui-contract/src/runtime/egui/response.rs @@ -31,10 +31,12 @@ pub(crate) fn to_egui(sense: Sense) -> egui::Sense { mapped } -/// A root's egui widget over `rect`, clipped by the caller. egui gives a widget of a disabled `Ui` no focus stop and -/// drops the focus it holds; the sense the pipeline passes decides whether the root is a stop (a disabled control with -/// a reason is), so the stop and the focus are kept here. +/// A root's egui widget over `rect`; egui clips its interact rect. egui gives a widget of a disabled `Ui` no focus stop +/// and drops the focus it holds; the sense the pipeline passes decides whether the root is a stop (a disabled control +/// with a reason is), so the stop and the focus are kept here. A rect that is not a number is at no place +/// (`Rect::NOTHING`): egui takes no such rect, and nothing can hit it. pub(crate) fn widget(ui: &Ui, id: Id, rect: Rect, sense: Sense) -> Response { + let rect = if rect.any_nan() { Rect::NOTHING } else { rect }; let ctx = ui.ctx(); let held = ctx.memory(|memory| memory.has_focus(id)); let response = ui.interact(rect, id, to_egui(sense)); @@ -49,6 +51,22 @@ pub(crate) fn widget(ui: &Ui, id: Id, rect: Rect, sense: Sense) -> Response { response } +/// Adds `sense` to the egui widget `id` the running pass registered, at its rect: egui ORs the senses of a widget +/// registered again in a pass. Returns whether the widget took a sense it lacked; nothing for a widget the pass has +/// not registered, or one with no area inside its clip, which egui's hit test never names. +pub(crate) fn widen(ctx: &egui::Context, id: Id, sense: egui::Sense) -> bool { + let registered = ctx.viewport(|viewport| viewport.this_pass.widgets.get(id).map(|widget| (widget.sense, widget.interact_rect))); + let Some((has, rect)) = registered else { return false }; + if has.contains(sense) || !(rect.is_positive() && rect.is_finite()) { + return false; + } + // `read_response` answers from the running pass for a registered widget with a positive rect. + ctx.read_response(id).is_some_and(|response| { + let _ = response.interact(sense); + true + }) +} + /// Whether a pointer button went down on `response`'s widget and is still down. pub(crate) fn is_pressed(response: &Response) -> bool { response.is_pointer_button_down_on() diff --git a/crates/ui-contract/src/runtime/egui/widgets.rs b/crates/ui-contract/src/runtime/egui/widgets.rs index f5e916732..6bf6f57ca 100644 --- a/crates/ui-contract/src/runtime/egui/widgets.rs +++ b/crates/ui-contract/src/runtime/egui/widgets.rs @@ -41,12 +41,20 @@ pub(crate) fn above(ctx: &Context, below: Id, skip: &[Id]) -> Vec { found } +/// The sense of the widget `id` in the last finished pass, whose widget rects egui's hit test reads for the running +/// pass's press targets. Hover only when that pass did not show `id`. +pub(crate) fn sensed_last_pass(ctx: &Context, id: Id) -> egui::Sense { + ctx.widget_rect_last_pass(id).map_or(egui::Sense::hover(), |widget| widget.sense) +} + /// An egui widget the runtime makes for a purpose no component registers (a scrim that absorbs presses). #[cfg(feature = "testing")] pub(crate) fn note_widget(ctx: &Context, id: Id) { noted::with(ctx, |pass| { pass.widgets.insert(id); }); + // A replayed run notes it again, as it adds the widget again. + crate::runtime::replay::journal(ctx, || id, |ctx, &id| note_widget(ctx, id)); } #[cfg(not(feature = "testing"))] @@ -58,6 +66,8 @@ pub(crate) fn note_node(ctx: &Context, id: Id) { noted::with(ctx, |pass| { pass.nodes.insert(super::access::node_key(id)); }); + // A replayed run notes it again, as it adds the node again. + crate::runtime::replay::journal(ctx, || id, |ctx, &id| note_node(ctx, id)); } #[cfg(not(feature = "testing"))] @@ -76,6 +86,12 @@ pub(crate) struct ScrollRegion { #[cfg(feature = "testing")] pub(crate) fn note_scroll_region(ctx: &Context, view: Rect, content: Rect) { noted::with(ctx, |pass| pass.scrolls.push(ScrollRegion { view, content })); + // The view cuts what lies outside it, as a clip does: a replay cut by the clip around it cuts the view too. + crate::runtime::replay::journal( + ctx, + || (crate::runtime::Clip::new(view), content), + |ctx, &(view, content)| note_scroll_region(ctx, view.rect(), content), + ); } #[cfg(not(feature = "testing"))] diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index ca4c67570..38a7d029b 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -89,6 +89,8 @@ pub struct Scoped { /// The key of everything above that the style cache depends on. #[doc(hidden)] pub key: EnvKey, + /// The key of what a memoized view shown in the scope inherits beyond `key` (`scope_key`), once a view asked. + scope_key: std::sync::OnceLock, /// Ambient control size; the root default is `Md`. pub size: ControlSize, /// How the icon-only buttons of the scope show their glyph; the root default and a layer's is `Control`. @@ -235,6 +237,8 @@ pub struct Inherited { pub(crate) host: Option>, #[doc(hidden)] pub values: AppValues, + /// The context the env was built in: the accessors of tracked inputs note their reads into its records. + pub(crate) ctx: Context, } impl Deref for Scoped { @@ -372,13 +376,14 @@ impl Scoped { self.inherited_mut().values.set(InBar(false)); } - /// Ends the layout room of the enclosing body: its flow grid and content column. + /// Ends the layout room of the enclosing body: its flow grid and content column. The axes the body sizes from its + /// content stay (`content`): like `cell_fills` and `least`, they say what a child that fills takes there, its + /// measured size or the room, and the scope key holds them. pub(crate) fn start_room(&mut self) { self.grid = None; self.grid_top = false; self.content_column = false; self.given_column = false; - self.content = (false, false); self.row_room = None; self.row_line = None; self.first_line = None; @@ -389,6 +394,40 @@ impl Scoped { self.offered = None; } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its + /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the + /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line + /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The + /// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own + /// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then. + pub(crate) fn scope_key(&self) -> u128 { + *self.scope_key.get_or_init(|| { + use crate::contract::{MemoKey, MemoProps as _}; + let mut key = MemoKey::of_view(&self.ctx); + key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel)); + key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded, self.content)); + key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view)))); + self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key); + self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key); + self.measure.key(&mut key); + // State a key cannot follow, rebuilt each pass: a view under it runs in every pass. + if self.item_facts.is_some() || self.inside_label.is_some() { + key.changes_every_pass(); + } + for id in self.commands.ids() { + id.key(&mut key); + } + key.feed_hash(&(std::mem::discriminant(&self.motion.mode), self.canvas_pattern, self.tab_toggles_chrome, self.today)); + (&self.format, &self.dates, &self.host).key(&mut key); + let value_bytes = self.values.key(&mut key); + #[cfg(feature = "testing")] + crate::runtime::measure::count_memo_key_bytes(&self.ctx, key.bytes() + value_bytes); + #[cfg(not(feature = "testing"))] + let _ = value_bytes; + key.finish() + }) + } + /// The facts the collection recorded for the item `id`. pub(crate) fn facts_of(&self, id: Id) -> Option<&ItemFacts> { self.item_facts.as_deref().filter(|facts| facts.item == id) @@ -463,6 +502,9 @@ impl Env { let shell = Arc::new(windows::shell_of(ctx, pass::current_viewport(ctx))); let active = shell.window.active; let keyboard = Arc::new(crate::runtime::keys::layout_of(ctx)); + // The window facts and the layout are tracked inputs: a view that read them runs when they change. + crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, (*shell).clone()); + crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Keyboard, (*keyboard).clone()); let words = host_words(ctx, host.as_ref()); let key = EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash()) .with_line(line_ratio) @@ -488,8 +530,10 @@ impl Env { canvas_pattern: root.canvas_pattern, host, values: root.values.clone(), + ctx: ctx.clone(), }), key, + scope_key: std::sync::OnceLock::new(), ink: Ink::default(), surface: SurfaceKind::Background, size: ControlSize::Md, @@ -534,7 +578,7 @@ impl Env { /// The env of `ui`: the nearest entry up the `Ui` stack, else the running viewport's root env, so the `Ui` /// of an egui `Area` or `Window` reads the app's root values. For app panels (layer 8) and caller closures only. /// - /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`. + /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes. pub fn of(ui: &Ui) -> Env { let ctx = ui.ctx(); let viewport = pass::current_viewport(ctx); @@ -542,7 +586,9 @@ impl Env { stack::nearest(ui, |node| envs.entries.get(&node).cloned()).or_else(|| envs.root.clone()) }); let env = found.unwrap_or_else(|| Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx))); - if style::is_enabled(ui) { env } else { env.derive_local(|s| s.enabled = false) } + // egui's `invisible()` also disables the `Ui`, and a sizing `Ui` is invisible, not disabled: in a sizing pass + // the env keeps the enabled state the real run has, so a memoized view keys alike in both. + if style::is_enabled(ui) || ui.is_sizing_pass() { env } else { env.derive_local(|s| s.enabled = false) } } /// The running viewport's root env: what code with no `Ui` (the ghost layer) paints with. @@ -584,6 +630,7 @@ impl Env { pub(crate) fn derive(&self, f: impl FnOnce(&mut Scoped)) -> Env { let mut scoped = (*self.scoped).clone(); f(&mut scoped); + scoped.scope_key = std::sync::OnceLock::new(); scoped.key = EnvKey::new(scoped.tokens.key(), scoped.direction, scoped.scale, scoped.os, scoped.active, scoped.values.style_hash()) .with_line(scoped.line_ratio) .with_words(scoped.words.generation()); @@ -607,6 +654,7 @@ impl Env { pub(crate) fn derive_local(&self, f: impl FnOnce(&mut Scoped)) -> Env { let mut scoped = (*self.scoped).clone(); f(&mut scoped); + scoped.scope_key = std::sync::OnceLock::new(); Env { scoped: Arc::new(scoped) } } diff --git a/crates/ui-contract/src/runtime/env/app_values.rs b/crates/ui-contract/src/runtime/env/app_values.rs index 35e0f58a4..41cb894ea 100644 --- a/crates/ui-contract/src/runtime/env/app_values.rs +++ b/crates/ui-contract/src/runtime/env/app_values.rs @@ -1,12 +1,14 @@ //! App-defined env values: EnvValue, StyleValue and AppValues. +use crate::contract::{MemoKey, MemoProps}; use std::any::{Any, TypeId}; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Arc; -/// An app-defined value inherited down the tree like the library's own. -pub trait EnvValue: Clone + PartialEq + Send + Sync + 'static { +/// An app-defined value inherited down the tree like the library's own. `MemoProps`, because a memoized view under a +/// scope that sets it keys on it (`MemoView`): its key follows every value the view can read. +pub trait EnvValue: Clone + PartialEq + MemoProps + Send + Sync + 'static { /// A value that changes how components look is folded into the style key, so cached styles follow it. const AFFECTS_STYLE: bool = false; @@ -31,9 +33,20 @@ pub struct AppValues { entries: Arc, } +/// Feeds the value behind an entry into a key. +type Keyer = fn(&(dyn Any + Send + Sync), &mut MemoKey); + +fn keyer(value: &(dyn Any + Send + Sync), key: &mut MemoKey) { + if let Some(value) = value.downcast_ref::() { + value.key(key); + } +} + #[derive(Clone, Default)] struct ValueEntries { map: HashMap>, + /// How each value feeds a key, by type. + keyers: HashMap, /// The hash of each style-affecting value, by type. style: HashMap, /// The hash of every style-affecting value, independent of the order they were set in. @@ -68,6 +81,7 @@ impl AppValues { None => entries.style.remove(&TypeId::of::()), }; entries.map.insert(TypeId::of::(), Arc::new(value)); + entries.keyers.insert(TypeId::of::(), keyer::); entries.rehash(); self } @@ -77,6 +91,22 @@ impl AppValues { self.entries.style_hash } + /// Feeds every value into `key`, independent of the order they were set in: each value keys its own `MemoKey` (of + /// `key`'s view), and the sum of those keys is fed. Returns the bytes the values fed. + pub(crate) fn key(&self, key: &mut MemoKey) -> usize { + let (mut sum, mut bytes) = (0u128, 0); + for (ty, value) in &self.entries.map { + let Some(keyer) = self.entries.keyers.get(ty) else { continue }; + let mut one = key.child(); + one.feed_hash(ty); + keyer(&**value, &mut one); + sum = sum.wrapping_add(one.finish()); + bytes += one.bytes(); + } + key.write(&sum.to_le_bytes()); + bytes + } + /// A clone of the value, else `T::root()`. pub(crate) fn get(&self) -> T { self.entries.map.get(&TypeId::of::()).and_then(|value| value.downcast_ref::()).cloned().unwrap_or_else(T::root) @@ -92,6 +122,9 @@ impl AppValues { let entries = Arc::make_mut(&mut self.entries); for (ty, value) in &other.entries.map { entries.map.insert(*ty, Arc::clone(value)); + if let Some(keyer) = other.entries.keyers.get(ty) { + entries.keyers.insert(*ty, *keyer); + } match other.entries.style.get(ty) { Some(hash) => entries.style.insert(*ty, *hash), None => entries.style.remove(ty), diff --git a/crates/ui-contract/src/runtime/env/host_words.rs b/crates/ui-contract/src/runtime/env/host_words.rs index 650d3e121..1cf5091d2 100644 --- a/crates/ui-contract/src/runtime/env/host_words.rs +++ b/crates/ui-contract/src/runtime/env/host_words.rs @@ -7,31 +7,27 @@ use craft_i18n::{WordRows, Words}; use egui::Context; use std::sync::Arc; -/// The words of the installed `Host`, kept until the `Host` changes so that the word sets built from them are -/// built once. +/// The words of the installed `Host`, kept until another host is installed (`Host::generation`; `None` without a +/// host) so that the word sets built from them are built once. #[derive(Default)] struct HostWords { - host: Option>, - words: Option>, + words: Option<(Option, Arc)>, } /// The catalogs of `host` in its language, English without a host or a catalog. pub(super) fn host_words(ctx: &Context, host: Option<&Arc>) -> Arc { + let generation = host.map(|host| host.generation()); Service::::run(ctx, |cached| { - let same = match (&cached.host, host) { - (Some(kept), Some(host)) => std::sync::Weak::ptr_eq(kept, &Arc::downgrade(host)), - (None, None) => true, - _ => false, - }; - if let (true, Some(words)) = (same, &cached.words) { + if let Some((kept, words)) = &cached.words + && *kept == generation + { return Arc::clone(words); } let words = Arc::new(match host.and_then(|host| host.i18n_shared().map(|i18n| (Arc::clone(i18n), host.lang()))) { Some((i18n, lang)) => Words::from_i18n(i18n, lang), None => Words::english(), }); - cached.host = host.map(Arc::downgrade); - cached.words = Some(Arc::clone(&words)); + cached.words = Some((generation, Arc::clone(&words))); words }) } diff --git a/crates/ui-contract/src/runtime/env/shell.rs b/crates/ui-contract/src/runtime/env/shell.rs index 377016d08..c32a56f0d 100644 --- a/crates/ui-contract/src/runtime/env/shell.rs +++ b/crates/ui-contract/src/runtime/env/shell.rs @@ -2,10 +2,12 @@ //! carries them to the slots and the body. use super::{AppValues, EnvValue}; +use crate::runtime::egui::pass; +use crate::runtime::frame::{PerViewport, Stamped, Stored}; use egui::Rect; use std::fmt; +use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; -use std::sync::{Arc, Mutex}; /// The stable key of a slot. pub type SlotKey = &'static str; @@ -123,14 +125,16 @@ struct Inner { regions: ShellRegions, float_bounds: Rect, region: Option, - revealed_rects: RevealedRects, + /// The key of the shell's revealed rects: the same in every pass of the shell, so a replayed view registers its + /// rects for the shell that shows it. + reveals: egui::Id, dialog: DialogRecord, page_band: Option, } /// The room of the page band while a full-window page shows: the title-bar-high strip at the window's top and the room /// the window's ends take in it. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub struct PageBandRoom { /// The band's rect. @@ -149,15 +153,24 @@ impl PageBandRoom { } } -/// The rects that body content registered this pass for the edge it was revealed from. The registry is shared by the -/// clones of one `ShellCx`. -#[derive(Clone, Debug, Default)] -struct RevealedRects(Arc>>); +/// The rects that content registered on the running pass of a viewport for the edge it was revealed from, each with +/// the key of its shell. +#[derive(Default)] +struct RevealedRects(Vec<(egui::Id, RevealEdge, Rect)>); -impl PartialEq for RevealedRects { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } +impl Stored for RevealedRects {} + +fn with_revealed(ctx: &egui::Context, f: impl FnOnce(&mut RevealedRects) -> R) -> R { + let viewport = pass::current_viewport(ctx); + PerViewport::>::with_pass(ctx, viewport, pass::pass_nr(ctx, viewport), |rects, _| rects.0.clear(), f) +} + +crate::stays!(RevealEdge); + +/// Registers `rect` for `edge` with the shell keyed `reveals`, on the running pass. A replayed view registers it again. +fn note_reveal(ctx: &egui::Context, reveals: egui::Id, edge: RevealEdge, rect: Rect) { + crate::runtime::replay::journal(ctx, || (reveals, edge, rect), |ctx, &(reveals, edge, rect)| note_reveal(ctx, reveals, edge, rect)); + with_revealed(ctx, |rects| rects.0.push((reveals, edge, rect))); } /// How many dialogs, modals and windows the body showed on this pass. The record is shared by the clones of one @@ -176,6 +189,7 @@ impl ShellCx { /// mode allows and floating frames may go over the body. pub fn new(window: WindowKey, mode: BodyMode, regions: ShellRegions) -> Self { let float_bounds = regions.body; + let reveals = crate::runtime::memory::global("shell reveals", &window); let inner = Inner { window, mode, @@ -186,7 +200,7 @@ impl ShellCx { regions, float_bounds, region: None, - revealed_rects: RevealedRects::default(), + reveals, dialog: DialogRecord::default(), page_band: None, }; @@ -278,17 +292,28 @@ impl ShellCx { !self.inner.panels_hidden && (self.inner.mode == BodyMode::Normal || self.inner.tab_reveal) } + /// The same skeleton with its revealed rects registered under `id`, which stays the same across passes. Without + /// it they are keyed by the window; `AppShell` passes its own id, so an embedded shell keeps its rects apart from + /// the shell of the window around it. + #[must_use] + pub fn with_reveals_key(mut self, id: egui::Id) -> Self { + Arc::make_mut(&mut self.inner).reveals = id; + self + } + /// Registers `rect`, a revealed panel the body drew on this pass, as part of the revealed `edge`: the edge reveal - /// lasts while the pointer is over it, as it does over a revealed slot. Call it in the pass that draws the panel. - pub fn reveal_rect(&self, edge: RevealEdge, rect: Rect) { - if let Ok(mut rects) = self.inner.revealed_rects.0.lock() { - rects.push((edge, rect)); + /// lasts while the pointer is over it, as it does over a revealed slot. Call it in the pass that draws the panel; a + /// memoized view that replays registers it again. A measuring run registers nothing. + pub fn reveal_rect(&self, ctx: &egui::Context, edge: RevealEdge, rect: Rect) { + if crate::runtime::measure::effect(ctx, "shell::reveal_rect") { + note_reveal(ctx, self.inner.reveals, edge, rect); } } /// The rects registered with [`reveal_rect`](Self::reveal_rect) on this pass, in registration order. - pub fn revealed_rects(&self) -> Vec<(RevealEdge, Rect)> { - self.inner.revealed_rects.0.lock().map(|rects| rects.clone()).unwrap_or_default() + pub fn revealed_rects(&self, ctx: &egui::Context) -> Vec<(RevealEdge, Rect)> { + let reveals = self.inner.reveals; + with_revealed(ctx, |rects| rects.0.iter().filter(|(shell, _, _)| *shell == reveals).map(|&(_, edge, rect)| (edge, rect)).collect()) } /// Records that a container in this shell shows as a dialog, a modal, a full-window layer or an OS window. Every @@ -351,6 +376,30 @@ impl ShellCx { #[doc(hidden)] pub struct ShellEntry(#[doc(hidden)] pub Option); +/// The shell's input fields: the window, the body's mode, the reveal and visibility flags, the regions, the float +/// bounds and the room of a full-window page's band. The registries the body writes into (revealed rects, the dialog count) are its output, not an input; the +/// revealed rects' key is fixed for the shell's life. +impl crate::contract::MemoProps for ShellEntry { + fn key(&self, key: &mut crate::contract::MemoKey) { + let Some(shell) = &self.0 else { return key.write_u32(0) }; + let Inner { window, mode, tab_reveal, edges, tabs, panels_hidden, regions, float_bounds, region, page_band, reveals: _, dialog: _ } = + &*shell.inner; + key.write_u32(1); + key.feed_hash(window); + key.feed_hash(&std::mem::discriminant(mode)); + (*tab_reveal, *edges, *tabs, *panels_hidden).key(key); + regions.body.key(key); + key.write_u32(regions.slots.len() as u32); + for (slot, rect) in ®ions.slots { + slot.key(key); + rect.key(key); + } + float_bounds.key(key); + region.key(key); + page_band.key(key); + } +} + impl EnvValue for ShellEntry { fn root() -> Self { ShellEntry(None) diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 5e9de334e..914423660 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -52,7 +52,7 @@ const PERCENT: f64 = 100.0; /// The size of a point, the Point/Pica Size of the Units preference. An app sets it once on its root env with /// `RootEnv::values`; `Units` reads it for typed Points and Picas and for their conversion to other lengths. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, crate::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum PointSize { @@ -314,6 +314,15 @@ pub struct Units { point_size: PointSize, } +/// What every number it reads and writes depends on: the format, the unit words and the scope's words (each by its +/// generation) and the point size. +impl crate::contract::MemoProps for Units { + fn key(&self, key: &mut crate::contract::MemoKey) { + let Units { format, words, scope_words, readers: _, point_size } = self; + crate::contract::MemoProps::key(&(format, words, scope_words, point_size), key); + } +} + impl Units { /// The codec of a zoom field in percent: the percent reader, up to two decimals (the zoom ladder has rungs such as /// 66.67 %), with zoom typing (`a/b` as a ratio, a second separator cutting the text), so every zoom field reads diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 52591cf9a..f0eac57f0 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -130,7 +130,7 @@ pub enum RowPressed { /// takes a box wider than its line, a select fits its widest entry up to a field length, a rule shows only with the /// member after it, and a row too long for its room narrows its last units first. A layer or pane opened from the bar /// starts without it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct InBar(pub bool); diff --git a/crates/ui-contract/src/runtime/env/view.rs b/crates/ui-contract/src/runtime/env/view.rs index 3d4ca14d7..42d7cb568 100644 --- a/crates/ui-contract/src/runtime/env/view.rs +++ b/crates/ui-contract/src/runtime/env/view.rs @@ -58,11 +58,6 @@ impl<'a> EnvView<'a> { self.scoped.measure } - /// The roving group of the innermost body with `ContainerProps.roving`. - pub(crate) fn roving(&self) -> Option { - self.scoped.roving - } - /// The inside label the scope carries ([`inside_label`](EnvView::inside_label) reads it back). pub(crate) fn inside_held(&self) -> Option<&'a Held> { self.scoped.inside_label.as_ref() @@ -113,11 +108,13 @@ impl<'a> EnvView<'a> { /// The platform and the running viewport's window facts: the OS, the capabilities and the window's kind, /// chrome, state, insets and focus. pub fn shell(&self) -> &'a ShellInfo { + crate::runtime::replay::note_input(&self.scoped.ctx, crate::runtime::inputs::Input::Shell); &self.scoped.shell } /// The keyboard layout: which character each key position types, for text that names a key. pub fn keyboard_layout(&self) -> &'a craft_keymap::Layout { + crate::runtime::replay::note_input(&self.scoped.ctx, crate::runtime::inputs::Input::Keyboard); &self.scoped.keyboard } diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 473542516..ac9e6f5ab 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -19,6 +19,7 @@ use crate::runtime::egui::memory::FastMap; use crate::runtime::frame::PerViewport; use craft_behavior::{DocKey, OwnerClass, PartRef}; use egui::{Context, Id, IdSet, ViewportId}; +use std::fmt; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; @@ -48,6 +49,9 @@ pub struct StopRec { #[doc(hidden)] pub stop: Stop, pub(crate) scope: Option, + /// The component takes its place in its set from its roving group's members of this pass, which the group's owner + /// writes into its node at its own report (`group_positions`). Marked at the component's report. + pub(crate) group_position: bool, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -150,6 +154,9 @@ pub(crate) struct State { /// Last pass's `docs`: a focus request made between passes resolves against the components that last showed. pub(super) last_docs: FastMap, pub(super) revealed: Option, + /// The stop a request of the running pass named before any pass registered it: it takes the focus when it + /// registers later in the pass. A component asks for its own focus from `update`, and its stops register after. + pub(super) awaited: Option, pub(super) seen: FastMap, /// A scope moved focus to its initial stop in the running pass. pub(super) entered: bool, @@ -205,11 +212,20 @@ pub(crate) fn apply(ctx: &Context, acts: Vec) { /// Registers a stop of the running pass in the innermost open scope, in registration order. pub(crate) fn register_stop(ctx: &Context, stop: Stop) { - with(ctx, |state| { + let acts = with(ctx, |state| { let scope = state.open.last().map(|(id, _)| *id); state.stop_ids.insert(stop.id); - state.stops.push(StopRec { stop, scope }); + let rec = StopRec { stop, scope, group_position: false }; + let acts = if state.awaited == Some(rec.stop.key()) { + state.awaited = None; + state.focus_stop(rec.clone()) + } else { + Vec::new() + }; + state.stops.push(rec); + acts }); + apply(ctx, acts); } /// Registers the app's own egui widget `id`, drawn in the running pass, as its window's document canvas: a focus stop @@ -286,15 +302,22 @@ impl Transcript { } /// The transcript as a replay registers it with `outer` the innermost open scope: a record under the scope that - /// was open around the run goes under `outer`, and a replayed scope is no new scope (`entering` is false). + /// was open around the run goes under `outer`, a replayed scope is no new scope (`entering` is false), and its + /// opener is the focus service's, not the run's (`opener`). fn placed(&self, outer: Option) -> Transcript { let place = |scope: Option| if scope == self.outer { outer } else { scope }; Transcript { - stops: self.stops.iter().map(|rec| StopRec { stop: rec.stop.clone(), scope: place(rec.scope) }).collect(), + stops: self + .stops + .iter() + .map(|rec| StopRec { stop: rec.stop.clone(), scope: place(rec.scope), group_position: rec.group_position }) + .collect(), scopes: self .scopes .iter() - .map(|(id, scope)| (*id, ScopeRec { parent: place(scope.parent), entering: scope.entering.map(|_| false), ..scope.clone() })) + .map(|(id, scope)| { + (*id, ScopeRec { parent: place(scope.parent), entering: scope.entering.map(|_| false), opener: None, ..scope.clone() }) + }) .collect(), groups: self.groups.clone(), row_sets: self.row_sets.clone(), @@ -303,10 +326,26 @@ impl Transcript { } } +impl Transcript { + /// The first record in which the replays of `self` and `other` differ (`placed`): the kind, its index and both + /// sides, `None` on a side that has fewer records. `None` when they register the same. + pub(crate) fn first_difference(&self, other: &Self) -> Option { + fn first(kind: &str, left: &[T], right: &[T]) -> Option { + let index = + left.iter().zip(right).position(|(a, b)| a != b).or_else(|| (left.len() != right.len()).then(|| left.len().min(right.len())))?; + Some(format!("{kind} {index}: left {:?} / right {:?}", left.get(index), right.get(index))) + } + let [a, b] = [self.placed(None), other.placed(None)]; + first("stop", &a.stops, &b.stops) + .or_else(|| first("scope", &a.scopes, &b.scopes)) + .or_else(|| first("roving group", &a.groups, &b.groups)) + .or_else(|| first("row groups", &a.row_sets, &b.row_sets)) + } +} + impl PartialEq for Transcript { fn eq(&self, other: &Self) -> bool { - let [a, b] = [self.placed(None), other.placed(None)]; - (a.stops, a.scopes, a.groups, a.row_sets) == (b.stops, b.scopes, b.groups, b.row_sets) + self.first_difference(other).is_none() } } @@ -343,9 +382,12 @@ pub(crate) fn transcript(ctx: &Context, mark: Mark) -> Transcript { /// as the run would have. A replayed scope is no new scope: it moves no focus when it shows again. pub(crate) fn replay(ctx: &Context, transcript: &Transcript) { let frame = crate::runtime::egui::pass::frame_nr(ctx, viewport(ctx)); + let focused = egui_focus::focused(ctx); with(ctx, |state| { let placed = transcript.placed(state.open.last().map(|(id, _)| *id)); - for (id, scope) in placed.scopes { + for (id, mut scope) in placed.scopes { + // No replayed scope has a noted opener: an overlay, which notes one, blocks its record. + scope.opener = opener(state, id, None, focused); if scope.entering.is_none() { state.seen.insert(id, frame); } @@ -415,12 +457,29 @@ pub(crate) fn register_row_groups(ctx: &Context, owner: Id, rtl: bool, mut ids: with(ctx, |state| state.row_sets.push(RowGroups { owner, rtl, ids })); } -/// The place of the component `id`'s own stop among last pass's members of the roving group `group`. -pub(crate) fn group_position(ctx: &Context, id: Id, group: Id) -> Option { +/// Marks the component `id`'s own stop of this pass in the roving group `group` as taking its place in the set from +/// the group's members (`group_positions`). A component with no such stop this pass keeps the place it reported. +pub(crate) fn takes_group_position(ctx: &Context, id: Id, group: Id) { with(ctx, |state| { - let members = || state.last_stops.iter().filter(|rec| rec.stop.group == Some(group) && rec.stop.part.is_none()); - let index = members().position(|rec| rec.stop.id == id)?; - Some(crate::runtime::access::SetPosition::new(index).of(members().count())) + if let Some(rec) = state.stops.iter_mut().rev().find(|rec| rec.stop.id == id && rec.stop.part.is_none() && rec.stop.group == Some(group)) { + rec.group_position = true; + } + }); +} + +/// The places of the members of the roving group `group` that take theirs from the group (`takes_group_position`), +/// among this pass's members: the components with their own stop in it, in registration order. The group's owner +/// asks at its report, after its body's members have run. +pub(crate) fn group_positions(ctx: &Context, group: Id) -> Vec<(Id, crate::runtime::access::SetPosition)> { + with(ctx, |state| { + let members: Vec<&StopRec> = state.stops.iter().filter(|rec| rec.stop.group == Some(group) && rec.stop.part.is_none()).collect(); + let count = members.len(); + members + .iter() + .enumerate() + .filter(|(_, rec)| rec.group_position) + .map(|(index, rec)| (rec.stop.id, crate::runtime::access::SetPosition::new(index).of(count))) + .collect() }) } @@ -443,8 +502,7 @@ pub(crate) fn push_scope_from( let focused = egui_focus::focused(ctx); with(ctx, |state| { let parent = state.open.last().map(|(parent, _)| *parent); - let opener = noted.or_else(|| focused.and_then(|root| state.focused.get(&root).copied().or(Some((root, None))))); - let opener = state.last_scopes.get(&id).map_or(opener, |last| last.opener.or(opener)); + let opener = opener(state, id, noted, focused); state.scopes.insert(id, ScopeRec { policy, parent, label, opener, closing, entering }); state.scope_order.push(id); let first = state.stops.len(); @@ -452,6 +510,17 @@ pub(crate) fn push_scope_from( }); } +/// The opener of the scope `id` registered in the running pass, by a run or a replay alike: taken once, when the scope +/// first appears, as the stop `noted` or else the stop of the focused widget `focused`; then kept from the pass before, +/// with what focus entering it noted there (`note_entry`). It is never taken again from the focus of a later pass, +/// which may be a stop inside the scope itself. +fn opener(state: &State, id: Id, noted: Option, focused: Option) -> Option { + match state.last_scopes.get(&id) { + Some(last) => last.opener, + None => noted.or_else(|| focused.map(|root| state.focused.get(&root).copied().unwrap_or((root, None)))), + } +} + /// The innermost scope open in the running pass: the scope whose body is being shown. #[doc(hidden)] pub fn open_scope(ctx: &Context) -> Option { @@ -624,6 +693,12 @@ pub(crate) fn request_now(ctx: &Context, target: FocusTarget) { apply(ctx, acts); } +/// Whether egui key focus is on the widget `root` for another component's stop: an arena member, whose stop's widget +/// is its root's (`Stop::root`). +pub(crate) fn held_for_member(ctx: &Context, root: Id) -> bool { + egui_focus::focused(ctx) == Some(root) && focused_stop(ctx).is_some_and(|(id, _)| id != root) +} + /// Whether `at` (screen points) lies in a popup layer opened above the layer of the widget that holds egui focus: a /// press or a wheel there is the popup's, not the focused widget's. The layer under `at` is the layer test's; the /// focused widget's layer is egui's last-pass record of it, since a stop records no layer of its own. @@ -666,6 +741,7 @@ pub(crate) fn stop_rec(ctx: &Context, key: StopKey) -> Option { /// The registration of the stop focus is on. #[doc(hidden)] pub fn focused_rec(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Focus); let focused = egui_focus::focused(ctx); with(ctx, |state| { state.focus_now = focused; @@ -850,6 +926,7 @@ pub(crate) fn begin(ctx: &Context, tab_all_controls: bool, dialog_tab: TabReach) }; let tab_to_egui = input.nav.tab_to_egui; let (acts, announcements, host_focus) = with(ctx, |state| { + state.awaited = None; let host_focus = state.record.host_focus; state.tab_to_egui = tab_to_egui; let (acts, announcements) = nav::begin(state, input); @@ -913,6 +990,11 @@ pub(crate) fn scope_chain(ctx: &Context, rec: &StopRec) -> Vec { }) } +/// Where key focus is, as the tracked input `Focus` compares it: the focused widget and whether its ring shows. +pub(crate) fn focus_state(ctx: &Context) -> (Option, bool) { + (egui_focus::focused(ctx), with(ctx, |state| state.visible)) +} + /// Whether focus sits inside a menu and arrived by keyboard. #[doc(hidden)] pub fn keyboard_in_menu(ctx: &Context) -> bool { diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 5bf6cc480..c8a60dd78 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -387,8 +387,10 @@ impl State { let found = self.find_stop(key).or_else(|| self.stops.iter().chain(&self.last_stops).find(|rec| rec.stop.id == key.0).cloned()); match found { Some(rec) => self.focus_stop(rec), + // An app's own widget, or a stop that registers later in this pass, which then takes the focus. None => { self.revealed = Some(key); + self.awaited = Some(key); self.focus_now = Some(key.0); vec![Act::Focus(key.0, Default::default())] } diff --git a/crates/ui-contract/src/runtime/focus/registration.rs b/crates/ui-contract/src/runtime/focus/registration.rs index f2d9fb531..d251d2eda 100644 --- a/crates/ui-contract/src/runtime/focus/registration.rs +++ b/crates/ui-contract/src/runtime/focus/registration.rs @@ -180,33 +180,6 @@ impl Group { } } -/// What a component's part group joined: the enclosing body roving group and the pass that recorded it. -#[derive(Clone, Copy)] -struct PartJoin { - group: Id, - pass: u64, -} - -fn part_join_slot(parts: Id) -> Id { - sub(parts, "body_group") -} - -/// Records that the part group `parts` of component `id` joins the body roving group `group` in this pass: the -/// component's focusable parts become members of `group` in reading order, so Tab visits the group once and -/// arrows cross between the parts and the group's other members. -pub(crate) fn join_part_group(ctx: &Context, group: Id, id: Id, parts: Id) { - let slot = part_join_slot(parts); - store::put(ctx, slot, PartJoin { group, pass: crate::runtime::pointer::pass_of(ctx) }); - crate::runtime::memory::adopt::(ctx, id, slot); -} - -/// The body roving group the part group `parts` joined in this pass or the one before, else `None`: parts of a -/// component that never joined stay in their own part group. -pub(crate) fn part_group(ctx: &Context, parts: Id) -> Option { - let join = store::peek_clone::(ctx, part_join_slot(parts))?; - (join.pass.saturating_add(1) >= crate::runtime::pointer::pass_of(ctx)).then_some(join.group) -} - /// The innermost open `KeepAnchor` layer opened from the stop `opener`, the collection its opener hands list keys /// to (the stop with the collection's key role that is registered inside the layer's focus scope) and the layer's /// policy. `None` while no such layer is open or it has no collection. diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 6227665c2..b6804a2b8 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -28,7 +28,7 @@ pub struct FrameInput { pub commands: CommandInput, /// The app's `Host`, read through `EnvView::host`. The app keeps one `Arc` 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>, /// The modifiers the app's own tablet or latched-key reader holds down beyond the window's input. pub latched: Mods, @@ -447,23 +447,11 @@ pub(crate) fn announce(ctx: &Context, text: String) { pass_state::with::(ctx, |state| state.output.announcements.push(text)); } -/// Asks for another pass of the viewport the running pass belongs to. 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)); } @@ -588,7 +576,24 @@ pub(crate) fn facts(ctx: &Context) -> PassFacts { }) } -/// The running pass's time in seconds, read once by the begin hook. +/// The pass clock in seconds rounded down to a multiple of `step`, for content that changes with time (a rescan every +/// few seconds, a "5 minutes ago"): the running view is shown again at the next multiple. Between two steps a run +/// shows what the last one showed, so a memoized view that reads it replays until the next step and runs then. A +/// `step` of zero or less returns the clock and shows the view again in every pass. +pub fn stepped_clock(ctx: &Context, step: f64) -> f64 { + let now = clock(ctx); + if step <= 0.0 { + crate::runtime::motion::note_unsettled(ctx); + return now; + } + let at = (now / step).floor() * step; + crate::runtime::motion::wake_at(ctx, at + step); + at +} + +/// The running pass's time in seconds, read once by the begin hook. Content that changes with time reads +/// [`stepped_clock`], which shows it again when the value it read changes; this read notes nothing, for timing +/// events in the component that has the pointer or the focus. #[doc(hidden)] pub fn clock(ctx: &Context) -> f64 { match running(ctx) { diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs new file mode 100644 index 000000000..8b4e3eb3d --- /dev/null +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -0,0 +1,145 @@ +//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's +//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held), each with a generation +//! that moves when its value changes. The accessor that reads one notes it into the records open around the running +//! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation +//! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed +//! runs when it is shown again. +//! +//! The scroll view a nested `Lazy` child decides by is noted too, as `Scroll`; it has no generation: the record keeps +//! the view it ran with, and a replay needs the same view. + +use crate::runtime::egui::pass; +use crate::runtime::frame::PerViewport; +use egui::Context; +use std::any::Any; + +/// A framework input a view reads outside its props. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Input { + /// The modifiers held (`Cx::modifiers`, `pointer::mods`). + Modifiers, + /// The pointer's frame (`pointer::frame`, `pointer::with_pass_pointer`). + Pointer, + /// The keys held, Caps Lock and whether a key arrived (`keys::input::down`, `keyed`, `lock_keys::caps_lock`). + Keys, + /// The platform and window facts (`EnvView::shell`). + Shell, + /// The keyboard layout (`EnvView::keyboard_layout`). + Keyboard, + /// The keymap: the chords commands show (`commands::chord`, `bindings`, `holder`, a resolved command's chord). + Keymap, + /// A drag session and its payloads (`drag::active`, `started`). + Drag, + /// Where key focus is (`focus::focused_rec`, `focus_in_scope`, `commands::focus_within`). + Focus, + /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). + Overlays, + /// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value. + Scroll, +} + +impl Input { + pub(crate) const ALL: [Input; 10] = [ + Input::Modifiers, + Input::Pointer, + Input::Keys, + Input::Shell, + Input::Keyboard, + Input::Keymap, + Input::Drag, + Input::Focus, + Input::Overlays, + Input::Scroll, + ]; + + fn bit(self) -> u16 { + 1 << self as u16 + } +} + +/// The inputs a run read. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Inputs(u16); + +impl Inputs { + pub(crate) fn insert(&mut self, input: Input) { + self.0 |= input.bit(); + } + + pub(crate) fn extend(&mut self, other: Inputs) { + self.0 |= other.0; + } + + pub(crate) fn contains(self, input: Input) -> bool { + self.0 & input.bit() != 0 + } + + /// The inputs in the set that have a generation. + pub(crate) fn generational(self) -> impl Iterator { + Input::ALL.into_iter().filter(move |input| *input != Input::Scroll && self.contains(*input)) + } +} + +/// The generations of the inputs a run read, taken when it started. +pub(crate) type Seen = [u64; Input::ALL.len()]; + +/// A viewport's generations, and the last value each observed input had. +#[derive(Default)] +struct Generations { + gens: Seen, + last: [Option>; Input::ALL.len()], +} + +impl crate::runtime::frame::Stored for Generations {} + +fn with(ctx: &Context, f: impl FnOnce(&mut Generations) -> R) -> R { + PerViewport::::with(ctx, pass::current_viewport(ctx), f) +} + +/// Moves the generation of `input` in the running viewport: its value changed. +pub(crate) fn bump(ctx: &Context, input: Input) { + with(ctx, |generations| generations.gens[input as usize] += 1); +} + +/// Notes the value `input` has now in the running viewport, and moves its generation when it differs from the last +/// one noted. +pub(crate) fn observe(ctx: &Context, input: Input, value: T) { + with(ctx, |generations| { + let slot = &mut generations.last[input as usize]; + if slot.as_ref().and_then(|last| last.downcast_ref::()) != Some(&value) { + if slot.is_some() { + generations.gens[input as usize] += 1; + } + *slot = Some(Box::new(value)); + } + }); +} + +/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are +/// observed here; the pointer and the modifiers by the pointer's begin hook, the window facts and the layout where +/// the frame's root env is built, the keymap by the command board. +pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { + match input { + Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)), + Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)), + Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), + Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), + Input::Keymap => return crate::runtime::commands::keymap_generation(ctx), + Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} + } + with(ctx, |generations| generations.gens[input as usize]) +} + +/// The generation of every input now, for a run that starts. +pub(crate) fn seen(ctx: &Context) -> Seen { + let mut seen = Seen::default(); + for input in Input::ALL { + seen[input as usize] = generation(ctx, input); + } + seen +} + +/// Whether an input of `read` has another generation now than in `seen`. +pub(crate) fn moved(ctx: &Context, read: Inputs, seen: &Seen) -> bool { + read.generational().any(|input| generation(ctx, input) != seen[input as usize]) +} diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index c50335514..b7eac2e3c 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -178,6 +178,29 @@ pub struct Recorded { pub hits: Vec, } +/// A replay at another place keeps the record its run made, moved with it. +impl crate::runtime::Shift for Arc { + fn shifted(&self, by: &egui::RecordShift) -> Self { + let elements = + self.elements.iter().map(|element| Element { rect: by.rect(element.rect), content: by.rect(element.content), ..element.clone() }); + let hits = self.hits.iter().map(|hit| HitArea { rect: by.rect(hit.rect), ..hit.clone() }); + Arc::new(Recorded { layer: self.layer, elements: elements.collect(), hits: hits.collect() }) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + if self.elements.len() != to.elements.len() || self.hits.len() != to.hits.len() { + return Arc::clone(self); + } + let elements = self.elements.iter().zip(&to.elements).map(|(element, to)| Element { + rect: element.rect.snapped(&to.rect, within), + content: element.content.snapped(&to.content, within), + ..element.clone() + }); + let hits = self.hits.iter().zip(&to.hits).map(|(hit, to)| HitArea { rect: hit.rect.snapped(&to.rect, within), ..hit.clone() }); + Arc::new(Recorded { layer: self.layer, elements: elements.collect(), hits: hits.collect() }) + } +} + impl Recorded { /// The rect of the element at `index` where Tab stops on it: its hit area when it has one, else its box. pub fn stop_rect(&self, index: usize) -> Option { @@ -237,12 +260,19 @@ pub fn record(ui: &mut Ui, key: Id, body: impl FnOnce(&mut Ui) -> R) -> (R, O let out = body(ui); let Some(open) = pass_state::with::(&ctx, |log| log.open.pop()) else { return (out, None) }; let recorded = Arc::new(finish(&ctx, open)); - write(&ctx, key, |kept| { - let changed = kept.recorded.as_deref() != Some(&*recorded); - kept.recorded = Some(Arc::clone(&recorded)); + keep(&ctx, key, &recorded); + // A memoized view that replays this region keeps its record as the run left it. + crate::runtime::replay::journal(&ctx, || (key, Arc::clone(&recorded)), |ctx, (key, recorded)| keep(ctx, *key, recorded)); + (out, Some(recorded)) +} + +/// Keeps `recorded` as the record of the region `key`. +fn keep(ctx: &Context, key: Id, recorded: &Arc) { + write(ctx, key, |kept| { + let changed = kept.recorded.as_deref() != Some(&**recorded); + kept.recorded = Some(Arc::clone(recorded)); changed }); - (out, Some(recorded)) } /// The latest record of the region `key`, read as a value: when the region shows later in the pass with a different @@ -295,9 +325,9 @@ 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. -fn edited(ctx: &Context, read: BindKey, editor: Id) { +/// 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. +pub(crate) fn edited(ctx: &Context, read: BindKey, editor: Id) { crate::runtime::lazy::note_edit(ctx, read); if reads::earlier(ctx, read, editor).other { log::debug!(target: crate::runtime::egui::sizing::RERUN_LOG, "{editor:?} edited {read:?}, read earlier in the pass"); diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index 354630670..f104baba8 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -27,7 +27,7 @@ pub use claims::take_claimed; pub(crate) use claims::take_first_claimed; /// The types `Intents` reads and returns, for an app that reads the window's intents (`with_window_intents`). pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef}; -pub(crate) use input::{claims_press, input_hook, queue_nav, take_menu_keys, take_nav}; +pub(crate) use input::{claims_press, input_hook, keys_state, queue_nav, take_menu_keys, take_nav}; #[doc(hidden)] pub use input::{down, keyed}; pub use intents::Intents; diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index a67c03ec9..78074d5fb 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -583,12 +583,20 @@ fn note_down(down: &mut Vec, event: &KeyEvent) { /// down). #[doc(hidden)] pub fn down(ctx: &Context) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keys); current(ctx, |stage| stage.down.clone()) } +/// The key state, as the tracked input `Keys` compares it: the keys down, whether a key arrived and Caps Lock. +pub(crate) fn keys_state(ctx: &Context) -> (Vec, bool, bool) { + let (down, keyed) = current(ctx, |stage| (stage.down.clone(), stage.keyed)); + (down, keyed, crate::runtime::lock_keys::caps_on(ctx)) +} + /// Whether the running viewport's input hook read a key press, typed text or a clipboard event in this pass, the ones /// the key stage took from egui's input included: an app that redraws state after input asks this, not egui's events. pub fn keyed(ctx: &Context) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keys); current(ctx, |stage| stage.keyed) } diff --git a/crates/ui-contract/src/runtime/keys/nodes.rs b/crates/ui-contract/src/runtime/keys/nodes.rs index 2266a989b..aed007d29 100644 --- a/crates/ui-contract/src/runtime/keys/nodes.rs +++ b/crates/ui-contract/src/runtime/keys/nodes.rs @@ -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| { diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index 6cdb90671..5482b9b59 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -678,7 +678,7 @@ fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, 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 { let (mut routed, menu_keys) = current(ctx, |stage| (stage.routed.keys().flatten().copied().collect::>(), !stage.menu.is_empty())); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index b5b630cdd..4da3ef9fc 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -186,6 +186,8 @@ enum Undo { /// An input the entry open at the place read, before the draft read it. Input(usize, Id, Option), Contribution(TakeBack), + /// What restores a write the draft made to a store outside layout memory (`note_undo`). + Store(TakeBack), } impl Scope { @@ -243,10 +245,18 @@ pub(crate) struct Entries { /// The drafts open, innermost last. drafts: Vec, ask: bool, + /// How many times a discard pass was asked, so a record open around the asking run notes it (`with`). + asks: u64, asked: Option, } impl Entries { + /// Asks for the frame's discard pass. + fn ask_discard(&mut self) { + self.ask = true; + self.asks += 1; + } + /// A real run found the content changed: drops the kept transcripts of `body` and of every body the real run is /// inside, up to the first boundary, and asks for the discard pass. fn changed(&mut self, frame: u64, body: Option) { @@ -268,7 +278,7 @@ impl Entries { break; } } - self.ask = true; + self.ask_discard(); } /// The innermost open transcript: a body's or a boundary, past the measure calls open inside it. @@ -325,8 +335,9 @@ impl Entries { } /// Takes a draft that ended back: the records, kept transcripts and transcript entries are as before it. Returns - /// what takes its contributions back, in reverse order, to run outside the memory's lock. - fn take_back(&mut self, draft: Draft) -> Vec { + /// what takes its contributions and its writes to other stores back, in reverse order, to run outside the memory's + /// lock, each with whether it takes a contribution back. + fn take_back(&mut self, draft: Draft) -> Vec<(TakeBack, bool)> { let mut later = Vec::new(); for undo in draft.undo.into_iter().rev() { match undo { @@ -365,7 +376,8 @@ impl Entries { } } } - Undo::Contribution(undo) => later.push(undo), + Undo::Contribution(undo) => later.push((undo, true)), + Undo::Store(undo) => later.push((undo, false)), } } if let Some((at, len)) = draft.items @@ -403,7 +415,17 @@ impl Moment { } fn with(ctx: &Context, moment: &Moment, f: impl FnOnce(&mut Entries) -> R) -> R { - PerViewport::::with(ctx, moment.viewport, f) + let (out, asked) = PerViewport::::with(ctx, moment.viewport, |memory| { + let asks = memory.asks; + let out = f(memory); + (out, memory.asks != asks) + }); + // The ask reaches egui only in the end hook, after the runs of the pass: the record open around the run that asked + // notes it here, as every other discard request is counted in egui's output (`replay::close`). + if asked { + crate::runtime::replay::note_discard(ctx); + } + out } /// The size entry under `id` as this pass places by it. A placement that read the entry (`None` on a block's @@ -412,7 +434,7 @@ pub(crate) fn read(ctx: &Context, id: Id) -> Option { if crate::runtime::measure::active(ctx) { return peeking(ctx, |read| read(id)); } - journal_keep(ctx, id); + crate::runtime::replay::note_layout_keep(ctx, id); let moment = Moment::of(ctx); with(ctx, &moment, |memory| { let entry = memory.entries.entry(id).or_default(); @@ -441,7 +463,7 @@ pub(crate) fn peeking(ctx: &Context, f: impl FnOnce(&dyn Fn(Id) -> Option tolerance); @@ -487,8 +509,11 @@ pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, dropped: bo /// hands forward a measure: it serves the rest of this pass, and a later pass that takes the kept measurement of a body /// it ran in gets it with that measurement, where the content that found it does not run. A real run emits it too: a /// text other than the one a kept transcript gave the pass shows that transcript changed. +/// +/// A memoized view that replays emits it again. pub fn emit_text(ctx: &Context, id: Id, text: Option<&str>) { emit(ctx, id, Recorded::Text(text.map(Arc::from))); + super::replay::journal(ctx, || (id, text.map(Arc::::from)), |ctx, (id, text)| emit(ctx, *id, Recorded::Text(text.clone()))); } /// The text a run of this pass handed forward under `id` ([`emit_text`]), or a kept transcript gave this pass. @@ -675,14 +700,34 @@ pub(crate) fn draft(ctx: &Context, run: impl FnOnce() -> R, keep: impl FnOnce } Some(memory.take_back(draft)) }); - for undo in undo.into_iter().flatten() { + for (undo, contribution) in undo.into_iter().flatten() { guard::emitting(|| undo(ctx)); #[cfg(feature = "testing")] - crate::runtime::measure::count_contribution(ctx, -1); + if contribution { + crate::runtime::measure::count_contribution(ctx, -1); + } + let _ = contribution; } (out, kept) } +/// Whether a draft is open (`draft`): a store outside layout memory that a measuring run writes hands what restores +/// the write to `note_undo`. +pub(crate) fn drafting(ctx: &Context) -> bool { + with(ctx, &Moment::of(ctx), |memory| !memory.drafts.is_empty()) +} + +/// Adds `undo`, which restores a write to a store outside layout memory (the lazy children's entries), to the innermost +/// open draft: a draft taken back runs it, so the draft leaves nothing behind; one kept hands it to the draft around it. +/// Nothing outside a draft. +pub(crate) fn note_undo(ctx: &Context, undo: TakeBack) { + with(ctx, &Moment::of(ctx), |memory| { + if let Some(draft) = memory.drafts.last_mut() { + draft.undo.push(Undo::Store(undo)); + } + }); +} + /// Runs `f` as content whose emits no enclosing transcript takes, and whose real run no enclosing body checks: a /// collection's rows and its largest-row probe (kept by its own transcript), a layer's content, a lazy /// child. `stops_changes`: a change the real run finds inside drops no kept transcript outside. Content whose extent @@ -904,7 +949,7 @@ pub(crate) fn begin_measure(ctx: &Context, body: Id) { /// Closes the measuring run of `body` and keeps its transcript under the inputs `key` it ran under. pub(crate) fn end_measure(ctx: &Context, body: Id, key: K) { - journal_keep(ctx, body); + crate::runtime::replay::note_layout_keep(ctx, body); let moment = Moment::of(ctx); with(ctx, &moment, |memory| { let Some(at) = memory.measuring.iter().rposition(|open| matches!(open, Open::Body { id, .. } if *id == body)) else { return }; @@ -957,7 +1002,7 @@ pub(crate) fn kept_serves(ctx: &Context, b if !reuse_allowed(ctx) || !crate::runtime::measure::outermost(ctx) { return false; } - journal_keep(ctx, body); + crate::runtime::replay::note_layout_keep(ctx, body); let moment = Moment::of(ctx); if with(ctx, &moment, |memory| memory.probing()) { return false; @@ -1119,27 +1164,26 @@ pub fn kept_leaves(ctx: &Context) -> usize { pub(crate) fn ask_discard(ctx: &Context) { log::debug!(target: sizing::RERUN_LOG, "a discard asked at {}", std::panic::Location::caller()); let moment = Moment::of(ctx); - with(ctx, &moment, |memory| memory.ask = true); + with(ctx, &moment, Entries::ask_discard); } -/// Notes in the run records open around the running code that a replay keeps the entry and the kept transcript of -/// `id`: the replayed run does not reach them, and an entry no pass touched in a frame is dropped. -fn journal_keep(ctx: &Context, id: Id) { - crate::runtime::replay::journal( - ctx, - || id, - |ctx, id| { - let moment = Moment::of(ctx); - with(ctx, &moment, |memory| { - if let Some(entry) = memory.entries.get_mut(id) { - entry.touched = moment.frame; - } - if let Some(kept) = memory.kept.get_mut(id) { - kept.touched = moment.frame; - } - }); - }, - ); +/// Keeps the entries and kept transcripts of `ids` through this frame, for a replayed run that kept them +/// (`replay::note_layout_keep`): the replay does not reach them, and an entry no pass touched in a frame is dropped. +pub(crate) fn keep(ctx: &Context, ids: &[Id]) { + if ids.is_empty() { + return; + } + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + for id in ids { + if let Some(entry) = memory.entries.get_mut(id) { + entry.touched = moment.frame; + } + if let Some(kept) = memory.kept.get_mut(id) { + kept.touched = moment.frame; + } + } + }); } /// The end hook: asks egui for at most one discard pass per frame, and for a repaint when a change cannot get one, so @@ -1208,12 +1252,17 @@ pub(crate) mod guard { ("runtime::windows::Shared", "window shells: read"), ("runtime::windows::Record", "window records: read"), ("runtime::windows::hit::Exclusive", "exclusive windows: read"), + ("runtime::env::shell::RevealedRects", "revealed rects: read; registered in real runs only"), ("runtime::focus::State", "focus: read; stops register in real runs only"), ("runtime::keys::Stage", "key stage: read"), ("primitives::sensing::Arenas", "arenas: read; members join in real runs only"), ("runtime::pointer::", "pointer state: read; sensing is skipped in measuring runs"), ("runtime::wheel::State", "wheel: read"), ("runtime::drag::", "drag board and targets: read; targets register in real runs"), + ( + "runtime::inputs::Generations", + "framework input generations: a replay decided in a measuring run compares them; observing syncs the values a real run of the pass sees", + ), ("runtime::overlay::", "overlays: read; opens and closes are effects skipped in measuring runs"), ("contract::overlay::popups::Popups", "popups: read"), ("runtime::replay::Recorder", "run records: opened and closed by real runs; registrations journal there only while one is open"), diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index b147bd677..3a46b3231 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -9,21 +9,38 @@ //! 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`) 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}; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; +use crate::runtime::inputs::{self, Input}; +use crate::runtime::layout_memory; use crate::runtime::reads::BindKey; use crate::runtime::replay::{self, Record}; use crate::style::EnvKey; -use egui::{Context, Id, IdMap, IdSet, Layout, Rect, Vec2}; -use std::collections::HashSet; +use egui::emath::GuiRounding as _; +use egui::{Context, Id, IdMap, IdSet, Layout, RecordShift, Rect, Vec2}; +use std::any::Any; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; +/// What a memoized view's run returned, kept for its replays. +pub(crate) type Output = Arc; + +/// What a child's runs are keyed by. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Key { + /// Nothing: a `Lazy` child or a collection row, which runs whenever it is in view. + None, + /// A memoized view's props key (`contract::MemoView`), taken again after each run. + Memo(u128), +} + /// The view of the innermost scroll area, as the run that lays its content out sees it: the rect the pass shows, /// placed where this run puts the content (a measuring run lays it out from offset zero). #[derive(Clone, Copy, Debug, PartialEq)] @@ -36,10 +53,6 @@ pub(crate) struct View { /// The axes the area scrolls along (x, y). pub(crate) axes: (bool, bool), pub(crate) rtl: bool, - /// The child the area's scroll position names. - pub(crate) anchor: Option, - /// The child the area glides to (`Lazy::reveal`). - pub(crate) reveal: Option, } impl View { @@ -54,6 +67,11 @@ impl View { pub(crate) fn estimate(&self, along: f32) -> Vec2 { Vec2::new(if self.axes.0 { along } else { 0.0 }, if self.axes.1 { along } else { 0.0 }) } + + /// The view moved by `offset`, with its area. + fn moved(self, offset: Vec2) -> View { + View { rect: self.rect.translate(offset), content: self.content.translate(offset), ..self } + } } /// A scroll position named by content: the child `child` starts `at` from the view's start edge. The scroll area @@ -68,6 +86,12 @@ pub(crate) struct Anchor { /// Where the children of a scroll area started in the real run that laid its content out, from the view's start. #[derive(Clone, Copy, Debug, Default)] pub(crate) struct Placed { + /// The child the area's scroll position names, the child it glides to (`Lazy::reveal`) and the axes it scrolls + /// along, as the area had them when the run began. They are the area's own state, not inputs of its children, so + /// a replayed child reports against the area's current ones. + names: (Option, Option, (bool, bool)), + /// The view the run lays the content out for (`begin`), which a child's rect is placed from. + view: Option, /// The place and extent of the child the area's anchor names, when the run reached it. pub(crate) anchor: Option<(Vec2, Vec2)>, /// The first child, in flow order, that starts at or after the view's start, and its place. @@ -77,15 +101,24 @@ pub(crate) struct Placed { } impl Placed { - /// Notes that the child `id` took a place `at` from the view's start and is `extent` long, in a view whose area - /// scrolls along `axes` and names `anchor`. - pub(crate) fn note(&mut self, (anchor, axes): (Option, (bool, bool)), id: Id, at: Vec2, extent: Vec2) { + /// No places yet, for an area that names `anchor` as its scroll position, glides to `reveal` and scrolls along + /// `axes`. + pub(crate) fn named(anchor: Option, reveal: Option, axes: (bool, bool)) -> Placed { + Placed { names: (anchor, reveal, axes), ..Placed::default() } + } + + /// Notes that the child `id` took a place `at` from the view's start and is `extent` long. + pub(crate) fn note(&mut self, id: Id, at: Vec2, extent: Vec2) { + let (anchor, reveal, axes) = self.names; if anchor == Some(id) { self.anchor = Some((at, extent)); } if self.first.is_none() && (!axes.0 || at.x >= 0.0) && (!axes.1 || at.y >= 0.0) { self.first = Some((id, at)); } + if reveal == Some(id) { + self.reveal = Some(at); + } } } @@ -101,28 +134,40 @@ pub(crate) enum Decision { struct Entry { /// The scroll area the child is kept under. owner: Option, - /// The extent of the last measuring run and of the last real run that showed the child. A run that skips the - /// child takes the extent of its own kind: a content-sized scroll area is offered another room in its measuring - /// run than in its real run, so each kind places the child as it last laid it out. Out of view the child keeps - /// it at any room; it is measured again when it meets the reach. - sizes: [Option; 2], + /// What the last measuring run and the last real run that showed the child measured. A run that skips the child + /// takes the extent of its own kind: a content-sized scroll area is offered another room in its measuring run than + /// in its real run, so each kind places the child as it last laid it out. Out of view the child keeps it at any + /// room; it is measured again when it meets the reach. + sizes: [Option; 2], /// What the child registered with the focus service in the last real run that showed it. Out of view the /// child registers it again in its place, so Tab and F6 reach its stops; it runs while one of them holds focus /// or a focus request asks to reveal one. focus: Arc, /// 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>, /// The last measuring run of a measure-only child (`measured`). measured: Option, - /// 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 pass a collection row's extent was last measured in (`remember`). + measured_in: Option, /// The last frame that read or wrote the entry. touched: u64, } -/// Where a settling child ran: it is settled only while it runs at the same place, in the same environment. +/// What a run that showed a child measured: the extent it took, the key of the content it showed and the room it was +/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Measured { + pub(crate) size: Vec2, + pub(crate) key: Key, + pub(crate) room: Rect, +} + +/// 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 { /// The region its parent offered it. @@ -131,24 +176,78 @@ pub(crate) struct Place { pub(crate) layer: Layer, pub(crate) layout: Layout, pub(crate) pixels_per_point: f32, + /// The font atlas the run's text points into (`Fonts::atlas_generation`): egui clears the atlas when it fills up + /// and rebuilds it for new text options, and a kept galley's glyphs then name other glyphs. + pub(crate) atlas: u64, /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, } +/// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room. +#[derive(Clone, Copy, Debug)] +struct Moved { + shift: RecordShift, + with_clip: bool, +} + +impl Place { + /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its + /// size, the layer, layout, scale, font atlas and environment are the ones the run had. The record moves by the + /// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there + /// gives) and, for a move, the record holds nothing a move cannot place (`movable`: no paint callback) on an + /// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow + /// the clip when either: + /// - the clip moved with the room (`with_clip`): every rect and clip moves exactly, whatever the clip cut; + /// - the run lay wholly inside its clip: nothing of it was culled (widgets skip paint outside the clip, and every + /// nested `Lazy` child in the scroll view around it ran), and every clip set inside it lies within the run's clip, + /// so the run's clip becomes the clip now and inner clips move (`RecordShift::clip`). + /// + /// Otherwise it runs: a run cut by its clip lacks what was culled. + fn shift_to(&self, rect: Rect, now: Place, movable: bool, transformed: bool) -> Option { + let offset = now.room.min - self.room.min; + let same = now.room.size() == self.room.size() + && now.layer == self.layer + && now.layout == self.layout + && now.pixels_per_point == self.pixels_per_point + && now.atlas == self.atlas + && now.env == self.env; + let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed); + if !same || !placeable { + return None; + } + let shift = RecordShift { offset, ran_clip: self.clip, clip: now.clip }; + let with_clip = now.clip == self.clip.translate(offset); + (with_clip || self.clip.contains_rect(rect)).then_some(Moved { shift, with_clip }) + } +} + +/// Whether content in `area` moved by `offset` lies where a run at the new place puts it: the move is a whole step of +/// egui's UI rounding, which every widget rect is rounded to, and a whole physical pixel, which paint snaps to +/// (`Surface`, text). A move between them leaves a rounded rect off the grid a run there rounds it to. Both roundings +/// take a half step away from zero (`f32::round`), so a coordinate on a half step rounds to the same place after the +/// move only on the same side of zero: the area keeps its side of zero along each axis. +pub(crate) fn keeps_placement(area: Rect, offset: Vec2, pixels_per_point: f32) -> bool { + let moved = area.translate(offset); + let one_side = |(min, max): (f32, f32), (to_min, to_max): (f32, f32)| (min >= 0.0 && to_min >= 0.0) || (max <= 0.0 && to_max <= 0.0); + offset == offset.round_ui() + && offset == offset.round_to_pixels(pixels_per_point) + && one_side((area.min.x, area.max.x), (moved.min.x, moved.max.x)) + && one_side((area.min.y, area.max.y), (moved.min.y, moved.max.y)) +} + /// The last measuring run of a measure-only child: content a pass measures and never shows, as a page `Pages` holds /// out of view. #[derive(Clone)] struct MeasuredRun { - facts: replay::Facts, - /// The pass and the frame it ran in. + /// The values it read. + reads: Vec, + /// 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. @@ -158,39 +257,46 @@ struct Settled { rect: Rect, /// The pointer was over it, or one of its stops held focus: it runs again to show that they left. engaged: bool, - /// The version of the app data it showed (`Lazy::content`). - content: Option, + /// What it ran for: its props key after the run. + key: Key, + /// The pass it ran in. + pass: u64, + /// The edit serial when it started (`note_edit`): a later pass of its frame replays it only if no value it read was + /// edited after that. + edits: u64, + /// What a memoized view's run returned, which its replays return. + output: Option, + /// The generation of ended shown lives after the run (`memory::ended_generation`). + lives: u64, + /// The generation of each framework input when the run started (`runtime::inputs`): a memoized view whose run read + /// one replays only while it is the same. + seen: inputs::Seen, + /// The view of the scroll area around it when it ran: a run that decided a nested `Lazy` child by it replays only + /// while it is the same. + view: Option, } -/// 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 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, or with an edit of a given value, unsettles them for that frame and the next. Either may change app data - /// the framework does not track; a child with a content version sees that change as a new version. - unversioned_through: u64, - /// The pass whose input was looked at. - scanned: u64, - /// The values changed in a frame, and the frame. - edited: (u64, HashSet), + /// The values changed in a frame, each with the serial of its last edit, and the frame. + edited: (u64, HashMap), + /// The serial of the last edit (`note_edit`). + serial: u64, } 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.unversioned_through = self.unversioned_through.max(frame + 1); - } - } + /// The values edited in `frame`, each with the serial of its last edit; `None` when there were none. + fn edited_in(&self, frame: u64) -> Option> { + (self.edited.0 == frame && !self.edited.1.is_empty()).then(|| self.edited.1.clone()) } } +/// Of the values `edited` in a frame, the ones whose last edit came after the edit serial `since`. +fn edited_since(edited: Option<&HashMap>, since: u64) -> Option> { + edited.map(|edited| edited.iter().filter(|(_, serial)| **serial > since).map(|(key, _)| *key).collect()) +} + #[derive(Default)] pub(crate) struct Store { entries: IdMap, @@ -203,6 +309,19 @@ pub(crate) struct Store { pruned: u64, } +impl Entry { + /// Whether the entry is shown: touched in this frame or the one before, or kept by a scroll area that did not run + /// (a tab switched away), whose kept offset its extent places. + fn live(&self, frame: u64, reached: &IdMap) -> bool { + self.touched + 1 >= frame || self.owner.is_some_and(|owner| reached.get(&owner).is_none_or(|ran| ran + 1 < frame)) + } + + /// Whether the entry keeps a memoized view's run. + fn memo(&self) -> bool { + self.settled.as_ref().is_some_and(|settled| matches!(settled.key, Key::Memo(_))) + } +} + impl Store { /// The entry of the child `id` of the scroll area `owner`, touched in `frame`. fn touch(&mut self, owner: Option, id: Id, frame: u64) -> &mut Entry { @@ -225,9 +344,18 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { if store.pruned != frame { store.pruned = frame; let reached = &store.reached; - store.entries.retain(|_, entry| { - entry.touched + 1 >= frame || entry.owner.is_some_and(|owner| reached.get(&owner).is_none_or(|ran| ran + 1 < frame)) - }); + store.entries.retain(|_, entry| entry.memo() || entry.live(frame, reached)); + // A memoized view's entry outlives its absence while the absent ones are at most twice as many as the shown + // ones, the longest absent dropped first: a view shown again with the same props replays. + let shown = store.entries.values().filter(|entry| entry.memo() && entry.live(frame, reached)).count(); + let mut absent: Vec<(u64, Id)> = + store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)).collect(); + if absent.len() > 2 * shown { + absent.sort_unstable_by_key(|(touched, _)| *touched); + for (_, id) in &absent[..absent.len() - 2 * shown] { + store.entries.remove(id); + } + } let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect(); store.reached.retain(|owner, _| owners.contains(owner)); } @@ -235,17 +363,41 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { }) } +/// Runs `f` on the store as `with` does, for a write to the entry of the child `id`: inside a draft +/// (`layout_memory::draft`) the entry as it was goes to the draft, so a measuring run taken back leaves the entry, its +/// extents and this pass's decisions included, as it found it. +fn write(ctx: &Context, id: Id, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { + let drafting = layout_memory::drafting(ctx); + let (out, before) = with(ctx, |store, pass_nr, frame| { + let before = drafting.then(|| store.entries.get(&id).cloned()); + (f(store, pass_nr, frame), before) + }); + if let Some(before) = before { + let viewport = pass::current_viewport(ctx); + layout_memory::note_undo( + ctx, + Box::new(move |ctx: &Context| { + PerViewport::::with(ctx, viewport, |store| match before { + Some(entry) => drop(store.entries.insert(id, entry)), + None => drop(store.entries.remove(&id)), + }); + }), + ); + } + out +} + /// Decides whether the child `id`, whose content starts at `at` in this run, runs this pass. It runs when its extent /// placed at `at` meets the view, or when one of its stops holds focus or is the target of a focus request. Its /// extent is the one a run showed it at, else `estimate`. The first run of a pass decides; every later run of the /// pass gets the same answer, so a measuring run and the real run lay out the same children. pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision { let targets = crate::runtime::focus::targets(ctx); - let decision = with(ctx, |store, pass_nr, frame| { + write(ctx, id, |store, pass_nr, frame| { let entry = store.touch(Some(view.owner), id, frame); let kind = usize::from(!sizing); // A child the other kind of run showed last takes that run's extent. - let size = entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(estimate); + let size = entry.sizes[kind].or(entry.sizes[1 - kind]).map_or(estimate, |measured| measured.size); let skip = match entry.decided { Some((decided_in, skip)) if decided_in == pass_nr => skip, _ => { @@ -256,20 +408,15 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - } }; if skip { Decision::Skip(size) } else { Decision::Run } - }); - #[cfg(feature = "testing")] - if matches!(decision, Decision::Skip(_)) { - crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); - } - decision + }) } -/// Records what a run that showed the child `id` found: its extent in a run of this kind and, from a real run, what -/// it registered with the focus service. -pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, size: Vec2, sizing: bool, registered: Option) { - with(ctx, |store, _, frame| { +/// Records what a run that showed the child `id` found: what it measured in a run of this kind and, from a real run, +/// what it registered with the focus service. +pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, measured: Measured, registered: Option) { + write(ctx, id, |store, _, frame| { let entry = store.touch(owner, id, frame); - entry.sizes[usize::from(!sizing)] = Some(size); + entry.sizes[usize::from(!sizing)] = Some(measured); if let Some(registered) = registered { entry.focus = Arc::new(registered); } @@ -285,106 +432,165 @@ 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, and the extent that run -/// took in a run of this kind (`sizing`). The first run of a pass decides from what changed since that run; a real run -/// also needs the child at the `place` it ran at, which a measuring run cannot tell. +/// 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 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 /// none of that held in its last run; /// - none of its stops holds focus or is the target of a focus request, now or in its last run; /// - no 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`); -/// - its content version is the one of its last run, and its environment (theme, density, scale, language, window -/// active) the one it ran in; -/// - no frame unsettled every child (`unsettle`): an app's repaint request outside every settling child, this frame or -/// the one before; -/// - for a child with no content version: no input other than pointer motion and no edit of a given value -/// (`note_given_edit`) this frame or the one before; -/// - the run did nothing a replay cannot repeat (`runtime::replay`). -pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { - // Keyed calls feed their 8-byte content version into the key. - #[cfg(feature = "testing")] - if content.is_some() { - crate::runtime::measure::count_memo_key_bytes(ctx, 8); - } - let input = ctx.input(|input| { - input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) - }); +/// - 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 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; +/// - 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: Id, + sizing: Option, + place: Option, + view: Option, + key: Key, +) -> Option<(Vec2, Rect, RecordShift)> { 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 settled = with(ctx, |store, pass_nr, frame| { - store.changes.scan(pass_nr, frame, input); + let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some()); + let settled = write(ctx, id, |store, pass_nr, frame| { let changes = &store.changes; - // Usually empty: only the values written this frame. - let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone()); - let unsettled = changes.unsettled_through >= frame || (content.is_none() && changes.unversioned_through >= frame); + // Usually `None`: only the values written this frame. + let edited = changes.edited_in(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; - settled.frame < frame - && settled.content == content - && !settled.engaged - && !facts.blocked - && 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 } }; - let at = |settled: &Settled| place.is_none_or(|place| place == settled.place); - let settled = entry.settled.clone().filter(|settled| replays && at(settled)); + // A measuring run cannot tell the place: it replays where the run was. + let moved = |settled: &Settled| match place { + Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed), + None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }), + }; + let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled))); if replays && settled.is_none() { entry.replays = Some((pass_nr, false)); } - let kind = usize::from(!sizing); - settled.map(|settled| (entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(settled.rect.size()), settled)) + settled.and_then(|(moved, settled)| { + // An extent depends on the room's size, not on where the room is. + let size = match sizing { + Some(room) => entry.sizes[0].filter(|measured| measured.key == settled.key && measured.room.size() == room.size())?.size, + None => entry.sizes[1].filter(|measured| measured.key == settled.key).map_or(settled.rect.size(), |measured| measured.size), + }; + Some((size, moved, settled)) + }) }); - // The pointer over it, or a press that started on it, is read outside the store. - let Some((size, settled)) = settled else { - #[cfg(feature = "testing")] - crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); - return None; - }; - if engaged(ctx, &settled) { - with(ctx, |store, pass_nr, _| { + // The pointer over it, a press that started on it, the memory of the components it showed, the framework inputs it + // read and the commands queued for its instances are read outside the store. + let (size, Moved { shift, with_clip }, settled) = settled?; + let rect = shift.rect(settled.rect); + // The scroll view a nested child decided by: the run's, moved with the record, while the clip moved with it; a run + // that lay wholly in its clip ran every nested child, which holds at any view. + 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) + || moved(ctx, &settled, view) + { + write(ctx, id, |store, pass_nr, _| { if let Some(entry) = store.entries.get_mut(&id) { entry.replays = Some((pass_nr, false)); } }); - #[cfg(feature = "testing")] - crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); return None; } - #[cfg(feature = "testing")] - crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Replayed); - Some(size) + Some((size, rect, shift)) } -/// Whether the pointer is over the rect the settled run took on its layer, or a press that is held started there. -fn engaged(ctx: &Context, settled: &Settled) -> bool { - let rect = settled.rect.intersect(settled.place.clip); - let screen = ctx.layer_transform_to_global(settled.place.layer).map_or(rect, |transform| transform * rect); - ctx.rect_contains_pointer(settled.place.layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin)) +/// Whether something a memoized view's run read outside its props moved since: a framework input it read has another +/// generation, the scroll view a nested `Lazy` child decided by is another than the one it needs (`view`: the view it +/// needs and the view now, in a real run whose record replays only in that view; a measuring run lays the content out +/// from offset zero, so its view is not the one the real run decided by), or a command waits for one of its instances. +fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option)>) -> bool { + let facts = &settled.record.facts; + inputs::moved(ctx, facts.inputs, &settled.seen) + || (facts.inputs.contains(Input::Scroll) && view.is_some_and(|(needs, now)| needs != now)) + || crate::runtime::commands::queued_for(ctx, &facts.instances) } -/// Adds the last real run of the settling child `id` to the running pass, in place of running it. -pub(crate) fn replay_settled(ctx: &Context, id: Id) { - let settled = with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.clone())); - if let Some(settled) = settled { - replay::replay(ctx, &settled.record); +/// Whether the pointer is over `rect` (shown) on `layer`, or a press that is held started there. +fn engaged(ctx: &Context, layer: Layer, rect: Rect) -> bool { + let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); + 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 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 { + let settled = with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.clone()))?; + replay::replay(ctx, &settled.record, shift); + settled.output.clone() +} + +/// Compares the audit run of the memoized view `name` (`id`), which added `record`, took `rect` and returned `output`, +/// with its kept run replayed at the place `shift` names (`runtime::audit`). +#[cfg(feature = "testing")] +pub(crate) fn audit( + ctx: &Context, + name: &'static str, + id: Id, + run: crate::runtime::audit::Shown<'_>, + same: Option, + shift: &RecordShift, +) { + // A pass that turned to discard during the audit run paints nothing: its run is no shown run to compare with. + if ctx.will_discard() { + return; } + let Some(kept) = with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.clone())) else { return }; + let kept_run = crate::runtime::audit::Shown { record: &kept.record, rect: kept.rect, output: kept.output.as_ref() }; + crate::runtime::audit::compare(name, id, (kept_run, shift), run, same); +} + +/// What the last real run of the memoized view `id` returned, for a measuring run that takes its kept extent. +pub(crate) fn kept_output(ctx: &Context, id: Id) -> Option { + with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.as_ref()?.output.clone())) +} + +/// The serial of the last edit (`note_edit`): a run notes it when it starts. +pub(crate) fn edits(ctx: &Context) -> u64 { + with(ctx, |store, _, _| store.changes.serial) } /// Keeps the entry of the child `id` this frame: a replayed run does not reach the children inside it. @@ -394,125 +600,118 @@ pub(crate) fn keep(ctx: &Context, owner: Option, id: Id) { }); } -/// Keeps the real run `record` of the settling child `id`, which ran at `place`, took `rect` and showed the app data -/// of version `content`. -pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, content: Option) { +/// 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, + pub(crate) edits: u64, + pub(crate) seen: inputs::Seen, + pub(crate) view: Option, + pub(crate) output: Option, +} + +/// Keeps the real run `record` of the memoized view `id`, which ran at `place` and took `rect`. A run in a pass egui +/// will discard keeps none: egui paints nothing of that pass (`Painter::is_visible` is false in it), so the run registers +/// invisible widgets and no nodes, which a shown pass's replay must not add. The kept record stays the last shown pass's. +pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, Ran { key, edits, seen, view, output }: Ran) { + if ctx.will_discard() { + return; + } let targets = focus::targets(ctx); let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); - let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, content }; - settled.engaged |= engaged(ctx, &settled); - with(ctx, |store, _, frame| { + let lives = crate::runtime::memory::ended_generation(ctx); + let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, key, pass: 0, edits, output, lives, seen, view }; + settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip)); + with(ctx, |store, pass_nr, frame| { settled.frame = frame; + settled.pass = pass_nr; if let Some(entry) = store.entries.get_mut(&id) { entry.settled = Some(Arc::new(settled)); } }); } -/// Drops the kept run of the settling child `id`: its last run is not one it settles on, so it runs again. -pub(crate) fn forget(ctx: &Context, id: Id) { - with(ctx, |store, _, _| { - if let Some(entry) = store.entries.get_mut(&id) { - entry.settled = None; - } - }); -} - -/// 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 and no edit of a given value. 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)> { - 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)> { with(ctx, |store, pass_nr, frame| { - store.changes.scan(pass_nr, frame, input); - let changes = &store.changes; - let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone()); - let unsettled = changes.unsettled_through >= frame || changes.unversioned_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) { - with(ctx, |store, pass_nr, frame| { - store.touch(None, id, frame).measured = Some(MeasuredRun { facts, pass: pass_nr, frame, place, size }); +/// 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, size: Vec2) { + write(ctx, id, |store, pass_nr, frame| { + 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 edited = &mut store.changes.edited; - if edited.0 != frame { - *edited = (frame, HashSet::new()); + let changes = &mut store.changes; + if changes.edited.0 != frame { + changes.edited = (frame, HashMap::new()); } - edited.1.insert(key); + changes.serial += 1; + changes.edited.1.insert(key, changes.serial); }); } -/// 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)); -} - -/// Unsettles the settling children with no content version for this frame and the next: an edit of a given value, -/// which the app applies to data the framework does not track. A child with a content version sees what the edit -/// changed in its data as a new version, as it does for input. -pub(crate) fn note_given_edit(ctx: &Context) { - with(ctx, |store, _, frame| store.changes.unversioned_through = store.changes.unversioned_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). +/// Records the extent of a row of the collection `owner` that was measured this pass. The collection places the rows +/// it does not build by it (its item layout answers for rows it never built), and every run of the pass that reaches +/// the row takes it without measuring the row again. pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) { - shown(ctx, Some(owner), id, size, false, None); + write(ctx, id, |store, pass_nr, frame| { + let entry = store.touch(Some(owner), id, frame); + entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING }); + entry.measured_in = Some(pass_nr); + }); } -/// Runs `f` with a reader of the extents the rows of the collection `owner` had in the last pass that built them, for -/// a collection that reads many entries at once. -pub(crate) fn reading(ctx: &Context, owner: Id, f: impl FnOnce(&dyn Fn(Id) -> Option) -> R) -> R { - with(ctx, |store, _, frame| { +/// Runs `f` with a reader of the extents the rows of the collection `owner` had in the last pass that measured them, +/// each with whether that pass is this one, for a collection that reads many entries at once. +pub(crate) fn reading(ctx: &Context, owner: Id, f: impl FnOnce(&dyn Fn(Id) -> Option<(Vec2, bool)>) -> R) -> R { + with(ctx, |store, pass_nr, frame| { store.reached.insert(owner, frame); let store = std::cell::RefCell::new(store); f(&|id| { let mut store = store.borrow_mut(); let entry = store.entries.get_mut(&id)?; entry.touched = frame; - entry.sizes[1].or(entry.sizes[0]) + let size = entry.sizes[1].or(entry.sizes[0]).map(|measured| measured.size)?; + Some((size, entry.measured_in == Some(pass_nr))) }) }) } -/// Starts the real run that lays out the content of the scroll area `owner`: the children it places report to it. -pub(crate) fn begin(ctx: &Context, owner: Id) { +/// Starts the real run that lays out the content of the scroll area of `view`, which names `anchor` as its scroll +/// position and glides to `reveal`: the children it places report to it. +pub(crate) fn begin(ctx: &Context, view: View, anchor: Option, reveal: Option) { with(ctx, |store, _, _| { - store.placed.insert(owner, Placed::default()); + store.placed.insert(view.owner, Placed { view: Some(view), ..Placed::named(anchor, reveal, view.axes) }); }); } /// Reports, in the real run that lays out the content of `view`'s area, that the child `id` took `rect`, run or not. pub(crate) fn place(ctx: &Context, view: &View, id: Id, rect: Rect) { - let at = view.start_of(rect) - view.start_of(view.rect); + note_place(ctx, view.owner, id, rect); +} + +/// Reports that the child `id` of the area `owner` took `rect`. A settled run around the child that is replayed later +/// reports it again, moved with the run, and the area takes its place from the view it shows then; an area inside the +/// replayed run does not lay out in that pass, and its places were taken (`placed`). +fn note_place(ctx: &Context, owner: Id, id: Id, rect: Rect) { + replay::journal(ctx, || (owner, id, rect), |ctx, &(owner, id, rect)| note_place(ctx, owner, id, rect)); with(ctx, |store, _, _| { - if let Some(placed) = store.placed.get_mut(&view.owner) { - placed.note((view.anchor, view.axes), id, at, rect.size()); - if view.reveal == Some(id) { - placed.reveal = Some(at); - } + if let Some(placed) = store.placed.get_mut(&owner) + && let Some(view) = placed.view + { + placed.note(id, view.start_of(rect) - view.start_of(view.rect), rect.size()); } }); } diff --git a/crates/ui-contract/src/runtime/lock_keys.rs b/crates/ui-contract/src/runtime/lock_keys.rs index 948ec7779..453e18d85 100644 --- a/crates/ui-contract/src/runtime/lock_keys.rs +++ b/crates/ui-contract/src/runtime/lock_keys.rs @@ -16,6 +16,12 @@ struct Reading { /// Whether Caps Lock is on in this pass: the state injected input holds, else the platform's. #[doc(hidden)] pub fn caps_lock(ctx: &Context) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keys); + caps_on(ctx) +} + +/// `caps_lock` without noting the read. +pub(crate) fn caps_on(ctx: &Context) -> bool { if let Some(on) = crate::runtime::egui::injected::caps_lock(ctx) { return on; } diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 969020d63..6a789786a 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -84,6 +84,14 @@ struct RowMeasures { rows: Vec<(Id, u32)>, } +/// The collection rows whose item was built, by item id, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +struct RowBuilds { + pass: u64, + rows: Vec<(Id, u32)>, +} + /// The rows that asked their body units for their least widths, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -166,9 +174,19 @@ pub fn take_effects(ctx: &Context) -> Vec<&'static str> { store::with::(ctx, |log| if log.pass == frame { std::mem::take(&mut log.effects) } else { Vec::new() }) } +/// Whether the running code is a run of the replay audit (`runtime::audit`): that is the audit's work, not the pass's, +/// so the count trials count nothing in it. +#[cfg(feature = "testing")] +fn uncounted(ctx: &Context) -> bool { + super::replay::in_audit_run(ctx) +} + /// Counts a measuring run of the contents of the body `id` in this pass. #[cfg(feature = "testing")] pub(crate) fn count_body(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } let pass = ctx.cumulative_pass_nr(); store::with::(ctx, |log| { if log.pass != pass { @@ -184,6 +202,9 @@ pub(crate) fn count_body(ctx: &Context, id: Id) { /// Counts a contribution a measuring run made in this pass (`delta` 1), or a draft took back (-1). #[cfg(feature = "testing")] pub(crate) fn count_contribution(ctx: &Context, delta: i64) { + if uncounted(ctx) { + return; + } let pass = ctx.cumulative_pass_nr(); store::with::(ctx, |log| { if log.pass != pass { @@ -217,7 +238,7 @@ pub fn body_runs(ctx: &Context) -> Vec<(Id, u32)> { /// Counts a run of a component of the type `name` in this pass, measuring or real. Counts nothing without `testing`. pub(crate) fn count_run(ctx: &Context, name: &'static str) { #[cfg(feature = "testing")] - { + if !uncounted(ctx) { let pass = ctx.cumulative_pass_nr(); pass_state::with::(ctx, |log| { if log.pass != pass { @@ -244,6 +265,9 @@ pub fn last_pass_runs(ctx: &Context) -> Vec<(&'static str, u32)> { /// Counts a build and measure of the rows of the collection `id` for the largest in this pass. #[cfg(feature = "testing")] pub(crate) fn count_widest(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } let pass = ctx.cumulative_pass_nr(); store::with::(ctx, |log| { if log.pass != pass { @@ -266,6 +290,9 @@ pub fn widest_runs(ctx: &Context) -> Vec<(Id, u32)> { /// Counts a build and measure of the height of a collection's auto row, kept under `id`, in this pass. #[cfg(feature = "testing")] pub(crate) fn count_row_measure(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } let pass = ctx.cumulative_pass_nr(); store::with::(ctx, |log| { if log.pass != pass { @@ -285,6 +312,31 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) } +/// Counts a build of the item `id` of a collection row in this pass: for a measure, or to show it. +#[cfg(feature = "testing")] +pub(crate) fn count_row_build(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = RowBuilds { pass, rows: Vec::new() }; + } + match log.rows.iter_mut().find(|(row, _)| *row == id) { + Some((_, count)) => *count += 1, + None => log.rows.push((id, 1)), + } + }); +} + +/// The collection rows whose item was built in the last pass, by item id, and how many times each. +#[cfg(feature = "testing")] +pub fn row_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) +} + /// Counts a chord text an access report read for a node in this pass. #[cfg(feature = "testing")] pub(crate) fn count_chord_text(ctx: &Context) { @@ -337,6 +389,9 @@ pub fn last_pass_wake_walks(ctx: &Context) -> u32 { /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } let pass = ctx.cumulative_pass_nr(); store::with::(ctx, |log| { if log.pass != pass { @@ -355,45 +410,71 @@ pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| log.runs.clone()) } -/// What a settling child's decision was. +/// 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] -pub enum Settle { - /// The child ran. +pub enum MemoRun { + /// It ran. Ran, - /// The child's last run was replayed in place of running. + /// Its last run was replayed in place of running. Replayed, - /// The child is out of view and took its last extent without running. + /// It is out of view and took its last extent without running. OutOfView, } -/// The settled-test decisions of one pass. +/// How each memoized view took part in one pass (real runs only), and in every pass of one frame (every call, the +/// calls of sizing and measuring runs included). #[cfg(feature = "testing")] #[derive(Default)] -pub(crate) struct SettleLog { +pub(crate) struct MemoLog { pass: u64, - decisions: Vec<(Id, Settle)>, + runs: Vec<(&'static str, Id, MemoRun)>, + frame: u64, + frame_runs: Vec<(&'static str, Id, MemoRun)>, } -/// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and -/// `lazy::decide` (out of view); a rename of that decision point moves both calls. +/// Counts how the view `name` (`id`) took part in a call of this pass; `real` for a call in a real run. Fed by +/// `contract::Lazy`'s one runner, which memoized views share. #[cfg(feature = "testing")] -pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { +pub(crate) fn count_memo_run(ctx: &Context, name: &'static str, id: Id, run: MemoRun, real: bool) { + if uncounted(ctx) { + return; + } let pass = ctx.cumulative_pass_nr(); - pass_state::with::(ctx, |log| { - if log.pass != pass { - *log = SettleLog { pass, decisions: Vec::new() }; + let frame = super::egui::pass::frame_nr(ctx, super::egui::pass::current_viewport(ctx)); + pass_state::with::(ctx, |log| { + if log.frame != frame { + log.frame = frame; + log.frame_runs.clear(); + } + log.frame_runs.push((name, id, run)); + if real { + if log.pass != pass { + log.pass = pass; + log.runs.clear(); + } + log.runs.push((name, id, run)); } - log.decisions.push((id, what)); }); } -/// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. +/// How the memoized views (by name, `"Lazy"` for a `Lazy` child) took part in the real run of the last pass, in the +/// order they were decided; empty when that pass decided none. #[cfg(feature = "testing")] -pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { +pub fn last_pass_memo_runs(ctx: &Context) -> Vec<(&'static str, Id, MemoRun)> { let last = ctx.cumulative_pass_nr().saturating_sub(1); - pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) + pass_state::with::(ctx, |log| if log.pass == last { log.runs.clone() } else { Vec::new() }) +} + +/// How the memoized views took part in every pass of the last frame, in order: every call, those of sizing and +/// measuring runs included (a `Ran` there is a measuring run, which keeps no record). Empty when that frame decided +/// none. +#[cfg(feature = "testing")] +pub fn last_frame_memo_runs(ctx: &Context) -> Vec<(&'static str, Id, MemoRun)> { + let viewport = super::egui::pass::current_viewport(ctx); + let last = super::egui::pass::frame_nr(ctx, viewport).saturating_sub(1); + pass_state::with::(ctx, |log| if log.frame == last { log.frame_runs.clone() } else { Vec::new() }) } /// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. @@ -444,10 +525,12 @@ fn last_totals(ctx: &Context, f: impl FnOnce(&Totals) -> R, none: R) -> R { }) } -/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes -/// per call with a content version). +/// Counts `bytes` fed into a memo key in this pass: a memoized view's key, before its run and after it. #[cfg(feature = "testing")] pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { + if uncounted(ctx) { + return; + } totals(ctx, |log| log.key_bytes += bytes); } @@ -460,6 +543,9 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { /// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. #[cfg(feature = "testing")] pub(crate) fn count_text_layout(ctx: &Context) { + if uncounted(ctx) { + return; + } totals(ctx, |log| log.text_layouts += 1); } @@ -472,6 +558,9 @@ pub fn last_pass_text_layouts(ctx: &Context) -> u32 { /// Counts a measure call of a leaf component of the type `name` in this pass. #[cfg(feature = "testing")] pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { + if uncounted(ctx) { + return; + } totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { Some((_, count)) => *count += 1, None => log.asks.push((name, 1)), diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 98442632e..27ed98177 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -218,6 +218,16 @@ pub(crate) struct Registry { slots: FastMap<(Id, u8, TypeId), SlotRecord>, /// Evicted slots, moved out inside the end hook; the first pipeline run of the next pass drops them. graveyard: Vec, + /// Moves each time owners' shown lives end (`evict`, `end_shown`). + ended_generation: u64, + /// The generation at which each owner's shown life ended, until it registers again: a kept run that registered it + /// before then showed state that is gone (`ended_since`). + ended: FastMap, + /// Writes of the saved value under each key's id made outside a component's edit (`set_saved_value`, + /// `forget_saved`), which a saved binding in a memoized view's props feeds. + saved_writes: FastMap, + /// Session slots forgotten (`forget`), which a kept binding in a memoized view's props feeds. + session_writes: u64, /// Slot records write-back has written, for the count trials. #[cfg(feature = "testing")] written: usize, @@ -257,12 +267,40 @@ impl Seen { /// for 3 passes of the viewport that last showed it and 0.5 s are evicted by `evict`. pub(crate) fn register_owner(ctx: &Context, owner: Id) { crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| register_owner(ctx, owner)); + crate::runtime::replay::note_owner(ctx, owner); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); + reg.ended.remove(&owner); }); } +/// The generation of ended shown lives now: a kept run stores it, and `ended_since` compares with it. +pub(crate) fn ended_generation(ctx: &Context) -> u64 { + pass_state::with::(ctx, |reg| reg.ended_generation) +} + +/// Whether the shown life of one of `owners` ended after the generation `since`: a run that registered them showed +/// shown-tier state (remembered values, drafts, text state) that memory has dropped since. +pub(crate) fn ended_since(ctx: &Context, owners: &[Id], since: u64) -> bool { + pass_state::with::(ctx, |reg| { + !reg.ended.is_empty() && owners.iter().any(|owner| reg.ended.get(owner).is_some_and(|ended| *ended > since)) + }) +} + +/// How many times the saved value under `key` was written outside a component's edit, and how many times session slots +/// were forgotten: what a saved or kept binding in a memoized view's props feeds. +pub(crate) fn writes(ctx: &Context, key: Option<&SaveKey>) -> (u64, u64) { + pass_state::with::(ctx, |reg| (key.and_then(|key| reg.saved_writes.get(&key.id()).copied()).unwrap_or(0), reg.session_writes)) +} + +/// Ends the shown lives of `owners` in the registry's generation count. +fn end_lives(reg: &mut Registry, owners: impl IntoIterator) { + reg.ended_generation += 1; + let generation = reg.ended_generation; + reg.ended.extend(owners.into_iter().map(|owner| (owner, generation))); +} + /// Eviction, run by the end hook. An owner that `owner_due` finds due loses its shown and press entries (a press /// entry whose press never ended goes with its owner). Session and saved entries go only through `forget` and /// `forget_saved`. @@ -276,6 +314,7 @@ pub(crate) fn evict(ctx: &Context) { return; } reg.owners.retain(|id, _| !dead.contains(id)); + end_lives(reg, dead.iter().copied()); let moved = take_shown(ctx, reg, |owner| dead.contains(&owner)); QUEUED.fetch_add(moved.len(), Ordering::Release); reg.graveyard.extend(moved); @@ -288,7 +327,12 @@ pub(crate) fn evict(ctx: &Context) { /// hook, so the slots drop here and their dispose hooks (a running gesture's removal) report in this pass. False when /// `owner` has no record: its life ended already, or it never ran. pub(crate) fn end_shown(ctx: &Context, owner: Id) -> bool { - let moved = pass_state::with::(ctx, |reg| reg.owners.remove(&owner).map(|_| take_shown(ctx, reg, |of| of == owner))); + let moved = pass_state::with::(ctx, |reg| { + reg.owners.remove(&owner).map(|_| { + end_lives(reg, [owner]); + take_shown(ctx, reg, |of| of == owner) + }) + }); moved.is_some() } @@ -311,6 +355,7 @@ static QUEUED: AtomicUsize = AtomicUsize::new(0); /// Removes the session slots under `id` (all types). The only way a session slot goes. pub(crate) fn forget(ctx: &Context, id: Id) { forget_tier(ctx, id, SESSION); + pass_state::with::(ctx, |reg| reg.session_writes += 1); } /// The saved value under `key`, outside a dialog: an app reads one SAVED value through the same store the dialogs' @@ -328,6 +373,13 @@ pub fn set_saved_value(ctx: &Context, key: &SaveKey, value: T) { stage.touched.get_mut().clear(); *stage.saved::(key) = value; stage.write_back(); + saved_written(ctx, key); +} + +/// Notes a write of the saved value under `key` outside a component's edit: a memoized view whose props bind it runs. +fn saved_written(ctx: &Context, key: &SaveKey) { + pass_state::with::(ctx, |reg| *reg.saved_writes.entry(key.id()).or_default() += 1); + crate::runtime::lazy::note_edit(ctx, crate::runtime::reads::BindKey::Saved(Id::NULL.with(key))); } /// Removes the saved slots of `key` and the value stored under it. The only way a saved slot goes. @@ -337,6 +389,7 @@ pub(crate) fn forget_saved(ctx: &Context, key: &SaveKey) { if let Some(host) = Env::host_of(ctx) { forget_stored(&host, key); } + saved_written(ctx, key); } fn forget_tier(ctx: &Context, id: Id, tier: u8) { @@ -479,11 +532,7 @@ impl MemoryStage { return; } self.claimed.borrow_mut().push(base); - let viewport = pass::current_viewport(&self.ctx); - let pass_nr = pass::pass_nr(&self.ctx, viewport); - let duplicate = - PerViewport::>::with_pass(&self.ctx, viewport, pass_nr, |claimed, _| claimed.clear(), |claimed| !claimed.insert(base)); - debug_assert!(!duplicate, "an id is the base of two open stages in one pass"); + claim_id(&self.ctx, base, "an id is the base of two open stages in one pass"); } /// Read-only access for `measure_in`: opens no stage. @@ -844,9 +893,13 @@ impl Default for FactRecord { } impl Facts { - /// Registers `fact` for the next pass of the running viewport. + /// Registers `fact` for the next pass of the running viewport. A settled view's replay registers it again. #[doc(hidden)] - pub fn register(ctx: &Context, fact: T) { + pub fn register(ctx: &Context, fact: T) + where + T: PartialEq + std::fmt::Debug + crate::runtime::Shift, + { + crate::runtime::replay::journal(ctx, || fact.clone(), |ctx, fact| Self::register(ctx, fact.clone())); Self::with_record(ctx, |record| record.this.push(fact)); } @@ -870,6 +923,18 @@ impl Facts { } } +/// Debug assertion: `id` is claimed once in a pass of its viewport, by an open stage or a memoized view's entry; a +/// second claim fails with `what`. +pub(crate) fn claim_id(ctx: &Context, id: Id, what: &'static str) { + if !cfg!(debug_assertions) { + return; + } + let viewport = pass::current_viewport(ctx); + let pass_nr = pass::pass_nr(ctx, viewport); + let duplicate = PerViewport::>::with_pass(ctx, viewport, pass_nr, |claimed, _| claimed.clear(), |claimed| !claimed.insert(id)); + debug_assert!(!duplicate, "{what}"); +} + /// Runs `f` on the session slot of `id` for a service or pattern that has no component context: the slot is read, /// changed and written back in one call, and it goes only through `forget`. Calls nest freely and repeat within a /// pass, because no stage claims a base. diff --git a/crates/ui-contract/src/runtime/mod.rs b/crates/ui-contract/src/runtime/mod.rs index 6ec5255d8..74870f6bb 100644 --- a/crates/ui-contract/src/runtime/mod.rs +++ b/crates/ui-contract/src/runtime/mod.rs @@ -1,6 +1,8 @@ //! Per-pass and per-frame services and the one egui adapter. pub mod access; +#[cfg(feature = "testing")] +pub(crate) mod audit; pub mod commands; pub mod cursor; pub mod drag; @@ -10,6 +12,7 @@ pub mod env; pub mod focus; pub mod frame; pub mod ime; +pub(crate) mod inputs; pub mod inspect; pub mod install; pub mod keys; @@ -30,11 +33,14 @@ pub(crate) mod reads; pub(crate) mod replay; pub mod requests; pub mod sampler; +pub(crate) mod shift; pub mod toast; pub mod wheel; pub mod windows; pub mod words; +pub use ::egui::RecordShift; pub use install::{InstallError, InstallSpec, install}; #[doc(hidden)] pub use replay::journal; +pub use shift::{Clip, Shift}; diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index 409654944..9f73466f1 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -250,7 +250,7 @@ pub fn now() -> web_time::Instant { } /// Marks the running viewport as having an animation that is not at its end value. -fn note_unsettled(ctx: &Context) { +pub(crate) fn note_unsettled(ctx: &Context) { crate::runtime::replay::note_unsettled(ctx); PerViewport::::with(ctx, pass::current_viewport(ctx), |wanted| wanted.unsettled = true); } @@ -283,6 +283,11 @@ pub(crate) fn layer_presence(ctx: &Context, base: Id, owner: Id, policy: MotionP let stage = MemoryStage::open_owned(ctx, memory::sub(base, "presence"), owner); let presence = Driver { stage: &stage, base, policy }.presence("open", open, spec); stage.write_back(); + // The exit that ends here is the last pass in which the layer's hosts run it: from the next pass `layer_fading` + // answers false and they skip it. What ran around it this pass does not hold for the next one. + if !open && !layer_fading(ctx, base) { + note_unsettled(ctx); + } presence } @@ -563,7 +568,7 @@ impl Driver<'_> { } /// Asks for a pass of the running viewport at `at`; the earliest request wins. -fn wake_at(ctx: &Context, at: f64) { +pub(crate) fn wake_at(ctx: &Context, at: f64) { crate::runtime::replay::note_wake(ctx, at); PerViewport::::with(ctx, pass::current_viewport(ctx), |wanted| wanted.wake = Some(wanted.wake.map_or(at, |old| old.min(at)))); } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index c0dc1615a..a6f1fcdce 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -292,9 +292,15 @@ fn with_persist(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut Pers /// Whether the layer `id` was shown last frame. pub fn is_open(ctx: &Context, id: Id) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| pass.last.iter().any(|entry| entry.id == id)) } +/// The layers shown last frame, as the tracked input `Overlays` compares them: each one's id and whether it exits. +pub(crate) fn open_state(ctx: &Context) -> Vec<(Id, bool)> { + with_pass(ctx, |pass| pass.last.iter().map(|entry| (entry.id, entry.exiting)).collect()) +} + /// Queues a close of the layer `id` (a popup or a container). The owner's step 9 or `OverlayUi::show` collects it and /// step 15 writes it. pub fn request_close(ctx: &Context, id: Id, why: CloseReason) { @@ -361,6 +367,7 @@ pub(crate) fn peek_close(ctx: &Context, id: Id) -> Option { /// Whether any layer of the running viewport that `filter` counts was shown last frame. pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| { pass.last.iter().filter(|entry| !entry.exiting).any(|entry| match filter { OpenFilter::Any => true, @@ -372,6 +379,7 @@ pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool { /// The layer that receives Cancel: the newest member of the topmost family that takes keys. pub fn top(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); let viewport = pass::current_viewport(ctx); let raised = with_persist(ctx, viewport, |persist| persist.raised.clone()); with_pass(ctx, |pass| { @@ -396,6 +404,7 @@ pub(crate) fn popup_above(ctx: &Context, layer: Layer, below: Layer) -> bool { /// `id` and everything opened from inside it, shown last frame. pub fn family(ctx: &Context, id: Id) -> SmallVec<[Id; 4]> { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| { let mut out: SmallVec<[Id; 4]> = SmallVec::new(); if pass.last.iter().any(|entry| entry.id == id) { @@ -420,6 +429,7 @@ pub(crate) fn open_entries(ctx: &Context) -> Vec { /// The entry of the layer `id` shown last frame. #[doc(hidden)] pub fn entry(ctx: &Context, id: Id) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| pass.last.iter().find(|entry| entry.id == id).cloned()) } @@ -479,7 +489,7 @@ pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side }); let viewport = pass::current_viewport(ctx); let first = (pass::root_frame_nr(ctx), pass::pass_nr(ctx, viewport)); - let (down, released) = pointer::with_pass_pointer(ctx, |read| { + let (down, released) = pointer::with_pass_raw(ctx, |read| { let released = read.frame.as_ref().filter(|frame| frame.release == Some(craft_behavior::PointerButton::Primary)).map(|frame| frame.pos); (read.primary_down, released) }); @@ -719,7 +729,7 @@ fn families(entries: &[OpenEntry], raised: &IdMap) -> Vec> { pub(crate) fn end_pass(ctx: &Context) { let viewport = pass::current_viewport(ctx); let (current, last_ids) = with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::>())); - let pressed = pointer::frame(ctx).press.map(|press| press.origin); + let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin); let order = with_persist(ctx, viewport, |persist| { let stamp = |id: Id, persist: &mut Persist| { persist.counter += 1; diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 5cda04263..47a8da311 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -116,7 +116,7 @@ pass_state! { #[cfg(feature = "testing")] type_runs: crate::runtime::measure::TypeRuns, #[cfg(feature = "testing")] - settle_log: crate::runtime::measure::SettleLog, + memo_log: crate::runtime::measure::MemoLog, #[cfg(feature = "testing")] pass_totals: crate::runtime::measure::PassTotals, } diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index cbd9d8597..4d309774f 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -7,6 +7,7 @@ use crate::runtime::drag; use crate::runtime::egui::areas::{self, Layer}; use crate::runtime::egui::{input, pass}; use crate::runtime::frame::{PerViewport, Stamped}; +use crate::runtime::inputs::{self, Input}; use craft_behavior::{ Buttons, MultiTouch, PartRef, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressStart, ResolveFor, Shape, Winner, count_clicks, resolve, @@ -218,21 +219,26 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { stirred: read.stirred, }; let hover_at = pass_pointer.hover; - let mods_before = PerViewport::>>::with_pass( - ctx, - viewport, - pass_nr, - |_, _| {}, - |record| { - let before = record.frame.as_ref().map(|frame| frame.mods); - *record = Arc::new(pass_pointer); - before - }, - ); - // The modifiers are a value components read (`Cx::modifiers`): a change runs the settled ones that read them. - if mods_before.is_some_and(|before| before != mods) { - crate::runtime::lazy::note_edit(ctx, crate::runtime::reads::BindKey::Modifiers); + // The pointer and the modifiers are tracked inputs: their generations move when the held facts change or the pass + // brings pointer events. + if let Some(frame) = &pass_pointer.frame { + inputs::observe(ctx, Input::Modifiers, frame.mods); + inputs::observe(ctx, Input::Pointer, (frame.pos, frame.buttons, pass_pointer.hover, pass_pointer.primary_down)); + let events = frame.delta != Vec2::ZERO + || frame.press.is_some() + || frame.release.is_some() + || frame.scroll != Vec2::ZERO + || frame.zoom != 1.0 + || frame.rotation != 0.0 + || frame.multi_touch.is_some() + || pass_pointer.stirred + || pass_pointer.focus_lost + || !pass_pointer.events.is_empty(); + if events { + inputs::bump(ctx, Input::Pointer); + } } + PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { shapes.last = std::mem::take(&mut shapes.this); shapes.last_bodies = std::mem::take(&mut shapes.this_bodies); @@ -273,9 +279,17 @@ pub(crate) fn pass_pointer(ctx: &Context) -> Arc { PerViewport::>>::with_pass(ctx, viewport, pass::pass_nr(ctx, viewport), |_, _| {}, |record| Arc::clone(record)) } -/// Reads what the begin hook read of the running pass in place, without cloning its events. +/// Reads what the begin hook read of the running pass in place, without cloning its events. A tracked input +/// (`runtime::inputs`): a memoized view that reads it runs when the pointer changes. #[doc(hidden)] pub fn with_pass_pointer(ctx: &Context, f: impl FnOnce(&PassPointer) -> R) -> R { + crate::runtime::replay::note_input(ctx, Input::Pointer); + with_pass_raw(ctx, f) +} + +/// `with_pass_pointer` without noting the read: for the hit sensing, press and drag steps of the component under the +/// pointer, which the pointer engages, and for the pass machinery. +pub(crate) fn with_pass_raw(ctx: &Context, f: impl FnOnce(&PassPointer) -> R) -> R { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| f(record)) @@ -294,12 +308,26 @@ pub(crate) fn buttons_of(ctx: &Context, viewport: ViewportId) -> Buttons { /// Reads the running pass's pointer frame, `None` before the begin hook, and its hover position in place. pub(crate) fn with_frame(ctx: &Context, f: impl FnOnce(Option<&PointerFrame>, Option) -> R) -> R { - with_pass_pointer(ctx, |pointer| f(pointer.frame.as_ref(), pointer.hover)) + with_pass_raw(ctx, |pointer| f(pointer.frame.as_ref(), pointer.hover)) } -/// The running pass's pointer input. +/// The running pass's pointer input. A tracked input (`runtime::inputs`): a memoized view that reads it runs when the +/// pointer changes. A view that reads only the modifiers reads [`mods`]. pub fn frame(ctx: &Context) -> PointerFrame { - with_pass_pointer(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame { + crate::runtime::replay::note_input(ctx, Input::Pointer); + frame_raw(ctx) +} + +/// The modifiers held in the running pass, with the latched ones (`PointerFrame::mods`). A tracked input: a memoized +/// view that reads them runs when they change, and only then. +pub fn mods(ctx: &Context) -> Mods { + crate::runtime::replay::note_input(ctx, Input::Modifiers); + with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods)) +} + +/// `frame` without noting the read: for the steps of the component under the pointer and the pass machinery. +pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame { + with_pass_raw(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame { pos: None, delta: Vec2::ZERO, buttons: Buttons::empty(), @@ -370,7 +398,7 @@ pub(crate) fn cancel_of_pass(ctx: &Context) -> Option { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); let requested = PerViewport::::with(ctx, viewport, |memory| memory.requested.filter(|(nr, _)| *nr == pass_nr).map(|(_, reason)| reason)); - requested.or_else(|| with_pass_pointer(ctx, |pointer| pointer.focus_lost).then_some(PressCancel::FocusLost)) + requested.or_else(|| with_pass_raw(ctx, |pointer| pointer.focus_lost).then_some(PressCancel::FocusLost)) } /// Writes `shapes` of the arena rooted at `root`, shown through `clip` (layer space), into the running pass's shape @@ -385,8 +413,8 @@ pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer let shapes: Vec> = shapes.into_iter().collect(); crate::runtime::replay::journal( ctx, - || (layer, root, clip, shapes.clone()), - |ctx, (layer, root, clip, shapes)| record_shapes(ctx, *layer, *root, *clip, shapes.iter().cloned()), + || (layer, root, crate::runtime::Clip::new(clip), shapes.clone()), + |ctx, (layer, root, clip, shapes)| record_shapes(ctx, *layer, *root, clip.rect(), shapes.iter().cloned()), ); add_shapes_in(ctx, viewport, layer, root, clip, shapes); } diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 31bd88acf..e89c74986 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -15,8 +15,12 @@ use std::sync::Arc; /// lives. A given value has none. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) enum BindKey { - /// A write-through place: its address and the type stored there. + /// A write-through place: its address and the type stored there. An address names the place in its pass only: + /// a record kept for a later pass keeps no such read. Place(usize, TypeId), + /// A field of a `Tracked` value (`bind_tracked!`) or a story value: the value's source id, the field's offset in + /// it, its size and its type. + Tracked(u64, usize, usize, TypeId), /// Session memory under this component id. Kept(Id), /// The saved tier under the key with this hash. @@ -27,8 +31,20 @@ pub(crate) enum BindKey { Command(u32, Option), /// A command the focused stop answers for (an edit it takes): the command's number. FocusedEdit(u32), - /// The modifiers held, with the latched ones (`Cx::modifiers`). - Modifiers, +} + +impl BindKey { + /// Whether an edit of `self` changes the value a reader of `read` read: the same value, or, within one source, a + /// value whose span overlaps the edited one's. A whole story value's edit changes each field of it a story binds + /// (`StoryData::value_at`), and a field's edit changes the whole value the Properties editor reads. + pub(crate) fn reaches(self, read: BindKey) -> bool { + match (self, read) { + (BindKey::Tracked(source, offset, size, _), BindKey::Tracked(read_source, at, read_size, _)) if size > 0 && read_size > 0 => { + source == read_source && (at.wrapping_sub(offset) < size || offset.wrapping_sub(at) < read_size) + } + _ => self == read, + } + } } /// One measure a reader made from the value it read: what it was offered and the size it took. @@ -39,6 +55,8 @@ pub(crate) struct Sample { pub took: Vec2, } +crate::stays!(Read); + #[derive(Clone, Debug, PartialEq)] struct Read { key: BindKey, @@ -98,7 +116,11 @@ pub(crate) fn note(ctx: &Context, key: BindKey, reader: Id, measuring: bool, sam } else { let read = Read { key, reader, measuring, runs, samples }; crate::runtime::replay::note_read(ctx, key); - crate::runtime::replay::journal(ctx, || read.clone(), |ctx, read| with(ctx, |reads| reads.reads.push(read.clone()))); + // The reads are a set to what reads them: a run that measures a component again (a kept transcript's check) + // reads nothing new. A place's address names it in this pass only: a replay in a later pass notes no such read. + if !matches!(key, BindKey::Place(..)) { + crate::runtime::replay::journal_distinct(ctx, || read.clone(), |ctx, read| with(ctx, |reads| reads.reads.push(read.clone()))); + } with(ctx, |reads| reads.reads.push(read)); } } @@ -146,11 +168,11 @@ pub(crate) struct EarlierReads { pub samples: Vec, } -/// The reads of `key` made so far in this pass, as `editor`'s edit of it sees them. +/// The reads `key` reaches (`BindKey::reaches`) made so far in this pass, as `editor`'s edit of it sees them. pub(crate) fn earlier(ctx: &Context, key: BindKey, editor: Id) -> EarlierReads { with(ctx, |reads| { let mut earlier = EarlierReads::default(); - for read in reads.reads.iter().filter(|read| read.key == key) { + for read in reads.reads.iter().filter(|read| key.reaches(read.key)) { if read.reader != editor { earlier.other = true; continue; diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 749a12c6d..b22730d9a 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -1,21 +1,25 @@ -//! 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 in +//! the real run (`journaling`): +//! 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}; use crate::runtime::frame; +use crate::runtime::inputs::{Input, Inputs}; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; -use egui::{Context, IdSet}; +use crate::runtime::shift::Shift; +use egui::{Context, IdSet, RecordShift}; use std::any::Any; use std::collections::HashSet; use std::fmt; @@ -28,9 +32,14 @@ use std::sync::atomic::{AtomicUsize, Ordering}; pub(crate) struct Entry(Arc); trait Noted: Send + Sync { - fn call(&self, ctx: &Context); + fn call(&self, ctx: &Context, shift: &RecordShift); + /// The entry a replay at the place `shift` names calls (`call`). + fn shifted(&self, shift: &RecordShift) -> Entry; fn as_any(&self) -> &dyn Any; fn same(&self, other: &dyn Noted) -> bool; + /// `same`, with each argument's coordinates and floats compared within `within` points (`Shift::snapped`). + #[cfg(feature = "testing")] + fn same_within(&self, other: &dyn Noted, within: f32) -> bool; fn describe(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result; } @@ -41,11 +50,19 @@ struct Note { impl Noted for Note where - A: PartialEq + fmt::Debug + Send + Sync + 'static, - F: Fn(&Context, &A) + Send + Sync + 'static, + A: PartialEq + fmt::Debug + Shift + Send + Sync + 'static, + F: Fn(&Context, &A) + Copy + Send + Sync + 'static, { - fn call(&self, ctx: &Context) { - (self.again)(ctx, &self.args); + fn shifted(&self, shift: &RecordShift) -> Entry { + Entry(Arc::new(Note { args: self.args.shifted(shift), again: self.again })) + } + + fn call(&self, ctx: &Context, shift: &RecordShift) { + if shift.is_none() { + (self.again)(ctx, &self.args); + } else { + (self.again)(ctx, &self.args.shifted(shift)); + } } fn as_any(&self) -> &dyn Any { @@ -57,6 +74,11 @@ where other.as_any().downcast_ref::().is_some_and(|other| other.args == self.args) } + #[cfg(feature = "testing")] + fn same_within(&self, other: &dyn Noted, within: f32) -> bool { + other.as_any().downcast_ref::().is_some_and(|other| self.args.snapped(&other.args, within) == other.args) + } + fn describe(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}({:?})", std::any::type_name::(), self.args) } @@ -82,13 +104,23 @@ static OPEN: AtomicUsize = AtomicUsize::new(0); pub(crate) struct Recorder { journal: Vec, open: Vec, + /// A replay is calling its journal's entries (`replay`): what they register is noted already. + replaying: bool, } struct Open { from: usize, + /// How many discard requests the pass's output held when the record opened. + discards: usize, focus: focus::Mark, egui: egui::PassMark, facts: Facts, + /// The record is kept for a later pass (a memoized view's), not used only within its pass (a measure-only child's): + /// it keeps no read of a place by address, which names the place in this pass only. + kept: bool, + /// The record is around a run of the replay audit (`runtime::audit`). + #[cfg(feature = "testing")] + audit: bool, } impl Open { @@ -96,9 +128,13 @@ impl Open { fn empty(ctx: &Context) -> Open { Open { from: 0, + discards: discard_requests(ctx), focus: focus::mark(ctx), egui: ctx.pass_mark(), facts: Facts { blocked: crate::runtime::access::scope::depth(ctx) > 0, ..Facts::default() }, + kept: true, + #[cfg(feature = "testing")] + audit: false, } } } @@ -114,6 +150,18 @@ pub(crate) struct Facts { pub(crate) wake: Option, /// The run did something a replay cannot repeat. pub(crate) blocked: bool, + /// The run asked for a discard pass: what it added is what the pass is thrown away for, so it is never replayed. + pub(crate) discards: bool, + /// The components whose memory owners registered in the run (`memory::register_owner`): a replay needs their + /// shown-tier state still kept (`memory::ended_since`). + pub(crate) owners: Vec, + /// The layout memory entries the run kept (`note_layout_keep`): a replay keeps them (`layout_memory::keep`). + pub(crate) layout_keeps: Vec, + /// The framework inputs the run read outside its props (`runtime::inputs`). + pub(crate) inputs: Inputs, + /// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one + /// is taken only by a run, so a replay waits until the queue holds none. + pub(crate) instances: Vec, } /// What one real run of a region added to its pass. @@ -126,6 +174,14 @@ pub(crate) struct Record { pub(crate) facts: Facts, } +impl Record { + /// Whether a replay can add the record at another place: egui's records hold no paint callback + /// (`PassRecords::paints_callback`). + pub(crate) fn movable(&self) -> bool { + !self.egui.paints_callback() + } +} + /// Whether a record is open around the running code. pub(crate) fn recording(ctx: &Context) -> bool { OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| !recorder.open.is_empty()) @@ -134,11 +190,32 @@ pub(crate) fn recording(ctx: &Context) -> bool { /// Opens a record around the real run of a region, which `close` ends. A run inside an open label scope cannot be /// replayed: the scope's patches reach nodes the record would not hold. pub(crate) fn open(ctx: &Context) { - let open = Open::empty(ctx); + push(ctx, Open::empty(ctx)); +} + +/// Opens a record used only within its pass, around a measuring run of a measure-only child, which `close` ends: it +/// keeps the places the run read by address too. +pub(crate) fn open_in_pass(ctx: &Context) { + push(ctx, Open { kept: false, ..Open::empty(ctx) }); +} + +fn push(ctx: &Context, open: Open) { pass_state::with::(ctx, |recorder| recorder.open.push(Open { from: recorder.journal.len(), ..open })); OPEN.fetch_add(1, Ordering::AcqRel); } +/// Opens a record around a run of the replay audit, which `close` ends as any other. +#[cfg(feature = "testing")] +pub(crate) fn open_audit(ctx: &Context) { + push(ctx, Open { audit: true, ..Open::empty(ctx) }); +} + +/// Whether the running code is inside a run of the replay audit. +#[cfg(feature = "testing")] +pub(crate) fn in_audit_run(ctx: &Context) -> bool { + OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| recorder.open.iter().any(|open| open.audit)) +} + /// Ends the innermost record, the one around a run on `layer`: paint or widgets on another layer block it. pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { OPEN.fetch_sub(1, Ordering::AcqRel); @@ -154,8 +231,14 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { if let Some(outer) = recorder.open.last_mut() { outer.facts.unsettled |= open.facts.unsettled; outer.facts.blocked |= open.facts.blocked; + outer.facts.discards |= open.facts.discards; + outer.facts.owners.extend(open.facts.owners.iter().copied()); + outer.facts.layout_keeps.extend(open.facts.layout_keeps.iter().copied()); outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake); - outer.facts.reads.extend(open.facts.reads.iter().copied()); + let kept = outer.kept; + outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..)))); + outer.facts.inputs.extend(open.facts.inputs); + outer.facts.instances.extend(open.facts.instances.iter().copied()); } else { recorder.journal.clear(); } @@ -163,15 +246,89 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { }); let egui = ctx.pass_records_since(&open.egui); let mut facts = open.facts; - facts.blocked |= egui.layers().any(|on| on != layer); + // Every measure of an entry keeps it again: the record keeps each one once. + facts.layout_keeps.sort_unstable_by_key(|id| id.value()); + facts.layout_keeps.dedup(); + // A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees: + // its run is never replayed. + facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback(); + // Every discard request reaches egui's output (`sizing::request_discard` and egui's own); layout memory's waits + // for the end of the pass and notes itself (`note_discard`). + facts.discards |= discard_requests(ctx) > open.discards; Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts } } +#[cfg(feature = "testing")] +impl Record { + /// Whether the run painted a paint callback, which keeps it from being replayed. + pub(crate) fn paints_callback(&self) -> bool { + self.egui.paints_callback() + } + + /// How a replay of `self` at the place `shift` names differs from the real run `run` there: one line per kind that + /// differs (paint, widget rects and AccessKit nodes; focus registrations; the journal; the values and framework + /// inputs read), each with its first difference. + pub(crate) fn differences(&self, run: &Record, shift: &RecordShift) -> Vec { + let within = crate::runtime::audit::WITHIN; + let mut found = Vec::new(); + match self.egui.shifted(shift).first_difference(&run.egui, within) { + // The display names a widget by its rect only; the difference may be in its sense, state or interact rect. + Some(egui::PassRecordsDiff::Widget { index, left, right }) => found.push(format!("widget rect {index}: left {left:?} / right {right:?}")), + // The display names a node by its bounds only; the difference may be in any other property. + Some(egui::PassRecordsDiff::Node { index, left, right }) => { + found.push(format!("AccessKit node {index}: left {left:?} / right {right:?}")) + } + Some(diff) => found.push(format!("paint, widgets or AccessKit: {diff}")), + None => {} + } + if let Some(diff) = self.focus.first_difference(&run.focus) { + found.push(format!("focus: {diff}")); + } + let shifted: Vec = self.journal.iter().map(|entry| entry.0.shifted(shift)).collect(); + let (left, right) = (&shifted, &run.journal); + if let Some(index) = left + .iter() + .zip(right) + .position(|(a, b)| !a.0.same_within(&*b.0, within)) + .or_else(|| (left.len() != right.len()).then(|| left.len().min(right.len()))) + { + found.push(format!("journal entry {index}: left {:?} / right {:?}", left.get(index), right.get(index))); + } + // A replay notes the kept run's reads and inputs in place of the run's: one the kept run missed is one a later + // edit doesn't rerun the view for. + if self.facts.reads != run.facts.reads { + let only = |a: &HashSet, b: &HashSet| { + let mut only: Vec = a.difference(b).map(|key| format!("{key:?}")).collect(); + only.sort_unstable(); + only + }; + found.push(format!( + "reads: left only {:?} / right only {:?}", + only(&self.facts.reads, &run.facts.reads), + only(&run.facts.reads, &self.facts.reads) + )); + } + if self.facts.inputs != run.facts.inputs { + let list = |inputs: Inputs| Input::ALL.into_iter().filter(|input| inputs.contains(*input)).collect::>(); + found.push(format!("inputs: left {:?} / right {:?}", list(self.facts.inputs), list(run.facts.inputs))); + } + found + } +} + impl Facts { /// Whether the run these facts are of still holds at `now`, after the values `edited` changed in the frame: nothing - /// in it moves, the time it asked to be shown again has not come, and it read none of them. + /// in it moves, the time it asked to be shown again has not come, and it read none of them, nor a value overlapping one. pub(crate) fn quiet(&self, now: f64, edited: Option<&HashSet>) -> bool { - !self.unsettled && self.wake.is_none_or(|at| at > now) && edited.is_none_or(|edited| self.reads.is_disjoint(edited)) + !self.unsettled && self.wake.is_none_or(|at| at > now) && edited.is_none_or(|edited| !edited.iter().any(|edit| self.read(*edit))) + } + + /// Whether the run read a value the edit of `edit` changes (`BindKey::reaches`). + fn read(&self, edit: BindKey) -> bool { + match edit { + BindKey::Tracked(..) => self.reads.iter().any(|read| edit.reaches(*read)), + _ => self.reads.contains(&edit), + } } } @@ -182,18 +339,35 @@ fn min_wake(a: Option, b: Option) -> Option { } } -/// Adds `record` to the running pass in place of the run that made it. -pub(crate) fn replay(ctx: &Context, record: &Record) { - ctx.replay_pass_records(&record.egui, &egui::RecordShift::none(egui::Rect::EVERYTHING)); +/// Adds `record` to the running pass in place of the run that made it, at the place `shift` names: egui's records and +/// every journal entry move by the one shift (`Shift`). The focus transcript holds no place: a stop's place is its +/// root widget's rect, which egui's records move. +pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { + ctx.replay_pass_records(&record.egui, shift); focus::replay(ctx, &record.focus); - for entry in &record.journal { - entry.0.call(ctx); + // The records open around the replay hold its journal at the place it replays at, as a run there would have noted + // it: an entry's call notes nothing, whether it is a service's own registration call or not. + let noting = recording(ctx); + if noting { + pass_state::with::(ctx, |recorder| { + recorder.journal.extend(record.journal.iter().map(|entry| if shift.is_none() { entry.clone() } else { entry.0.shifted(shift) })); + recorder.replaying = true; + }); } + for entry in &record.journal { + entry.0.call(ctx, shift); + } + if noting { + pass_state::with::(ctx, |recorder| recorder.replaying = false); + } + crate::runtime::layout_memory::keep(ctx, &record.facts.layout_keeps); if let Some(at) = record.facts.wake { crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); } with_open(ctx, |facts| { + facts.layout_keeps.extend(record.facts.layout_keeps.iter().copied()); facts.reads.extend(record.facts.reads.iter().copied()); + facts.inputs.extend(record.facts.inputs); facts.wake = min_wake(facts.wake, record.facts.wake); }); } @@ -215,26 +389,69 @@ 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), so everything the registration depends on is in the arguments. A capture fails /// the build, not `cargo check`: the size assert is a constant that is evaluated only when the code is generated. -/// Two notes of the same `again` with equal arguments are the same registration. 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 makes it -/// again. +/// 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 view's replay makes it again. pub fn journal(ctx: &Context, args: impl FnOnce() -> A, again: F) where - A: PartialEq + fmt::Debug + Send + Sync + 'static, - F: Fn(&Context, &A) + Send + Sync + 'static, + A: PartialEq + fmt::Debug + Shift + Send + Sync + 'static, + F: Fn(&Context, &A) + Copy + Send + Sync + 'static, { const { assert!(std::mem::size_of::() == 0, "`journal`'s `again` captures nothing: pass its state in `args`") }; - if recording(ctx) { + if journaling(ctx) { let entry = Entry(Arc::new(Note { args: args(), again })); pass_state::with::(ctx, |recorder| recorder.journal.push(entry)); } } +/// Whether a registration the running code makes goes into the open records' journal: a record is open, no replay is +/// adding its journal, and no measuring run is in progress. A journal holds what the real run registered: a measuring +/// run inside it (a body measuring its content) runs only in a pass that measures, and what it hands forward lives in +/// that body's kept transcript, so a replay in a pass that measures nothing adds only what the real run added. +fn journaling(ctx: &Context) -> bool { + recording(ctx) && !crate::runtime::measure::active(ctx) && !pass_state::with::(ctx, |recorder| recorder.replaying) +} + +/// `journal` for a registration that a second equal one adds nothing to: the innermost open record keeps it once, so +/// its journal does not depend on how many times its run made it. +pub(crate) fn journal_distinct(ctx: &Context, args: impl FnOnce() -> A, again: F) +where + A: PartialEq + fmt::Debug + Shift + Send + Sync + 'static, + F: Fn(&Context, &A) + Copy + Send + Sync + 'static, +{ + const { assert!(std::mem::size_of::() == 0, "`journal_distinct`'s `again` captures nothing: pass its state in `args`") }; + if journaling(ctx) { + let entry = Entry(Arc::new(Note { args: args(), again })); + pass_state::with::(ctx, |recorder| { + let from = recorder.open.last().map_or(0, |open| open.from); + if !recorder.journal[from..].contains(&entry) { + recorder.journal.push(entry); + } + }); + } +} + /// Notes that the running code read the value `key`. pub(crate) fn note_read(ctx: &Context, key: BindKey) { - with_open(ctx, |facts| { - facts.reads.insert(key); - }); + if OPEN.load(Ordering::Acquire) > 0 && frame::running(ctx).is_some() { + pass_state::with::(ctx, |recorder| { + if let Some(open) = recorder.open.last_mut() + && (!open.kept || !matches!(key, BindKey::Place(..))) + { + open.facts.reads.insert(key); + } + }); + } +} + +/// Notes that the running code read the framework input `input`. +pub(crate) fn note_input(ctx: &Context, input: Input) { + with_open(ctx, |facts| facts.inputs.insert(input)); +} + +/// Notes that the command scope instance `id` registered in the running code. +pub(crate) fn note_instance(ctx: &Context, id: egui::Id) { + with_open(ctx, |facts| facts.instances.push(id)); } /// Notes that something in the running code still moves. @@ -251,3 +468,25 @@ pub(crate) fn note_wake(ctx: &Context, at: f64) { pub(crate) fn block(ctx: &Context) { with_open(ctx, |facts| facts.blocked = true); } + +/// Notes that the running code asked for a discard pass that reaches egui only at the end of the pass (layout memory's +/// measured changes): every other request is counted in egui's output (`close`). +pub(crate) fn note_discard(ctx: &Context) { + with_open(ctx, |facts| facts.discards = true); +} + +/// Notes that the running code kept the layout memory entry and kept transcript of `id`: a replay of the records open +/// around it keeps them too, as the replay reaches neither. +pub(crate) fn note_layout_keep(ctx: &Context, id: egui::Id) { + with_open(ctx, |facts| facts.layout_keeps.push(id)); +} + +/// Notes that the memory owner `owner` registered in the running code. +pub(crate) fn note_owner(ctx: &Context, owner: egui::Id) { + with_open(ctx, |facts| facts.owners.push(owner)); +} + +/// How many discard requests the running pass's output holds. +fn discard_requests(ctx: &Context) -> usize { + ctx.output(|output| output.request_discard_reasons.len()) +} diff --git a/crates/ui-contract/src/runtime/shift.rs b/crates/ui-contract/src/runtime/shift.rs new file mode 100644 index 000000000..b5cb2ad2e --- /dev/null +++ b/crates/ui-contract/src/runtime/shift.rs @@ -0,0 +1,208 @@ +//! What a replay at another place moves (`Shift`): a settled region's record replays where its room is now, so every +//! registration it journaled (`runtime::journal`) and what a memoized view returned move by the replay's one +//! `RecordShift`, the same one egui's records move by. + +use egui::{Pos2, RecordShift, Rect}; +use smallvec::SmallVec; +use std::sync::Arc; + +/// A value a record holds, at the place a replay adds the record (`RecordShift`): rects and points move with the record, +/// clip rects (`Clip`) go through the replay's clip, and everything else stays. There is no default: a type states how +/// it moves. `Vec2` has no impl, as a size and a move are both `Vec2`; a type holding one says which it is. +pub trait Shift { + /// `self` at the place `by` names. + #[must_use] + fn shifted(&self, by: &RecordShift) -> Self; + + /// `self` with each coordinate `shifted` moves, and each distance a hit shape holds (`reach`, `min_across`), taken + /// from `to` where the two lie within `within` points; everything else, a bare float included, stays. The replay + /// audit compares a moved record with a real run this way (`==` after it): positions off the float grid moved by a + /// whole pixel differ from the same positions computed at the new place by rounding only. + #[must_use] + fn snapped(&self, to: &Self, within: f32) -> Self; +} + +/// `value`, or `to` when the two lie within `within` of each other. +pub fn snap(value: f32, to: f32, within: f32) -> f32 { + if (value - to).abs() <= within { to } else { value } +} + +/// A clip rect a record holds: the clip of the code around the record becomes the replay's clip, a clip set inside it +/// moves with it (`RecordShift::clip`). A clip with no area is `Rect::NOTHING`, however it came about: one clip passes +/// nothing. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clip(Rect); + +impl Clip { + /// The record's clip for the clip rect `clip`. + pub fn new(clip: Rect) -> Self { + Clip(if clip.is_positive() { clip } else { Rect::NOTHING }) + } + + /// The clip rect. + pub fn rect(self) -> Rect { + self.0 + } +} + +impl Shift for Clip { + fn shifted(&self, by: &RecordShift) -> Self { + Clip::new(by.clip(self.0)) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + Clip(self.0.snapped(&to.0, within)) + } +} + +impl Shift for Rect { + fn shifted(&self, by: &RecordShift) -> Self { + by.rect(*self) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + Rect::from_min_max(self.min.snapped(&to.min, within), self.max.snapped(&to.max, within)) + } +} + +impl Shift for Pos2 { + fn shifted(&self, by: &RecordShift) -> Self { + by.pos(*self) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + Pos2::new(snap(self.x, to.x, within), snap(self.y, to.y, within)) + } +} + +/// Types with no place: they stay as they are at any place. +#[macro_export] +#[doc(hidden)] +macro_rules! stays { + ($($ty:ty),* $(,)?) => { + $(impl $crate::runtime::Shift for $ty { + #[allow(clippy::clone_on_copy)] + fn shifted(&self, _: &$crate::runtime::RecordShift) -> Self { + self.clone() + } + + #[allow(clippy::clone_on_copy)] + fn snapped(&self, _: &Self, _: f32) -> Self { + self.clone() + } + })* + }; +} + +// A scalar is a length, a fraction, a zoom, a time or a count, which a replay at another place never changes, so the +// audit compares it exactly; a coordinate is a `Pos2` or a `Rect`. +stays!(craft_behavior::PartRef, craft_behavior::Sense); +stays!((), bool, f32, f64, u8, u16, u32, u64, usize, i32, i64, String, Arc, &'static str, egui::Id, egui::LayerId, egui::TextureId); + +impl Shift for Option { + fn shifted(&self, by: &RecordShift) -> Self { + self.as_ref().map(|value| value.shifted(by)) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + match (self, to) { + (Some(value), Some(to)) => Some(value.snapped(to, within)), + _ => self.as_ref().map(|value| value.snapped(value, within)), + } + } +} + +/// `values`, each taken from the item of `to` at its index by `snapped` when both hold as many. +fn snapped_items<'a, T: Shift + 'a>(values: impl ExactSizeIterator, to: impl ExactSizeIterator, within: f32) -> Vec { + if values.len() == to.len() { + values.zip(to).map(|(value, to)| value.snapped(to, within)).collect() + } else { + values.map(|value| value.snapped(value, within)).collect() + } +} + +impl Shift for [T; N] { + fn shifted(&self, by: &RecordShift) -> Self { + std::array::from_fn(|index| self[index].shifted(by)) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + std::array::from_fn(|index| self[index].snapped(&to[index], within)) + } +} + +impl Shift for Vec { + fn shifted(&self, by: &RecordShift) -> Self { + self.iter().map(|value| value.shifted(by)).collect() + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + snapped_items(self.iter(), to.iter(), within) + } +} + +impl Shift for SmallVec<[T; N]> { + fn shifted(&self, by: &RecordShift) -> Self { + self.iter().map(|value| value.shifted(by)).collect() + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + snapped_items(self.iter(), to.iter(), within).into_iter().collect() + } +} + +macro_rules! tuples { + ($(($($name:ident $index:tt),+)),*) => { + $(impl<$($name: Shift),+> Shift for ($($name,)+) { + fn shifted(&self, by: &RecordShift) -> Self { + ($(self.$index.shifted(by),)+) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + ($(self.$index.snapped(&to.$index, within),)+) + } + })* + }; +} + +impl Shift for craft_behavior::HitShape { + fn shifted(&self, by: &RecordShift) -> Self { + self.translated(by.offset) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + self.snapped(to, within) + } +} + +/// A hit shape in a body layer's space (`local`) moves too: a record holding a transformed body never moves, as the +/// body's own layer blocks it. +impl Shift for craft_behavior::Shape { + fn shifted(&self, by: &RecordShift) -> Self { + self.translated(by.offset) + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + self.snapped(to, within) + } +} + +/// A wheel taker's rect is its view; how far it can still scroll is a distance. +impl Shift for craft_behavior::WheelTaker +where + craft_behavior::WheelTaker: Clone, +{ + fn shifted(&self, by: &RecordShift) -> Self { + let mut taker = self.clone(); + taker.rect = by.rect(self.rect); + taker + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + let mut taker = self.clone(); + taker.rect = self.rect.snapped(&to.rect, within); + taker + } +} + +tuples!((A 0), (A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3), (A 0, B 1, C 2, D 3, E 4), (A 0, B 1, C 2, D 3, E 4, F 5)); diff --git a/crates/ui-contract/src/runtime/windows/hit.rs b/crates/ui-contract/src/runtime/windows/hit.rs index c09d143a5..5a5ba18a2 100644 --- a/crates/ui-contract/src/runtime/windows/hit.rs +++ b/crates/ui-contract/src/runtime/windows/hit.rs @@ -35,6 +35,8 @@ pub enum ResizeEdge { BottomRight, } +crate::stays!(WindowHit); + /// What a part of the window does for the operating system: a press on it moves the window, resizes it from an edge, /// or is a caption button. A component tags a part with it through `PartBuilder::exclusive`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -307,8 +309,8 @@ pub(super) fn with_exclusive(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)); diff --git a/crates/ui-contract/src/testing/focus.rs b/crates/ui-contract/src/testing/focus.rs index eed6399f6..6ea67d6f4 100644 --- a/crates/ui-contract/src/testing/focus.rs +++ b/crates/ui-contract/src/testing/focus.rs @@ -159,3 +159,8 @@ pub fn register_node(ctx: &Context, node: Id, owner: Id, part: Option, pub fn context_request(ctx: &Context, id: Id) -> Option { keys::context_request(ctx, id) } + +/// The stops the running pass registered so far, in order: each stop's component and the roving group it is in. +pub fn pass_stop_groups(ctx: &Context) -> Vec<(Id, Option)> { + focus::with(ctx, |state| state.stops.iter().map(|rec| (rec.stop.id, rec.stop.group)).collect()) +} diff --git a/crates/ui-contract/src/testing/layout.rs b/crates/ui-contract/src/testing/layout.rs index 4f6bbe796..ef65b574a 100644 --- a/crates/ui-contract/src/testing/layout.rs +++ b/crates/ui-contract/src/testing/layout.rs @@ -137,3 +137,15 @@ pub fn in_row_region(ui: &mut Ui, rect: egui::Rect, body: impl FnOnce(&mut Ui pub fn allocate(ui: &mut Ui, size: Vec2) -> egui::Rect { crate::runtime::egui::alloc::space(ui, size) } + +/// The innermost scroll area `ui` lays content out for, as the area keys its scroll state. +pub fn scroll_area(ui: &Ui) -> Option { + crate::runtime::env::Env::of(ui).view().lazy_view().map(|view| view.owner) +} + +/// The child the scroll position of the scroll area `area` ([`scroll_area`]) is named by: the first child at or after +/// the view's start in the last real run that laid the content out, which keeps what is in view in place while +/// extents before it change. +pub fn scroll_anchor(ctx: &egui::Context, area: Id) -> Option { + crate::contract::body::scroll::anchor_of(ctx, area) +} diff --git a/crates/ui-contract/src/testing/memory.rs b/crates/ui-contract/src/testing/memory.rs index f61acd471..5f029eb59 100644 --- a/crates/ui-contract/src/testing/memory.rs +++ b/crates/ui-contract/src/testing/memory.rs @@ -89,7 +89,7 @@ pub fn global(name: &'static str, scope: impl Hash + Debug) -> Id { } /// Registers `fact` for the next pass of the running viewport. -pub fn register_fact(ctx: &Context, fact: T) { +pub fn register_fact(ctx: &Context, fact: T) { Facts::register(ctx, fact); } diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index f6993ccd3..4aef0c89f 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -39,14 +39,15 @@ pub mod wheel; pub mod windows; pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registration}; +pub use crate::runtime::audit::{in_run as in_audit_run, set as audit_replays}; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ - Settle, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, - last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_runs, last_pass_settles, - last_pass_text_layouts, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs, + last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, + last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; @@ -54,7 +55,8 @@ pub use frames::Frames; pub use stage::{least_stage_width, room_height, stage, stage_fitting, stage_width}; #[doc(hidden)] pub use story::{ - CollectionKind, Drive, EditKind, Grip, Required, Story, StoryData, StoryOutput, StoryRegistration, StorySnapshot, show_as_only_item, stories, + CollectionKind, Drive, EditKind, Grip, Required, Story, StoryData, StoryOutput, StoryRegistration, StorySnapshot, ValueAt, show_as_only_item, + stories, }; pub use windows::install_spec; diff --git a/crates/ui-contract/src/testing/replay_trials.rs b/crates/ui-contract/src/testing/replay_trials.rs index 4ffd1f52c..30981b581 100644 --- a/crates/ui-contract/src/testing/replay_trials.rs +++ b/crates/ui-contract/src/testing/replay_trials.rs @@ -71,6 +71,26 @@ fn journal_entries_compare_by_their_call_and_arguments() { assert_ne!(first.journal[1], other_call.journal[1], "another call with the same arguments"); } +/// A registration whose `again` notes itself, as the services' public registration calls do. +fn renote(ctx: &egui::Context, args: &(egui::Id, u32)) { + replay::journal(ctx, || *args, renote); +} + +// A record replayed inside the run of another record is part of that run: the outer record holds each of its journal +// entries once, whether the entry's call notes itself again or not, so the outer record's own replay registers them. +#[trial] +fn a_record_replayed_inside_another_run_is_in_its_journal() { + let mut frames = Frames::new(); + let id = fixture::named_id("owner"); + let inner = record(&mut frames, |ctx| { + replay::journal(ctx, || (id, 1), note_a); + renote(ctx, &(id, 2)); + }); + assert_eq!(inner.journal.len(), 2, "both notes are in the inner record"); + let outer = record(&mut frames, |ctx| replay::replay(ctx, &inner, &egui::RecordShift::none(Rect::EVERYTHING))); + assert_eq!(outer.journal, inner.journal, "the outer record holds the replayed journal, each entry once"); +} + // A focus transcript with one changed stop compares unequal to the run before it; one with the same stops equal. #[trial] fn a_transcript_with_one_changed_stop_compares_unequal() { @@ -117,7 +137,7 @@ fn layer_scope_record(frames: &mut Frames, outer: Option, entering: bo } replay::open(&ctx); focus::register_stop(&ctx, Stop::new(fixture::named_id("beside"), KeyUse::CODE)); - focus::push_scope_from(&ctx, scope, FocusPolicy::NONE, None, None, false, Some(entering)); + focus::push_scope_from(&ctx, scope, FocusPolicy::POPUP, None, None, false, Some(entering)); focus::register_stop(&ctx, Stop::new(stop, KeyUse::CODE)); focus::pop_scope(&ctx); record = Some(replay::close(&ctx, fixture::layer_of(ui))); @@ -167,7 +187,7 @@ fn a_replayed_member_stacks_above_the_members_before_it() { let shown = |ui: &mut egui::Ui, replayed: bool| { sensing::sense_members(ui, arena, &[spec(before, Rect::from_min_size(Pos2::ZERO, Vec2::splat(10.0))), spec(cover, rect)]); if replayed { - replay::replay(ui.ctx(), &recorded); + replay::replay(ui.ctx(), &recorded, &egui::RecordShift::none(Rect::EVERYTHING)); return None; } let ctx = ui.ctx().clone(); @@ -189,3 +209,27 @@ fn a_replayed_member_stacks_above_the_members_before_it() { }); assert_eq!(hovered, Some([true, false]), "the replayed child is above the member that covers it"); } + +// A popup scope that appears with nothing focused has no opener, and keeps none once focus moved into it: the opener is +// taken when the scope first appears, never from a later pass's focus, which is a stop inside the scope itself. A +// recorded first pass, the next real run and a replay then register the same. +#[trial] +fn a_scope_keeps_the_opener_of_the_pass_it_appeared_in() { + let mut frames = Frames::new(); + let [scope, stop] = [fixture::named_id("popup"), fixture::named_id("inside")]; + let mut openers = Vec::new(); + let mut focused = Vec::new(); + for first in [true, false, false] { + frames.frame(Vec::new(), |ui| { + let ctx = ui.ctx().clone(); + focused.push(focus::focused_stop(&ctx)); + focus::register_stop(&ctx, Stop::new(fixture::named_id("beside"), KeyUse::CODE)); + focus::push_scope_from(&ctx, scope, FocusPolicy::POPUP, None, None, false, Some(first)); + focus::register_stop(&ctx, Stop::new(stop, KeyUse::CODE)); + focus::pop_scope(&ctx); + openers.push(focus::with(&ctx, |state| state.scopes.get(&scope).map(|rec| rec.opener))); + }); + } + assert_eq!(focused[1], Some((stop, None)), "focus moved into the popup after its first pass"); + assert_eq!(openers, vec![Some(None); 3], "the popup keeps the opener of its first pass"); +} diff --git a/crates/ui-contract/src/testing/sensing.rs b/crates/ui-contract/src/testing/sensing.rs index f9d54b99c..e68ec0229 100644 --- a/crates/ui-contract/src/testing/sensing.rs +++ b/crates/ui-contract/src/testing/sensing.rs @@ -365,6 +365,7 @@ fn show_root(ui: &mut Ui, ctx: &Context, root: &ProbeRoot) -> RootReport { }; // The owner places its `over` parts once its body has shown: above its members. sensing::place_over_widgets(ui, id, None, &decls); + sensing::widen_root(ctx, id, false); RootReport { root: SenseReport { id, diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index 82be87491..449ca6619 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -3,7 +3,8 @@ use super::Fixture; use crate::contract::{CollectionEvent, Inner, Outcome, TooltipSpec}; use crate::runtime::commands::CommandStates; -use craft_behavior::{EditEvent, EditEvents, PartKey, PartRef, Value}; +use craft_behavior::{EditEvent, EditEvents, Mixed, PartKey, PartRef, Value}; +use craft_tracked::{Revision, Tracked}; use egui::{Id, Response, Ui, Vec2}; use std::any::{Any, TypeId}; use std::collections::HashMap; @@ -243,6 +244,84 @@ pub struct StoryData { notes: HashMap<(&'static str, TypeId), Box>, /// The story's `disabled_text`. disabled_text: Option<&'static str>, + /// Moves when [`StoryData::settle`] finds the values changed: the revision a memoized view of the story keys on. + written: Tracked<()>, + /// The values as the last [`StoryData::settle`] found them. + settled: Option, + /// The revision after the last [`StoryData::settle`]: a write through a binding ([`StoryData::bind`]) moved it + /// since, and settle moves it no further for that write. + settled_at: Option, +} + +/// A story value as the Properties editor binds it ([`StoryData::__slot`]). +#[doc(hidden)] +pub struct Slot<'a> { + pub value: &'a mut dyn Shown, + pub how: Option<&'a Edit>, + pub count: &'a std::cell::Cell, + pub source: u64, + pub offset: usize, +} + +impl Slot<'_> { + /// A binding of the value as `T`, as [`StoryData::bind`] makes it; `None` when the value is not a `T`. + pub fn bind(&mut self) -> Option> { + let value = self.value.any_mut().downcast_mut::()?; + Some(crate::contract::Bind::__tracked(value, self.count, self.source, self.offset)) + } +} + +/// Where a story value lies ([`StoryData::value_at`]): its data's source, its name and its place in memory, so a binding +/// of the value or of a field of it names that field by source and the field's offset in the value, as `bind_tracked!` +/// names a field of a `Tracked`. A write through such a binding moves the story's revision. +#[derive(Clone, Copy)] +pub struct ValueAt<'a> { + count: &'a std::cell::Cell, + source: u64, + /// The value's key in the data's source (`slot_offset`): a part of it is keyed by this plus its offset. + key: usize, + base: usize, + size: usize, +} + +impl<'a> ValueAt<'a> { + /// Where `value`, the story value named `name`, lies in the data whose writes `count` counts under `source`. + fn of(count: &'a std::cell::Cell, source: u64, name: &'static str, value: &T) -> Self { + ValueAt { count, source, key: slot_offset(name, TypeId::of::()), base: std::ptr::from_ref::(value).addr(), size: size_of::() } + } + + /// A binding of `part`, the value itself or a field inside it. + /// + /// # Panics + /// + /// When `part` does not lie inside the value (a field behind a pointer, or another value). + pub fn bind<'b, F: Value>(self, part: &'b mut F) -> crate::contract::Bind<'b, F> + where + Self: 'b, + { + let offset = self.offset_of(std::ptr::from_ref::(part).addr(), size_of::()); + crate::contract::Bind::__tracked(part, self.count, self.source, offset) + } + + /// Like [`ValueAt::bind`] for a field that may be mixed: an edit makes it concrete. + /// + /// # Panics + /// + /// When `part` does not lie inside the value. + pub fn bind_mixed<'b, F: Value>(self, part: &'b mut Mixed) -> crate::contract::Bind<'b, F> + where + Self: 'b, + { + let offset = self.offset_of(std::ptr::from_ref::>(part).addr(), size_of::>()); + crate::contract::Bind::__tracked_mixed(part, self.count, self.source, offset) + } + + /// The key of the part at address `at`, `size` bytes long: the value's key plus the part's offset in it. + fn offset_of(self, at: usize, size: usize) -> usize { + let offset = at.wrapping_sub(self.base); + assert!(offset <= self.size && size <= self.size - offset, "a story value binding names a part inside the value"); + self.key.wrapping_add(offset) + } } /// How the Properties editor edits a value, beyond what its type says. @@ -338,6 +417,112 @@ impl StoryData { } } + /// A binding of the value named `name` of type `T`, created from `init` on first use. Every view that binds a value + /// shows and edits one value: the story's view, and the Properties editor in the same pass. The binding names + /// the value by this data's source, so a reader that replays sees an edit made later in its pass, and an edit + /// moves the [`revision`](Self::revision) at the write. + #[allow(clippy::unreachable, reason = "the slot key holds the type, so the downcast cannot fail")] + pub fn bind(&mut self, name: &'static str, init: T) -> crate::contract::Bind<'_, T> { + let StoryData { values, written, .. } = self; + let slot = values.entry((name, TypeId::of::())).or_insert_with(|| Box::new(init)); + let (_, count, source) = written.__split_for_bind(); + match slot.any_mut().downcast_mut::() { + Some(value) => crate::contract::Bind::__tracked(value, count, source, slot_offset(name, TypeId::of::())), + None => unreachable!("a slot's value has the type its key names"), + } + } + + /// Like [`StoryData::bind`] for a value that may be mixed, as a multi-selection field shows it; an edit makes it + /// concrete. + #[allow(clippy::unreachable, reason = "the slot key holds the type, so the downcast cannot fail")] + pub fn bind_mixed(&mut self, name: &'static str, init: Mixed) -> crate::contract::Bind<'_, T> { + let StoryData { values, written, .. } = self; + let slot = values.entry((name, TypeId::of::>())).or_insert_with(|| Box::new(init)); + let (_, count, source) = written.__split_for_bind(); + match slot.any_mut().downcast_mut::>() { + Some(value) => crate::contract::Bind::__tracked_mixed(value, count, source, slot_offset(name, TypeId::of::>())), + None => unreachable!("a slot's value has the type its key names"), + } + } + + /// Like [`StoryData::bind`] for a number the Properties editor keeps inside `range`. + pub fn bind_ranged(&mut self, name: &'static str, init: T, range: RangeInclusive) -> crate::contract::Bind<'_, T> { + self.how.entry((name, TypeId::of::())).or_insert(Edit::Range(range)); + self.bind(name, init) + } + + /// Called by the Properties editor only: the value under `key` with what binds it as [`StoryData::bind`] does (the + /// write count, the source and the value's place in the data). + #[doc(hidden)] + pub fn __slot(&mut self, key: (&'static str, TypeId)) -> Option> { + let StoryData { values, how, written, .. } = self; + let value = values.get_mut(&key)?.as_mut(); + let (_, count, source) = written.__split_for_bind(); + Some(Slot { value, how: how.get(&key), count, source, offset: slot_offset(key.0, key.1) }) + } + + /// Called by the Properties editor only: it wrote the value under `key` outside a binding (an assignment after a + /// picked choice or an edited number). The revision moves, and a view that read the value earlier in the pass + /// runs again. + #[doc(hidden)] + pub fn __wrote(&mut self, ctx: &egui::Context, key: (&'static str, TypeId)) { + *self.written = (); + let size = self.values.get(&key).map_or(0, |value| size_of_val(&**value)); + let read = crate::runtime::reads::BindKey::Tracked(self.written.source(), slot_offset(key.0, key.1), size, key.1); + crate::runtime::inspect::edited(ctx, read, Id::NULL); + } + + /// The value named `name` of type `T`, created from `init` on first use, with where it lies ([`ValueAt`]): a + /// binding of the value or of a part of it (`at.bind(&mut value.0)`) names that part by this data's source, as + /// [`StoryData::bind`] does, while the story keeps the value to read and pass on. + #[allow(clippy::unreachable, reason = "the slot key holds the type, so the downcast cannot fail")] + pub fn value_at(&mut self, name: &'static str, init: T) -> (&mut T, ValueAt<'_>) { + let StoryData { values, written, .. } = self; + let slot = values.entry((name, TypeId::of::())).or_insert_with(|| Box::new(init)); + let (_, count, source) = written.__split_for_bind(); + match slot.any_mut().downcast_mut::() { + Some(value) => { + let at = ValueAt::of(count, source, name, value); + (value, at) + } + None => unreachable!("a slot's value has the type its key names"), + } + } + + /// Two values by name, each created from its init on first use and returned with where it lies, as + /// [`StoryData::value_at`] returns one: for a story that binds a value it must keep by its own name beside another, + /// such as a dialog's `open`, which the gallery closes and opens by that name, beside the value the dialog edits. + /// + /// # Panics + /// + /// When both name the same value (the same name and type). + #[allow(clippy::unreachable, reason = "both values exist and each slot key holds its type, so neither lookup can fail")] + pub fn pair_at(&mut self, a: (&'static str, A), b: (&'static str, B)) -> ((&mut A, ValueAt<'_>), (&mut B, ValueAt<'_>)) { + let StoryData { values, written, .. } = self; + let (key_a, key_b) = ((a.0, TypeId::of::()), (b.0, TypeId::of::())); + values.entry(key_a).or_insert_with(|| Box::new(a.1)); + values.entry(key_b).or_insert_with(|| Box::new(b.1)); + let (_, count, source) = written.__split_for_bind(); + let [Some(slot_a), Some(slot_b)] = values.get_disjoint_mut([&key_a, &key_b]) else { unreachable!("both values were created above") }; + let (Some(value_a), Some(value_b)) = (slot_a.any_mut().downcast_mut::(), slot_b.any_mut().downcast_mut::()) else { + unreachable!("a slot's value has the type its key names") + }; + let (at_a, at_b) = (ValueAt::of(count, source, a.0, value_a), ValueAt::of(count, source, b.0, value_b)); + ((value_a, at_a), (value_b, at_b)) + } + + /// Like [`StoryData::value_at`] for a number the Properties editor keeps inside `range`. + pub fn ranged_at(&mut self, name: &'static str, init: T, range: RangeInclusive) -> (&mut T, ValueAt<'_>) { + self.how.entry((name, TypeId::of::())).or_insert(Edit::Range(range)); + self.value_at(name, init) + } + + /// Like [`StoryData::value_at`] for a value that is one of `options`, which the Properties editor offers by label. + pub fn choice_at(&mut self, name: &'static str, init: T, options: &[(&'static str, T)]) -> (&mut T, ValueAt<'_>) { + self.choice(name, init.clone(), options); + self.value_at(name, init) + } + /// Like [`StoryData::value`] for a number the Properties editor keeps inside `range`. pub fn ranged(&mut self, name: &'static str, init: T, range: RangeInclusive) -> &mut T { self.how.entry((name, TypeId::of::())).or_insert(Edit::Range(range)); @@ -358,6 +543,30 @@ impl StoryData { now.assign(&**was); } } + self.settle(); + } + + /// Moves the [`revision`](Self::revision) when a value was added or changed since the last call. The accessors hand + /// out `&mut T`, so a write leaves no trace of its own: comparing the values after code that may have written them + /// (a story's run, an editor's pass) is the only signal that one happened. Notes are not compared: only a run + /// writes them, and a run is what a reader of the revision would repeat. + pub fn settle(&mut self) { + let same = self.settled.as_ref().is_some_and(|last| { + last.values.len() == self.values.len() && last.values.iter().all(|(key, was)| self.values.get(key).is_some_and(|now| now.same(&**was))) + }); + if !same { + if self.settled_at.is_none_or(|at| at == self.written.revision()) { + *self.written = (); + } + self.settled = Some(self.snapshot()); + } + self.settled_at = Some(self.written.revision()); + } + + /// The revision of the values: unique to this data, and moved by every [`settle`](Self::settle) that finds a + /// change, so equal revisions mean the values a memoized view showed. + pub fn revision(&self) -> Revision { + self.written.revision() } /// The names of the values that differ from `before`; a value added since counts as changed. @@ -391,6 +600,14 @@ impl StoryData { } } +/// A story's data as props, by its [`revision`](StoryData::revision). A view that shows the story settles the data at +/// the end of its run, so a run that changed a value runs once more, from the changed values, and then replays. +impl crate::contract::MemoProps for &mut StoryData { + fn key(&self, key: &mut crate::contract::MemoKey) { + crate::contract::MemoProps::key(&self.revision(), key); + } +} + type Held = ((&'static str, TypeId), Box); /// The values of a [`StoryData`] at one moment. @@ -568,3 +785,12 @@ where { crate::contract::show_item_in_flow(ui, row, crate::runtime::access::SetPosition::new(0).of(1)) } + +/// A story value's place in its data, by its name and type, as the data keeps it: with the data's source it names the +/// value in every pass (`BindKey::Tracked`), and a part of it by this plus the part's offset. +fn slot_offset(name: &str, ty: TypeId) -> usize { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (name, ty).hash(&mut hasher); + hasher.finish() as usize +} diff --git a/crates/ui-contract/tests/it/contract/fixes.rs b/crates/ui-contract/tests/it/contract/fixes.rs index dccd6512b..561cb7689 100644 --- a/crates/ui-contract/tests/it/contract/fixes.rs +++ b/crates/ui-contract/tests/it/contract/fixes.rs @@ -18,7 +18,7 @@ use std::cell::RefCell; type Log = RefCell>; /// A style-affecting app value the body hands to its children. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnvValue)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnvValue, craft_ui::contract::MemoProps)] #[env(style, root = Tone(1))] struct Tone(u8); diff --git a/crates/ui-contract/tests/it/contract/pages.rs b/crates/ui-contract/tests/it/contract/pages.rs index 602463d0e..ddb73adc7 100644 --- a/crates/ui-contract/tests/it/contract/pages.rs +++ b/crates/ui-contract/tests/it/contract/pages.rs @@ -1,4 +1,4 @@ -//! `Pages`: a hidden page is measured only, and its measure is reused while nothing it read changed. +//! `Pages`: a hidden page is measured only, once in each pass. use craft_ui::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Pages, Props as _, Role, Show as _}; use craft_ui::style::StyleCx; @@ -47,7 +47,7 @@ impl Component for Width<'_> { /// Two pages: page 0 shows a fixed-width leaf that can edit `value`; page 1, hidden, is as wide as `value`. struct Scene { - /// The value, kept in place across frames: a settled reader knows a bound value by where it lives. + /// The value both pages bind. value: RefCell, /// What page 0's leaf sets the value to in the next pass that shows it. set_to: Cell>, @@ -80,29 +80,30 @@ impl Scene { self.width.set(shown.response.rect.width()); } - /// The hidden page's runs in one frame with no input. - fn frame(&self, frames: &mut Frames) -> usize { + /// The hidden page's runs in one frame with no input, and the frame's passes. + fn frame(&self, frames: &mut Frames) -> (usize, usize) { self.hidden_runs.set(0); - frames.frame(vec![], |ui| self.show(ui)); - self.hidden_runs.get() + let passes = frames.frame(vec![], |ui| self.show(ui)); + (self.hidden_runs.get(), passes) } } -/// The pages take the size of the largest, a hidden one included; in a settled frame the hidden page's measure is -/// reused and its closure runs in no pass. +/// The pages take the size of the largest, a hidden one included, and each pass measures the hidden page once: the +/// page closure reads app data the framework does not track, so no pass takes the size an earlier pass measured. #[trial] -fn a_settled_hidden_page_runs_no_body() { +fn a_hidden_page_is_measured_once_in_each_pass() { let scene = Scene::new(); let mut frames = Frames::new(); frames.idle(30, |ui| scene.show(ui)); assert!(scene.width.get() > 20.0, "the pages are as wide as the hidden page, wider than the shown one"); for frame in 0..4 { - assert_eq!(scene.frame(&mut frames), 0, "settled frame {frame} ran the hidden page"); + let (runs, passes) = scene.frame(&mut frames); + assert_eq!(runs, passes, "settled frame {frame} measured the hidden page once in each pass"); } } -/// An edit of a value the hidden page read measures that page again in the frame of the edit, once, and the pages take -/// its new size there. The edit is a `set`, as a click on a control makes it. +/// An edit of a value the hidden page read earlier in the pass runs the pass again, which measures that page again, +/// and the pages take its new size in the frame of the edit. The edit is a `set`, as a click on a control makes it. #[trial] fn an_edit_of_a_value_a_hidden_page_read_measures_it_again() { let scene = Scene::new(); @@ -110,8 +111,8 @@ fn an_edit_of_a_value_a_hidden_page_read_measures_it_again() { frames.idle(30, |ui| scene.show(ui)); let before = scene.width.get(); scene.set_to.set(Some(before * 3.0)); - assert_eq!(scene.frame(&mut frames), 1, "the edit measured the hidden page again, once"); + let (runs, passes) = scene.frame(&mut frames); + assert!(passes > 1, "the edit of a value read earlier in the pass ran the pass again"); + assert_eq!(runs, passes, "each pass measured the hidden page once"); assert!(scene.width.get() > before, "the pages took the hidden page's new width in the frame of the edit"); - frames.idle(30, |ui| scene.show(ui)); - assert_eq!(scene.frame(&mut frames), 0, "the hidden page settles again"); } diff --git a/crates/ui-contract/tests/it/runtime/env.rs b/crates/ui-contract/tests/it/runtime/env.rs index d6155f189..0923dfab5 100644 --- a/crates/ui-contract/tests/it/runtime/env.rs +++ b/crates/ui-contract/tests/it/runtime/env.rs @@ -6,7 +6,7 @@ use craft_ui::runtime::env::{Env, EnvValue, with_env}; use craft_ui::testing::memory::scoped; use craft_ui::testing::{Frames, trial}; -#[derive(Clone, Debug, PartialEq, EnvValue)] +#[derive(Clone, Debug, PartialEq, EnvValue, craft_ui::contract::MemoProps)] #[env(root = Units("pt"))] struct Units(&'static str); diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 16ae912b5..5c0ba16b2 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -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 = RefCell::new(Seen::default()); + /// What the probe in the routed view recorded when it last ran. + static INSIDE_SEEN: RefCell = 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, open: Cell, room: Cell, - seen: RefCell, } 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)"); } diff --git a/crates/ui-contract/tests/it/runtime/pointer.rs b/crates/ui-contract/tests/it/runtime/pointer.rs index bc1a2db24..272682332 100644 --- a/crates/ui-contract/tests/it/runtime/pointer.rs +++ b/crates/ui-contract/tests/it/runtime/pointer.rs @@ -90,6 +90,52 @@ fn canvas(transform: Option) -> ProbeRoot { const ZOOM: CanvasTransform = CanvasTransform::new(2.0, Vec2::new(10.0, 5.0)); +/// A root's egui widget, and its transformed body's forwarding widget, sense what the members that joined it in the +/// same pass sense: a member that clicks makes them click from the first frame, and one gone or added changes them in +/// that frame. +#[trial] +fn a_root_widget_senses_what_its_members_sense_in_the_same_pass() { + let with_member = Rc::new(std::cell::Cell::new(true)); + let shown = with_member.clone(); + let mut show_frame = move |ui: &mut Ui| { + let root = ProbeRoot::new("canvas", rect(100.0, 100.0, 500.0, 300.0), Sense::empty()) + .arena() + .part(ProbePart::new(BACKGROUND, rect(100.0, 100.0, 500.0, 300.0), Sense::DRAG).level(HitLevel::Background, 0)) + .transformed(ZOOM) + .blocker(Vec2::new(500.0, 300.0)); + let root = if shown.get() { root.member(ProbeMember::new("tool", rect(160.0, 160.0, 90.0, 30.0), Sense::CLICK)) } else { root }; + show(ui, &[root]); + }; + let clicks = |frames: &Frames| { + [ProbeRoot::id("canvas"), ProbeRoot::transform_widget("canvas")] + .map(|id| frames.ctx.widget_rect_last_pass(id).map(|widget| widget.sense.senses_click())) + }; + let mut frames = Frames::new(); + frames.idle(1, &mut show_frame); + assert_eq!(clicks(&frames), [Some(true); 2], "the first frame's widgets click with their member"); + with_member.set(false); + frames.idle(1, &mut show_frame); + assert_eq!(clicks(&frames), [Some(false); 2], "the widgets stop clicking in the frame the member goes"); + with_member.set(true); + frames.idle(1, &mut show_frame); + assert_eq!(clicks(&frames), [Some(true); 2], "the widgets click again in the frame the member comes back"); +} + +/// A root its clip cuts registers its whole rect as its egui widget's rect, and the part inside the clip as the rect +/// egui's hit test uses, as egui's own widgets do: its response reports and reveals where the root is. +#[trial] +fn a_root_cut_by_its_clip_keeps_its_whole_rect_and_senses_inside_the_clip() { + let (whole, clip) = (rect(100.0, 100.0, 200.0, 100.0), rect(0.0, 0.0, 400.0, 150.0)); + let mut show_frame = move |ui: &mut Ui| { + ui.set_clip_rect(clip); + show(ui, &[ProbeRoot::new("cut", whole, Sense::CLICK)]); + }; + let mut frames = Frames::new(); + frames.idle(1, &mut show_frame); + let widget = frames.ctx.widget_rect_last_pass(ProbeRoot::id("cut")).expect("the root's widget"); + assert_eq!((widget.rect, widget.interact_rect), (whole, whole.intersect(clip)), "the whole rect, sensed inside the clip"); +} + /// Skeleton: `frames_pointer::button_on_canvas_click_and_slop_drag` and `..._on_zoomed_canvas_...`. fn member_on_canvas(transform: Option) { let (mut show_frame, log) = scene(vec![canvas(transform)]); diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index a4e6917af..b68a0ed35 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -11,12 +11,14 @@ use craft_i18n::Direction; use craft_theme::{ControlSize, Mode}; use craft_ui::buttons::Button; use craft_ui::contract::Show as _; -use craft_ui::contract::{CommandSet, Commands as _, Gap, Pad, Props as _, ShowContainer as _, Sizing, StoryLayout, Surface, ThemeScope}; +use craft_ui::contract::{ + CommandSet, Commands as _, Gap, MemoProps, MemoView, Outbox, Pad, Props as _, ShowContainer as _, Sizing, StoryLayout, Surface, ThemeScope, +}; use craft_ui::display::{InspectLayers, InspectOverlay, Shade, Text}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::runtime::env::Env; use craft_ui::runtime::env::with_env; -use craft_ui::runtime::inspect::{self, Recorded}; +use craft_ui::runtime::inspect; use craft_ui::runtime::layout_memory; use craft_ui::sections::{HeaderCommand, HeaderStrength, Panel}; use craft_ui::style::SurfaceKind; @@ -25,7 +27,6 @@ use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration, least_stage_w /// A story's show function. type StoryFn = fn(&mut Ui, &mut StoryData) -> StoryOutput; use egui::{Id, Rect, Ui}; -use std::sync::Arc; /// The header commands of a card. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] @@ -44,25 +45,30 @@ pub enum CardCommands { } /// The appearance values a card sets for its story beyond the window's. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, MemoProps)] #[non_exhaustive] pub struct Look { /// The mode the story's tokens resolve in. + #[memo_props(hash = "a fieldless enum of the theme")] pub mode: Option, /// The layout direction. + #[memo_props(hash = "a fieldless enum of the i18n crate")] pub direction: Option, /// The control size. + #[memo_props(hash = "a fieldless enum of the theme")] pub size: Option, /// The component set. pub set: Option, } /// One story a card shows. +#[derive(MemoProps)] #[non_exhaustive] pub struct CardStory<'a> { /// The index of the story in the catalog: the key of its state. pub index: usize, /// The story. + #[memo_props(address = "registrations are static items")] pub story: &'static StoryRegistration, /// The story's caption. pub caption: &'a str, @@ -76,6 +82,7 @@ impl<'a> CardStory<'a> { } /// What one card shows. +#[derive(MemoProps)] #[non_exhaustive] pub struct Card<'a> { /// The id scope of the card: unique among the cards of a pass. @@ -131,9 +138,48 @@ const COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4]; /// wide as its widest story, so each value sits a gap past its control, as the old gallery showed it. const FORM_ROWS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::fill(1.0)]; +/// The states of the stories a card shows, by catalog index. +type States<'a, 's> = &'s mut [(usize, &'a mut CardState)]; + +/// The state of the story at catalog index `index`. +fn state_of<'s>(states: &'s mut [(usize, &mut CardState)], index: usize) -> &'s mut CardState { + match states.iter_mut().find(|(at, _)| *at == index) { + Some((_, state)) => state, + None => unreachable!("the card holds the state of each of its stories"), + } +} + +/// What a card's view reads: the card and the states of its stories. The card's own run reports through `events`. +#[derive(MemoProps)] +struct CardProps<'a> { + card: &'a Card<'a>, + states: Vec<(usize, &'a mut CardState)>, + events: Outbox<'a, CardEvents>, +} + +fn card_view(props: &mut CardProps<'_>, ui: &mut Ui) -> Option { + let CardProps { card, states, events } = props; + let shown = card.run(ui, states); + let rect = shown.rect; + events.send(shown); + rect +} + impl Card<'_> { - /// Shows the card in the room `ui` offers, with the states of its stories. + /// Shows the card in the room `ui` offers, with the states of its stories: a memoized view, which replays its last + /// run until the card, a state of its stories or what it shows around it changes. A replay reports no events. pub fn show(&self, ui: &mut Ui, cells: &mut Cells) -> CardEvents { + let indices: Vec = self.stories.iter().map(|story| story.index).collect(); + let states = cells.states_of(&indices); + let mut sent = Vec::new(); + let props = CardProps { card: self, states, events: Outbox::new(&mut sent) }; + let rect = MemoView::new(("gallery.card", &self.key), props, card_view).show(ui).flatten(); + let mut events = sent.pop().unwrap_or_default(); + events.rect = rect; + events + } + + fn run(&self, ui: &mut Ui, states: States<'_, '_>) -> CardEvents { let mut events = CardEvents::default(); // A story on the card's own surface sits inside the card's padding; any other surface runs edge to edge under the // header band. @@ -160,7 +206,7 @@ impl Card<'_> { if self.usable { commands.push(HeaderCommand::new(IconId::new("check"), CardCommands::Use).size(ControlSize::Sm)); } - let away = self.stories.iter().any(|story| cells.get(&story.index).is_some_and(|state| state.changed() || state.dialog.shown)); + let away = states.iter().any(|(_, state)| state.changed() || state.dialog.shown); if away { commands.push(HeaderCommand::new(IconId::new("undo"), CardCommands::Reset).size(ControlSize::Sm)); } @@ -173,16 +219,16 @@ impl Card<'_> { } } events.pressed |= cx.surface_pressed(); - self.stories_in(ui, cells); + self.stories_in(ui, &mut *states); }); events.rect = Some(shown.response.rect); events } /// The card's stories in its layout; a lone story outside form rows without its caption. - fn stories_in(&self, ui: &mut Ui, cells: &mut Cells) { + fn stories_in(&self, ui: &mut Ui, states: States<'_, '_>) { if let ([story], false) = (self.stories, self.layout == StoryLayout::FormRows) { - self.body(ui, story, None, cells); + self.body(ui, story, None, states); return; } match self.layout { @@ -191,7 +237,7 @@ impl Card<'_> { for story in self.stories { Text::new(story.caption.to_owned()).show(ui); let body = self.story_body(story, None); - body.show(ui, cells.entry(story.index).or_default()); + body.show(ui, state_of(states, story.index)); Text::new(body.value_text(ui).unwrap_or_default()).shade(Shade::Muted).show(ui); } }); @@ -205,14 +251,14 @@ impl Card<'_> { let columns = fit.clamp(1, usize::from(most).clamp(1, COLUMNS.len())); Grid::new(&COLUMNS[..columns]).gap(Gap::Item).fill_width().show(ui, |ui, _| { for story in self.stories { - self.body(ui, story, Some(story.caption), cells); + self.body(ui, story, Some(story.caption), states); } }); } _ => { Stack::new().fill_width().show(ui, |ui, _| { for story in self.stories { - self.body(ui, story, Some(story.caption), cells); + self.body(ui, story, Some(story.caption), states); } }); } @@ -220,8 +266,8 @@ impl Card<'_> { } /// The body of `story`, with its state, under `caption` when given. - fn body(&self, ui: &mut Ui, story: &CardStory<'_>, caption: Option<&str>, cells: &mut Cells) -> BodyShown { - self.story_body(story, caption).show(ui, cells.entry(story.index).or_default()) + fn body(&self, ui: &mut Ui, story: &CardStory<'_>, caption: Option<&str>, states: States<'_, '_>) -> BodyShown { + self.story_body(story, caption).show(ui, state_of(states, story.index)) } /// The body of `story` under `caption` when given. @@ -231,7 +277,7 @@ impl Card<'_> { look: self.look, gated: self.gated, caption: caption.map(str::to_owned), - inspect: self.inspect.map(|inspected| (region_key(inspected.tab, story.index), inspected.layers)), + inspect: self.inspect.as_ref().map(|inspected| (region_key(&inspected.tab, story.index), inspected.layers)), ..StoryBody::new(key, story.story, self.surface, self.room, Pad::None) } } @@ -266,7 +312,8 @@ pub struct StoryBody { pub struct BodyShown { /// Where the story shows in flow: its surface; `None` while the button that opens the story's dialog shows. pub flow: Option, - /// The story's output when the pass ran it for real: not in a sizing pass, nor held back behind its button. + /// The story's output when the pass ran it for real: not in a sizing pass or a replay of its view, nor held back + /// behind its button. pub output: Option, } @@ -307,45 +354,40 @@ impl StoryBody { // A story that has not painted yet runs only in a pass that can still be discarded: what the shell's count finds // open would paint otherwise. The next frame's first pass runs it. let runs = state.dialog.painted || craft_ui::runtime::frame::discardable(ui.ctx()); - // Whether the story ran for real in this pass (not in a measuring run, nor in place of a kept measurement), and - // whether a dialog of it showed then. - let ran = std::cell::Cell::new(None); - let value_key = self.value_key(); - let data = &mut state.data; - // The record of the story's real run, when it is inspected. - let mut recorded = None; - // The story's output of its real run. - let mut real = None; - let surface = host.stack().show(ui, |ui, cx| { - if !runs { - return; - } - let shell = cx.shell(); - let before = shell.as_ref().map_or(0, |shell| shell.dialogs_shown()); - let (output, record) = host.content(ui, show, data, self.inspect.map(|(key, _)| key)); - recorded = record.or(recorded.take()); - if let Some(readout) = &output.readout { - Text::new(readout.clone()).shade(Shade::Muted).show(ui); - } - layout_memory::emit_text(ui.ctx(), value_key, output.value_text.as_deref()); - if !ui.is_sizing_pass() { - ran.set(Some(shell.is_some_and(|shell| shell.dialogs_shown() > before))); - real = Some(output); - } - }); + let mut reported = Vec::new(); + let props = StoryProps { + show, + data: &mut state.data, + host, + runs, + region: self.inspect.map(|(key, _)| key), + value_key: self.value_key(), + reported: Outbox::new(&mut reported), + }; + let surface = MemoView::new((host.id, "story"), props, story_view).show(ui); + // What a real run of the story in this pass reported; `None` when it did not run for real. + let run = reported.pop(); + // Whether a dialog of the story showed in that run. + let ran = run.as_ref().and_then(|run| run.dialog); + // The story's output of that run. + let real = run.and_then(|run| run.output); if !runs { ui.ctx().request_repaint(); } - if let (Some((key, layers)), Some(recorded)) = (self.inspect, recorded) { + if let Some((key, layers)) = self.inspect + && let Some(recorded) = inspect::recorded(ui.ctx(), key) + { let pointed = inspect::pointed(ui.ctx(), key); let overlay = InspectOverlay::new(recorded).layers(layers); let overlay = match pointed { Some(index) => overlay.pointed(index), None => overlay, }; - overlay.show_at(ui, surface.output.rect); + if let Some(rect) = surface { + overlay.show_at(ui, rect); + } } - if let Some(shown) = ran.get() { + if let Some(shown) = ran { let dialog = &mut state.dialog; if shown && !dialog.painted { close_at_start(state); @@ -361,7 +403,7 @@ impl StoryBody { // only the measuring run or held the story back has not made them yet. state.note_start(); } - BodyShown { flow: Some(surface.output.rect), output: real } + BodyShown { flow: surface, output: real } } /// The shown value as the story's component words it ([`StoryOutput::value_text`]), as this pass's run of the @@ -382,11 +424,12 @@ fn close_at_start(state: &mut CardState) { if let Some(open) = state.data.present::("open") { *open = false; } + state.data.settle(); state.start = None; } /// What a story runs in inside its card. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, MemoProps)] struct Host<'a> { caption: Option<&'a str>, id: Id, @@ -417,33 +460,72 @@ impl Host<'_> { } stack } +} - /// The caption, when the story has one. - fn caption_in(&self, ui: &mut Ui) { - if let Some(caption) = self.caption { - Text::new(caption.to_owned()).shade(Shade::Muted).show(ui); - } - } +/// What a story's run reported: whether a dialog of it showed and the story's output, both `None` in a sizing run. +struct StoryRun { + dialog: Option, + output: Option, +} - /// The story under its caption, in the card's direction and control size; shown as the inspected region `region` - /// when given, with the region's record of a real run. - fn content(&self, ui: &mut Ui, show: StoryFn, data: &mut StoryData, region: Option) -> (StoryOutput, Option>) { - self.caption_in(ui); - let (look, gated) = (self.look, self.gated); - with_env( - ui, - |env| { - env.direction = look.direction; - env.size = look.size; - env.wheel = gated.then_some(craft_ui::runtime::env::WheelScope::Gated); - if let Some(set) = look.set { - env.values.set(set); - } - }, - |ui| match region { - Some(key) => inspect::record(ui, key, |ui| show(ui, data)), - None => (show(ui, data), None), - }, - ) - } +/// What a story's view shows: the story's surface with the story under its caption, in the card's direction and control +/// size, as the inspected region `region` when given, and its readout under it. The surface is in the view, so a story +/// that fills takes its content's height there, as the surface sizes from its content. +#[derive(MemoProps)] +struct StoryProps<'a> { + #[memo_props(hash = "a fn pointer names the story's code")] + show: StoryFn, + data: &'a mut StoryData, + host: Host<'a>, + /// Whether the story runs in this pass: the surface shows empty otherwise. + runs: bool, + region: Option, + /// Where the story's value text is handed forward (`layout_memory::emit_text`). + value_key: Id, + /// What the run reported: a replay sends nothing. + reported: Outbox<'a, StoryRun>, +} + +fn story_view(props: &mut StoryProps<'_>, ui: &mut Ui) -> Rect { + let StoryProps { show, data, host, runs, region, value_key, reported } = props; + let (host, show, region, value_key) = (*host, *show, *region, *value_key); + host.stack() + .show(ui, |ui, cx| { + if !*runs { + return; + } + let shell = cx.shell(); + let before = shell.as_ref().map_or(0, |shell| shell.dialogs_shown()); + if let Some(caption) = host.caption { + Text::new(caption.to_owned()).shade(Shade::Muted).show(ui); + } + let look = host.look; + let output = with_env( + ui, + |env| { + env.direction = look.direction; + env.size = look.size; + env.wheel = host.gated.then_some(craft_ui::runtime::env::WheelScope::Gated); + if let Some(set) = look.set { + env.values.set(set); + } + }, + |ui| match region { + Some(key) => inspect::record(ui, key, |ui| show(ui, data)).0, + None => show(ui, data), + }, + ); + // The run may have changed a value: settling moves the revision the view keys on, so it runs once more and + // replays. + data.settle(); + if let Some(readout) = &output.readout { + Text::new(readout.clone()).shade(Shade::Muted).show(ui); + } + layout_memory::emit_text(ui.ctx(), value_key, output.value_text.as_deref()); + let real = !ui.is_sizing_pass(); + let dialog = real.then(|| shell.is_some_and(|shell| shell.dialogs_shown() > before)); + reported.send(StoryRun { dialog, output: real.then_some(output) }); + }) + .output + .rect } diff --git a/crates/ui-gallery/src/chrome/dock.rs b/crates/ui-gallery/src/chrome/dock.rs index f75054afb..dac9db2fc 100644 --- a/crates/ui-gallery/src/chrome/dock.rs +++ b/crates/ui-gallery/src/chrome/dock.rs @@ -1,26 +1,65 @@ //! The dock: what the dock asks of the viewer for each panel of the shown workspace. -use super::panels::Panels; -use crate::viewer::{GalleryCommands, PanelId, Preview}; +use super::inspect::{self, Inspect}; +use super::overview::{self, Centre}; +use super::panels::{self, ThemePanels}; +use super::variants::{VariantsEvent, VariantsIn}; +use crate::viewer::{Browser, GalleryCommands, PanelId, Preview}; use craft_behavior::dock::Permissions; use craft_theme::variant::Tone; use craft_ui::contract::Show as _; -use craft_ui::contract::{BodyCx, SizeLimits}; +use craft_ui::contract::{BodyCx, Outbox, SizeLimits, Tracked}; +use craft_ui::display::InspectLayers; use craft_ui::docking::{DockHeights, DockPanels, PanelSpec}; use craft_ui::menu::PanelRow; use craft_ui::notices::Notice; use craft_window::policy::WindowKind; use egui::Ui; -/// The viewer's panels as the dock's contents. +/// The viewer's panels as the dock's contents. The panels' requests that change the viewer beyond the browser's state +/// collect in `opened` and `variants_out` for the shell to apply after the dock. #[non_exhaustive] pub struct GalleryDock<'a> { - /// What the panel bodies read and edit. - pub panels: Panels<'a>, + /// What the panels browse. + pub browser: &'a mut Browser, + /// Where the inspector is on. + pub inspect: Inspect, + /// The drawings the inspector shows; the Inspect panel edits them. + pub layers: &'a mut Tracked, + /// The centre tab an open Variants view is in, and the view. + pub variants: Option<(PanelId, VariantsIn)>, + /// The theme workspace's panels. + pub theme: ThemePanels<'a>, /// What the theme workspace's preview shows. pub preview: Preview, /// The mock application the App preview shows. pub app: &'a mut crate::mock::MockState, + /// The components whose tab a panel asked to open in this pass. + pub opened: Vec<&'static str>, + /// What the Variants view asked for in this pass. + pub variants_out: Vec, +} + +impl GalleryDock<'_> { + /// The centre tab `tab`'s view of the browser, with the rest of the browser's values the Overview reads. + fn centre_body(&mut self, ui: &mut Ui, tab: &PanelId) { + let Browser { catalog, filter, selection, story_of, cells, generation, level, followed, .. } = &mut *self.browser; + let centre = Centre { + catalog, + selection, + story_of, + cells, + generation: *generation, + inspected: self.inspect.of(tab, **self.layers), + variants: self.variants.as_ref().filter(|(owner, _)| owner == tab).map(|(_, view)| *view), + opened: Outbox::new(&mut self.opened), + variants_out: Outbox::new(&mut self.variants_out), + }; + match tab { + PanelId::Overview => overview::overview(ui, centre, filter, level, followed), + _ => overview::component_tab(ui, centre, tab), + } + } } impl DockPanels for GalleryDock<'_> { @@ -48,7 +87,12 @@ impl DockPanels for GalleryDock<'_> { (PanelId::Preview, Preview::Components) => { Notice::new(Tone::Info, "The Controls level comes with the overview.").show(ui); } - _ => self.panels.show(ui, *panel), + (PanelId::Components, _) => panels::components(ui, self.browser, &mut self.opened), + (PanelId::Stories, _) => panels::stories(ui, self.browser), + (PanelId::Properties, _) => panels::properties(ui, self.browser), + (PanelId::Inspect, _) => inspect::panel(ui, self.browser, &self.inspect, self.layers), + (PanelId::Overview | PanelId::Component(_), _) => self.centre_body(ui, panel), + _ => self.theme.show(ui, panel), } } diff --git a/crates/ui-gallery/src/chrome/inspect.rs b/crates/ui-gallery/src/chrome/inspect.rs index 4db7b920c..e5adda691 100644 --- a/crates/ui-gallery/src/chrome/inspect.rs +++ b/crates/ui-gallery/src/chrome/inspect.rs @@ -1,12 +1,13 @@ //! The inspector: while the Inspect panel is in front, the selected card's stories are shown as inspected regions //! with the inspector's drawing over each, and the panel lists what each region showed. -use super::overview::{SpecStory, selected_type, target_story}; -use super::panels::Panels; -use crate::viewer::PanelId; +use super::overview::SpecStory; +use super::panels::view_id; +use crate::viewer::{Browser, Catalog, PanelId}; use craft_theme::variant::Tone; + use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft_ui::contract::{MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _, Tracked, bind_tracked}; use craft_ui::display::{InspectLayers, Shade, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::Env; @@ -15,28 +16,27 @@ use craft_ui::sections::Section; use craft_ui::style::TypeRole; use egui::{Id, Ui}; -/// What the inspector shows in a pass. +/// Where the inspector is on in a pass, as the dock layout says. +#[derive(Clone, Debug, Default, PartialEq, MemoProps)] #[non_exhaustive] -pub struct Inspect<'a> { +pub struct Inspect { /// The Inspect panel is in front in the components workspace, with no Variants view open: the selected card's /// stories are recorded and drawn over. pub on: bool, /// The centre tabs in front whose selected card is inspected: the Overview, the selected component's tab. pub front: Vec, - /// The drawings shown. - pub layers: &'a mut InspectLayers, } -impl Inspect<'_> { - /// What the selected card of `tab` inspects, when the inspector is on and the tab is in front. - pub fn of(&self, tab: Option, selected: bool) -> Option { - let tab = tab.filter(|tab| self.on && selected && self.front.contains(tab))?; - Some(Inspected { tab, layers: *self.layers }) +impl Inspect { + /// How the selected card of `tab` is inspected with the drawings `layers`, when the inspector is on and the tab is + /// in front. + pub fn of(&self, tab: &PanelId, layers: InspectLayers) -> Option { + (self.on && self.front.contains(tab)).then(|| Inspected { tab: tab.clone(), layers }) } } /// How a card's stories are inspected: the tab the card is in, which keys their regions, and the drawings shown. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Inspected { /// The centre tab the card is in. @@ -46,21 +46,40 @@ pub struct Inspected { } /// The inspected region of the story at catalog index `story` on the selected card of `tab`. -pub fn region_key(tab: PanelId, story: usize) -> Id { +pub fn region_key(tab: &PanelId, story: usize) -> Id { Id::NULL.with("gallery.inspect").with(tab).with(story) } +/// What the Inspect panel reads and edits. The records it lists are read through `inspect::recorded`, which the +/// framework tracks: a changed record runs the view. +#[derive(MemoProps)] +struct InspectProps<'a> { + catalog: &'a Catalog, + /// The selected component. + selected: Option<&'static str>, + /// The catalog index of the story it shows. + target: Option, + inspect: &'a Inspect, + layers: &'a mut Tracked, +} + /// The Inspect panel: the drawing switches, then for each front tab one section per story of the selected card with the /// elements its region showed, then the selected component's declared facts. -pub(super) fn panel(ui: &mut Ui, p: &mut Panels<'_>) { - let sections = regions(p); +pub(super) fn panel(ui: &mut Ui, browser: &mut Browser, inspect: &Inspect, layers: &mut Tracked) { + let (selected, target) = (browser.selected_type(), browser.target_story()); + let props = InspectProps { catalog: &browser.catalog, selected, target, inspect, layers }; + let _ = MemoView::new(view_id(&PanelId::Inspect), props, panel_view).show(ui); +} + +fn panel_view(props: &mut InspectProps<'_>, ui: &mut Ui) { + let sections = regions(props); let least = Env::of(ui).tokens.size.control.sm; - let (catalog, selected) = (p.catalog, selected_type(p)); - let layers = &mut *p.inspect.layers; + let InspectProps { catalog, selected, layers, .. } = props; Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { - Checkbox::new(Bind::bound(&mut layers.padding)).label("Padding").show(ui); - Checkbox::new(Bind::bound(&mut layers.hits)).label("Hit areas").show(ui); - Checkbox::new(Bind::bound(&mut layers.focus)).label("Focus order").show(ui); + let (padding, hits, focus) = bind_tracked!(layers => padding, hits, focus); + Checkbox::new(padding).label("Padding").show(ui); + Checkbox::new(hits).label("Hit areas").show(ui); + Checkbox::new(focus).label("Focus order").show(ui); Text::new(format!("Hit areas under {least} pt (size.control.sm) are flagged.")).role(TypeRole::Caption).shade(Shade::Muted).show(ui); for (at, (key, caption)) in sections.iter().enumerate() { Section::new(caption.clone()).id_salt(*key).initially_open(at == 0).show(ui, |ui, _| { @@ -72,19 +91,21 @@ pub(super) fn panel(ui: &mut Ui, p: &mut Panels<'_>) { }); }); } - super::panels::declared(ui, catalog, selected); + super::panels::declared(ui, catalog, *selected); }); } /// The regions the panel lists, with their captions: the stories of the selected card of each front tab. -fn regions(p: &Panels<'_>) -> Vec<(Id, String)> { - let Some(type_name) = selected_type(p).filter(|_| p.inspect.on) else { return Vec::new() }; - let (Some(component), Some(target)) = (p.catalog.component(type_name), target_story(p, type_name)) else { return Vec::new() }; - let Some(group) = p.catalog.group_at(type_name, target) else { return Vec::new() }; - let stories = p.catalog.group_stories(type_name, group); - let tabs = p.inspect.front.iter().filter(|tab| matches!(tab, PanelId::Overview) || **tab == PanelId::Component(type_name)); +fn regions(props: &InspectProps<'_>) -> Vec<(Id, String)> { + let InspectProps { catalog, selected, target, inspect, .. } = props; + let Some(type_name) = selected.filter(|_| inspect.on) else { return Vec::new() }; + let (Some(component), Some(target)) = (catalog.component(type_name), *target) else { return Vec::new() }; + let Some(group) = catalog.group_at(type_name, target) else { return Vec::new() }; + let stories = catalog.group_stories(type_name, group); + let tab = PanelId::component(type_name); + let tabs = inspect.front.iter().filter(|front| matches!(front, PanelId::Overview) || **front == tab); tabs.flat_map(|tab| { - stories.iter().map(|&index| (region_key(*tab, index), SpecStory::of(p.catalog, index, &component.name).caption)).collect::>() + stories.iter().map(|&index| (region_key(tab, index), SpecStory::of(catalog, index, &component.name).caption)).collect::>() }) .collect() } diff --git a/crates/ui-gallery/src/chrome/mod.rs b/crates/ui-gallery/src/chrome/mod.rs index df44c1e37..acb1e7e0a 100644 --- a/crates/ui-gallery/src/chrome/mod.rs +++ b/crates/ui-gallery/src/chrome/mod.rs @@ -15,6 +15,6 @@ pub use card::{BodyShown, Card, CardEvents, CardStory, Look, StoryBody}; pub use inspect::{Inspect, Inspected, region_key}; pub use options::options_bar; pub use overview::{Spec, SpecStory, overview_card}; -pub use panels::Panels; +pub use panels::ThemePanels; pub use persist::Persisted; pub use shell::Gallery; diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs index 9960c64b4..8651a8db1 100644 --- a/crates/ui-gallery/src/chrome/overview.rs +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -1,14 +1,18 @@ //! The centre tabs: the Overview (the cards of one level), a component's tab (a card per story group) and the Variants view -//! that replaces the front one. +//! that replaces the front one. Each tab's body is a memoized view around its cards, which are memoized views of their +//! own. use super::card::{Card, CardEvents, CardStory, Look}; -use super::panels::Panels; -use super::variants; -use crate::viewer::{Catalog, ComponentInfo, PanelId, TreeKey, by_level, entry_of}; +use super::inspect::Inspected; +use super::panels::{StoryOf, selected_of, target_story, view_id}; +use super::variants::{self, VariantsEvent, VariantsIn}; +use crate::viewer::{Catalog, Cells, ComponentInfo, PanelId, TreeKey, by_level, entry_of}; use craft_behavior::{ColumnWidth, Selection}; use craft_theme::variant::Tone; use craft_theme::{Tokens, TypeRole}; -use craft_ui::contract::{Bind, BodyCx, Entry, Gap, Lazy, Pad, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, StoryLayout}; +use craft_ui::contract::{ + Bind, BodyCx, Entry, Gap, Lazy, MemoProps, MemoView, Outbox, Pad, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, StoryLayout, Tracked, +}; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::{Grid, Row, Stack}; use craft_ui::notices::Notice; @@ -125,18 +129,29 @@ pub(super) struct Reported { pub events: CardEvents, } -/// The index in `catalog` of the story the component registered as `type_name` shows: the one picked for it, else its -/// first. -pub(super) fn target_story(p: &Panels<'_>, type_name: &'static str) -> Option { - p.catalog.pick(type_name, p.story_of.get(type_name).copied()) -} - -/// The selected component's registered name. -pub(super) fn selected_type(p: &Panels<'_>) -> Option<&'static str> { - p.selection.items.iter().rev().find_map(|key| match key { - TreeKey::Component(type_name) => Some(*type_name), - _ => None, - }) +/// What a centre tab's view reads and edits besides its own values: the browser's state its cards show and change, and +/// where its requests go. +#[derive(MemoProps)] +#[non_exhaustive] +pub struct Centre<'a> { + /// What is listed. + pub catalog: &'a Catalog, + /// The selected row of the tree; a card press selects its component. + pub selection: &'a mut Tracked>, + /// The story each component's card shows. + pub story_of: &'a mut Tracked, + /// The shown stories' states. + pub cells: &'a mut Cells, + /// The reset count the cards' id scopes carry. + pub generation: u32, + /// How the tab's selected card is inspected, while the inspector is on and the tab is in front. + pub inspected: Option, + /// The Variants view open in this tab. + pub variants: Option, + /// The components whose tab a card asked to open. + pub opened: Outbox<'a, &'static str>, + /// What the Variants view asked for. + pub variants_out: Outbox<'a, VariantsEvent>, } /// The window's background (an embedded shell, which paints it and keeps its cards' dialogs in the tab) with the @@ -150,22 +165,24 @@ pub(super) fn on_background(ui: &mut Ui, key: &str, mut add: impl FnMut(&mut Ui, } /// The cards in one or two columns, scrolling vertically; each row is as tall as its tallest card. A row out of view -/// does not run (`Lazy`), and a settled card in view repaints its last run (`Lazy::settles`); the card of the component -/// `reveal` names glides to the top of the view. The selected card of -/// `tab` is inspected while the inspector is on. The cards report into `reported`. +/// does not run (`Lazy`). Each card and each story in it is a memoized view that replays its last run until its inputs +/// change (the story's data by its revision, the card's look and state, the room and place). The card of the component +/// `reveal` names glides to the top of the view. The selected card is inspected as `inspected` says. The cards report +/// into `reported`. +#[expect(clippy::too_many_arguments, reason = "the grid's own values beside the shared cells; a struct would only rename them")] pub(super) fn grid( ui: &mut Ui, scroll_id: impl std::hash::Hash + std::fmt::Debug, - tab: Option, + inspected: Option<&Inspected>, cards: &[Spec], - p: &mut Panels<'_>, + cells: &mut Cells, + generation: u32, one_column: bool, reveal: Option<&'static str>, ) -> Vec { let mut reported = Vec::new(); let tokens = Env::of(ui).tokens.clone(); let columns = if one_column || ui.available_width() < 2.0 * card_min_width(&tokens) { 1 } else { 2 }; - let generation = p.generation; // A story that fills takes its content height, at most the view's, as on the old gallery's tiles. let room = ui.available_height(); Stack::new().fill().scroll(Scroll::vertical()).gap(Gap::CardRow).id_salt(scroll_id).show(ui, |ui, _| { @@ -179,13 +196,12 @@ pub(super) fn grid( Lazy::new((generation, columns, keys), estimate).reveal(revealed).show(ui, |ui| { Grid::new(if columns == 1 { ONE } else { TWO }).gap(Gap::CardColumn).fill_width().show(ui, |ui, _| { for (at, spec) in chunk.iter().enumerate() { - // A settled card repaints its last run; a card that does not run reports nothing, as it took - // no press and ran no command. - Lazy::new((generation, spec.key.as_str()), spec.estimate(&tokens)).settles(true).show(ui, |ui| { + // A card out of view does not run and reports nothing, as it took no press and ran no command. + Lazy::new((generation, spec.key.as_str()), spec.estimate(&tokens)).show(ui, |ui| { let stories = spec.card_stories(); let mut card = spec.card(&stories, format!("{}-{generation}", spec.key), room); - card.inspect = p.inspect.of(tab, spec.selected); - let events = card.show(ui, p.cells); + card.inspect = inspected.filter(|_| spec.selected).cloned(); + let events = card.show(ui, cells); reported.push(Reported { spec: row * columns + at, events }); }); } @@ -197,52 +213,76 @@ pub(super) fn grid( } /// Applies what the cards reported: a press selects the card's component and picks the card's first story unless the -/// picked one is on the card, Open opens its tab, Reset gives the card's stories their start values. -pub(super) fn apply(p: &mut Panels<'_>, cards: &[Spec], reported: Vec) { +/// picked one is on the card, Open asks for its tab, Reset gives the card's stories their start values. A value is +/// written only when it changes. +pub(super) fn apply(c: &mut Centre<'_>, cards: &[Spec], reported: Vec) { for Reported { spec, events } in reported { let Some(spec) = cards.get(spec) else { continue }; if events.reset { for story in &spec.stories { - p.cells.entry(story.index).or_default().reset(); + c.cells.state_of(story.index).reset(); } } if events.opened { - *p.open_request = Some(spec.type_name); + c.opened.send(spec.type_name); } if events.pressed || events.opened { - *p.selection = Selection::single(TreeKey::Component(spec.type_name)); + let single = Selection::single(TreeKey::Component(spec.type_name)); + if **c.selection != single { + **c.selection = single; + } // The picked story stays while it is one of the card's; else the card's first story is picked. - let picked = target_story(p, spec.type_name); + let picked = target_story(c.catalog, c.story_of, spec.type_name); if let Some(first) = spec.stories.first() && !spec.stories.iter().any(|story| Some(story.index) == picked) { - p.story_of.insert(spec.type_name, first.story.story.name); + c.story_of.insert(spec.type_name, first.story.story.name); } } } } -/// The selection, when it changed since the Overview's cards last followed it, and its component's level as the shown -/// one. -fn follow_selection(p: &mut Panels<'_>) -> Option> { - let selected = selected_type(p); - if *p.followed == Some(selected) { - return None; - } - if let Some(entry) = selected.and_then(entry_of) { - *p.level = entry.level.title().to_owned(); - } - Some(selected) +/// What the Overview reads and edits. +#[derive(MemoProps)] +struct OverviewProps<'a> { + centre: Centre<'a>, + /// The text that narrows the levels' components. + filter: &'a Tracked, + /// The level shown, by its title. + level: &'a mut Tracked, + /// The selection the cards last followed. + followed: &'a mut Tracked>>, } /// The Overview: the level select over the cards of the level's components. -pub(super) fn overview(ui: &mut Ui, p: &mut Panels<'_>) { - if variants::show(ui, p, PanelId::Overview) { +pub(super) fn overview( + ui: &mut Ui, + centre: Centre<'_>, + filter: &Tracked, + level: &mut Tracked, + followed: &mut Tracked>>, +) { + let props = OverviewProps { centre, filter, level, followed }; + let _ = MemoView::new(view_id(&PanelId::Overview), props, overview_view).show(ui); +} + +fn overview_view(p: &mut OverviewProps<'_>, ui: &mut Ui) { + let OverviewProps { centre, filter, level: shown_level, followed } = p; + let (shown_level, followed) = (&mut **shown_level, &mut **followed); + if variants::show(ui, centre) { return; } - let follow = follow_selection(p); - let groups = by_level(p.catalog, p.filter); - let Some(shown) = groups.iter().position(|(level, _)| level.title() == p.level.as_str()).or(if groups.is_empty() { None } else { Some(0) }) + // The selection, when it changed since the cards last followed it; its component's level becomes the shown one. + let selected = selected_of(centre.selection); + let follow = (**followed != Some(selected)).then_some(selected); + if follow.is_some() + && let Some(entry) = selected.and_then(entry_of) + && shown_level.as_str() != entry.level.title() + { + **shown_level = entry.level.title().to_owned(); + } + let groups = by_level(centre.catalog, filter.as_str()); + let Some(shown) = groups.iter().position(|(level, _)| level.title() == shown_level.as_str()).or(if groups.is_empty() { None } else { Some(0) }) else { on_background(ui, "overview", |ui, _| { Notice::new(Tone::Info, "No components match the filter.").show(ui); @@ -251,27 +291,28 @@ pub(super) fn overview(ui: &mut Ui, p: &mut Panels<'_>) { }; let level = groups[shown].0; let entries: Vec> = groups.iter().map(|(level, _)| Entry::new(*level, level.title())).collect(); - let selected = selected_type(p); - let cards: Vec = groups[shown].1.iter().filter_map(|component| component_card(p, component, selected)).collect(); + let cards: Vec = + groups[shown].1.iter().filter_map(|component| component_card(centre.catalog, centre.story_of, component, selected)).collect(); let mut chosen = level; let mut reported = Vec::new(); // The cards follow the selection in the pass they run: its card glides into view, and only then is it followed. let mut ran = false; + let (inspected, generation) = (centre.inspected.clone(), centre.generation); on_background(ui, "overview", |ui, _| { ran = true; Row::new().show(ui, |ui, _| { Text::new("Level:").shade(Shade::Muted).show(ui); Select::new("Level", Bind::bound(&mut chosen), &entries).sizing(Sizing::Content).show(ui); }); - reported = grid(ui, level.title(), Some(PanelId::Overview), &cards, p, false, follow.flatten()); + reported = grid(ui, level.title(), inspected.as_ref(), &cards, centre.cells, generation, false, follow.flatten()); }); if ran && let Some(selected) = follow { - *p.followed = Some(selected); + **followed = Some(selected); } if chosen != level { - *p.level = chosen.title().to_owned(); + **shown_level = chosen.title().to_owned(); } - apply(p, &cards, reported); + apply(centre, &cards, reported); } /// The stories of group `group` of the component registered as `type_name`, under their captions. @@ -280,14 +321,14 @@ fn group_stories(catalog: &Catalog, type_name: &'static str, group: usize, name: } /// The group the component registered as `type_name` shows: the group of its picked story, else its first. -fn target_group(p: &Panels<'_>, type_name: &'static str) -> usize { - target_story(p, type_name).and_then(|at| p.catalog.group_at(type_name, at)).unwrap_or(0) +fn target_group(catalog: &Catalog, story_of: &StoryOf, type_name: &'static str) -> usize { + target_story(catalog, story_of, type_name).and_then(|at| catalog.group_at(type_name, at)).unwrap_or(0) } /// The Overview's card of `component`: the cases of the group of its picked story; selected when it is the selected /// component. -fn component_card(p: &Panels<'_>, component: &ComponentInfo, selected: Option<&'static str>) -> Option { - let mut spec = overview_card(p.catalog, component, target_group(p, component.type_name))?; +fn component_card(catalog: &Catalog, story_of: &StoryOf, component: &ComponentInfo, selected: Option<&'static str>) -> Option { + let mut spec = overview_card(catalog, component, target_group(catalog, story_of, component.type_name))?; spec.selected = selected == Some(component.type_name); Some(spec) } @@ -317,19 +358,40 @@ pub fn overview_card(catalog: &Catalog, component: &ComponentInfo, group: usize) }) } +/// What a component's tab reads and edits. +#[derive(MemoProps)] +struct ComponentTabProps<'a> { + centre: Centre<'a>, + /// The tab. + tab: &'a PanelId, + /// The registered name of the tab's component, when the catalog lists it. + type_name: Option<&'static str>, +} + /// A component's tab: each story group of the component as a card in one column, titled with the group's name. -pub(super) fn component_tab(ui: &mut Ui, p: &mut Panels<'_>, type_name: &'static str) { - if variants::show(ui, p, PanelId::Component(type_name)) { +pub(super) fn component_tab(ui: &mut Ui, centre: Centre<'_>, tab: &PanelId) { + let type_name = match tab { + PanelId::Component(name) => centre.catalog.component_named(name), + _ => None, + }; + let props = ComponentTabProps { centre, tab, type_name }; + let _ = MemoView::new(view_id(tab), props, component_tab_view).show(ui); +} + +fn component_tab_view(p: &mut ComponentTabProps<'_>, ui: &mut Ui) { + let ComponentTabProps { centre, type_name, .. } = p; + if variants::show(ui, centre) { return; } - let (Some(entry), Some(component)) = (entry_of(type_name), p.catalog.component(type_name)) else { + let found = type_name.and_then(|type_name| Some((type_name, entry_of(type_name)?, centre.catalog.component(type_name)?))); + let Some((type_name, entry, component)) = found else { on_background(ui, "component", |ui, _| { Notice::new(Tone::Info, "The component has no stories.").show(ui); }); return; }; - let target = target_group(p, type_name); - let chosen = selected_type(p) == Some(type_name); + let target = target_group(centre.catalog, centre.story_of, type_name); + let chosen = selected_of(centre.selection) == Some(type_name); let cards: Vec = component .groups .iter() @@ -339,7 +401,7 @@ pub(super) fn component_tab(ui: &mut Ui, p: &mut Panels<'_>, type_name: &'static type_name, title: group.name.clone(), note: None, - stories: group_stories(p.catalog, type_name, at, &entry.name), + stories: group_stories(centre.catalog, type_name, at, &entry.name), layout: entry.story_layout(&group.name), surface: entry.surface, open: false, @@ -350,6 +412,9 @@ pub(super) fn component_tab(ui: &mut Ui, p: &mut Panels<'_>, type_name: &'static }) .collect(); let mut reported = Vec::new(); - on_background(ui, "component", |ui, _| reported = grid(ui, ("component", type_name), Some(PanelId::Component(type_name)), &cards, p, true, None)); - apply(p, &cards, reported); + let (inspected, generation) = (centre.inspected.clone(), centre.generation); + on_background(ui, "component", |ui, _| { + reported = grid(ui, ("component", type_name), inspected.as_ref(), &cards, centre.cells, generation, true, None); + }); + apply(centre, &cards, reported); } diff --git a/crates/ui-gallery/src/chrome/panels.rs b/crates/ui-gallery/src/chrome/panels.rs index b31ba7167..70130d511 100644 --- a/crates/ui-gallery/src/chrome/panels.rs +++ b/crates/ui-gallery/src/chrome/panels.rs @@ -1,17 +1,22 @@ //! The bodies of the viewer's panels: the component tree, the target component's stories and facts, the inspector, //! and the theme workspace's tokens, problems, detail and app sizes. The dock draws each panel's tab and frame. +//! +//! The tree, the stories and the properties are memoized views: each reads only its props, so it runs when a value it +//! reads changes and otherwise adds its last run again. The theme panels run every pass. use super::describe; -use super::inspect::{self, Inspect}; -use super::overview; -use crate::viewer::{self, CardState, Catalog, Cells, ComponentInfo, PanelId, TreeKey, TreeRow, TreeRows}; +use crate::viewer::{self, Browser, CardState, Catalog, ComponentInfo, PanelId, TreeKey, TreeRow, TreeRows}; use craft_behavior::IconId; use craft_behavior::{Selection, keyed}; use craft_theme::Explained; use craft_theme::report::ContrastReport; use craft_theme_editor::{AppLayerEditor, Problems, ThemeSubject, ThemeWorkspace, TokenBrowser, TokenDetail}; + use craft_ui::buttons::IconButton; -use craft_ui::contract::{Bind, CollectionEvent, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft_ui::contract::{ + Bind, CollectionEvent, MemoProps, MemoView, Outbox, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, + Tracked, bind_tracked, +}; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::{List, ListRow, OpenSet, RowEvent, TrailingFace, TrailingPart}; @@ -24,45 +29,26 @@ use egui::Ui; use std::collections::HashMap; use std::sync::Arc; -/// What the panels read and edit in one pass. -#[non_exhaustive] -pub struct Panels<'a> { - /// What is listed. - pub catalog: &'a Catalog, - /// The text that narrows the tree. - pub filter: &'a mut String, - /// The selected row of the tree. - pub selection: &'a mut Selection, - /// The open level groups. - pub open: &'a mut OpenSet, - /// The story each component's card shows. - pub story_of: &'a mut HashMap<&'static str, &'static str>, - /// The shown stories' values. - pub cells: &'a mut Cells, - /// The component whose tab the tree asked to open in this pass. - pub open_request: &'a mut Option<&'static str>, - /// The selection the Overview's cards last followed. - pub followed: &'a mut Option>, - /// The selected component the tree last opened the level of. - pub tree_seen: &'a mut Option>, - /// The reset count the cards' id scopes carry. - pub generation: u32, - /// What the theme panels share. - pub themes: &'a mut ThemeWorkspace, - /// The theme and appearance the theme panels explain. - pub subject: ThemeSubject<'a>, - /// The level the Overview shows, by its title. - pub level: &'a mut String, - /// The Variants view of the target story, while one is open. - pub variants: &'a mut Option, - /// The centre tab the Variants view is open in. - pub variants_tab: &'a mut Option, - /// The root values; a Variants card that is used sets its value. - pub env: &'a mut craft_ui::runtime::env::RootEnv, - /// The row the Problems view picked in this pass, which the token browser brings into view. - pub revealed: Option, - /// What the inspector shows. - pub inspect: Inspect<'a>, +/// The story each component's card shows, by the component's registered name and the story's name. +pub(super) type StoryOf = HashMap<&'static str, &'static str>; + +/// The registered name of the component `selection` selects. +pub(super) fn selected_of(selection: &Selection) -> Option<&'static str> { + selection.items.iter().rev().find_map(|key| match key { + TreeKey::Component(type_name) => Some(*type_name), + _ => None, + }) +} + +/// The index in `catalog` of the story the component registered as `type_name` shows: the one picked for it, else its +/// first. +pub(super) fn target_story(catalog: &Catalog, story_of: &StoryOf, type_name: &str) -> Option { + catalog.pick(type_name, story_of.get(type_name).copied()) +} + +/// The id of the memoized view of `panel`'s body. +pub(super) fn view_id(panel: &PanelId) -> (&'static str, &PanelId) { + ("gallery.panel", panel) } /// `add` filling the panel's body and scrolling vertically; the dock group insets the body. The body may run more than @@ -88,11 +74,6 @@ fn fact(ui: &mut Ui, name: &'static str, value: impl Into

, Rect, &mut Ui, &mut BodyCx<'_>) + 'a, ) -> DockColumnOutput

{ - let (column, spec, auto_collapse, edge, own, arrow, content) = - (self.column, self.spec, self.auto_collapse, self.edge, self.bar, self.arrow, self.content); + let (column, spec, auto_collapse, edge, own, arrow) = (self.column, self.spec, self.auto_collapse, self.edge, self.bar, self.arrow); let mut bar = BarRecord::default(); let shown = &mut bar; let body = move |ui: &mut Ui, body: &mut BodyCx<'_>| { @@ -262,9 +255,7 @@ impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { let plan = column_plan(column, spec, body.rect, own, &sizes, drags); if own == ColumnBar::Own { let band = bar_band(ui, plan.bar, edge); - *shown = settled_bar(ui, band, content, |ui| { - column_grip(column, spec, body).map(|grip| show_bar(ui, body, band, true, auto_collapse, arrow, grip)).unwrap_or_default() - }); + *shown = show_bar(ui, band, true, auto_collapse, arrow, false, column_grip(column, spec, body)); } for (group, rect) in column.groups.iter().zip(&plan.groups) { view(group, *rect, ui, body); @@ -521,13 +512,13 @@ impl Component for DockColumn<'_, P> { } /// The grip of the column bar: a drag moves the whole column, its ghost the column's size and its panels' names. -pub(super) fn column_grip(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, body: &BodyCx<'_>) -> Option> { +pub(super) fn column_grip(column: &Column

, spec: &dyn Fn(&P) -> PanelSpec, body: &BodyCx<'_>) -> Option> { let first = column.groups.first()?; let anchor = first.panels.first()?; let active = PanelKey::of(first.active_panel().unwrap_or(anchor)); - let name = bar_name(column, spec, &body.words::().move_column); + let name = Label::from(bar_name(column, spec, &body.words::().move_column)); let ghost = (body.rect.size(), Label::from(panel_names(column, spec))); - Some(GroupGrip::new(DragUnit::Column(anchor.clone()), active).ghost(ghost).label(name)) + Some(ColumnGrip { unit: DragUnit::Column(anchor.clone()), active, ghost, name }) } /// Registers the drop bands of the two edges of the column in `rect` with the dock `dock`: a drop there makes a new diff --git a/crates/ui-panels/src/docking/dock_column/bar.rs b/crates/ui-panels/src/docking/dock_column/bar.rs index 10d8dac39..5d5990bc4 100644 --- a/crates/ui-panels/src/docking/dock_column/bar.rs +++ b/crates/ui-panels/src/docking/dock_column/bar.rs @@ -4,21 +4,22 @@ use crate::buttons::IconButton; use crate::buttons::icon_button::IconButtonStyleKey; use crate::contract::overlay::Trigger; -use crate::contract::{Access, BodyCx, Lazy, Name, PaintUi, Props as _, Role, Show as _, ShowContainer as _, WordSetCx as _}; +use crate::contract::{Access, MemoProps, MemoView, Name, Outbox, PaintUi, Props as _, Role, Show as _, ShowContainer as _}; use crate::docking::group::GroupGrip; -use crate::docking::{ColumnArrow, DockWords, PanelSpec}; +use crate::docking::{ColumnArrow, DockWords, DragUnit, GroupDrag, PanelKey, PanelSpec}; use crate::menu::{GroupItem, Menu, MenuWords, PanelMenu, PanelRow}; use crate::runtime::env::Label; use craft_behavior::PartKey; use craft_behavior::dock::{Column, DockEdge}; use craft_theme::variant::Tone; use craft_theme::{ControlSize, CustomVariant, Emphasis, States, Tokens, Variant, VariantLook}; -use egui::{Rect, Ui, UiBuilder}; +use egui::{Rect, Ui, UiBuilder, Vec2}; +use std::hash::Hash; /// The chevron of a column's bar: a click collapses an expanded column to icons and expands an iconic one. pub(in crate::docking) const CHEVRON: PartKey = PartKey::new("chevron"); -/// What the column bar recorded while the body ran, for the container to read when it finishes. +/// What the user did on a column bar this pass, for the container to read when it finishes. #[derive(Default)] pub(in crate::docking) struct BarRecord { /// The user asked to collapse (`true`) or expand (`false`) the column. @@ -27,6 +28,26 @@ pub(in crate::docking) struct BarRecord { pub(in crate::docking) picked: Option, } +/// What the user did on a column bar, as its view sends it. +enum BarEvent { + /// A double click on the band: collapse (`true`) or expand (`false`) the column. + Iconic(bool), + /// A dock row of the column menu. + Picked(GroupItem), + /// A drag of the column started on the band. + DragStarted, +} + +/// The grip of a column bar's band: what a drag on it moves and shows. +pub(in crate::docking) struct ColumnGrip

{ + pub(in crate::docking) unit: DragUnit

, + pub(in crate::docking) active: PanelKey, + /// The column's extent where the drag starts and the name its drop region shows. + pub(in crate::docking) ghost: (Vec2, Label), + /// The band's name. + pub(in crate::docking) name: Label, +} + /// The look of the collapse control: ghost, with the muted text until the pointer is over it, and no fill under the /// pointer. fn collapse_look(tokens: &Tokens) -> VariantLook { @@ -75,66 +96,93 @@ pub(in crate::docking) fn bar_band(ui: &Ui, bar: Rect, edge: DockEdge) -> Rect { bar_slots(bar, edge, crate::runtime::env::Env::of(ui).direction.is_rtl()).1 } -/// Shows `band`, the band of a column bar ([`bar_band`]), and the column menu: a drag on `grip` moves the column, a double click -/// collapses or expands it, and a context request opens the column menu, which offers the collapse only where the -/// column's double arrow (`arrow`) collapses it. The chevron at the bar's outer end is the column's own part. Returns -/// what the user did. -pub(in crate::docking) fn show_bar( +/// Shows a column's bar in `band`: the band of a column bar ([`bar_band`]) and the column menu, as a memoized view +/// ([`column_bar`]) held to the band. A drag on the band moves the column, a double click collapses or expands it, and a +/// context request opens the column menu, which offers the collapse only where the column's double arrow (`arrow`) +/// collapses it. The chevron at the bar's outer end is the column's own part. `icons` is a collapsed column's bar. +/// Returns what the user did. +#[allow(clippy::too_many_arguments, reason = "one argument per input of the bar's view")] +pub(in crate::docking) fn show_bar( ui: &mut Ui, - body: &mut BodyCx<'_>, band: Rect, expanded: bool, auto_collapse: bool, arrow: ColumnArrow, - grip: GroupGrip

, + icons: bool, + grip: Option>, ) -> BarRecord { - let words = body.words::(); - let menu_words = body.words::(); - let toggle = ColumnArrow::Collapse.name(&words, expanded); let mut record = BarRecord::default(); - if band.width() <= 0.0 { - return record; + let Some(ColumnGrip { unit, active, ghost, name }) = grip.filter(|_| band.is_positive()) else { return record }; + let mut sent = Vec::new(); + ui.scope_builder(UiBuilder::new().max_rect(band), |ui| { + let props = BarProps { expanded, auto_collapse, arrow, unit, active, ghost: ghost.1, name, sent: Outbox::new(&mut sent) }; + // Keyed by its column's scope id: unique among the bars of a scroll area's columns. As for the tab row, the env + // around it holds only values its key follows, so it replays at rest. + let _ = MemoView::new(ui.scope_id(), props, column_bar::

).show(ui); + }); + for event in sent { + match event { + BarEvent::Iconic(iconic) => record.iconic = Some(iconic), + BarEvent::Picked(item) => record.picked = Some(item), + // The column's extent goes on the drag here, outside the view, whose measuring runs see no extent: a + // collapsed column's drag floats it collapsed with its icons under the pointer. + BarEvent::DragStarted => { + crate::runtime::drag::amend::>(ui.ctx(), |drag| { + if icons { + drag.strip = Some(ghost.0); + } else { + drag.source = Some(ghost.0); + } + }); + } + } } + record +} + +/// The props of a column bar's view. +#[derive(MemoProps)] +struct BarProps<'a, P> { + expanded: bool, + auto_collapse: bool, + arrow: ColumnArrow, + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + unit: DragUnit

, + active: PanelKey, + /// The name the column's drop region shows. + ghost: Label, + name: Label, + sent: Outbox<'a, BarEvent>, +} + +/// A column bar's band, held to the view's room, and the column menu. +fn column_bar(props: &mut BarProps<'_, P>, ui: &mut Ui) { + let band = ui.max_rect(); + let env = crate::runtime::env::Env::of(ui); + let (words, menu_words) = (env.words::(), env.words::()); + let toggle = ColumnArrow::Collapse.name(&words, props.expanded); + let grip = GroupGrip::new(props.unit.clone(), props.active).ghost(props.ghost.clone()).label(props.name.clone()); let held = grip.show_at(ui, band); - if held.double_pressed { - record.iconic = Some(expanded); + if held.drag_started { + props.sent.send(BarEvent::DragStarted); } - let collapse = (arrow == ColumnArrow::Collapse).then(|| PanelRow::Item(crate::contract::Entry::new(GroupItem::CollapseToIcons, toggle))); + if held.double_pressed { + props.sent.send(BarEvent::Iconic(props.expanded)); + } + let collapse = (props.arrow == ColumnArrow::Collapse).then(|| PanelRow::Item(crate::contract::Entry::new(GroupItem::CollapseToIcons, toggle))); let auto = PanelRow::Item( - crate::contract::Entry::new(GroupItem::AutoCollapse, Label::from(menu_words.panel_auto_collapse.as_str().to_owned())).checked(auto_collapse), + crate::contract::Entry::new(GroupItem::AutoCollapse, Label::from(menu_words.panel_auto_collapse.as_str().to_owned())) + .checked(props.auto_collapse), ); let rows: Vec<_> = collapse.into_iter().chain([auto]).collect(); let picked = Menu::new(Label::from(words.panels.as_str().to_owned())) .opened_by(&held.response, Trigger::Context) .show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked); - record.picked = picked.inner.flatten(); - record -} - -/// Shows a column's bar in `band` through `show`, in a child `Ui` held to the band. With a `content` version (the -/// dock's [`DockPanels::spec_version`](crate::docking::DockPanels::spec_version) joined with its arrangement) the bar -/// settles: it runs when that version, its band or something the framework tracks in it changed, or the pointer or -/// focus is on it, and otherwise repaints its last run, which reports nothing. -pub(in crate::docking) fn settled_bar(ui: &mut Ui, band: Rect, content: Option, show: impl FnOnce(&mut Ui) -> BarRecord) -> BarRecord { - if !band.is_positive() { - return BarRecord::default(); + if let Some(item) = picked.inner.flatten() { + props.sent.send(BarEvent::Picked(item)); } - ui.scope_builder(UiBuilder::new().max_rect(band), |ui| { - // Keyed by its column's scope id: unique among the bars of a scroll area's columns. - let lazy = Lazy::new(ui.scope_id(), 0.0).settles(content.is_some()); - let lazy = match content { - Some(version) => lazy.content(version), - None => lazy, - }; - lazy.show(ui, |ui| { - let record = show(ui); - // The grip takes no room in flow; the run covers the band, so the pointer over it runs it again. - ui.expand_to_include_rect(band); - record - }) - }) - .inner - .unwrap_or_default() + // The grip takes no room in flow; the run covers the band, so the pointer over it runs it again. + ui.expand_to_include_rect(band); } /// The name of a column's bar: the labels of its panels. diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index 736913aa5..44fe2eb95 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -17,7 +17,7 @@ use egui::{Context, Id, Pos2, Rect, Vec2}; use std::hash::Hash; /// What a dock drag moves: one panel, or the whole group, floating window or column of a panel. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DragUnit

{ /// The panel alone. @@ -410,7 +410,7 @@ impl DropTarget> for DockDro } /// The arrangement a dock drag started on: the dock area and the revision of the workspace it showed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct Arrangement { pub dock: Id, @@ -418,7 +418,7 @@ pub struct Arrangement { } /// The env value a dock area puts into its body: the arrangement it shows. `None` outside a dock area. -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, Copy, PartialEq, crate::contract::MemoProps)] struct InDock(Option); impl EnvValue for InDock { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index fb1899f91..ea0f215f2 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -2,20 +2,22 @@ //! button, over the body of the active panel. The band and the button are the group's own parts. use super::commands::DockCommands; -use super::drop::{self, DragUnit, start_group_drag, start_icon_drag}; +use super::drop::{self, DragUnit, start_group_drag}; use super::targets::{DockSizes, DockSpot, DockTargets, ZoneRule}; use super::words::DockWords; use super::{PanelDrag, PanelKey, PanelTitle}; use crate::buttons::IconButton; +use crate::contract::overlay::Anchor; use crate::contract::{ Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, HeaderEdge, HeaderParts, HeaderRegion, - ListDrag, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, ShowCollection as _, - ShowContainer as _, Sizing, WordSetCx as _, + ListDrag, MeasureCx, MemoProps, MemoView, Name, Outbox, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, + Role, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusTarget}; +use crate::runtime::memory::sub; use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind}; use crate::tabs::{Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; @@ -55,7 +57,9 @@ impl Outcome for GroupGripOutput { } /// The handle a group is dragged by: an unmarked band over the empty room of the group's header. A drag starts through [`start_group_drag`] with the grip's unit; a double -/// click is reported for the group to minimize. +/// click is reported for the group to minimize. The drag starts with no extent: a caller whose unit has one sets it on +/// the drag (`GroupDrag::source`, or `strip` for a collapsed column's icons) with `drag::amend` in the pass the grip +/// reports `drag_started`. A grip in a memoized view so holds no size in its props, which a measuring run sees as zero. #[derive(crate::contract::Component, crate::contract::Props)] #[component(probe(GroupGrip))] pub struct GroupGrip { @@ -63,16 +67,12 @@ pub struct GroupGrip { common: Common, unit: DragUnit

, active: PanelKey, - /// The unit's extent where the drag starts and the name its drop region shows. + /// The name the unit's drop region shows. #[prop] - ghost: Option<(Vec2, Label)>, + ghost: Option

{ /// The grip of `unit`, whose shown panel is `active`. pub fn new(unit: DragUnit

, active: PanelKey) -> Self { - GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, icons: false, double: false, started: false } + GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, double: false, started: false } } } @@ -107,11 +107,7 @@ impl Component for GroupGrip

{ fn update(&mut self, cx: &mut Cx<'_, Self>) { self.double = cx.press().double_pressed(); if self.movable && matches!(cx.press().phase, PressPhase::DragStart { .. }) { - match self.ghost.clone() { - Some((strip, label)) if self.icons => start_icon_drag(cx, self.unit.clone(), self.active, strip, label), - // The ghost's extent is the group's own. - ghost => start_group_drag(cx, self.unit.clone(), self.active, ghost.as_ref().map(|(size, _)| *size), ghost.map(|(_, label)| label)), - } + start_group_drag(cx, self.unit.clone(), self.active, None, self.ghost.clone()); self.started = true; } } @@ -131,8 +127,34 @@ fn grip_width(tokens: &Tokens) -> f32 { } /// The panel menu button at the header's end edge. pub(super) const MENU: PartKey = PartKey::new("panel_menu"); +/// Where the group menu hangs while a context request on a tab holds it open: the request's point. +const MENU_AT: &str = "menu_at"; +/// The point of a context request on a tab in the last pass, which opens the group menu. +const MENU_ASKED: &str = "menu_asked"; + +#[derive(Clone, Copy, Default)] +struct MenuAt(Option); + +#[derive(Clone, Copy, Default)] +struct MenuAsked(Option); type HeaderHookFn<'a> = Box) + 'a>; +type MenuRowsFn<'a> = Box Vec + 'a>; + +/// The rows of a group's menu, built while the menu is open: the panel menu button and a context request on a tab open +/// it. +pub struct MenuRows<'a>(MenuRowsFn<'a>); + +impl<'a> MenuRows<'a> { + /// Rows that `rows` builds each pass the menu shows. + pub fn new(rows: impl FnMut() -> Vec + 'a) -> Self { + MenuRows(Box::new(rows)) + } + + fn rows(&mut self) -> Vec { + (self.0)() + } +} /// A closure that adds the host's items to a group's header, before the tab strip. pub struct HeaderHook<'a>(HeaderHookFn<'a>); @@ -249,9 +271,10 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { /// sides take no drop, and its top, bottom and middle zones reach across them. #[prop(flag)] in_window: bool, - /// The rows of the group menu: the panel menu button and a context request on a tab open them. - #[prop] - menu: Vec, + /// The rows of the group menu, read while it is open: the panel menu button and a context request on a tab open + /// it. + #[prop(func = "FnMut() -> Vec")] + menu: Option>, /// Whether the panel menu button shows beside the tabs; a context request on a tab opens the menu either way. #[prop] panel_menu_shown: bool, @@ -287,7 +310,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< dock: None, zones: ZoneRule::Fraction, in_window: false, - menu: Vec::new(), + menu: None, panel_menu_shown: true, command_states: Vec::new(), extra: None, @@ -297,9 +320,9 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< .label(title) } - /// Whether the panel menu button shows: it is asked for and the menu has rows. + /// Whether the panel menu button shows: it is asked for and the group has a menu. fn shows_menu_button(&self) -> bool { - self.panel_menu_shown && !self.menu.is_empty() + self.panel_menu_shown && self.menu.is_some() } /// The panel menu button's face. @@ -367,15 +390,25 @@ impl Component for } } - /// The panel menu, opened by its button. + /// The group menu, opened by the panel menu button, under it, or by a context request on a tab, at the request's + /// point. Its rows are built only while it is open. fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { - if cx.part_if_declared(MENU).is_none() { + let Some(menu) = self.menu.as_mut() else { return }; + let popup = cx.popup("panel_menu"); + let at_id = sub(cx.core.id, MENU_AT); + if !popup.is_open(cx) { + cx.core.memory.shown::(at_id).0 = None; return; } - let popup = cx.popup("panel_menu"); + let at = cx.core.memory.shown::(at_id).0; + let anchor = match at { + Some(at) => Anchor::Point(at), + None if cx.part_if_declared(MENU).is_some() => ui.anchor_part(MENU), + None => Anchor::Pointer, + }; let name = cx.words::().panel_menu.clone(); - let rows = self.menu.clone(); - let layer = crate::menu::layer(false).anchor(ui.anchor_part(MENU)); + let rows = menu.rows(); + let layer = crate::menu::layer(false).anchor(anchor); if let Some(item) = ui.show(popup, layer, |ui, _| { Menu::inline(name.clone()).show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked).inner.flatten() }) { @@ -394,6 +427,15 @@ impl Component for fn update(&mut self, cx: &mut Cx<'_, Self>) { self.size = cx.rect.size(); + // A context request on a tab in the last pass opens the group menu at its point. + let asked = std::mem::take(&mut cx.core.memory.shown::(sub(cx.core.id, MENU_ASKED)).0); + if self.menu.is_some() { + let popup = cx.popup("panel_menu"); + if let Some(at) = asked { + cx.core.memory.shown::(sub(cx.core.id, MENU_AT)).0 = Some(at); + popup.open(cx); + } + } if let Some(grip) = cx.part_if_declared(GRIP).map(|grip| grip.press) { self.reported.toggle_minimized |= grip.double_pressed(); if self.movable && matches!(grip.phase, PressPhase::DragStart { .. }) { @@ -418,11 +460,15 @@ impl Component for } } - /// A drag that started on the strip's empty room in the header starts here: the header runs after `update`. + /// A drag that started on the strip's empty room in the header starts here, and a context request on a tab is kept + /// for the next pass's `update` to open the group menu: the header runs after `update`. fn finish(mut self, mut cx: Cx<'_, Self>) -> DockGroupOutput { if self.reported.empty_drag && self.movable { self.start_drag(&mut cx); } + if let Some(request) = &self.reported.menu { + cx.core.memory.shown::(sub(cx.core.id, MENU_ASKED)).0 = Some(request.at); + } let Reported { picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started, .. } = self.reported; DockGroupOutput { response: cx.response.clone(), picked, closed, menu, item, commands, toggle_minimized, torn_off, drag_started } } @@ -446,7 +492,8 @@ impl Container for HeaderParts::NONE.end(band + button) } - /// The host's items and the tab strip, on one line. + /// The host's items, then the tab row, on one line. The tab row is a memoized view (`tab_row`): it runs when its + /// tabs, its room or the input on it change, else it replays, and what the user did on it comes out of its outbox. fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { for (command, state) in self.command_states.drain(..) { cx.publish(command, state); @@ -454,78 +501,157 @@ impl Container for while let Some((command, _)) = cx.take_command::() { self.reported.commands.push(command); } - let words = cx.words::(); - let from = PanelKey::of(&self.anchor); let started = drop::started(&cx.env); - let (panels, active, closable, wheel_selects) = (self.panels, self.active, self.closable, self.wheel_selects_tabs); - let menu_rows = self.menu.clone(); - let panel_menu = words.panel_menu.clone(); let mut extra = self.extra.take(); - let name = Label::from(words.panels.as_str().to_owned()); let env = crate::runtime::env::Env::of(ui); - let (dock, anchor, rtl) = (self.dock, self.anchor.clone(), env.direction.is_rtl()); + let rtl = env.direction.is_rtl(); let (line, gap) = (env.tokens.size.panel_header, env.tokens.space.gap.item); ui.set_min_height(line); let surface_pressed = cx.surface_pressed(); + let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; + let mut sent = Vec::new(); + let strip = ui + .with_layout(layout, |ui| { + ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) + if let Some(hook) = extra.as_mut() { + hook.run(ui, cx); + } + let row = TabRow { + anchor: self.anchor.clone(), + panels: self.panels, + active: self.active, + closable: self.closable, + wheel_selects: self.wheel_selects_tabs, + dock: self.dock, + sent: Outbox::new(&mut sent), + }; + // The env around the tab row holds only values its key follows (the shell, the dock's arrangement, a + // floating window's layer), no handle or context rebuilt each pass, so it replays at rest. + MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui) + }) + .inner; + self.extra = extra; + // A press on the group's empty body focuses its panel, as in Photoshop. + if surface_pressed && let Some(strip) = strip { + focus::request(ui.ctx(), FocusTarget::Id(strip)); + } let size = self.size; let reported = &mut self.reported; - let drags = crate::runtime::drag::started(ui.ctx()); - let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; - ui.with_layout(layout, |ui| { - ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) - if let Some(hook) = extra.as_mut() { - hook.run(ui, cx); - } - let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str())); - let closes = |panel: &PanelTitle| closable && panel.closable; - let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel }; - let mut strip = TabStrip::new(name.clone()) - .kind(kind) - .shown(active) - .tear_off() - .natural_height(true) - .drag_payload(move |drag: &ListDrag| Some(PanelDrag { panel: drag.grabbed, from, source: Some(size), started })); - if wheel_selects { - strip = strip.wheel_selects(); - } - let strip = strip.show_items(ui, &source, &mut |key, _| { - let panel = panels.iter().find(|panel| &panel.key == key); - let title = panel.map_or_else(Label::default, |panel| panel.title.clone()); - Tab::new(title).closable(panel.is_some_and(closes)) - }); - let strip_id = strip.response.response.id; - // A press on the group's empty body focuses its panel, as in Photoshop. - if surface_pressed { - focus::request(ui.ctx(), FocusTarget::Id(strip_id)); - } - for event in strip.response.events { - if let crate::contract::CollectionEvent::Selection(craft_behavior::SelectionChange::Set(keys)) = event { - reported.picked = keys.last().copied().or(reported.picked); + for event in sent { + match event { + TabEvent::Picked(key) => reported.picked = Some(key), + TabEvent::Closed(key) => reported.closed.push(key), + TabEvent::Menu(request) => reported.menu = Some(request), + TabEvent::TornOff(torn) => reported.torn_off = Some(torn), + // The strip's empty room is a handle the group is dragged by; a double click on it minimizes the group. + TabEvent::EmptyDrag => reported.empty_drag = true, + TabEvent::EmptyDouble => reported.toggle_minimized = true, + // The tab's drag records the arrangement it started on and the group's size, which only the group reads: + // the tab row's measuring runs see no size. + TabEvent::DragStarted => { + reported.drag_started = true; + crate::runtime::drag::amend::(ui.ctx(), |drag| { + drag.started = started; + drag.source = Some(size); + }); } } - if let Some(dock) = dock { - register_insertions(ui.ctx(), dock, &anchor, panels, &strip.tab_rects, rtl); - } - reported.drag_started |= crate::runtime::drag::started(ui.ctx()) != drags - && crate::runtime::drag::active::(ui.ctx()).is_some_and(|drag| drag.from == from); - reported.picked = strip.picked.or(reported.picked); - reported.closed.extend(strip.closed); - reported.menu = strip.menu.or(reported.menu.take()); - reported.torn_off = strip.torn_off.or(reported.torn_off.take()); - // The strip's empty room is a handle the group is dragged by; a double click on it minimizes the group. - reported.empty_drag |= strip.empty_drag; - reported.toggle_minimized |= strip.empty_double; - if !menu_rows.is_empty() { - let rows = menu_rows.clone(); - let shown = Menu::context(panel_menu.clone(), &strip.response.response) - .show(ui, |ui, _| PanelMenu::new(Vec::new(), rows.clone()).show(ui).picked); - reported.item = shown.inner.flatten().or(reported.item); - } - }); - self.extra = extra; + } } } +/// What the user did on a group's tab row, in the order the row reported it. +enum TabEvent { + /// A tab was picked (a click, the wheel, the overflow menu); the last pick wins. + Picked(PanelKey), + /// A tab's close button or a middle click closed it. + Closed(PanelKey), + /// A context request on a tab: the group menu opens at its point. + Menu(ContextMenuRequest), + /// A tab was dragged out of the dock's windows. + TornOff(TornOff), + /// A drag started on the strip's empty room: the group's drag. + EmptyDrag, + /// A double click on the strip's empty room. + EmptyDouble, + /// A tab's drag started. + DragStarted, +} + +/// The props of a group's tab row: the tabs and how they show, the group's size where a tab's drag starts, and the +/// outbox for what the user did. +#[derive(MemoProps)] +struct TabRow<'a, P> { + /// The group's anchor panel, which names its drop spots. + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + anchor: P, + panels: &'a [PanelTitle], + active: PanelKey, + closable: bool, + wheel_selects: bool, + dock: Option, + sent: Outbox<'a, TabEvent>, +} + +/// A group's tab strip with its tab insertion spots. Returns the strip's id. +fn tab_row(row: &mut TabRow<'_, P>, ui: &mut Ui) -> Id { + let env = crate::runtime::env::Env::of(ui); + let name = Label::from(env.words::().panels.as_str().to_owned()); + let rtl = env.direction.is_rtl(); + let (panels, active, closable) = (row.panels, row.active, row.closable); + let from = PanelKey::of(&row.anchor); + let drags = crate::runtime::drag::started(ui.ctx()); + let source = keyed(panels, |panel: &PanelTitle| panel.key).with_text(|panel| Cow::Borrowed(panel.title.as_str())); + let closes = |panel: &PanelTitle| closable && panel.closable; + let kind = if panels.iter().any(closes) { TabKind::Document } else { TabKind::Panel }; + let mut strip = TabStrip::new(name) + .kind(kind) + .shown(active) + .tear_off() + .natural_height(true) + .drag_payload(move |drag: &ListDrag| Some(PanelDrag { panel: drag.grabbed, from, source: None, started: None })); + if row.wheel_selects { + strip = strip.wheel_selects(); + } + let strip = strip.show_items(ui, &source, &mut |key, _| { + let panel = panels.iter().find(|panel| &panel.key == key); + let title = panel.map_or_else(Label::default, |panel| panel.title.clone()); + Tab::new(title).closable(panel.is_some_and(closes)) + }); + for event in strip.response.events { + if let crate::contract::CollectionEvent::Selection(craft_behavior::SelectionChange::Set(keys)) = event + && let Some(key) = keys.last() + { + row.sent.send(TabEvent::Picked(*key)); + } + } + if let Some(dock) = row.dock { + register_insertions(ui.ctx(), dock, &row.anchor, panels, &strip.tab_rects, rtl); + } + if crate::runtime::drag::started(ui.ctx()) != drags && crate::runtime::drag::active::(ui.ctx()).is_some_and(|drag| drag.from == from) { + row.sent.send(TabEvent::DragStarted); + } + if let Some(key) = strip.picked { + row.sent.send(TabEvent::Picked(key)); + } + for key in strip.closed { + row.sent.send(TabEvent::Closed(key)); + } + if let Some(request) = strip.menu { + row.sent.send(TabEvent::Menu(request)); + } + if let Some(torn) = strip.torn_off { + row.sent.send(TabEvent::TornOff(torn)); + } + if strip.empty_drag { + row.sent.send(TabEvent::EmptyDrag); + } + if strip.empty_double { + row.sent.send(TabEvent::EmptyDouble); + } + strip.response.response.id +} + /// Registers the tab insertion spots of a group: the half of each shown tab nearer the start edge inserts before /// it, the other half after it, and each spot's mark is the line at the boundary it inserts at. fn register_insertions( diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 3ece3c89a..cc8f6cc19 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -2,8 +2,7 @@ use super::divider::{self, Divider, Drag}; use super::dock_column::{ - BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, settled_bar, - show_bar, + BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, }; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; use crate::buttons::IconButton; @@ -192,10 +191,6 @@ pub struct IconicColumn<'a, P: Value + Hash + 'static> { /// The rect the dock may grow within, which bounds how wide its inner edge can make the column. #[prop] within: Rect, - /// The version of what the column's bar shows of the host's panels and the arrangement: with one, the bar settles - /// (`Lazy::content`). - #[prop] - content: Option, open: Bind<'a, Option

>, view: Option>, /// The bar's rect this pass. @@ -252,7 +247,6 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { bar: ColumnBar::Own, auto_collapse: false, within: Rect::NOTHING, - content: None, open, view: None, bar_rect: Rect::NOTHING, @@ -710,10 +704,6 @@ impl Container for IconicColumn<'_, P> { } let (column, spec, auto_collapse) = (self.column, self.spec, self.auto_collapse); let band = bar_band(ui, self.bar_rect, self.edge); - self.record = settled_bar(ui, band, self.content, |ui| { - column_grip(column, spec, cx) - .map(|grip| show_bar(ui, cx, band, false, auto_collapse, ColumnArrow::Collapse, grip.icons(true))) - .unwrap_or_default() - }); + self.record = show_bar(ui, band, false, auto_collapse, ColumnArrow::Collapse, true, column_grip(column, spec, cx)); } } diff --git a/crates/ui-panels/src/docking/iconic/stories.rs b/crates/ui-panels/src/docking/iconic/stories.rs index 98fed0018..e80670a50 100644 --- a/crates/ui-panels/src/docking/iconic/stories.rs +++ b/crates/ui-panels/src/docking/iconic/stories.rs @@ -75,9 +75,9 @@ fn open_first_flyout(fixture: &mut Fixture) { #[story(IconicColumn<'static, u8>, covers = [Open], drive = Drive::Custom(open_first_flyout))] fn icon_flyout_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let open = data.value("open", None::); + let (open, open_at) = data.value_at("open", None::); let column = Column::new(vec![Group::new(vec![0, 1], 0), Group::new(vec![2], 0)]); - let column = IconicColumn::new("Panels", global("iconic column", "open story"), &column, Bind::bound(open), &spec); + let column = IconicColumn::new("Panels", global("iconic column", "open story"), &column, open_at.bind(open), &spec); at_stage(ui, column, |group, at, ui, _| { let GroupAt::Show(rect) = at else { return None }; let title = group.active_panel().map_or_else(String::new, |panel| spec(panel).label.as_str().to_owned()); @@ -115,16 +115,16 @@ fn flyout_of(ui: &mut Ui, open: Bind<'_, Option>) -> StoryOutput { #[story(IconicColumn<'static, u8>, covers = [Mixed], drive = Drive::Never)] fn flyouts_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let open = data.value("open", Mixed::>::Mixed); - flyout_of(ui, Bind::bound_mixed(open)) + let (open, open_at) = data.value_at("open", Mixed::>::Mixed); + flyout_of(ui, open_at.bind_mixed(open)) } #[story(IconicColumn<'static, u8>, covers = [Invalid], drive = Drive::Never)] fn a_flyout_of_a_panel_not_in_the_column(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let open = data.value("open", Some(9u8)); + let (open, open_at) = data.value_at("open", Some(9u8)); let in_column = |open: &Option| match open { Some(panel) if *panel > 1 => Validity::Refuse(Message::new("The column has no such panel")), _ => Validity::Ok, }; - flyout_of(ui, Bind::bound(open).check(in_column)) + flyout_of(ui, open_at.bind(open).check(in_column)) } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index dc680bb41..6f5c0a214 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -35,7 +35,7 @@ pub use config::{DockConfig, DockSides}; pub use drop::{Arrangement, end_replaced_drags}; pub use drop::{DockDrag, DockDropTarget, DockDropped, DragUnit, float_drop, resolve_drop, start_group_drag, start_icon_drag}; pub use event::{DockEvent, FloatSpace, HidePanels}; -pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook}; +pub use group::{DockGroup, DockGroupOutput, DockGroupStyle, GroupGrip, GroupGripOutput, GroupGripStyle, HeaderHook, MenuRows}; pub use floating::{FloatingGroup, FloatingGroupOutput, FloatingGroupStyle, WindowColumn}; pub use panels::{DockPanels, request_actions}; @@ -84,7 +84,7 @@ use tree::{FrameRules, SplitHandle}; const HANDLE: PartKey = PartKey::new("handle"); /// The stable key of a panel. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub struct PanelKey(pub u64); @@ -103,7 +103,7 @@ impl PanelKey { } /// A panel as its group's strip shows it. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub struct PanelTitle { /// The panel. diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index a988978d6..bdcd51b00 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -13,13 +13,16 @@ use egui::{Context, Id, Ui}; /// 1. `group_view`, with the group's panels and where the group goes. When it returns a height the host took the group /// itself: the dock shows no tab strip and no panel body for that group, and calls neither `group_header` nor `body` /// for it. A flyout measures its group before it shows it, so a host view runs at `GroupAt::Measure` too. -/// 2. Otherwise, when the group runs (every pass, or only when something it shows changed while its chrome settles; -/// see `spec_version`): `panel_rows` for its shown panel, `group_header` once, inside the group's header region -/// before its tab strip, then `body` for the panels whose bodies are shown. A floating window's menu reads -/// `panel_rows` every pass. +/// 2. Otherwise `group_header` once, inside the group's header before its tab strip, then `body` for the panels whose +/// bodies are shown. /// -/// A panel's `spec` is read every pass, so a host may change a label or a limit between passes; a host whose chrome -/// settles (`spec_version`) changes that version with it. The dock's actions name a group by one of its panels. +/// Each of these runs every pass the group shows. A host memoizes inside them: a body or view shown through a +/// [`MemoView`](crate::contract::MemoView) runs only when its props changed or input reached it, and otherwise repaints +/// its last run. The dock's own chrome (each group's tab row, each column's bar) is memoized on what it shows: the +/// panels' specs, the arrangement and the look. +/// +/// A panel's `spec` and `permissions` are read every pass, so a host may change a label or a limit between passes. +/// `panel_rows` is read while the group's menu is open. The dock's actions name a group by one of its panels. pub trait DockPanels

{ /// What the dock reads of `panel`. fn spec(&self, panel: &P) -> PanelSpec; @@ -36,33 +39,11 @@ pub trait DockPanels

{ /// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge. fn body(&mut self, panel: &P, ui: &mut Ui, cx: &mut BodyCx<'_>); - /// The version of the app data `panel`'s body shows that the framework does not track (a document's revision, a - /// job's progress). With one, the body settles (`Lazy::settles` with `Lazy::content`): it runs only when its - /// version, its room or something the framework tracks in it changed, the pointer is over it or focus is in it, and - /// otherwise repaints its last run. A [`group_view`](Self::group_view) settles the same way under the version of - /// the group's shown panel, its panels and its shown tab: the version covers what the view shows, and whether the - /// host takes the group depends only on its panels. `None` (the default) runs the body, and the view, every pass. - fn content(&self, _panel: &P) -> Option { - None - } - - /// The version of what the dock's chrome shows of the host's panels: every panel's `spec` (its name, icon and - /// limits), its `permissions`, what `group_header` shows, and whether `panel_rows` gives any rows (the group - /// shows its panel menu button only then; the rows themselves are read when the group runs). With one, each group's header and tab strip and each - /// column's bar settle (`Lazy::settles` with `Lazy::content`): they run only when this version, the arrangement, - /// their room or something the framework tracks in them changed, the pointer is over them or focus is in them, and - /// otherwise repaint their last run. A group settles only when its shown panel's body has a [`content`](Self::content) - /// version too. `None` (the default) runs the chrome every pass. - fn spec_version(&self) -> Option { - None - } - /// Takes the group holding `panels`, whose tab `active` is selected, in place of its tab strip and body: at /// `GroupAt::Show(rect)` it shows its view in `ui`, which the dock holds to `rect` and clips to it; at /// `GroupAt::Measure(width)` it measures that view at `width` the way it shows it. It returns the height the view /// takes (at `Show`, the rect's). `None` (the default) leaves the group to the dock, at both. A canvas group uses - /// the panels to tell which document it holds and draws it in the room `ui` has. At `Show` the view settles when - /// the shown panel has a [`content`](Self::content) version: a settled view repaints its last run instead of running. + /// the panels to tell which document it holds and draws it in the room `ui` has. fn group_view(&mut self, _panels: &[P], _active: usize, _ui: &mut Ui, _at: GroupAt, _cx: &mut BodyCx<'_>) -> Option { None } @@ -72,7 +53,8 @@ pub trait DockPanels

{ fn group_header(&mut self, _panels: &[P], _active: usize, _ui: &mut Ui, _cx: &mut BodyCx<'_>) {} /// The host's rows of `panel`'s menu, shown before the dock's own rows (the default has none): command rows, - /// which run by themselves. + /// which run by themselves. Read while the menu of `panel`'s group is open, and once per pass for whether the + /// group shows its panel menu button. fn panel_rows(&mut self, _panel: &P) -> Vec { Vec::new() } diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 9e08e6d01..71b53c765 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -60,25 +60,25 @@ fn drag_handle(fixture: &mut Fixture) { #[story(SplitArea<'static, usize>, covers = [Default], drive = Drive::Custom(drag_handle))] fn columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let layout = data.value("dock", two_columns()); + let (layout, layout_at) = data.value_at("dock", two_columns()); let shown = layout.clone(); - dock(ui, Bind::bound(layout), &shown) + dock(ui, layout_at.bind(layout), &shown) } #[story(SplitArea<'static, usize>, covers = [Mixed], drive = Drive::Custom(drag_handle))] fn layouts_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let layout = data.value("dock", Mixed::>::Mixed); - dock(ui, Bind::bound_mixed(layout), &two_columns()) + let (layout, layout_at) = data.value_at("dock", Mixed::>::Mixed); + dock(ui, layout_at.bind_mixed(layout), &two_columns()) } #[story(SplitArea<'static, usize>, covers = [Invalid], drive = Drive::Custom(drag_handle))] fn a_dock_of_one_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let layout = data.value("dock", Layout::new(Some(Node::tabs(vec![LAYERS], 0)), Vec::new())); + let (layout, layout_at) = data.value_at("dock", Layout::new(Some(Node::tabs(vec![LAYERS], 0)), Vec::new())); let shown = layout.clone(); let needs_two = |layout: &Layout| { if layout.panels().len() < 2 { Validity::Refuse(Message::new("A dock needs two panels")) } else { Validity::Ok } }; - dock(ui, Bind::bound(layout).check(needs_two), &shown) + dock(ui, layout_at.bind(layout).check(needs_two), &shown) } #[story(DockGroup<'static, usize>, covers = [Default])] @@ -106,7 +106,7 @@ fn open_panel_menu(fixture: &mut Fixture) { fn panel_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let panels = titles(&[LAYERS, CHANNELS]); let rows = [DockCommands::FloatPanel, DockCommands::FloatGroup].map(|command| PanelRow::Command(CommandRef::from(command))).to_vec(); - DockGroup::new(LAYERS, &panels, panels[0].key).menu(rows).show(ui, |_, _| ()).output.into() + DockGroup::new(LAYERS, &panels, panels[0].key).menu(move || rows.clone()).show(ui, |_, _| ()).output.into() } #[story(GroupGrip, covers = [Default])] @@ -143,7 +143,7 @@ impl DockPanels for NumberedPanels { #[story(WindowMenuRows<'static, u32>, covers = [Default], drive = Drive::Never)] fn window_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let layout = Layout::new(Some(Node::tabs(vec![1], 0)), Vec::new()); - let menu = Menu::new("Window").open(Bind::bound(data.value("open", true))).show(ui, |ui, _| { + let menu = Menu::new("Window").open(data.bind("open", true)).show(ui, |ui, _| { WindowMenuRows::new(&layout, &NumberedPanels, &[1, 2]).show(ui); }); StoryOutput::from(menu.output) diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index 0698d501b..358e6b0b5 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -193,6 +193,17 @@ impl DockSizes { } } +/// A spot names panels and sides: it has no place, so a replay at another place keeps it. +impl crate::runtime::Shift for DockSpot

{ + fn shifted(&self, _: &egui::RecordShift) -> Self { + self.clone() + } + + fn snapped(&self, _: &Self, _: f32) -> Self { + self.clone() + } +} + /// Where a drop would land. A group is named by an anchor: any panel in it. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -454,8 +465,8 @@ impl DockTargets

{ } } -/// 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 DockTargets

{ /// 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 @@ -509,12 +520,12 @@ impl DockTargets

{ 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(ctx: &Context, args: impl FnOnce() -> A, again: F) where - A: PartialEq + Debug + Send + Sync + 'static, - F: Fn(&Context, &A) + Send + Sync + 'static, + A: PartialEq + Debug + crate::runtime::Shift + Send + Sync + 'static, + F: Fn(&Context, &A) + Copy + Send + Sync + 'static, { crate::runtime::journal(ctx, args, again); } diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 4484234a9..99e0f0f9a 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -8,18 +8,18 @@ use crate::contract::{ Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, NoValue, Outcome, Pad, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, WordSetCx as _, }; -use crate::contract::{BodyCx, BodyLayout}; +use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox}; use crate::docking::DockGrid; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; use crate::runtime::access::Name; -use crate::runtime::commands::Commands as _; +use crate::runtime::commands::resolver_in; use crate::runtime::env::Label; use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind}; use craft_behavior::overlay::Side; use craft_behavior::{IconId, Metrics, NavShape, Proposal, Roving, Sense, Value}; use craft_theme::ControlSize; -use egui::{Response, Ui, Vec2}; +use egui::{Id, Response, Ui, Vec2}; mod data; mod drag; @@ -79,19 +79,12 @@ impl Outcome for ToolRailOutput { } } -/// What the buttons of one pass reported. -struct Collected { - select: Option, - double_clicked: Option, - edit_toolbar: Option, - flyout: Option, - dropped: Option, -} - -impl Default for Collected { - fn default() -> Self { - Collected { select: None, double_clicked: None, edit_toolbar: None, flyout: None, dropped: None } - } +/// What the slot grid's view sends out of a run. +enum RailEvent { + Select(T), + DoubleClicked(T), + Flyout(SlotId), + Dropped(ToolDropped), } type FooterFn<'a> = Box; @@ -109,7 +102,7 @@ type FooterFn<'a> = Box; /// grid. While the toolbar is edited the buttons are dragged and take drops, and report the drop in the output. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, probe(ToolRail<'static, u8>))] -pub struct ToolRail<'a, T: Value + 'static> { +pub struct ToolRail<'a, T: Value + MemoProps + 'static> { #[common] common: Common, #[container] @@ -134,7 +127,7 @@ pub struct ToolRail<'a, T: Value + 'static> { columns: usize, } -impl<'a, T: Value + 'static> ToolRail<'a, T> { +impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> { /// A one-column rail named `label` over `slots`, with `current` the host's tool and `last_used` what the slots /// showed last. pub fn new(label: impl Into

Outcome for DropActionOutput

{ } /// Whether an accepted drag is over the enclosing drop slot, which the slot's body reads to show its child enabled. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] struct Accepting(bool); impl EnvValue for Accepting { diff --git a/crates/ui-panels/src/sections/group_box/stories.rs b/crates/ui-panels/src/sections/group_box/stories.rs index 1dfe7d4f3..b1cc4cefd 100644 --- a/crates/ui-panels/src/sections/group_box/stories.rs +++ b/crates/ui-panels/src/sections/group_box/stories.rs @@ -18,7 +18,7 @@ fn toggle_gate(fixture: &mut Fixture) { #[story(GroupBox<'static>, covers = [Default], drive = Drive::Custom(toggle_gate))] fn group_box(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - GroupBox::new("Grid", Some(Bind::bound(data.value("gate", true)))).show(ui, |ui, _| body(ui)).into() + GroupBox::new("Grid", Some(data.bind("gate", true))).show(ui, |ui, _| body(ui)).into() } #[story(GroupBox<'static>, covers = [], drive = Drive::Never)] @@ -28,18 +28,18 @@ fn group_box_without_gate(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(GroupBox<'static>, covers = [], drive = Drive::Never)] fn group_box_gate_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - GroupBox::new("Grid", Some(Bind::bound(data.value("gate", false)))).show(ui, |ui, _| body(ui)).into() + GroupBox::new("Grid", Some(data.bind("gate", false))).show(ui, |ui, _| body(ui)).into() } #[story(GroupBox<'static>, covers = [Mixed], drive = Drive::Never)] fn group_box_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - GroupBox::new("Grid", Some(Bind::bound_mixed(data.value("mixed", Mixed::Mixed)))).show(ui, |ui, _| body(ui)).into() + GroupBox::new("Grid", Some(data.bind_mixed("mixed", Mixed::Mixed))).show(ui, |ui, _| body(ui)).into() } #[story(GroupBox<'static>, covers = [Invalid], drive = Drive::Never)] fn group_box_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_on = |on: &bool| if *on { Validity::Refuse(Message::new("Not available")) } else { Validity::Ok }; - GroupBox::new("Grid", Some(Bind::bound(data.value("gate", true)).check(refuse_on))).show(ui, |ui, _| body(ui)).into() + GroupBox::new("Grid", Some(data.bind("gate", true).check(refuse_on))).show(ui, |ui, _| body(ui)).into() } fn toggle_apply(fixture: &mut Fixture) { @@ -51,7 +51,7 @@ fn toggle_apply(fixture: &mut Fixture) { #[story(GroupBox<'static>, covers = [], drive = Drive::Custom(toggle_apply))] fn group_box_apply(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let value = *data.value("opacity", Mixed::>::Mixed); - GroupBox::apply("Opacity", Bind::bound(data.value("apply", false))) + GroupBox::apply("Opacity", data.bind("apply", false)) .show(ui, |ui, _| { NumberField::new("Opacity", Bind::given(value)).show(ui); }) @@ -60,7 +60,7 @@ fn group_box_apply(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(GroupBox<'static>, covers = [], drive = Drive::Never)] fn group_box_apply_on(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - GroupBox::apply("Opacity", Bind::bound(data.value("apply", true))) + GroupBox::apply("Opacity", data.bind("apply", true)) .show(ui, |ui, _| { NumberField::new("Opacity", Bind::given(Some(80.0))).show(ui); }) @@ -69,11 +69,11 @@ fn group_box_apply_on(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(GroupBox<'static>, covers = [], drive = Drive::Never)] fn group_box_apply_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - GroupBox::apply("Opacity", Bind::bound_mixed(data.value("mixed", Mixed::::Mixed))).show(ui, |_, _| {}).into() + GroupBox::apply("Opacity", data.bind_mixed("mixed", Mixed::::Mixed)).show(ui, |_, _| {}).into() } #[story(GroupBox<'static>, covers = [], drive = Drive::Never)] fn group_box_apply_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_on = |on: &bool| if *on { Validity::Refuse(Message::new("Not available")) } else { Validity::Ok }; - GroupBox::apply("Opacity", Bind::bound(data.value("apply", true)).check(refuse_on)).show(ui, |_, _| {}).into() + GroupBox::apply("Opacity", data.bind("apply", true).check(refuse_on)).show(ui, |_, _| {}).into() } diff --git a/crates/ui-panels/src/sections/panel/stories.rs b/crates/ui-panels/src/sections/panel/stories.rs index 398c31068..d988ddda0 100644 --- a/crates/ui-panels/src/sections/panel/stories.rs +++ b/crates/ui-panels/src/sections/panel/stories.rs @@ -2,7 +2,7 @@ use super::Panel; use crate::buttons::Button; -use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use crate::contract::{Props as _, Show as _, ShowContainer as _}; use crate::menu::MenuItem; use crate::primitives::IconSpec; use crate::sections::sample::body; @@ -33,7 +33,7 @@ fn panel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { fn panel_with_actions_and_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let shown = Panel::new("Layers") .titled() - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .subtitle("3 layers") .icon(IconSpec::svg(IconId::new("settings"))) .actions([HeaderAction::Menu, HeaderAction::Float, HeaderAction::Close]) diff --git a/crates/ui-panels/src/sections/reorderable/stories.rs b/crates/ui-panels/src/sections/reorderable/stories.rs index 4e3db441f..2acd677a4 100644 --- a/crates/ui-panels/src/sections/reorderable/stories.rs +++ b/crates/ui-panels/src/sections/reorderable/stories.rs @@ -1,7 +1,6 @@ //! Stories of `ReorderableSections`. use super::{ReorderableSections, SectionButton, SectionSpec}; -use crate::contract::Bind; use crate::sections::sample::body; use crate::sections::{SectionKey, SectionLayout}; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -22,7 +21,7 @@ fn reorderable_sections(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { .collect(); let mut initial = SectionLayout::new(specs.iter().map(|spec| spec.key.clone())); initial.set_folded(&SectionKey::new("folders"), true); - let layout = Bind::bound(data.value("layout", initial)); + let layout = data.bind("layout", initial); ReorderableSections::new("Sidebar", layout, &specs) .show(ui, |ui, key: &SectionKey, _| { if IDS.iter().any(|(id, _, count)| *id == key.as_str() && *count > 0) { diff --git a/crates/ui-panels/src/sections/section/stories.rs b/crates/ui-panels/src/sections/section/stories.rs index 360b6b9ec..4af0a2091 100644 --- a/crates/ui-panels/src/sections/section/stories.rs +++ b/crates/ui-panels/src/sections/section/stories.rs @@ -1,7 +1,7 @@ //! Stories of `Section`. use super::Section; -use crate::contract::{Bind, Role, Show as _, ShowContainer as _}; +use crate::contract::{Role, Show as _, ShowContainer as _}; use crate::display::Text; use crate::sections::sample::body; use crate::sections::{HeaderAction, HeaderStrength}; @@ -17,13 +17,13 @@ fn toggle_disclosure(fixture: &mut Fixture) { #[story(Section<'static>, covers = [Default], drive = Drive::Custom(toggle_disclosure))] fn section(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let shown = Section::new("Layers").open(Bind::bound(data.value("open", true))).show(ui, |ui, _| body(ui)); + let shown = Section::new("Layers").open(data.bind("open", true)).show(ui, |ui, _| body(ui)); shown.output.into() } #[story(Section<'static>, covers = [], drive = Drive::Never)] fn section_closed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let shown = Section::new("Layers").open(Bind::bound(data.value("open", false))).show(ui, |ui, _| body(ui)); + let shown = Section::new("Layers").open(data.bind("open", false)).show(ui, |ui, _| body(ui)); shown.output.into() } @@ -41,15 +41,14 @@ fn section_caption(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(Section<'static>, covers = [], drive = Drive::Never)] fn section_with_menu_and_reorder(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let shown = - Section::new("Layers").open(Bind::bound(data.value("open", true))).actions([HeaderAction::Menu]).reorder(true).show(ui, |ui, _| body(ui)); + let shown = Section::new("Layers").open(data.bind("open", true)).actions([HeaderAction::Menu]).reorder(true).show(ui, |ui, _| body(ui)); shown.output.into() } #[story(Section<'static>, covers = [], drive = Drive::Never)] fn section_with_controls(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let shown = Section::new("Recent") - .open(Bind::bound(data.value("open", true))) + .open(data.bind("open", true)) .controls(|ui, _| { Text::new("12 items").show(ui); }) diff --git a/crates/ui-panels/src/sections/stack/stories.rs b/crates/ui-panels/src/sections/stack/stories.rs index 58a026f3f..25a77bae4 100644 --- a/crates/ui-panels/src/sections/stack/stories.rs +++ b/crates/ui-panels/src/sections/stack/stories.rs @@ -1,7 +1,7 @@ //! Stories of `SectionStack`. use super::SectionStack; -use crate::contract::{Bind, Role, ShowContainer as _}; +use crate::contract::{Role, ShowContainer as _}; use crate::sections::Section; use crate::sections::sample::body; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -48,7 +48,7 @@ fn section_stack_closed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { stack .show(ui, |ui, _| { rows.each(ui, |ui, key, slot| { - let open = Bind::bound(data.value(TITLES[usize::from(*key)], *key == 0)); + let open = data.bind(TITLES[usize::from(*key)], *key == 0); Section::new(TITLES[usize::from(*key)]).open(open).in_stack(slot).show(ui, |ui, _| body(ui)).output }); }) diff --git a/crates/ui-panels/src/sections/title_row/stories.rs b/crates/ui-panels/src/sections/title_row/stories.rs index e69656d48..822ee8182 100644 --- a/crates/ui-panels/src/sections/title_row/stories.rs +++ b/crates/ui-panels/src/sections/title_row/stories.rs @@ -1,7 +1,7 @@ //! Stories of `TitleRow`. use super::{HeaderAction, HeaderStrength, TitleRow}; -use crate::contract::{Bind, Pad, Show as _, ShowContainer as _, Validity}; +use crate::contract::{Pad, Show as _, ShowContainer as _, Validity}; use crate::display::{Divider, Text}; use crate::layout_components::Stack; use crate::primitives::IconSpec; @@ -33,18 +33,18 @@ fn title_row(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(TitleRow<'static>, covers = [Default])] fn title_row_with_disclosure(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TitleRow::new("Layers").disclosure(Bind::bound(data.value("open", false))).show(ui).edit.into() + TitleRow::new("Layers").disclosure(data.bind("open", false)).show(ui).edit.into() } #[story(TitleRow<'static>, covers = [Mixed], drive = Drive::Never)] fn title_row_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - TitleRow::new("Grid").gate(Bind::bound_mixed(data.value("mixed", Mixed::Mixed))).show(ui).edit.into() + TitleRow::new("Grid").gate(data.bind_mixed("mixed", Mixed::Mixed)).show(ui).edit.into() } #[story(TitleRow<'static>, covers = [Invalid], drive = Drive::Never)] fn title_row_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_on = |on: &bool| if *on { Validity::Refuse(Message::new("Not available")) } else { Validity::Ok }; - TitleRow::new("Grid").gate(Bind::bound(data.value("gate", true)).check(refuse_on)).show(ui).edit.into() + TitleRow::new("Grid").gate(data.bind("gate", true).check(refuse_on)).show(ui).edit.into() } #[story(TitleRow<'static>, covers = [], drive = Drive::Never)] diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 8c84717f3..4401d77be 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -4,7 +4,7 @@ use super::hide::{self, Shown}; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, Lazy, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; @@ -247,9 +247,6 @@ struct Scene<'s, P> { rtl: bool, /// The docked places floating panels left, for Dock Panel. floated: &'s [(P, Location

)], - /// The key of what every region of the chrome shows of the pass beyond its own room ([`chrome_key`]); `None` when - /// the host gives no [`DockPanels::spec_version`], and the chrome runs every pass. - chrome: Option, } /// The spec of `panel` in `specs`, or an unnamed one. @@ -300,7 +297,6 @@ struct Look { /// gave any, and the panel commands' states. struct GroupParts { titles: Vec, - menu: Vec, hosted: bool, states: Vec<(DockCommands, CommandState)>, } @@ -410,7 +406,6 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { hide, maximized: maximized.as_ref(), auto_collapse, - locked, sizes, rtl, }; @@ -509,7 +504,6 @@ struct Input<'i, P> { hide: HidePanels<'i, P>, maximized: Option<&'i P>, auto_collapse: bool, - locked: bool, sizes: DockSizes, rtl: bool, } @@ -536,7 +530,7 @@ fn show_area( panels: &mut dyn DockPanels

, mut flyout: Option<&mut Bind<'_, Option

>>, ) -> Passed

{ - let Input { id, ctx, current, config, specs, hide, maximized, auto_collapse, locked, sizes, rtl } = *input; + let Input { id, ctx, current, config, specs, hide, maximized, auto_collapse, sizes, rtl } = *input; let shell = body.shell(); let mut memory = body.memory::>().clone(); let keys: HashMap = current.layout.panels().into_iter().map(|panel| (PanelKey::of(panel), panel.clone())).collect(); @@ -545,7 +539,6 @@ fn show_area( let layout: &Layout

= &view.layout; let bounds = shell.as_ref().map_or(body.rect, ShellCx::float_bounds); let space = float_space(bounds, &sizes, config, specs); - let chrome = panels.spec_version().map(|version| chrome_key(layout, version, config, locked, auto_collapse)); let scene = Scene { dock: id, sizes, @@ -559,7 +552,6 @@ fn show_area( auto_collapse, rtl, floated: ¤t.floated, - chrome, }; let open = open_of(&mut flyout, body, &memory); let mut pass = Pass { @@ -597,8 +589,8 @@ fn show_area( let Some(path) = scene.layout.dock_path(edge) else { continue }; let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue }; leaves.push((path.clone(), rect)); - if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed() && crate::runtime::measure::effect(ctx, "shell::reveal_rect")) { - shell.reveal_rect(if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); + if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed()) { + shell.reveal_rect(ctx, if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); } pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() }); } @@ -757,51 +749,6 @@ fn panel_menu_rows( (rows, hosted) } -/// The key of what the chrome's regions show beyond their own room: the host's panel specs (`version`), the config, -/// whether the workspace is locked, Auto-Collapse, and the shown arrangement: which panels each group, column and -/// floating window holds, the shown tab, and the minimized, open, iconic and stepped states, which the panel menus' -/// command states and move targets read across groups. Sizes are left out: a size reaches a region as its room. -fn chrome_key(layout: &Layout

, version: u64, config: &DockConfig, locked: bool, auto_collapse: bool) -> u64 { - use std::hash::Hasher; - fn column(shown: &Column

, hasher: &mut impl Hasher) { - (shown.iconic, shown.steps, shown.groups.len()).hash(hasher); - for group in &shown.groups { - (&group.panels, group.active, group.minimized).hash(hasher); - } - } - fn node(shown: &Node

, hasher: &mut impl Hasher) { - std::mem::discriminant(shown).hash(hasher); - match shown { - Node::Split { first, second, .. } => { - node(first, hasher); - node(second, hasher); - } - Node::Tabs { panels, active, .. } => (panels, active).hash(hasher), - Node::Stack { entries, .. } => { - for entry in entries { - (&entry.panel, entry.open).hash(hasher); - } - } - Node::Dock { side, columns, .. } => { - side.hash(hasher); - columns.iter().for_each(|one| column(one, hasher)); - } - // `Node` is non_exhaustive: a variant added later hashes only its discriminant until it is listed here. - _ => {} - } - } - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (version, config, locked, auto_collapse).hash(&mut hasher); - if let Some(root) = &layout.root { - node(root, &mut hasher); - } - for window in &layout.floating { - (window.id, window.edge).hash(&mut hasher); - column(&window.column, &mut hasher); - } - hasher.finish() -} - /// Whether `spec` is a document's: its group shows its body edge to edge. Every other docked body fills its group's /// body, inset from its edges by the panel padding: the group is the body's panel and its tab the body's title, so a /// docked body pads and frames nothing itself. @@ -902,26 +849,11 @@ impl Pass<'_, P> { return Some(height); } let shown = &members[active]; - let content = self.panels.content(shown); - // A host view settles as a panel body does, under the shown panel's content version (`DockPanels::content`): - // it runs again when that version, the group's panels or the shown tab change. - let view_version = content.map(|content| { - use std::hash::Hasher; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (content, members, active).hash(&mut hasher); - hasher.finish() - }); - // The group settles when the host versions its specs and the shown body: it runs again when the pass's chrome - // key, the body's version or how the group shows changes. - let version = scene.chrome.zip(content).map(|(chrome, content)| { - use std::hash::Hasher; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (chrome, content, members, active, look.minimized, look.section, look.in_window).hash(&mut hasher); - hasher.finish() - }); let words = body.words::(); let panels = RefCell::new(&mut *self.panels); // The tab titles, the menu rows and the panel commands' states, built when the group runs. + // The tab titles, whether the host gives menu rows and the panel commands' states, built once per pass; the + // menu's rows are built only while it is open. let parts: OnceCell = OnceCell::new(); let parts_of = || { parts.get_or_init(|| { @@ -929,22 +861,23 @@ impl Pass<'_, P> { .iter() .map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable)) .collect(); - let (menu, hosted) = panel_menu_rows(scene, &mut **panels.borrow_mut(), &words, shown); + let hosted = !panels.borrow_mut().panel_rows(shown).is_empty(); let permissions = |panel: &P| scene.permissions(panel); let states = dock_states(&DockScene::new(scene.layout, scene.space, false, &permissions).floated(scene.floated), shown); - GroupParts { titles, menu, hosted, states } + GroupParts { titles, hosted, states } }) }; // The group with `members[at]` shown: as it shows, or as it is measured. let make = |at: usize, minimized: bool| { let panels = &panels; - let GroupParts { titles, menu, hosted, states } = parts_of(); + let words = &words; + let GroupParts { titles, hosted, states } = parts_of(); let mut group = DockGroup::new(anchor.clone(), titles, PanelKey::of(&members[at])) .extra(move |ui, body| panels.borrow_mut().group_header(members, at, ui, body)) .dock(self.dock) .zones(scene.config.zone_rule()) .movable(scene.permissions(shown).movable) - .menu(menu.clone()) + .menu(move || panel_menu_rows(scene, &mut **panels.borrow_mut(), words, shown).0) .panel_menu_shown(*hosted) .command_states(states.clone()); if look.in_window { @@ -970,50 +903,27 @@ impl Pass<'_, P> { } GroupAt::Show(rect) => rect, }; - // One child `Ui` held to the group's rect, whether the group settles or not. It takes the parent's next id, as - // the group did before it settled, so a change of the group's first tab keeps every id inside; each Lazy is - // keyed by its `Ui`'s id, unique among the groups of a dock in a scroll area too. The host view runs first and - // settles; where the host leaves the group to the dock, the group shows in its place and settles under its own - // version. + // One child `Ui` held to the group's rect. It takes the parent's next id, so a change of the group's first tab + // keeps every id inside. The host's view runs first, held to the group's rect and clipped to it: it lays out in + // the group's room, never in the room the area has left. Where the host leaves the group to the dock, the + // group shows in its place. Both run every pass; the host memoizes inside its view, the group inside its + // header and its bodies. let output = ui .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - let view = Lazy::new(ui.unique_id(), 0.0).settles(view_version.is_some()); - let view = match view_version { - Some(version) => view.content(version), - None => view, - }; - view.show_or( - ui, - |ui| { - // The view draws held to the group's rect and clipped to it: it lays out in the group's room, - // never in the room the area has left. - let taken = ui - .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - ui.shrink_clip_rect(rect); - panels.borrow_mut().group_view(members, active, ui, at, body) - }) - .inner; - // The run covers the group, so the pointer over it runs the view again. - taken.map(|_| ui.expand_to_include_rect(rect)) - }, - |ui| { - let lazy = Lazy::new(ui.unique_id(), 0.0).settles(version.is_some()); - let lazy = match version { - Some(version) => lazy.content(version), - None => lazy, - }; - lazy.show(ui, |ui| { - let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output; - // `show_at` takes no room in flow; the run covers the group, so the pointer over it runs it again. - ui.expand_to_include_rect(rect); - output - }) - }, - ) + let taken = ui + .scope_builder(UiBuilder::new().max_rect(rect), |ui| { + ui.shrink_clip_rect(rect); + panels.borrow_mut().group_view(members, active, ui, at, body) + }) + .inner; + match taken { + Some(_) => None, + None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output), + } }) .inner; - // A host view took the group, or a settled view or group replayed its last run: nothing reached it. - let output = output.and_then(Result::err).flatten()?; + // A host view took the group. + let output = output?; // The size `panel` floats at out of this group: the group's width, and the height the group measures at with // `panel` shown in a floating window's room, so content that fills the body takes that room. let fitted = |ui: &Ui, panel: &P| { @@ -1187,28 +1097,22 @@ impl Pass<'_, P> { } let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; let work = if column.iconic { - let mut shown = IconicColumn::new(name, dock, column, Bind::given(open), &spec) + let shown = IconicColumn::new(name, dock, column, Bind::given(open), &spec) .edge(edge) .opens(opens) .bar(bar) .within(within) .auto_collapse(scene.auto_collapse); - if let Some(chrome) = scene.chrome { - shown = shown.content(chrome); - } let output = shown.show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at, in_window)); self.report.flyout.extend(output.edit.events); ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout } } else { - let mut shown = DockColumn::new(name, dock, column, &spec) + let shown = DockColumn::new(name, dock, column, &spec) .edge(edge) .bar(bar) .arrow(self.arrow_of(column)) .within(within) .auto_collapse(scene.auto_collapse); - if let Some(chrome) = scene.chrome { - shown = shown.content(chrome); - } let output = shown.show_groups_at(ui, cell, |group, rect, ui, body| { self.group_of(ui, body, group, GroupAt::Show(rect), in_window); }); @@ -1504,13 +1408,7 @@ fn window_edit( } } -/// Shows `panel`'s body in a group's body; a panel with a content version settles (`DockPanels::content`). +/// Shows `panel`'s body in a group's body. It runs every pass the group shows; the host memoizes inside it. fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) { - let content = panels.borrow().content(panel); - match content { - Some(version) => { - Lazy::new(("panel", PanelKey::of(panel).0), 0.0).settles(true).content(version).show(ui, |ui| panels.borrow_mut().body(panel, ui, body)); - } - None => panels.borrow_mut().body(panel, ui, body), - } + panels.borrow_mut().body(panel, ui, body); } diff --git a/crates/ui-patterns/src/patterns/dock/area/stories.rs b/crates/ui-patterns/src/patterns/dock/area/stories.rs index c6d6b82fa..7d798c226 100644 --- a/crates/ui-patterns/src/patterns/dock/area/stories.rs +++ b/crates/ui-patterns/src/patterns/dock/area/stories.rs @@ -2,7 +2,7 @@ use super::DockArea; use crate::contract::SizeLimits; -use crate::contract::{Bind, BodyCx, Show as _}; +use crate::contract::{BodyCx, Show as _}; use crate::display::Text; use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, PanelSpec}; use crate::menu::PanelRow; @@ -104,8 +104,8 @@ fn workspace() -> Workspace { } fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo) -> StoryOutput { - let workspace = data.value("workspace", workspace()); - DockArea::new("Dock", Bind::bound(&mut *workspace), demo, DockConfig::default()).show(ui).into() + let (workspace, workspace_at) = data.value_at("workspace", workspace()); + DockArea::new("Dock", workspace_at.bind(&mut *workspace), demo, DockConfig::default()).show(ui).into() } #[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never)] diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs index c444e9a44..1524b93f0 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs @@ -34,7 +34,7 @@ fn blur_story(ui: &mut Ui, data: &mut StoryData, preview: bool, layout: ParamLay let preview = *data.value("preview", preview); let layout = *data.choice("layout", layout, &LAYOUTS); let comparing = *data.value("comparing", false); - let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true))).history(true).layout(layout); + let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(data.bind("open", true)).history(true).layout(layout); let dialog = if preview { dialog.previews(true).preview(picture(ui, comparing)) } else { dialog }; let shown = dialog.show(ui); *data.value("comparing", false) = shown.comparing; @@ -65,7 +65,7 @@ fn param_dialog_stacked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(ParamDialog<'static>, covers = [], drive = Drive::Never)] fn param_dialog_close_without_reset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)) - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .cancel_label(Label::from("Close")) .alt_resets(false) .show(ui) @@ -77,7 +77,7 @@ const COMMAND_SPEC: &str = r#"{"name":text,"size":1..100=10,"method":"fit|fill", #[story(ParamDialog<'static>, covers = [], drive = Drive::Never)] fn param_dialog_with_footer_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ParamDialog::new("color-table", "Color Table", Param::parse_list(SPEC)) - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .extra_buttons(vec![("load".to_owned(), Label::from("Load…")), ("save".to_owned(), Label::from("Save…"))]) .footer_note("About 1.2 MB") .show(ui) @@ -111,5 +111,5 @@ fn hosted_param_dialog_with_a_refused_ok(ui: &mut Ui, data: &mut StoryData) -> S #[story(ParamDialog<'static>, covers = [], drive = Drive::Never)] fn command_form(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - ParamDialog::command("fit-image", "Fit Image", Param::parse_list(COMMAND_SPEC)).opened(Bind::bound(data.value("open", true))).show(ui).into() + ParamDialog::command("fit-image", "Fit Image", Param::parse_list(COMMAND_SPEC)).opened(data.bind("open", true)).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs index 90dbccd30..25d17f695 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs @@ -10,7 +10,9 @@ use crate::buttons::IconButton; use crate::contract::clicked; use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field}; use crate::patterns::form_dialogs::form::{read_bind, write_bind}; -use crate::patterns::presets::{GroupPath, NamedPresetEvent, NamedPresetRow, PickerField, PresetLibrary, PresetPicker, PresetRow, PresetState}; +use crate::patterns::presets::{ + GroupPath, NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetLibrary, PresetPicker, PresetRow, PresetState, +}; use crate::runtime::requests::{HostAnswer, PathFilter, PathKind, PathRequest}; use crate::text::TextField; use craft_behavior::IconId; @@ -723,7 +725,7 @@ impl Pass<'_> { let picker = PresetPicker::new(words.preset.clone(), Bind::given(current), &rows, Bind::bound(&mut held.picker)).field(PickerField::Name); NamedPresetRow::new(words.preset.clone(), picker) .suggest_name(words.new_preset_name.as_str().to_owned()) - .check_name(|typed| presets.name_error(typed)) + .check_name(NameCheck::new(presets.names(), |names, typed| names.name_error(typed))) .show(ui) }; for event in shown.events { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/export/stories.rs index 1f6977f0d..1ba76d91d 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export/stories.rs @@ -4,7 +4,6 @@ use super::{ ExportAsDialog, ExportOptions, ExportOptionsKind, ExportPreview, FormatOptions, FormatOptionsDialog, HostedExportAs, HostedFormatOptions, JpegOptions, OutputPathRow, SizeEstimate, TargaOptions, }; -use crate::contract::Bind; use crate::dialog::stories::{hosted, hosted_with}; use crate::patterns::form_dialogs::PreviewState; use crate::patterns::presets::{GroupPath, PresetLibrary}; @@ -150,11 +149,11 @@ const CHOSEN_PATH: &str = "/renders/poster_final.mov"; fn output_path_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let with_templates = *data.value("templates", true); let chosen = *data.value("file_chosen", false); - let path = data.value("path", TEMPLATE_PATH.to_owned()); + let (path, path_at) = data.value_at("path", TEMPLATE_PATH.to_owned()); if chosen != (*path == CHOSEN_PATH) { *path = if chosen { CHOSEN_PATH } else { TEMPLATE_PATH }.to_owned(); } - let mut row = OutputPathRow::new(Bind::bound(&mut *path)); + let mut row = OutputPathRow::new(path_at.bind(&mut *path)); if with_templates { row = row.templates(vec![ (TEMPLATE_PATH.to_owned(), Label::from("Comp name")), diff --git a/crates/ui-patterns/src/patterns/form_dialogs/file_list/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/file_list/stories.rs index df19bddc4..3a39d021d 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/file_list/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/file_list/stories.rs @@ -1,7 +1,6 @@ //! Stories of the file list picker. use super::{FileList, FileListMode, FileListPicker}; -use craft_ui::contract::Bind; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use std::path::PathBuf; @@ -18,7 +17,7 @@ fn file_list_picker_files(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut start = FileList::default(); start.add(photos()); let open = [PathBuf::from("/photos/trip/dusk.png")]; - FileListPicker::new("Files to load", Bind::bound(data.value("files", start))) + FileListPicker::new("Files to load", data.bind("files", start)) .folder_mode(true) .open_files(&open) .info(&|_| Some("1200 × 800 px, 300 ppi, RGB".to_owned())) @@ -28,12 +27,12 @@ fn file_list_picker_files(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(FileListPicker<'static>, covers = [Empty], drive = Drive::Never)] fn file_list_picker_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - FileListPicker::new("Files to load", Bind::bound(data.value("empty", FileList::default()))).show(ui).into() + FileListPicker::new("Files to load", data.bind("empty", FileList::default())).show(ui).into() } #[story(FileListPicker<'static>, covers = [], drive = Drive::Never)] fn file_list_picker_folder(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let start = FileList { mode: FileListMode::Folder, folder: Some(PathBuf::from("/photos/trip")), ..FileList::default() }; let files = photos(); - FileListPicker::new("Files to load", Bind::bound(data.value("folder", start))).folder_mode(true).folder_files(&files).show(ui).into() + FileListPicker::new("Files to load", data.bind("folder", start)).folder_mode(true).folder_files(&files).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/form/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/form/stories.rs index 615b66c30..1d571bb4c 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/form/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/form/stories.rs @@ -70,29 +70,27 @@ fn form_dialog_body_accept(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// A form without OK: Close, and the Mark (Enter) and Mark All buttons, which count what they marked. #[story(FormDialog<'static, bool>, covers = [], drive = Drive::Never)] fn form_dialog_close(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mut open = *data.value("open", false); + let ((open, open_at), (entry, entry_at)) = data.pair_at(("open", false), ("entry", "Craft".to_owned())); if clicked(&Button::new("Mark Entry…").show(ui)) { - open = true; + *open = true; } - let mut entry = data.value("entry", "Craft".to_owned()).clone(); - let output = FormDialog::new("Mark Entry", Bind::bound(&mut entry)) - .opened(Bind::bound(&mut open)) + let output = FormDialog::new("Mark Entry", entry_at.bind(&mut *entry)) + .opened(open_at.bind(&mut *open)) .buttons(FormButtons::Close) .extra_buttons([FooterButton::new("Mark", DialogRole::Accept), FooterButton::new("Mark All", DialogRole::Other)]) .show(ui, |ui, _, value| { TextField::new("Entry", Bind::bound(value)).show(ui); true }); + if let Some(value) = output.value { + *entry = value; + } let marked = match output.picked { Some(2) => 1, Some(3) => 10, _ => 0, }; *data.value("marked", 0_u32) += marked; - *data.value("open", false) = open; - if let Some(value) = output.value { - *data.value("entry", String::new()) = value; - } output.response.into() } @@ -100,7 +98,7 @@ fn form_dialog_close(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn form_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let ok_enabled = *data.value("ok_enabled", true); FormDialog::own("Options") - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .show(ui, |ui, _, value| { Checkbox::new(Bind::bound(value)).label(Label::from("Smooth")).show(ui); ok_enabled diff --git a/crates/ui-patterns/src/patterns/form_dialogs/guides/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/guides/stories.rs index 88d6187bc..49a6d6f36 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/guides/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/guides/stories.rs @@ -29,8 +29,8 @@ fn units(data: &mut StoryData) -> GuideUnits { #[story(NewGuideDialog<'static>, covers = [], drive = Drive::Never)] fn new_guide_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let units = units(data); - let values = data.value("values", NewGuideValues::default()); - NewGuideDialog::new(units, Bind::bound(values)).opened(Bind::given(true)).show(ui).into() + let (values, values_at) = data.value_at("values", NewGuideValues::default()); + NewGuideDialog::new(units, values_at.bind(values)).opened(Bind::given(true)).show(ui).into() } #[story(NewGuideDialog<'static>, covers = [], drive = Drive::Never)] @@ -39,8 +39,8 @@ fn new_guide_dialog_edit(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let axis = if *data.value("horizontal_guide", true) { Axis::Y } else { Axis::X }; let mut guide = Guide::new(GuideKey::new(1), axis, EDITED_AT); guide.color = Some(GuideColor::Magenta.rgba()); - let values = data.value("values", NewGuideValues::of_guide(&guide, PREFERENCE)); - NewGuideDialog::edit(units, guide, PREFERENCE, Bind::bound(values)).opened(Bind::given(true)).show(ui).into() + let (values, values_at) = data.value_at("values", NewGuideValues::of_guide(&guide, PREFERENCE)); + NewGuideDialog::edit(units, guide, PREFERENCE, values_at.bind(values)).opened(Bind::given(true)).show(ui).into() } #[story(GuideLayoutDialog<'static>, covers = [], drive = Drive::Never)] @@ -48,9 +48,9 @@ fn guide_layout_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let units = units(data); let existing = *data.value("existing_guides", false); let artboards = *data.value("artboards", false); - let values = data.value("values", GuideLayoutValues::default()); + let (values, values_at) = data.value_at("values", GuideLayoutValues::default()); let document = GuideRect::new(0.0, 0.0, WIDTH, HEIGHT); - let mut dialog = GuideLayoutDialog::new(units, document, Bind::bound(values)).opened(Bind::given(true)); + let mut dialog = GuideLayoutDialog::new(units, document, values_at.bind(values)).opened(Bind::given(true)); if existing { dialog = dialog.existing(vec![Guide::new(GuideKey::new(1), Axis::X, WIDTH / 2.0), Guide::new(GuideKey::new(2), Axis::Y, HEIGHT / 2.0)]); } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs index 697cef3e4..8721caf2a 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/list_manager/stories.rs @@ -27,7 +27,7 @@ fn list_manager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { .name("Batch Export") .searchable(true) .note("This document also has a script project.".into()) - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .show(ui) .into() } @@ -37,27 +37,24 @@ fn list_manager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(ListManager<'static>, covers = [], drive = Drive::Never)] fn list_manager_name_box(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let words = Env::of(ui).words::(); - let mut name = data.value("name", String::new()).clone(); - let mut open = *data.value("open", false); + let ((name, name_at), (open, open_at)) = data.pair_at(("name", String::new()), ("open", false)); if clicked(&Button::new("Macros…").show(ui)) { - open = true; + *open = true; } let first = Cell::new(false); let actions = vec![ListManagerAction::run(&words), ListManagerAction::create(&words)]; let shown = ListManager::new("Macros", "Macro name:", entries(), actions) - .name_box(Bind::bound(&mut name)) + .name_box(name_at.bind(&mut *name)) .under_list(|ui| { if clicked(&Button::new("Name the first macro").show(ui)) { first.set(true); } }) - .opened(Bind::bound(&mut open)) + .opened(open_at.bind(&mut *open)) .show(ui); if first.get() { - name = "Align Layers".to_owned(); + *name = "Align Layers".to_owned(); } - *data.value("name", String::new()) = name; - *data.value("open", false) = open; shown.into() } @@ -74,7 +71,7 @@ fn list_manager_bookmark(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut by_name = *data.value("sort by name", true); let mut hidden = *data.value("hidden", false); let mut gone = data.value("deleted", Vec::::new()).clone(); - let open = data.value("open", false); + let (open, open_at) = data.value_at("open", false); if clicked(&Button::new("Bookmarks…").show(ui)) { *open = true; } @@ -103,7 +100,7 @@ fn list_manager_bookmark(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { hidden = on; } }) - .opened(Bind::bound(open)) + .opened(open_at.bind(open)) .show(ui); if let Some(choice) = &shown.choice && choice.action == "delete" @@ -123,7 +120,7 @@ fn list_manager_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let actions = vec![ListManagerAction::run(&words), ListManagerAction::create(&words)]; ListManager::new("Macros", "Macro name:", Vec::new(), actions) .empty("This document has no scripts or macros.".into()) - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .show(ui) .into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/navigator_options/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/navigator_options/stories.rs index 213e185bd..19b8212b4 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/navigator_options/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/navigator_options/stories.rs @@ -8,6 +8,6 @@ use egui::Ui; #[story(NavigatorOptionsDialog<'static>, covers = [], drive = Drive::Never)] fn navigator_options_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let options = data.value("options", NavigatorOptions::new(ProxyColor::Blue)); - NavigatorOptionsDialog::new(Bind::bound(options)).opened(Bind::given(true)).show(ui).into() + let (options, options_at) = data.value_at("options", NavigatorOptions::new(ProxyColor::Blue)); + NavigatorOptionsDialog::new(options_at.bind(options)).opened(Bind::given(true)).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs index bffa74685..042365588 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document.rs @@ -461,7 +461,7 @@ fn body(ui: &mut Ui, form: &mut FormCx<'_, '_>, values: &mut DocumentOptions, sh } if right.save { let name = session.naming.clone().unwrap_or_default(); - if details::refusal(&library, &name).is_none() { + if details::refusal(&library.names(), &name).is_none() { let preset = DocumentOptions { name: name.trim().to_owned(), ..values.clone() }; if let Ok(id) = library.add(&GroupPath::root(), &name, preset) { changed = true; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs index 8fc9a90d8..b1f23fd8c 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/details.rs @@ -7,12 +7,12 @@ use super::presets::{ use super::{NewDocumentWords, Read, Session, background_rgb, depth_label, mode_label}; use crate::buttons::Button; use crate::choice::{Checkbox, Segmented, Swatch}; -use crate::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked}; +use crate::contract::{Bind, Entry, FieldLayout, Gap, MemoProps, Props as _, Show as _, ShowContainer as _, Sizing, Validity, clicked}; use crate::display::{Shade, Text}; use crate::form::{Field, FieldGroup}; use crate::layout_components::{Grid, Row}; use crate::patterns::form_dialogs::LinkedSize; -use crate::patterns::presets::{PresetError, PresetLibrary}; +use crate::patterns::presets::{PresetError, PresetNames}; use crate::pickers::{Select, UnitSelect}; use crate::runtime::env::{Env, Label, Message, UnitKind}; use crate::runtime::focus::{self, FocusTarget}; @@ -326,17 +326,26 @@ pub(super) enum Refusal { Full, } -/// Whether `name` can be saved beside the presets of `library`: the library's name check, then its size limit. -pub(super) fn refusal(library: &PresetLibrary, name: &str) -> Option { - library.name_error(name).map(Refusal::Name).or_else(|| (library.total() >= MAX_SAVED).then_some(Refusal::Full)) +/// Whether `name` can be saved beside the presets named `names`: the library's name check, then its size limit. +pub(super) fn refusal(names: &PresetNames, name: &str) -> Option { + names.name_error(name).map(Refusal::Name).or_else(|| (names.len() >= MAX_SAVED).then_some(Refusal::Full)) } -/// The text that says why a preset cannot be saved. -fn refusal_message(read: &Read<'_>, refusal: &Refusal) -> Label { - match refusal { - Refusal::Name(PresetError::NameTaken) => read.library_words.name_taken.clone(), - Refusal::Name(_) => read.library_words.name_invalid.clone(), - Refusal::Full => read.words.too_many.clone(), +/// The texts that say why a preset cannot be saved. +#[derive(MemoProps)] +struct RefusalWords<'w> { + taken: &'w Label, + invalid: &'w Label, + full: &'w Label, +} + +impl RefusalWords<'_> { + fn message(&self, refusal: &Refusal) -> Label { + match refusal { + Refusal::Name(PresetError::NameTaken) => self.taken.clone(), + Refusal::Name(_) => self.invalid.clone(), + Refusal::Full => self.full.clone(), + } } } @@ -370,15 +379,21 @@ fn save_pane(ui: &mut Ui, session: &mut Session, read: &Read<'_>, right: &mut Ri let cancel = Env::of(ui).words::().cancel.clone(); let Some(name) = session.naming.clone() else { return }; let tried = session.name_tried; - let library = read.library; - let check = |typed: &String| match refusal(library, typed) { - Some(refused) if tried => Validity::Error(Message::new(refusal_message(read, &refused))), - _ => Validity::Ok, - }; + let refusals = RefusalWords { taken: &read.library_words.name_taken, invalid: &read.library_words.name_invalid, full: &read.words.too_many }; + let inputs = (read.library.names(), tried, refusals); Text::new(words.save_preset_title.clone()).role(TypeRole::Label).shade(Shade::Muted).show(ui); Field::new(words.preset_name.clone()).id_salt("preset-name").show(ui, |ui, _| { - let shown = - TextField::new(words.preset_name.clone(), Bind::given(name.clone()).check(check)).limit(MAX_NAME).select_on_focus().submits().show(ui); + let shown = TextField::new( + words.preset_name.clone(), + Bind::given(name.clone()).check_with(&inputs, |(names, tried, refusals), typed| match refusal(names, typed) { + Some(refused) if *tried => Validity::Error(Message::new(refusals.message(&refused))), + _ => Validity::Ok, + }), + ) + .limit(MAX_NAME) + .select_on_focus() + .submits() + .show(ui); if let Some(typed) = shown.value().cloned() { session.naming = Some(typed); session.name_tried = false; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/stories.rs index f305603dd..3fdcd5f12 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/stories.rs @@ -14,21 +14,22 @@ fn new_document_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { if clipboard { dialog = dialog.clipboard(PixelSize::new(1920, 1080)); } - dialog.opened(Bind::bound(data.value("open", true))).show(ui).into() + dialog.opened(data.bind("open", true)).show(ui).into() } #[story(NewDocumentDialog<'static>, covers = [], drive = Drive::Never)] fn new_document_dialog_with_app_presets(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let mut library = data.value("library", PresetLibrary::::new()).clone(); - let mut recent = data.value("recent", vec![DocumentOptions { name: "Poster".to_owned(), ..DocumentOptions::default() }]).clone(); - let mut tab = data.value("tab", "recent".to_owned()).clone(); - let output = NewDocumentDialog::new(Bind::kept()) - .saved(Bind::bound(&mut library)) - .recent(Bind::bound(&mut recent)) - .tab(Bind::bound(&mut tab)) - .opened(Bind::bound(data.value("open", true))) - .show(ui); - *data.value("library", PresetLibrary::::new()) = library; - *data.value("tab", "recent".to_owned()) = tab; - output.into() + let presets = ( + PresetLibrary::::new(), + vec![DocumentOptions { name: "Poster".to_owned(), ..DocumentOptions::default() }], + "recent".to_owned(), + ); + let (((library, recent, tab), presets_at), (open, open_at)) = data.pair_at(("presets", presets), ("open", true)); + NewDocumentDialog::new(Bind::kept()) + .saved(presets_at.bind(library)) + .recent(presets_at.bind(recent)) + .tab(presets_at.bind(tab)) + .opened(open_at.bind(open)) + .show(ui) + .into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs index 1c9754f40..31c3614de 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/password/stories.rs @@ -2,7 +2,7 @@ use super::{PasswordDialog, PasswordPurpose}; use crate::buttons::Button; -use crate::contract::{Bind, Show as _, clicked}; +use crate::contract::{Show as _, clicked}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -20,7 +20,7 @@ fn password_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { Asks::Open => PasswordPurpose::open("brochure.pdf"), Asks::Permissions => PasswordPurpose::permissions("brochure.pdf"), }; - let dialog = PasswordDialog::new(purpose).opened(Bind::bound(data.value("open", true))); + let dialog = PasswordDialog::new(purpose).opened(data.bind("open", true)); let dialog = if wrong { dialog.error(crate::runtime::env::Label::Static("That password is not correct.")) } else { dialog }; dialog.show(ui).into() } @@ -28,14 +28,14 @@ fn password_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// A new password that two empty fields clear; the dialog opens from its button. #[story(PasswordDialog<'static>, covers = [], drive = Drive::Never)] fn set_or_clear(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let open = data.value("open", false); + let (open, open_at) = data.value_at("open", false); if clicked(&Button::new("Set Password…").show(ui)) { *open = true; } - PasswordDialog::new(PasswordPurpose::SetOrClear).opened(Bind::bound(open)).show(ui).into() + PasswordDialog::new(PasswordPurpose::SetOrClear).opened(open_at.bind(open)).show(ui).into() } #[story(PasswordDialog<'static>, covers = [], drive = Drive::Never)] fn password_dialog_new_password(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - PasswordDialog::new(PasswordPurpose::Set).opened(Bind::bound(data.value("open", true))).show(ui).into() + PasswordDialog::new(PasswordPurpose::Set).opened(data.bind("open", true)).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/path_row/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/path_row/stories.rs index 6a89121d2..9ac41d8d2 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/path_row/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/path_row/stories.rs @@ -23,10 +23,10 @@ fn path_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// A row whose Browse is off, with the reason as the button's tooltip. #[story(PathRow<'static>, covers = [], drive = Drive::Never)] fn path_row_browse_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let path = data.value("path", "/photos/trip/sunrise.png".to_owned()); + let (path, path_at) = data.value_at("path", "/photos/trip/sunrise.png".to_owned()); let mut shown = StoryOutput::default(); Field::new("Image").show(ui, |ui, _| { - shown = PathRow::new("Image", Bind::bound(&mut *path)).browse_reason("Browsing needs the file service.").show(ui).into(); + shown = PathRow::new("Image", path_at.bind(&mut *path)).browse_reason("Browsing needs the file service.").show(ui).into(); }); shown } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/pdf_export.rs b/crates/ui-patterns/src/patterns/form_dialogs/pdf_export.rs index 85a89d70d..c669b4a87 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/pdf_export.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/pdf_export.rs @@ -21,7 +21,7 @@ use crate::form::{Field, FieldGroup}; use crate::layout_components::{Row, Stack}; use crate::list::{List, ListRow}; use crate::notices::{Notice, NoticeLayout}; -use crate::patterns::presets::{NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetState}; +use crate::patterns::presets::{NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetState}; use crate::pickers::Select; use crate::runtime::env::{Env, Label, UnitKind}; use crate::runtime::overlay::CloseReason; @@ -350,7 +350,9 @@ impl<'a> PdfExportDialog<'a> { } let named = NamedPresetRow::new(words.preset.clone(), picker) .suggest_name(words.new_preset_name.as_str().to_owned()) - .check_name(|typed| presets.iter().any(|preset| preset.name.eq_ignore_ascii_case(typed)).then_some(PresetError::NameTaken)) + .check_name(NameCheck::new(presets.iter().map(|preset| preset.name.as_str()).collect::>(), |names, typed| { + names.iter().any(|name| name.eq_ignore_ascii_case(typed)).then_some(PresetError::NameTaken) + })) .built_in(|key| built_in.contains(key)) .show(ui); for event in named.events { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/pdf_export/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/pdf_export/stories.rs index 6e5cc60b1..ab7249c19 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/pdf_export/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/pdf_export/stories.rs @@ -1,7 +1,6 @@ //! Stories of `PdfExportDialog`. use super::PdfExportDialog; -use crate::contract::Bind; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_pdf::settings::{PdfSettings, builtin_preset}; use egui::Ui; @@ -16,12 +15,12 @@ const PRESETS: [(&str, &str); 4] = #[story(PdfExportDialog<'static>, covers = [], drive = Drive::Never)] fn pdf_export_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let preset = *data.choice("preset", "default", &PRESETS); - let (settings, open, applied) = data.value("pdf", (PdfSettings::default(), true, "default")); + let (((settings, applied), pdf_at), (open, open_at)) = data.pair_at(("pdf", (PdfSettings::default(), "default")), ("open", true)); if *applied != preset { if let Some(found) = builtin_preset(preset, "Story") { *settings = found.settings; } *applied = preset; } - PdfExportDialog::new("Story", Bind::bound(settings)).opened(Bind::bound(open)).artboard_count(ARTBOARDS).show(ui).into() + PdfExportDialog::new("Story", pdf_at.bind(settings)).opened(open_at.bind(open)).artboard_count(ARTBOARDS).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/properties/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/properties/stories.rs index 7efff08e5..b9a6a6a6b 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/properties/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/properties/stories.rs @@ -25,13 +25,13 @@ fn tabs() -> Vec { #[story(PropertiesDialog<'static>, covers = [], drive = Drive::Never)] fn properties_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let read_only = *data.value("read_only", false); - let values = data.value("values", DialogFields::new()); - PropertiesDialog::new("Properties", tabs(), Bind::bound(values)).read_only(read_only).opened(Bind::given(true)).show(ui).into() + let (values, values_at) = data.value_at("values", DialogFields::new()); + PropertiesDialog::new("Properties", tabs(), values_at.bind(values)).read_only(read_only).opened(Bind::given(true)).show(ui).into() } #[story(PropertiesDialog<'static>, covers = [], drive = Drive::Never)] fn properties_dialog_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let read_only = *data.value("read_only", true); - let values = data.value("values", DialogFields::new()); - PropertiesDialog::new("Properties", tabs(), Bind::bound(values)).read_only(read_only).opened(Bind::given(true)).show(ui).into() + let (values, values_at) = data.value_at("values", DialogFields::new()); + PropertiesDialog::new("Properties", tabs(), values_at.bind(values)).read_only(read_only).opened(Bind::given(true)).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/report/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/report/stories.rs index 87aad51d4..25a9fe0f4 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/report/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/report/stories.rs @@ -1,7 +1,6 @@ //! Stories of `ReportDialog`. use super::{ReportDialog, ReportNote}; -use crate::contract::Bind; use crate::runtime::env::Label; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_theme::variant::Tone; @@ -22,5 +21,5 @@ fn report_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { if plain { dialog = dialog.lines((0..count).map(|n| Label::from(format!("page-{:03}.png: 2 layers merged", n + 1))).collect()); } - dialog.opened(Bind::bound(data.value("open", true))).show(ui).into() + dialog.opened(data.bind("open", true)).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/rows/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/rows/stories.rs index 2c9f75e2c..d0bba0bee 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/rows/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/rows/stories.rs @@ -3,7 +3,6 @@ use super::{DialogFields, ParamRows}; use crate::runtime::requests::PathKind; -use crate::contract::Bind; use crate::patterns::blend_keys::{BlendKeyEntry, BlendShortcut}; use crate::patterns::form_dialogs::{NumberUnit, Param, ParamKind}; use crate::patterns::presets::PresetRow; @@ -72,14 +71,14 @@ fn params() -> Vec { fn param_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let params = params(); let patterns = patterns(); - let fields = data.value("fields", DialogFields::new()); - ParamRows::new("Filter", ¶ms, Bind::bound(fields)).patterns(&patterns).show(ui).into() + let (fields, fields_at) = data.value_at("fields", DialogFields::new()); + ParamRows::new("Filter", ¶ms, fields_at.bind(fields)).patterns(&patterns).show(ui).into() } #[story(ParamRows<'static>, covers = [], drive = Drive::Never)] fn param_rows_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let params = params(); let patterns = patterns(); - let fields = data.value("fields", DialogFields::new()); - ParamRows::new("Filter", ¶ms, Bind::bound(fields)).patterns(&patterns).read_only(true).show(ui).into() + let (fields, fields_at) = data.value_at("fields", DialogFields::new()); + ParamRows::new("Filter", ¶ms, fields_at.bind(fields)).patterns(&patterns).read_only(true).show(ui).into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs index f7881525f..f466e8bea 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/stories.rs @@ -1,7 +1,6 @@ //! Stories of `SaveForWebDialog`. use super::{Animation, SaveForWebDialog, SaveForWebOptions, WebFormat, WebPictures, WebPreset, WebSlice, WebSlices, WebVariant}; -use crate::contract::Bind; use crate::primitives::TextureCache; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::PixelSize; @@ -48,16 +47,17 @@ fn save_for_web(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut pictures = WebPictures::new().original(original); pictures.set(WebVariant::new(0, 1, encoded, ENCODED_BYTES)); let flags = extras(data, false, true); - let (options, open) = data.value("web", (SaveForWebOptions::default(), true)); - with_extras(SaveForWebDialog::new("poster.psd", size(), pictures, Bind::bound(options)).opened(Bind::bound(open)), flags).show(ui).into() + let ((options, open), web_at) = data.value_at("web", (SaveForWebOptions::default(), true)); + with_extras(SaveForWebDialog::new("poster.psd", size(), pictures, web_at.bind(options)).opened(web_at.bind(open)), flags).show(ui).into() } #[story(SaveForWebDialog<'static>, covers = [], drive = Drive::Never)] fn save_for_web_pending_animation(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let original = picture(ui, "form-dialogs-web-original", Color32::from_rgb(0x8a, 0x6f, 0x4d)); let flags = extras(data, true, false); - let (options, open) = data.value("web-animation", (SaveForWebOptions::default(), true)); - let dialog = SaveForWebDialog::new("loop.psd", size(), WebPictures::new().original(original), Bind::bound(options)).opened(Bind::bound(open)); + let ((options, open), options_open_at) = data.value_at("web-animation", (SaveForWebOptions::default(), true)); + let dialog = SaveForWebDialog::new("loop.psd", size(), WebPictures::new().original(original), options_open_at.bind(options)) + .opened(options_open_at.bind(open)); with_extras(dialog, flags).show(ui).into() } @@ -79,8 +79,10 @@ fn save_for_web_color_table(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { ..SaveForWebOptions::default() }; let flags = extras(data, false, false); - let (options, open) = data.value("web-table", (start, true)); - with_extras(SaveForWebDialog::new("poster.psd", size(), pictures, Bind::bound(options)).opened(Bind::bound(open)), flags).show(ui).into() + let ((options, open), options_open_at) = data.value_at("web-table", (start, true)); + with_extras(SaveForWebDialog::new("poster.psd", size(), pictures, options_open_at.bind(options)).opened(options_open_at.bind(open)), flags) + .show(ui) + .into() } /// The slices of the slices story: three side by side. @@ -104,8 +106,10 @@ fn save_for_web_slices(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { pictures.set(WebVariant::new(0, 1, encoded, ENCODED_BYTES)); let start = SaveForWebOptions { slices: WebSlices::Selected(vec![2]), ..SaveForWebOptions::default() }; let flags = extras(data, false, false); - let (options, open) = data.value("web-slices", (start, true)); - let dialog = SaveForWebDialog::new("poster.psd", size(), pictures, Bind::bound(options)).opened(Bind::bound(open)).slices(story_slices()); + let ((options, open), options_open_at) = data.value_at("web-slices", (start, true)); + let dialog = SaveForWebDialog::new("poster.psd", size(), pictures, options_open_at.bind(options)) + .opened(options_open_at.bind(open)) + .slices(story_slices()); with_extras(dialog, flags).show(ui).into() } @@ -115,6 +119,8 @@ fn save_for_web_failed_encode(ui: &mut Ui, data: &mut StoryData) -> StoryOutput let mut pictures = WebPictures::new().original(original); pictures.set(WebVariant::failed(0, 1, "The encoder ran out of memory")); let flags = extras(data, false, false); - let (options, open) = data.value("web-failed", (SaveForWebOptions::default(), true)); - with_extras(SaveForWebDialog::new("poster.psd", size(), pictures, Bind::bound(options)).opened(Bind::bound(open)), flags).show(ui).into() + let ((options, open), options_open_at) = data.value_at("web-failed", (SaveForWebOptions::default(), true)); + with_extras(SaveForWebDialog::new("poster.psd", size(), pictures, options_open_at.bind(options)).opened(options_open_at.bind(open)), flags) + .show(ui) + .into() } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/watermark/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/watermark/stories.rs index e2286cdf4..d452e3280 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/watermark/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/watermark/stories.rs @@ -1,7 +1,6 @@ //! Stories of `Watermark`. use super::{Watermark, WatermarkSettings, WatermarkStyle}; -use crate::contract::Bind; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -22,7 +21,7 @@ fn kind_of(style: &WatermarkStyle) -> Kind { fn watermark_story(ui: &mut Ui, data: &mut StoryData, name: &'static str, start: WatermarkSettings) -> StoryOutput { let kind = *data.choice("style", kind_of(&start.style), &KINDS); let vertical = *data.value("vertical", start.vertical); - let settings = data.value(name, start); + let (settings, settings_at) = data.value_at(name, start); if kind_of(&settings.style) != kind { settings.style = match kind { Kind::Text => WatermarkStyle::Text("© Studio".to_owned()), @@ -30,7 +29,7 @@ fn watermark_story(ui: &mut Ui, data: &mut StoryData, name: &'static str, start: }; } settings.vertical = vertical; - let output: StoryOutput = Watermark::new("Watermark", Bind::bound(&mut *settings)).show(ui).into(); + let output: StoryOutput = Watermark::new("Watermark", settings_at.bind(&mut *settings)).show(ui).into(); let (kind, vertical) = (kind_of(&settings.style), settings.vertical); *data.choice("style", kind, &KINDS) = kind; *data.value("vertical", vertical) = vertical; diff --git a/crates/ui-patterns/src/patterns/panels/inspector/stories.rs b/crates/ui-patterns/src/patterns/panels/inspector/stories.rs index 7ee6a7414..15a80e0b4 100644 --- a/crates/ui-patterns/src/patterns/panels/inspector/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/inspector/stories.rs @@ -26,7 +26,7 @@ fn inspector(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let shown = stack .show(ui, |ui, _| { rows.each(ui, |ui, key, slot| { - let open = Bind::bound(data.value(TITLES[usize::from(*key)], true)); + let open = data.bind(TITLES[usize::from(*key)], true); Section::new(TITLES[usize::from(*key)]) .open(open) .in_stack(slot) diff --git a/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs b/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs index 7c65a0230..1e8761d82 100644 --- a/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs @@ -1,15 +1,14 @@ //! Stories of `ModifierKeysPanel`. use super::ModifierKeysPanel; -use crate::contract::Bind; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_keymap::Mods; use egui::Ui; #[story(ModifierKeysPanel<'static>, covers = [], drive = Drive::Never, title = "Shift latched")] fn modifier_keys_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let latched = data.value("latched", Mods::SHIFT); - ModifierKeysPanel::new(Bind::bound(&mut *latched)).show(ui); + let (latched, latched_at) = data.value_at("latched", Mods::SHIFT); + ModifierKeysPanel::new(latched_at.bind(&mut *latched)).show(ui); let readout = format!("{latched:?}"); StoryOutput::default().readout(readout) } diff --git a/crates/ui-patterns/src/patterns/panels/palette/stories.rs b/crates/ui-patterns/src/patterns/panels/palette/stories.rs index 3837a926e..205b881dd 100644 --- a/crates/ui-patterns/src/patterns/panels/palette/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/palette/stories.rs @@ -67,8 +67,7 @@ fn configured( ) -> StoryOutput { // The palette binds two story values; it edits a copy of `open`, which goes back after the pass. let mut open = *data.value("open", open_at_start); - let palette = - CommandPalette::new("Command palette", ENTRIES.as_slice(), Bind::bound(&mut open)).recents(Bind::bound(data.value("recents", recents))); + let palette = CommandPalette::new("Command palette", ENTRIES.as_slice(), Bind::bound(&mut open)).recents(data.bind("recents", recents)); let out = configure(palette).show(ui); *data.value("open", open_at_start) = open; let last = data.value("last", None::); diff --git a/crates/ui-patterns/src/patterns/panels/tour/stories.rs b/crates/ui-patterns/src/patterns/panels/tour/stories.rs index 3043f3ebe..8ed4951c9 100644 --- a/crates/ui-patterns/src/patterns/panels/tour/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/tour/stories.rs @@ -2,7 +2,7 @@ use super::{Tour, TourStep}; use crate::buttons::Button; -use crate::contract::{Bind, Show as _}; +use crate::contract::Show as _; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -14,6 +14,6 @@ fn tour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { TourStep::new("Properties", "The selected layer's settings show in this panel."), TourStep::new("Export", "When the poster is ready, export it from the File menu."), ]; - Tour::new("Welcome tour", &steps, Bind::bound(data.value("index", 0_usize))).show(ui); + Tour::new("Welcome tour", &steps, data.bind("index", 0_usize)).show(ui); StoryOutput::default() } diff --git a/crates/ui-patterns/src/patterns/preferences/page/stories.rs b/crates/ui-patterns/src/patterns/preferences/page/stories.rs index 148dc77a9..602f68258 100644 --- a/crates/ui-patterns/src/patterns/preferences/page/stories.rs +++ b/crates/ui-patterns/src/patterns/preferences/page/stories.rs @@ -1,6 +1,5 @@ //! Stories of `PreferencesPage`. -use crate::contract::Bind; use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, RowKind, RowSpec}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_theme::Rgba; @@ -70,7 +69,7 @@ impl PreferencesModel for Live { /// The page over the story's settings. fn page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut live = data.value("live", Live::default()).clone(); - let shown = PreferencesPage::new(Bind::bound(data.value("state", PreferencesState::default()))).show(ui, &mut live); + let shown = PreferencesPage::new(data.bind("state", PreferencesState::default())).show(ui, &mut live); *data.value("live", Live::default()) = live; shown.into() } diff --git a/crates/ui-patterns/src/patterns/preferences/window/stories.rs b/crates/ui-patterns/src/patterns/preferences/window/stories.rs index c99258552..25661722b 100644 --- a/crates/ui-patterns/src/patterns/preferences/window/stories.rs +++ b/crates/ui-patterns/src/patterns/preferences/window/stories.rs @@ -1,7 +1,7 @@ //! Stories of `PreferencesWindow`. use super::{PreferencesState, PreferencesWindow}; -use crate::contract::{Bind, Entry}; +use crate::contract::Entry; use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec}; use crate::runtime::env::UnitKind; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -109,8 +109,8 @@ impl PreferencesDraft for Demo { fn window(ui: &mut Ui, data: &mut StoryData, state: PreferencesState, demo: Demo) -> StoryOutput { let mut demo = data.value("demo", demo).clone(); - let state = data.value("state", state); - let shown = PreferencesWindow::new(Bind::bound(state)).embedded().show(ui, &mut demo).into(); + let (state, state_at) = data.value_at("state", state); + let shown = PreferencesWindow::new(state_at.bind(state)).embedded().show(ui, &mut demo).into(); *data.value("demo", Demo::default()) = demo; shown } diff --git a/crates/ui-patterns/src/patterns/presets/browser/stories.rs b/crates/ui-patterns/src/patterns/presets/browser/stories.rs index f561b7c68..ca62ae09b 100644 --- a/crates/ui-patterns/src/patterns/presets/browser/stories.rs +++ b/crates/ui-patterns/src/patterns/presets/browser/stories.rs @@ -2,7 +2,6 @@ use super::{PresetBrowser, PresetReorder}; use crate::choice::SwatchFace; -use crate::contract::Bind; use crate::list::ThumbAspect; use crate::patterns::presets::{PresetEvent, PresetFooterOptions, PresetRow, PresetState, PresetTiles}; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -59,7 +58,7 @@ fn preset_browser(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let slider = *data.value("slider", true); let new_group = *data.value("new_group", true); let selected = *data.value("selected", None::); - let mut browser = PresetBrowser::new("Swatches", Bind::bound(data.value("state", PresetState::::new())), &rows) + let mut browser = PresetBrowser::new("Swatches", data.bind("state", PresetState::::new()), &rows) .toolbar(true) .reorder(PresetReorder::items_and_groups().nest(NESTING)) .footer(PresetFooterOptions::new().slider(slider).new_group(new_group).can_delete(selected.is_some())); @@ -85,7 +84,7 @@ fn preset_browser(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn preset_browser_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let rows = library_rows(); let selected = *data.value("selected", None::); - let mut browser = PresetBrowser::new("Swatches", Bind::bound(data.value("state", PresetState::::new())), &rows).tiles(PresetTiles::Chips); + let mut browser = PresetBrowser::new("Swatches", data.bind("state", PresetState::::new()), &rows).tiles(PresetTiles::Chips); if let Some(key) = selected { browser = browser.selected(key); } diff --git a/crates/ui-patterns/src/patterns/presets/footer/stories.rs b/crates/ui-patterns/src/patterns/presets/footer/stories.rs index f7c04b7db..649c3e267 100644 --- a/crates/ui-patterns/src/patterns/presets/footer/stories.rs +++ b/crates/ui-patterns/src/patterns/presets/footer/stories.rs @@ -1,7 +1,6 @@ //! Stories of `PresetFooter`. use super::{PresetFooter, PresetFooterOptions}; -use crate::contract::Bind; use crate::sections::FooterAction; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::IconId; @@ -12,7 +11,7 @@ fn preset_footer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let slider = *data.value("slider", true); let new_group = *data.value("new_group", true); let count = *data.value("count", true); - let footer = PresetFooter::::new(Bind::bound(data.value("zoom", 1.0f64))).options( + let footer = PresetFooter::::new(data.bind("zoom", 1.0f64)).options( PresetFooterOptions::new() .slider(slider) .new_group(new_group) diff --git a/crates/ui-patterns/src/patterns/presets/manager/stories.rs b/crates/ui-patterns/src/patterns/presets/manager/stories.rs index 46edafa5e..92c8abc9c 100644 --- a/crates/ui-patterns/src/patterns/presets/manager/stories.rs +++ b/crates/ui-patterns/src/patterns/presets/manager/stories.rs @@ -19,7 +19,7 @@ fn show_manager(ui: &mut Ui, data: &mut StoryData, rows: &[PresetRow], load // `data` hands out one value at a time, so the picked kind is copied out and written back. let mut kind = *data.value("kind", 0u32); let mut manager = PresetManager::new("Preset Manager", &kinds, Bind::bound(&mut kind), rows) - .opened(Bind::bound(data.value("open", true))) + .opened(data.bind("open", true)) .can_rename(|key: &u32| *key != 1) .can_delete(|key: &u32| *key != 1); if load { diff --git a/crates/ui-patterns/src/patterns/presets/mod.rs b/crates/ui-patterns/src/patterns/presets/mod.rs index ccb51c5cf..3b480623e 100644 --- a/crates/ui-patterns/src/patterns/presets/mod.rs +++ b/crates/ui-patterns/src/patterns/presets/mod.rs @@ -25,8 +25,8 @@ pub use files::{PresetExport, PresetFileEvent, PresetFileFailure, PresetFileRequ pub use footer::{PresetFooter, PresetFooterEvent, PresetFooterOptions, PresetFooterOutput}; pub use manager::{HostedPresetManager, PresetManager, PresetManagerOutput, PresetManagerTaken}; pub use model::{ - CellShape, GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetKind, PresetLibrary, PresetRow, PresetTiles, - Preview, PreviewPaint, ThumbInfo, children_end, has_captions, nest_allowed, + CellShape, GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetKind, PresetLibrary, PresetNames, PresetRow, + PresetTiles, Preview, PreviewPaint, ThumbInfo, children_end, has_captions, nest_allowed, }; pub use named::{NameCheck, NamedPresetCommands, NamedPresetEvent, NamedPresetOutput, NamedPresetRow, NamedPresetStyle}; pub use panel_menu::{PresetCommands, PresetMenuAction, PresetPanelMenu}; diff --git a/crates/ui-patterns/src/patterns/presets/model.rs b/crates/ui-patterns/src/patterns/presets/model.rs index fe4a270ca..f8eea7598 100644 --- a/crates/ui-patterns/src/patterns/presets/model.rs +++ b/crates/ui-patterns/src/patterns/presets/model.rs @@ -4,7 +4,7 @@ mod apply; mod library; -pub use library::{GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetLibrary}; +pub use library::{GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetLibrary, PresetNames}; use crate::list::ThumbAspect; use crate::primitives::ContentPainterCx; diff --git a/crates/ui-patterns/src/patterns/presets/model/library.rs b/crates/ui-patterns/src/patterns/presets/model/library.rs index e22dce26f..4a98e8c7f 100644 --- a/crates/ui-patterns/src/patterns/presets/model/library.rs +++ b/crates/ui-patterns/src/patterns/presets/model/library.rs @@ -399,13 +399,12 @@ impl PresetLibrary { /// Why `name` cannot be a new preset's name, if it cannot: blank, or taken ignoring case. /// For a named row's `check_name`. pub fn name_error(&self, name: &str) -> Option { - if name.trim().is_empty() { - Some(PresetError::EmptyName) - } else if self.is_taken(name.trim()) { - Some(PresetError::NameTaken) - } else { - None - } + self.names().name_error(name) + } + + /// The presets' names, as the inputs of a name check in a binding or a named row (`check_with`). + pub fn names(&self) -> PresetNames<'_> { + PresetNames(&self.root) } /// The number of presets. @@ -440,7 +439,7 @@ impl PresetLibrary { } fn is_taken(&self, name: &str) -> bool { - self.items().iter().any(|i| same_name(&i.name, name)) + self.root.each(&mut |taken| same_name(taken, name)) } /// `base`, or "base 2", "base 3", … so the name is free across the library. @@ -452,6 +451,65 @@ impl PresetLibrary { } } +/// The names of a library's presets (`PresetLibrary::names`): what a check of a new name reads. It borrows the +/// library and walks its names when a check or a memoized view's key reads them. +#[derive(Clone, Copy)] +pub struct PresetNames<'l>(&'l dyn EachName); + +impl PresetNames<'_> { + /// Why `name` cannot be a new preset's name: blank, or taken ignoring case. + pub fn name_error(&self, name: &str) -> Option { + let name = name.trim(); + if name.is_empty() { + Some(PresetError::EmptyName) + } else if self.0.each(&mut |taken| same_name(taken, name)) { + Some(PresetError::NameTaken) + } else { + None + } + } + + /// How many presets there are. + pub fn len(&self) -> usize { + let mut count = 0; + self.0.each(&mut |_| { + count += 1; + false + }); + count + } + + /// Whether there are none. + pub fn is_empty(&self) -> bool { + !self.0.each(&mut |_| true) + } +} + +/// Every name, in display order, and their count. +impl craft_ui::contract::MemoProps for PresetNames<'_> { + fn key(&self, key: &mut craft_ui::contract::MemoKey) { + let mut count: u64 = 0; + self.0.each(&mut |name| { + craft_ui::contract::MemoProps::key(name, key); + count += 1; + false + }); + craft_ui::contract::MemoProps::key(&count, key); + } +} + +/// A walk over the names of a group's presets, its folders' included. +trait EachName { + /// Calls `f` with each name until it returns `true`; whether it did. + fn each(&self, f: &mut dyn FnMut(&str) -> bool) -> bool; +} + +impl EachName for PresetGroup { + fn each(&self, f: &mut dyn FnMut(&str) -> bool) -> bool { + self.items.iter().any(|item| f(&item.name)) || self.groups.iter().any(|group| group.each(f)) + } +} + pub(super) fn same_name(a: &str, b: &str) -> bool { a.to_lowercase() == b.to_lowercase() } diff --git a/crates/ui-patterns/src/patterns/presets/named.rs b/crates/ui-patterns/src/patterns/presets/named.rs index b5e03f2ed..559d0a743 100644 --- a/crates/ui-patterns/src/patterns/presets/named.rs +++ b/crates/ui-patterns/src/patterns/presets/named.rs @@ -15,7 +15,7 @@ use super::panel_menu::PresetCommands; use super::picker::PresetPicker; use super::words::PresetWords; use crate::buttons::{Button, IconButton}; -use crate::contract::{Bind, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, Trigger, Validity, clicked}; +use crate::contract::{Bind, MemoKey, MemoProps, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, Trigger, Validity, clicked}; use crate::display::Divider; use crate::form::Field; use crate::layout_components::Row; @@ -61,21 +61,74 @@ pub enum NamedPresetStyle { Menu, } -type NameCheckFn<'a> = Box Option + 'a>; - /// Whether a name may be used: the host's answer for a typed name. -pub struct NameCheck<'a>(NameCheckFn<'a>); +pub struct NameCheck<'a>(Box); impl<'a> NameCheck<'a> { - /// The check that runs `check`. - pub fn new(check: impl Fn(&str) -> Option + 'a) -> Self { - NameCheck(Box::new(check)) + /// The check `check`, reading `inputs` (the names already taken, as [`PresetNames`](super::PresetNames)). The + /// inputs are props and `check` is a `fn`, which captures nothing, as a binding's `check_with` takes them, so a + /// memoized view that holds the row sees every input of the check. + pub fn new(inputs: I, check: fn(&I, &str) -> Option) -> Self { + NameCheck(Box::new(WithInputs { inputs, check })) + } + + fn refuses(&self, name: &str) -> Option { + self.0.refuses(name) } } -impl NameCheck<'_> { +/// By its inputs and its `fn`, walked only when a memoized view takes the key. +impl MemoProps for NameCheck<'_> { + fn key(&self, key: &mut MemoKey) { + self.0.key(key); + } +} + +/// A name check: its answer, and the key of its inputs and `fn`. +trait NameChecker { + fn refuses(&self, name: &str) -> Option; + fn key(&self, key: &mut MemoKey); +} + +struct WithInputs { + inputs: I, + check: fn(&I, &str) -> Option, +} + +impl NameChecker for WithInputs { fn refuses(&self, name: &str) -> Option { - (self.0)(name) + (self.check)(&self.inputs, name) + } + + fn key(&self, key: &mut MemoKey) { + self.inputs.key(key); + key.write(&(self.check as usize).to_le_bytes()); + } +} + +/// What the name field checks a typed name against: the host's check, the suggestion an empty field stands for, the +/// name of the preset being renamed and the messages. +#[derive(MemoProps)] +struct Naming<'n, 'c> { + check_name: Option<&'n NameCheck<'c>>, + fallback: Option<&'n str>, + own: Option<&'n str>, + taken: &'n Label, + invalid: &'n Label, +} + +impl Naming<'_, '_> { + /// Why `name` cannot be used, as the field shows it. + fn problem(&self, name: &str) -> Option

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect }, ResizeSplit { path: Vec, size: SplitSize }, ResizeWindowSplit { panel: P, path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

} }`. Groups, columns and floating windows are named by a panel they contain. +- `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

} }`. Groups, columns and floating windows are named by a panel they contain. - `pub fn move_beside(panel: P, anchor: P, placement: DockPlacement

) -> Self`. Builds [`Action::Move`]. - `pub fn float(panel: P, rect: Rect) -> Self`. Builds [`Action::Float`]. - `pub fn close(panel: P) -> Self`. Builds [`Action::Close`]. - `pub fn activate(panel: P) -> Self`. Builds [`Action::Activate`]. - `pub fn open(panel: P, anchor: Option

) -> Self`. Builds [`Action::Open`]. - `pub fn open_at(panel: P, anchor: P, placement: DockPlacement

) -> Self`. Builds [`Action::OpenAt`]. - - `pub fn move_floating(panel: P, rect: Rect) -> Self`. Builds [`Action::MoveFloating`]. + - `pub fn move_floating(panel: P, rect: Rect) -> Self`. Builds [`Action::MoveFloating`] with no edge: the area takes the edge nearer `rect`. + - `pub fn move_floating_with_edge(panel: P, rect: Rect, edge: Option) -> Self`. Builds [`Action::MoveFloating`] with the window's edge. - `pub fn resize_split(path: Vec, size: SplitSize) -> Self`. Builds [`Action::ResizeSplit`]. - - `pub fn resize_window_split(panel: P, path: Vec, size: SplitSize) -> Self`. Builds [`Action::ResizeWindowSplit`]. - `pub fn set_stack_open(panel: P, open: bool) -> Self`. Builds [`Action::SetStackOpen`]. - `pub fn resize_stack(panel: P, height: Option) -> Self`. Builds [`Action::ResizeStack`]. - `pub fn move_group(panel: P, to: Target

) -> Self`. Builds [`Action::MoveGroup`]. @@ -475,6 +498,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn set_minimized(panel: P, minimized: bool) -> Self`. Builds [`Action::SetMinimized`]. - `pub fn set_iconic(panel: P, iconic: bool) -> Self`. Builds [`Action::SetIconic`]. - `pub fn resize_column(panel: P, width: f32) -> Self`. Builds [`Action::ResizeColumn`]. + - `pub fn set_column_steps(panel: P, steps: u16) -> Self`. Builds [`Action::SetColumnSteps`]. - `pub fn resize_group(panel: P, height: Option) -> Self`. Builds [`Action::ResizeGroup`]. - `pub fn resize_flyout_width(panel: P, width: Option) -> Self`. Builds [`Action::ResizeFlyoutWidth`]. - `pub fn move_flyout_top(panel: P, offset: Option) -> Self`. Builds [`Action::MoveFlyoutTop`]. @@ -484,39 +508,45 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `craft_behavior::dock::Arrangement`: `pub enum Arrangement { TileAllVertically, TileAllHorizontally, TwoUpVertical, TwoUpHorizontal, ThreeUpVertical, ThreeUpHorizontal, ThreeUpStacked, FourUp, SixUp, ConsolidateAllToTabs, Cascade, Tile, FloatInWindow, FloatAllInWindows, NewWindowForDocument, MatchZoom, MatchLocation, MatchRotation, MatchAll }`. One Window › Arrange entry. The n-up entries split the document area into that many - `pub fn group_count(self, documents: usize) -> Option`. How many document groups an n-up or tile arrangement wants, `None` for the window and - `pub fn enabled(self, documents: usize, groups: usize, floating: usize) -> bool`. Whether the entry is enabled with `documents` open and `floating` floating windows: -- `craft_behavior::dock::Column`: `pub struct Column

{ pub groups: Vec>, pub width: Option, pub iconic: bool, pub iconic_width: Option }`. One column of a dock: groups from top to bottom. +- `craft_behavior::dock::Column`: `pub struct Column

{ pub groups: Vec>, pub width: Option, pub iconic: bool, pub iconic_width: Option, pub steps: Option }`. One column of groups from top to bottom: a column of a dock, or the whole of a floating window. - `pub fn new(groups: Vec>) -> Self`. A column of `groups`, expanded at the theme's column width until the user resizes it. - `pub fn with_width(mut self, width: f32) -> Self`. The column resized to `width` points. -- `craft_behavior::dock::ColumnLocation`: `pub struct ColumnLocation { pub side: DockEdge, pub width: Option, pub iconic: bool, pub iconic_width: Option }`. The column a closed panel's group was in. - - `pub const fn new(side: DockEdge, width: Option, iconic: bool, iconic_width: Option) -> Self`. A column location on `side`, `width` points wide when expanded (the theme's column width for `None`). + - `pub fn with_iconic(mut self, iconic: bool) -> Self`. The column collapsed to icons, or expanded. + - `pub fn with_steps(mut self, steps: u16) -> Self`. The column `steps` content columns wide ([`Self::steps`]). + - `pub fn panels(&self) -> impl Iterator`. Every panel of the column, top group first. +- `craft_behavior::dock::ColumnLocation`: `pub struct ColumnLocation { pub side: Option, pub width: Option, pub iconic: bool, pub iconic_width: Option, pub steps: Option }`. The column a closed panel's group was in. + - `pub const fn new(side: Option, width: Option, iconic: bool, iconic_width: Option) -> Self`. A column location on `side` (`None` for a floating window's column), `width` points wide when expanded (the + - `pub const fn with_steps(mut self, steps: Option) -> Self`. The location with the column `steps` content columns wide ([`Column::steps`]). - `craft_behavior::dock::DockEdge`: `pub enum DockEdge { Start, End }`. The window edge a [`Node::Dock`] sits on, in reading order so right-to-left interfaces - `craft_behavior::dock::DockError`: `pub enum DockError { LimitExceeded, DuplicatePanel, MissingPanel, MissingTarget, InvalidSelection, InvalidGeometry, InvalidPlacement, NotAllowed, UnsupportedVersion }`. Why a layout edit or load was refused. The layout is unchanged when an edit fails. - `craft_behavior::dock::DockPlacement`: `pub enum DockPlacement

{ Tab { before: Option

}, Split(DockSide), SplitSized { zone: DockSide, size: SplitSize, outer: SplitSize }, Group { below: bool, height: Option }, Column { after: bool }, Edge(DockSide) }`. Where a moved panel goes relative to an anchor panel. - `pub fn tab(before: Option

) -> Self`. Builds [`DockPlacement::Tab`]. - `pub fn group(below: bool, height: Option) -> Self`. Builds [`DockPlacement::Group`]. - `pub fn column(after: bool) -> Self`. Builds [`DockPlacement::Column`]. - - `pub fn allowed_by(&self, anchor: Permissions, floating: bool) -> bool`. Whether the anchor's permissions take this placement: tabs need `accepts_tabs`, side + - `pub fn allowed_by(&self, anchor: Permissions) -> bool`. Whether the anchor's permissions take this placement: tabs need `accepts_tabs` and `shares_column`, a group - `craft_behavior::dock::DocumentGroup`: `pub struct DocumentGroup { pub id: u64, pub documents: Vec, pub shown: Option }`. A document group: the documents in one tab strip, one of them shown. - `pub fn new(id: u64, documents: Vec) -> Self`. A group with id `id` holding `documents`, none shown. -- `craft_behavior::dock::DocumentWindows`: `pub struct DocumentWindows { pub docked: Vec>, pub floating: Vec<(DocumentGroup, Rect)> }`. The document windows of the app: the tabbed groups in the canvas area and the floating ones. +- `craft_behavior::dock::DocumentWindows`: `pub struct DocumentWindows { pub docked: Vec>, pub floating: Vec<(DocumentGroup, Rect)>, pub arrangement: Option }`. The document windows of the app: the tabbed groups in the canvas area and the floating ones. Saved with each - `pub fn float(&mut self, document: &D, rect: Rect) -> Option`. Float `document` from its group into a new window at `rect`. A document alone in a - `pub fn float_all(&mut self, area: Rect, size: Vec2, step: f32)`. Every document into its own floating window, cascaded from `area`'s top left. A floating - `pub fn consolidate(&mut self, active: Option<&D>)`. Every document back into one docked group, the active one shown. A document in several - `pub fn split_into(&mut self, n: usize)`. Split the docked documents into `n` groups for an n-up arrangement, in order. The first - `pub fn new_window_for(&mut self, document: &D, rect: Rect) -> u64`. A second view of `document`: the same document id in a new window; the app keeps one + - `pub fn close_window(&mut self, id: u64) -> bool`. Closes floating window `id`. Its documents return to the first docked group, or to a new docked group when + - `pub fn add_document(&mut self, document: &D)`. Adds `document` to the first docked group, or to a new docked group when there is none. A document a group - `pub fn to_actions(&self, layout: &Layout

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The -- `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub root: Node

, pub rect: Rect, pub native: Option, pub minimized: bool }`. A floating window: a tree of groups like the docked layout's, without docks. - - `pub fn new(root: Node

, rect: Rect) -> Self`. A window holding `root`. Each call makes a new window, with a fresh [`Self::id`]: build +- `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column + - `pub fn new(column: Column

, rect: Rect) -> Self`. A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build - `pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self`. A window with one group. Each call makes a new window, as [`Self::new`] does. - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id`, for a layout the app builds in code, such as a default layout: - - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, in tree order. - - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. Groups stacked top to bottom, as a v1 layout stored them: each group over a vertical - - `pub fn groups(&self) -> Vec> where P: Clone,`. The window's groups, first to last. + - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, top group first. + - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, + - `pub fn groups(&self) -> &[Group

]`. The window's groups, top to bottom. - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such -- `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a dock column. +- `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a column, docked or floating. - `pub fn new(panels: Vec

, active: usize) -> Self`. A group of `panels` with tab `active` selected, expanded and with no preferred height or flyout geometry. - `pub fn active_panel(&self) -> Option<&P>`. The selected panel, or `None` when `active` is out of range. -- `craft_behavior::dock::GroupLocation`: `pub struct GroupLocation { pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option, pub column: Option }`. The group a closed panel was in, when that group was in a dock. +- `craft_behavior::dock::GroupLocation`: `pub struct GroupLocation { pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option, pub column: Option }`. The group a closed panel was in, when that group was in a column, docked or floating. - `pub const fn new(minimized: bool, height: Option, column: Option) -> Self`. A group location with the given state and column. - `pub const fn with_flyout_width(mut self, width: Option) -> Self`. The location with the group's flyout `width` points wide. - `pub const fn with_flyout_offset(mut self, offset: Option) -> Self`. The location with the group's flyout top `offset` points from its icons' top. @@ -527,7 +557,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. - `pub fn can_step_group(&self, panel: &P, up: bool, permissions: impl Fn(&P) -> Permissions) -> bool`. Whether [`Action::StepGroup`] would move `panel`'s group, for enabling a menu item. - `pub fn location(&self, panel: &P) -> Result, DockError>`. Capture a panel's nearest surviving group/split neighbor before hiding it. - - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. + - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. In a column, docked or floating, - `pub fn restore(&mut self, panel: P, location: &Location

) -> Result<(), DockError>`. Restore an absent panel at a captured location. Missing anchors are reported without - `pub fn open_at_edge(&mut self, panel: P) -> Result<(), DockError>`. Open an absent panel as a frame at the outer edge of the docked area, taking most of it: - `craft_behavior::dock::Location`: `pub struct Location

{ pub floating: Option, pub anchor: Option

, pub placement: DockPlacement

, pub size: Option, pub stack: Option<(bool, Option)>, pub sibling: Vec

, pub group: Option }`. A closed panel's former placement. Applications may retain this beside visibility flags. @@ -541,30 +571,35 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn split(axis: Axis, size: SplitSize, first: Node

, second: Node

) -> Self`. Two children along `axis`, sharing the room by `size`. - `pub fn stack(entries: Vec>) -> Self`. Builds [`Node::Stack`]. - `pub fn dock(side: DockEdge, columns: Vec>) -> Self`. Builds [`Node::Dock`]. -- `craft_behavior::dock::PanelPlace`: `pub enum PanelPlace { Node(Vec), Dock { path: Vec, column: usize, group: usize }, Floating { window: usize, path: Vec } }`. Where a panel is. Paths lead from the root: false is a split's first child, true its second. - - `pub fn tree_path(&self) -> Option<(Option, &[bool])>`. The tree (`None` for the docked layout, else a floating window) and the path of a +- `craft_behavior::dock::PanelPlace`: `pub enum PanelPlace { Node(Vec), Dock { path: Vec, column: usize, group: usize }, Floating { window: usize, group: usize } }`. Where a panel is. Paths lead from the root: false is a split's first child, true its second. + - `pub fn tree_path(&self) -> Option<&[bool]>`. The path of a `Tabs` or `Stack` node of the docked tree; `None` for a group of a column. + - `pub fn group_index(&self) -> Option`. The group's index in its column; `None` for a `Tabs` or `Stack` node of the docked tree. - `craft_behavior::dock::PanelState`: `pub enum PanelState { Hidden, Open, Front }`. What the Window menu shows for a panel. The model does not track the z-order of floating -- `craft_behavior::dock::Permissions`: `pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, pub accepts_tabs: bool, pub accepts_splits: bool }`. What may happen to a panel. [`Layout::apply_with_permissions`] enforces these for every - - `pub const ALL: Self`. Every right: the panel moves, floats, closes and takes tabs and splits. +- `craft_behavior::dock::Permissions`: `pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, pub accepts_tabs: bool, pub accepts_splits: bool, pub collapses: bool, pub shares_column: bool, pub docks_outside_columns: bool }`. What may happen to a panel. `Layout::apply_with_permissions` enforces these for every + - `pub const ALL: Self`. Every right: the panel moves, floats, closes, takes tabs and splits, collapses, shares its column and docks - `pub const PROTECTED: Self`. A document canvas: it stays docked and open, and takes neither tabs nor side splits. - `pub const fn movable(mut self, movable: bool) -> Self`. These permissions with [`Self::movable`] set to `movable`. - `pub const fn floatable(mut self, floatable: bool) -> Self`. These permissions with [`Self::floatable`] set to `floatable`. - `pub const fn closable(mut self, closable: bool) -> Self`. These permissions with [`Self::closable`] set to `closable`. - `pub const fn accepts_tabs(mut self, accepts_tabs: bool) -> Self`. These permissions with [`Self::accepts_tabs`] set to `accepts_tabs`. - `pub const fn accepts_splits(mut self, accepts_splits: bool) -> Self`. These permissions with [`Self::accepts_splits`] set to `accepts_splits`. + - `pub const fn collapses(mut self, collapses: bool) -> Self`. These permissions with [`Self::collapses`] set to `collapses`. + - `pub const fn shares_column(mut self, shares_column: bool) -> Self`. These permissions with [`Self::shares_column`] set to `shares_column`. + - `pub const fn docks_outside_columns(mut self, docks_outside_columns: bool) -> Self`. These permissions with [`Self::docks_outside_columns`] set to `docks_outside_columns`. - `pub fn is_protected(self) -> bool`. A canvas: it can neither move, close nor take tabs. `accepts_splits` and `floatable` - - `pub fn locked(self) -> Self`. Lock Workspace: nothing moves, floats or closes; tab and split drops keep their policy. + - `pub fn locked(self) -> Self`. Lock Workspace: nothing moves, floats or closes; tab and split drops and the column rights keep their policy. - `craft_behavior::dock::SIDE_ZONE_DEPTH_SHARE`: `pub const SIDE_ZONE_DEPTH_SHARE: f32`. The most of a body's smaller side that a [`ZoneSize::Depth`] zone reaches, so a body always keeps a middle. - `craft_behavior::dock::SIDE_ZONE_FRACTION`: `pub const SIDE_ZONE_FRACTION: f32`. Share of a body, from each edge, that means "beside" under [`ZoneSize::Fraction`]: of its width from the start - `craft_behavior::dock::SplitSize`: `pub enum SplitSize { Ratio(f32), FixedFirst(f32), FixedSecond(f32) }`. A transient sizing request. Applications may adapt their own persisted sizing enum. - `craft_behavior::dock::StackEntry`: `pub struct StackEntry

{ pub panel: P, pub open: bool, pub height: Option }`. One panel of a [`Node::Stack`] accordion. - `pub fn new(panel: P) -> Self`. An open accordion section for `panel` with no preferred height. -- `craft_behavior::dock::Target`: `pub enum Target

{ At { anchor: P, placement: DockPlacement

}, NewDock { side: DockEdge }, Float { rect: Rect } }`. Where a group, column or floating window goes. +- `craft_behavior::dock::Target`: `pub enum Target

{ At { anchor: P, placement: DockPlacement

}, NewDock { side: DockEdge }, Float { rect: Rect, edge: Option } }`. Where a group, column or floating window goes. - `pub fn at(anchor: P, placement: DockPlacement

) -> Self`. Builds [`Target::At`]. - `pub fn new_dock(side: DockEdge) -> Self`. Builds [`Target::NewDock`]. - - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`]. -- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. - - `pub const VERSION: u32`. The format version written to files. + - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. + - `pub fn float_with_edge(rect: Rect, edge: Option) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to. +- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)>, pub floated: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. + - `pub const VERSION: u32`. The format version written to files. Version 4 saves a floating window as one column; older floating - `pub fn revision(&self) -> u64`. The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else. - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next revision. - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. Closed panels record where they go back, so each one can be reopened @@ -604,17 +639,23 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn take_back(&mut self) -> Option`. Takes back the newest undo step without a redo entry, for an edit that was refused: `settled` returns to the - `pub fn can_undo(&self) -> bool`. An undo would change something. - `pub fn can_redo(&self) -> bool`. A redo would change something. + - `pub fn redo_len(&self) -> usize`. How many steps a redo can go forward. - `craft_behavior::edit_history::Step`: `pub enum Step { Undo, Redo }`. Which way [`EditHistory::step`] goes. ## `craft_behavior::editor` `EditorInput`: the one ordered input stream the IME engine produces and an editor part reads (18.4). -- `craft_behavior::editor::EditorInput`: `pub enum EditorInput { Text(Arc), Move(NavMove, MoveMods), Delete { forward: bool, by: Granularity }, DeleteSurrounding { before: usize, after: usize }, Select { anchor: TextPos, focus: TextPos }, Preedit { text: Arc, cursor: Option> }, ImeCommit, Edit(EditCommand), Newline, Tab, Cancel }`. One input of an editor part. +- `craft_behavior::editor::EditorInput`: `pub enum EditorInput { Text(Arc), Move(NavMove, MoveMods), Delete { forward: bool, by: Granularity }, DeleteSurrounding { before: usize, after: usize, unit: SurroundingUnit }, Select { anchor: TextPos, focus: TextPos }, Preedit { text: Arc, cursor: Option> }, ImeCommit, Edit(EditCommand), Newline, Tab, Cancel }`. One input of an editor part. - `pub const fn delete(forward: bool, by: Granularity) -> Self`. A `Delete` of `by`. + - `pub const fn delete_surrounding(before: usize, after: usize) -> Self`. A `DeleteSurrounding` of `before` and `after` characters. + - `pub const fn delete_surrounding_bytes(before: usize, after: usize) -> Self`. A `DeleteSurrounding` of `before` and `after` bytes of UTF-8 text, as winit reports it. - `pub fn preedit(text: impl Into>, cursor: Option>) -> Self`. A `Preedit` of `text` with the IME's cursor. - `pub const fn select(anchor: TextPos, focus: TextPos) -> Self`. A `Select` of `anchor` to `focus`. - `pub const fn is_read_only_safe(&self) -> bool`. Whether the input changes no text: a read-only editor receives only these (18.4). +- `craft_behavior::editor::SurroundingUnit`: `pub enum SurroundingUnit { Chars, Bytes }`. What an input method counts the text around the caret in. + - `pub fn chars_before(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the end of `text`, the editor's text before the deletion. A character + - `pub fn chars_after(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the start of `text`, the editor's text after the deletion. A ## `craft_behavior::eviction` @@ -631,7 +672,7 @@ The fit rules: which tabs, bar items or titles stay in a strip and which go to a - `pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self`. An item `extent` long in `section`. - `craft_behavior::fit::FitKeep`: `pub enum FitKeep { Free, Pinned, Menu }`. Whether an item may move into the overflow menu, or lives there. - `craft_behavior::fit::TabFit`: `pub struct TabFit { pub shown: Vec<(usize, f32)>, pub overflow: Vec, pub overflow_width: f32 }`. Tabs visible on a strip and tabs that need an overflow menu, all in original order. -- `craft_behavior::fit::fit`: `pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32) -> TabFit`. Fit tab widths into `available` points, shrinking the widest tabs first to a common cap. +- `craft_behavior::fit::fit`: `pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32, keep_selected: bool) -> TabFit`. Fit tab widths into `available` points, shrinking the widest tabs first to a common cap. - `craft_behavior::fit::fit_items`: `pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit`. Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. - `craft_behavior::fit::fit_whole`: `pub fn fit_whole(natural: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit`. Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. - `craft_behavior::fit::run_extent`: `pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) -> f64`. The length of the items marked in `shown`, with `gap` between neighbours of a section and `section_gap` between @@ -687,6 +728,8 @@ Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, focus after removal, the E Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the +- `craft_behavior::geometry::AXIS_BAND_DEGREES`: re-export of `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`. +- `craft_behavior::geometry::AspectHold`: re-export of `craft_behavior::geometry::crop::AspectHold`. - `craft_behavior::geometry::BoxAllow`: re-export of `craft_behavior::geometry::quad::BoxAllow`. - `craft_behavior::geometry::BoxDrag`: re-export of `craft_behavior::geometry::quad::BoxDrag`. - `craft_behavior::geometry::BoxPart`: re-export of `craft_behavior::geometry::quad::BoxPart`. @@ -716,6 +759,7 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::SelectionOperation`: re-export of `craft_behavior::geometry::selection_op::SelectionOperation`. - `craft_behavior::geometry::SnapGesture`: re-export of `craft_behavior::geometry::snap::SnapGesture`. - `craft_behavior::geometry::SnapKind`: re-export of `craft_behavior::geometry::snap::SnapKind`. +- `craft_behavior::geometry::SnapKinds`: re-export of `craft_behavior::geometry::snap::SnapKinds`. - `craft_behavior::geometry::SnapLine`: re-export of `craft_behavior::geometry::snap::SnapLine`. - `craft_behavior::geometry::SnapOptions`: re-export of `craft_behavior::geometry::snap::SnapOptions`. - `craft_behavior::geometry::SnapTarget`: re-export of `craft_behavior::geometry::snap::SnapTarget`. @@ -723,6 +767,7 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::StrokeLock`: re-export of `craft_behavior::geometry::move_gesture::StrokeLock`. - `craft_behavior::geometry::TransformMode`: re-export of `craft_behavior::geometry::quad::TransformMode`. - `craft_behavior::geometry::across_axis`: re-export of `craft_behavior::geometry::snap::across_axis`. +- `craft_behavior::geometry::axis_or_diagonal`: re-export of `craft_behavior::geometry::lock::axis_or_diagonal`. - `craft_behavior::geometry::coordinate_across`: re-export of `craft_behavior::geometry::snap::coordinate_across`. - `craft_behavior::geometry::crop_view`: re-export of `craft_behavior::geometry::crop::crop_view`. - `craft_behavior::geometry::crop_view_about`: re-export of `craft_behavior::geometry::crop::crop_view_about`. @@ -732,15 +777,19 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::lock_direction`: re-export of `craft_behavior::geometry::lock::lock_direction`. - `craft_behavior::geometry::marquee_pixels`: re-export of `craft_behavior::geometry::marquee::marquee_pixels`. - `craft_behavior::geometry::motion_across`: re-export of `craft_behavior::geometry::snap::motion_across`. +- `craft_behavior::geometry::outside_pieces`: re-export of `craft_behavior::geometry::outside::outside_pieces`. +- `craft_behavior::geometry::polygon_step`: re-export of `craft_behavior::geometry::lock::polygon_step`. - `craft_behavior::geometry::round_to_direction`: re-export of `craft_behavior::geometry::lock::round_to_direction`. - `craft_behavior::geometry::screen_step`: re-export of `craft_behavior::geometry::crop::screen_step`. - `craft_behavior::geometry::square_pixels`: re-export of `craft_behavior::geometry::marquee::square_pixels`. +- `craft_behavior::geometry::turn_grid`: re-export of `craft_behavior::geometry::crop::turn_grid`. - `craft_behavior::geometry::turn_to_45`: re-export of `craft_behavior::geometry::lock::turn_to_45`. ## `craft_behavior::geometry::crop` The crop frame's pure geometry: the box, where a press lands on it, what each gesture makes of it, the +- `craft_behavior::geometry::crop::AspectHold`: `pub enum AspectHold { Free, Ratio(f64), Diagonal }`. What a resize holds about the frame's proportions. - `craft_behavior::geometry::crop::CropBox`: `pub struct CropBox { pub rect: Rect, pub angle: f64 }`. The crop frame: a document rect and the angle it is turned by about its centre. - `pub const fn new(rect: Rect, angle: f64) -> Self`. The frame `rect` turned `angle` degrees about its centre. - `pub const fn upright(rect: Rect) -> Self`. An unturned frame. @@ -757,10 +806,11 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `pub fn nudged(&self, part: BoxPart, by: Vec2, ratio: Option) -> Self`. The frame after an arrow key moves `part` by `by`, as a plain drag of the part would, with `ratio` held. - `pub fn crop_size(&self) -> Option<(f64, f64)>`. The size Enter would crop to: the frame's own width and height in whole document units, at least 1; `None` - `pub fn size_ok(&self) -> bool`. Whether both sides are at least one document unit. - - `pub fn resized(&self, part: BoxPart, by: Vec2, ratio: Option, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on - - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, ratio: Option, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the + - `pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on + - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the - `pub fn turned_to(&self, grab: f64, to: Point, step: Option, image: bool) -> Self`. The frame turned from this one's angle by the pointer's sweep about the centre, from direction `grab` - `pub fn within(self, bounds: Rect, resizing: bool, held: bool) -> Option`. The frame kept inside `bounds`: an unturned frame is cut to it; a turned one is moved by the least that + - `pub fn kept_inside(&self, bounds: Rect) -> Option`. The frame at its angle kept inside `bounds` (#10869, an image-mode turn): `self`, bit for bit, when its turned - `pub fn level_angle(a: Point, b: Point) -> Option`. The frame angle (degrees, clockwise on the page, in -45..=45) that makes the line from `a` to `b` level, or - `pub fn fitted(&self, canvas: Size, angle: f64) -> Option`. The largest frame with this one's proportions that fits a canvas of `canvas` at `angle` degrees, centred on - `craft_behavior::geometry::crop::CropGuide`: `pub enum CropGuide { Thirds, Grid, Diagonal, Triangle, GoldenRatio, GoldenSpiral }`. The composition guide drawn inside a crop frame, in Photoshop's menu order. @@ -782,6 +832,7 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `craft_behavior::geometry::crop::screen_step`: `pub fn screen_step(view: &CanvasView, by: Vec2) -> Vec2`. An arrow step `by` (screen points) as the document vector it is in `view`, at one document unit per point. - `craft_behavior::geometry::crop::snap_angle`: `pub fn snap_angle(deg: f64, step: f64) -> f64`. `deg` on the nearest multiple of `step` degrees, brought into (-180, 180]; a step that is not finite and positive - `craft_behavior::geometry::crop::turn`: `pub fn turn(p: Point, c: Point, deg: f64) -> Point`. `p` turned `deg` degrees clockwise on screen (y down) about `c`. +- `craft_behavior::geometry::crop::turn_grid`: `pub fn turn_grid(w: f64, h: f64, step: f64, visible: Rect) -> Vec>`. The lines of the grid a default-mode turn shows over a `w` by `h` frame (screen points), in the frame's unit square ## `craft_behavior::geometry::draft` @@ -795,12 +846,14 @@ An outline being drawn by a selection or freeform tool, and how it closes: [`Out - `pub const fn new(close: f64, same_point: f64) -> Self`. A reach closing within `close` screen points of the first vertex and treating a press - `craft_behavior::geometry::draft::OutlineDraft`: `pub struct OutlineDraft`. The pointer state machine of an outline being drawn, shared by every lasso. - `pub fn new(kind: DraftKind, reach: DraftReach) -> Self`. An empty draft following `kind`'s rules, closing within `reach`. + - `pub fn locking_shift_drags(mut self) -> Self`. This draft with ⇧ holding a freehand drag to one of eight directions (see [`DraftKind::Mixed`]). - `pub fn kind(&self) -> DraftKind`. The rules this draft follows. - `pub fn set_reach(&mut self, reach: DraftReach)`. Changes the close radii; an open outline keeps its points. - `pub fn for_document(&mut self, key: u64) -> Option`. Records `key` as the active document's. An open outline begun under another key is - `pub fn press(&mut self, at: DraftPoint, has_selection: bool) -> Option`. The primary button went down at `at`; `has_selection` is whether the document has a - `pub fn drag(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down. Freehand and Mixed: the point is added - - `pub fn hover(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button up: only the rubber band follows (hover moves + - `pub fn move_to(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down while the reposition key is held: the whole outline moves by the + - `pub fn hover(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button up: only the rubber band follows, to where a click would place the - `pub fn release(&mut self, at: DraftPoint) -> Option`. The primary button went up at `at`. Freehand: closes. Mixed: closes unless straight - `pub fn mods_changed(&mut self, mods: Mods) -> Option`. The held modifiers changed. Mixed only: ⌥ pressed after the press (or pressed again after - `pub fn retract(&mut self) -> Option`. Removes the last vertex while [`takes_retract`](Self::takes_retract); removing the only @@ -821,14 +874,17 @@ Plane geometry the canvas overlays share, in document or screen units: segment c ## `craft_behavior::geometry::lock` -Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`] and [`turn_to_45`]. +Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`], +- `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`: `pub const AXIS_BAND_DEGREES: f64`. How near an axis, in degrees, a ⇧ line or anchor drag must point to snap onto the axis rather than the diagonal - `craft_behavior::geometry::lock::Directions`: `pub enum Directions { Four, Eight }`. The directions ⇧ locks a move to. - `pub const fn count(self) -> u32`. How many evenly spaced directions: 4 or 8. - `craft_behavior::geometry::lock::LOCK_HYSTERESIS_DEGREES`: `pub const LOCK_HYSTERESIS_DEGREES: f64`. Extra angle in degrees the pointer must pass the half-way line between two directions by +- `craft_behavior::geometry::lock::axis_or_diagonal`: `pub fn axis_or_diagonal(from: Point, point: Point) -> Point`. Shift's rule for the Line tool and anchor drags: within [`AXIS_BAND_DEGREES`] of an axis, `point` moves onto the - `craft_behavior::geometry::lock::lock_direction`: `pub fn lock_direction(d: Vec2, previous: Option, directions: Directions) -> Vec2`. `d` locked to the nearest of `directions` evenly spaced directions (0° = right, document y +- `craft_behavior::geometry::lock::polygon_step`: `pub fn polygon_step(from: Point, point: Point) -> Point`. Shift's polygon vertex: `point` moved to the nearest of eight directions from `from`; an axis keeps the - `craft_behavior::geometry::lock::round_to_direction`: `pub fn round_to_direction(angle: f64, directions: Directions) -> f64`. `angle` (radians, 0 = right, document y down) rounded to the nearest of `directions` evenly -- `craft_behavior::geometry::lock::turn_to_45`: `pub fn turn_to_45(from: Point, point: Point) -> Point`. `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the one ⇧ rule for a line, a +- `craft_behavior::geometry::lock::turn_to_45`: `pub fn turn_to_45(from: Point, point: Point) -> Point`. `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle ## `craft_behavior::geometry::marquee` @@ -862,6 +918,7 @@ A move by drag: direction lock, stroke lock and snapping along a ray. - `pub fn follow(&mut self, at: Point, mods: Mods, zoom: f64) -> Option`. The pointer moved to `at` (document units) with `mods` at `zoom` screen points per - `pub fn release(mut self, at: Point, mods: Mods, zoom: f64) -> MoveValue`. The release at `at`: the same lock as [`follow`](Self::follow) applies, so a release where - `pub fn value(&self) -> MoveValue`. The value of the last [`follow`](Self::follow): the offset and whether it copies. + - `pub fn left_press(&self) -> bool`. Whether the pointer, at a [`follow`](Self::follow), has been half a document unit or more from the press on - `pub fn locked(&self) -> Option`. The direction ⇧ holds the offset to, as the last locked offset; `None` while the move is free. - `craft_behavior::geometry::move_gesture::MoveValue`: `pub struct MoveValue { pub delta: Vec2, pub copy: bool }`. The value of a move drag. - `pub fn changed(&self) -> bool`. Whether the drag changes anything: an offset or a copy. A press and release without @@ -871,25 +928,34 @@ A move by drag: direction lock, stroke lock and snapping along a ray. - `pub fn locked(&self) -> bool`. Whether a direction is locked. - `pub fn reset(&mut self)`. Forget the lock (the stroke ended). +## `craft_behavior::geometry::outside` + +The canvas outside a convex hole, as convex pieces. + +- `craft_behavior::geometry::outside::outside_pieces`: `pub fn outside_pieces(canvas: [Point; 4], hole: &[Point]) -> Vec>`. Convex pieces that cover the canvas quad outside the convex `hole` exactly once: the canvas clipped by each + ## `craft_behavior::geometry::quad` Box geometry of transform boxes: where the box goes when a part of it is dragged, and the -- `craft_behavior::geometry::quad::BoxAllow`: `pub struct BoxAllow { pub rotate: bool, pub skew: bool, pub distort: bool }`. What the box's content allows. PhotoCraft: editable type refuses distort and perspective +- `craft_behavior::geometry::quad::BoxAllow`: `pub struct BoxAllow { pub rotate: bool, pub skew: bool, pub distort: bool, pub warp: bool }`. What the box's content allows. PhotoCraft: editable type refuses distort and perspective - `pub const fn new(rotate: bool, skew: bool, distort: bool) -> Self`. What the content allows: turning, skewing and distorting. + - `pub const fn with_warp(mut self, warp: bool) -> Self`. Whether the content allows warping. - `craft_behavior::geometry::quad::BoxDrag`: `pub enum BoxDrag { Move, Pivot, Rotate, Scale, Distort, Perspective, Skew, SlideCorner }`. What a drag of a box part does ([`BoxRules::drag_kind`]). - `craft_behavior::geometry::quad::BoxPart`: `pub enum BoxPart { Corner(u8), Edge(u8), Pivot, Inside, Outside }`. A part of a box under the pointer or picked from the keyboard. Edge `k` joins corners `k` and - `pub const fn index(self) -> u64`. The number a part is keyed by in a canvas control's part keys: 0 inside or outside, 1 to 4 the corners, 5 to - `pub const fn from_index(index: u64) -> Option`. The part keyed by `index`: the inverse of [`index`](Self::index), with 0 the inside. -- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64 }`. How drags change a box. +- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64 }`. How drags change a box. - `pub fn in_mode(mode: TransformMode) -> BoxRules`. The rules of `mode` with the default scale rule, a linked aspect, everything allowed and - `pub fn with_scale(mut self, scale: ScaleRule) -> BoxRules`. The rules with `scale` as the plain corner and edge drag rule. - `pub fn with_aspect_linked(mut self, linked: bool) -> BoxRules`. The rules with the options bar's aspect link on or off. - `pub fn with_allow(mut self, allow: BoxAllow) -> BoxRules`. The rules with `allow` as what the content permits. + - `pub fn with_min_side(mut self, side: f64) -> BoxRules`. The rules with `side` as the minimum side of a scaled box, in document units. - `pub fn effective_mode(&self) -> TransformMode`. The mode drags follow: a mode the content refuses scales as Free Transform does. - `pub fn allows(&self, part: BoxPart) -> bool`. Whether a drag of `part` changes the box: in Distort only the corners, the inside and the - `pub fn drag_kind(&self, part: BoxPart, mods: Mods) -> Option`. What a drag of `part` with `mods` held (as the host has them, before - `craft_behavior::geometry::quad::BoxState`: `pub struct BoxState { pub quad: [Point; 4], pub pivot: Point }`. A transform box: its four corners clockwise from the top left (as the box was before any + - `pub fn origin_of_pivot(&self, rect: Rect) -> Point`. The reference point's place within the box, carried to `rect`: the pivot through the - `pub const fn new(quad: [Point; 4], pivot: Point) -> Self`. A box with the corners `quad`, clockwise from the top left, and the reference point `pivot`. - `pub fn from_rect(r: Rect) -> Self`. The box of `r`, the reference point at its centre. - `pub fn moved(&self, by: Vec2) -> Self`. The box and its reference point moved by `by`. @@ -905,6 +971,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub fn scaled_about_pivot(&self, kx: f64, ky: f64) -> Self`. Scaled by `kx` and `ky` along the box's own axes about the reference point. A negative - `pub fn turned_about_pivot(&self, radians: f64) -> Self`. Turned by `radians` about the reference point. - `craft_behavior::geometry::quad::Homography`: `pub struct Homography`. A projective map of the plane: the unit square onto a box, so a box scales along its own axes + - `pub fn apply_in_front(&self, p: Point, within: Rect) -> Option`. [`Homography::apply`] for a point on the front side of the horizon, the side most of - `pub fn from_rows(rows: [[f64; 3]; 3]) -> Homography`. The map with these rows of (x, y, w) coefficients, applied to (x, y, 1). - `pub fn row(&self, i: usize) -> [f64; 3]`. Row `i` (0 to 2) of the matrix: the coefficients of x, y and the constant. - `pub fn unit_to_quad(q: [Point; 4]) -> Option`. The map taking (0, 0), (1, 0), (1, 1), (0, 1) to `q`'s corners; `None` for a degenerate @@ -913,7 +980,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::quad::Parts`: `pub struct Parts { pub w: f64, pub h: f64, pub angle: f64, pub skew_h: f64, pub skew_v: f64 }`. A box read as the options bar shows it: the starting rect scaled by `w` and `h`, skewed by - `pub const fn new(w: f64, h: f64, angle: f64, skew_h: f64, skew_v: f64) -> Self`. The readings: scale factors `w` and `h`, the `angle` in degrees and the two skews in degrees. - `craft_behavior::geometry::quad::SKEW_LIMIT`: `pub const SKEW_LIMIT: f64`. The skew fields' reach in degrees: a skew of ±90° would flatten the box (PhotoCraft's). -- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free }`. What a plain corner or edge drag does. +- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, Shape }`. What a plain corner or edge drag does. - `craft_behavior::geometry::quad::TransformMode`: `pub enum TransformMode { Free, Rotate, Skew, Distort, Perspective }`. Edit › Transform's modes. - `craft_behavior::geometry::quad::bisector`: `pub fn bisector(screen: &BoxState, i: usize) -> emath::Vec2`. Corner `i` of `screen`'s unit bisector, pointing into the box; zero for a collapsed corner. The - `craft_behavior::geometry::quad::drag`: `pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState`. The box after dragging `part` from `from` to `to` (document points) with `mods` held, from the @@ -939,6 +1006,12 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub const fn rect(at_press: Rect) -> Self`. A moving rectangle that was `at_press` when the gesture began. - `pub const fn axis(along: Axis) -> Self`. Only the coordinate across the lines that run `along` snaps: x for `Axis::Y`. - `craft_behavior::geometry::snap::SnapKind`: `pub enum SnapKind { Guide, Grid, Bounds, Center, LayerEdge, LayerCenter, Selection }`. What a target is, so an app can filter (Snap To › Guides only) and the lines can be drawn in + - `pub const fn is_smart(self) -> bool`. Whether the target's lines draw in the smart-guide colour: `LayerEdge`, `LayerCenter` and `Center`. +- `craft_behavior::geometry::snap::SnapKinds`: `pub struct SnapKinds`. A set of [`SnapKind`]s, a bit per kind: the kind filter a gesture passes to its snapping. + - `pub const ALL: SnapKinds`. Every kind. + - `pub const fn only(kind: SnapKind) -> Self`. The set of `kind` alone. + - `pub fn without(self, kind: SnapKind) -> Self`. This set without `kind`. + - `pub fn contains(self, kind: SnapKind) -> bool`. Whether `kind` is in this set. - `craft_behavior::geometry::snap::SnapLine`: `pub struct SnapLine { pub along: Axis, pub position: f64, pub kind: SnapKind, pub span: Option<(f64, f64)> }`. The line the UI draws for a snap that happened. - `craft_behavior::geometry::snap::SnapOptions`: `pub struct SnapOptions { pub on: bool, pub guides: bool, pub grid: bool, pub layers: bool, pub document_bounds: bool, pub selection: bool, pub smart_guides: bool }`. View › Snap To and View › Show › Smart Guides, as the app stores them. - `craft_behavior::geometry::snap::SnapTarget`: `pub struct SnapTarget { pub along: Axis, pub position: f64, pub kind: SnapKind, pub span: Option<(f64, f64)> }`. One snap position on one axis. @@ -946,12 +1019,16 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::snap::SnapTargets`: `pub struct SnapTargets`. The snap targets of one gesture. - `pub fn new() -> Self`. No targets. - `pub fn add(&mut self, target: SnapTarget)`. Add one target. + - `pub fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind)`. Add a rectangle's four edges as `edge` targets and its two centre lines as `center` - `pub fn with_document(self, options: &SnapOptions, bounds: Rect, guides: impl IntoIterator, grid: Option<(Point, Vec2)>,) -> Self`. Guides as full-height targets, grid lines of `spacing` from `origin` over `bounds`, the - `pub fn filtered(&self, keep: impl Fn(SnapKind) -> bool) -> SnapTargets`. Only the targets `keep` accepts (Snap To with one kind off). - `pub fn is_empty(&self) -> bool`. Whether there is no target. + - `pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option`. The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of - `pub fn nearest(&self, along: Axis, value: f64, tolerance: f64) -> Option`. The nearest target among the lines that run `along` an axis, within `tolerance` of `value` across them. - `pub fn snap_point(&self, point: Point, tolerance: f64) -> (Point, Vec)`. `point` snapped on each axis independently, with the lines to draw. + - `pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec)`. [`snap_point`](Self::snap_point) to the targets of a kind in `kinds` only (a Distort corner snaps to guides - `pub fn snap_rect(&self, rect: Rect, tolerance: f64) -> (Vec2, Vec)`. The offset that moves `rect` so its nearest edge or centre meets a target on each axis, + - `pub fn snap_rect_of(&self, rect: Rect, tolerance: f64, kinds: SnapKinds) -> (Vec2, Vec)`. [`snap_rect`](Self::snap_rect) to the targets of a kind in `kinds` only (moving a selection skips the selection's - `craft_behavior::geometry::snap::across_axis`: `pub const fn across_axis(along: Axis) -> Axis`. The axis across `along`: a line running along `Axis::Y` (vertical) is placed on `Axis::X`. - `craft_behavior::geometry::snap::coordinate_across`: `pub const fn coordinate_across(along: Axis, p: Point) -> f64`. The coordinate of `p` a line running `along` an axis is placed by: x for a line along `Axis::Y`. - `craft_behavior::geometry::snap::motion_across`: `pub fn motion_across(along: Axis) -> Vec2`. The document direction a line running `along` an axis moves in: x for a line along `Axis::Y`. A screen caller @@ -972,6 +1049,7 @@ The `Grid` cursor: columns resolved from last pass's measurements, and the cell - `pub fn region(&self) -> Rect`. The rect the next child measures and is placed in: from its column's start edge and its row's top, as large - `pub fn fill_room(&self) -> Vec2`. The room the next child fills when it fills its width: its column's width, which for a `Content` column is the - `pub fn in_content_column(&self) -> bool`. Whether the next child goes in a `Content` column. + - `pub fn column(&self) -> usize`. The column the next child goes in. - `pub fn widen(&mut self, size: Vec2)`. The cell last placed measured `size` after all: its column and row record that, and a `Content` column offers - `pub fn measured(&self) -> &GridMeasure`. What this pass measured. - `craft_behavior::grid::GridMeasure`: `pub struct GridMeasure { pub columns: Vec, pub rows: Vec, pub least: Vec }`. What a `Grid` pass measured: the widest child per column and the tallest per row, and the least each column @@ -987,19 +1065,25 @@ Hit shapes, their priority and the arena's resolve rule (8.3). - `craft_behavior::hit::HitPriority`: `pub struct HitPriority { pub level: HitLevel, pub sub: u8 }`. A part's rank among the shapes of its stack position: a node editor ranks port above wire above node body. - `pub const fn new(level: HitLevel, sub: u8) -> Self`. A priority at `level` and `sub`. - `pub const BODY: HitPriority`. The priority of a component body. -- `craft_behavior::hit::HitShape`: `pub enum HitShape { Rect(Rect), Circle { center: Pos2, radius: f32 }, Segment { a: Pos2, b: Pos2 }, Polyline { points: Vec, closed: bool }, Polygon(Vec), OutsidePolygon { within: Rect, polygon: Vec } }`. The geometry a part registers: the shape painted is the shape hit. +- `craft_behavior::hit::HitShape`: `pub enum HitShape { Rect(Rect), Circle { center: Pos2, radius: f32 }, Segment { a: Pos2, b: Pos2 }, Polyline { points: Vec, closed: bool, reach: f32 }, Polygon(Vec), OutsidePolygon { within: Rect, polygon: Vec } }`. The geometry a part registers: the shape painted is the shape hit. - `pub const fn circle(center: Pos2, radius: f32) -> Self`. A disc. - `pub const fn segment(a: Pos2, b: Pos2) -> Self`. A line segment. - - `pub fn polyline(points: Vec, closed: bool) -> Self`. A chain of segments, closed when `closed`. + - `pub fn polyline(points: Vec, closed: bool) -> Self`. A chain of segments, closed when `closed`, hit within [`LINE_REACH`]. + - `pub fn polyline_within(points: Vec, closed: bool, reach: f32) -> Self`. A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from - `pub fn outside_polygon(within: Rect, polygon: Vec) -> Self`. The part of `within` outside `polygon`. - `pub fn bounds(&self) -> Rect`. The smallest rectangle around the shape. + - `pub fn translated(&self, by: Vec2) -> Self`. The shape moved by `by`. + - `pub fn snapped(&self, to: &HitShape, within: f32) -> Self`. The shape with each coordinate taken from `to`'s where the two lie within `within` points, when both are the - `pub fn hit(&self, point: Pos2) -> bool`. Whether `point` hits the shape. - `craft_behavior::hit::LINE_REACH`: `pub const LINE_REACH: f32`. How far from a line a point still hits it, in points. - `craft_behavior::hit::ResolveFor`: `pub enum ResolveFor { Press, Hover }`. What a resolution is for. - `craft_behavior::hit::Shape`: `pub struct Shape { pub shape: HitShape, pub sense: Sense, pub owner: O, pub part: Option, pub priority: HitPriority, pub position: u32, pub local: bool, pub min_across: f32 }`. One registered shape of the shape record: a root's, a member's or a part's. + - `pub fn translated(&self, by: Vec2) -> Self`. The shape moved by `by`. + - `pub fn snapped(&self, to: &Shape, within: f32) -> Self`. The shape with its geometry and least size across taken from `to`'s where they lie within `within` points - `pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self`. A shape of `owner` at stack `position`. - `pub const fn min_across(mut self, across: f32) -> Self`. The hit area is at least `across` points wide and high. - `pub const fn local(mut self, local: bool) -> Self`. The shape lies in the body layer's space. + - `pub fn hits(&self, point: Pos2) -> bool`. Whether `point` lies in the hit area: the shape grown to be at least its `min_across` wide and high. The - `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool }`. The shape that won a resolution. - `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last - `craft_behavior::hit::resolve_mapped`: `pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFor, to_local: impl Fn(Pos2) -> Pos2) -> Option>`. [`resolve`] where shapes with `local` set are tested at `to_local(point)`. @@ -1253,8 +1337,8 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `craft_behavior::nav::StepResult`: `pub enum StepResult { Set(f64), Ignored }`. What a single-value move does. - `craft_behavior::nav::TypeAhead`: `pub struct TypeAhead`. Typed letters of the last second as one prefix. - `pub const fn new() -> Self`. An empty buffer. - - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix. - - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>) -> Option`. The entry a prefix picks: the first match from the position after `from` (from `from` itself when the + - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, + - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one - `craft_behavior::nav::ValueAxes`: `pub enum ValueAxes { Horizontal, Vertical, Both }`. The axes a single-value control reads moves on. - `craft_behavior::nav::ValueSteps`: `pub struct ValueSteps { pub value: f64, pub min: f64, pub max: f64, pub small: f64, pub large: f64, pub fine: f64, pub notch: f64 }`. The value and steps of a single-value control. - `pub const fn new(value: f64, min: f64, max: f64, small: f64, large: f64) -> Self`. Steps over `min..=max` from `value`. The fine step is `small / LARGE_STEPS` and a wheel notch is `small`. @@ -1265,7 +1349,7 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `craft_behavior::nav::step`: `pub fn step(shape: NavShape, outline: &dyn NavOutline, state: &mut NavState, mv: NavMove, mods: MoveMods) -> NavStep`. Steps the lead of a navigation of `shape` over `outline` by `mv`. `mods.extend` keeps the anchor at the - `craft_behavior::nav::step_until_changed`: `pub fn step_until_changed(from: T, step: impl Fn(T) -> T, same: impl Fn(T) -> bool) -> T`. The value `step` reaches from `from`, stepped again while a step still moves it and `same` says the value is the - `craft_behavior::nav::step_value`: `pub fn step_value(steps: &ValueSteps, axes: ValueAxes, mv: NavMove, mods: MoveMods) -> StepResult`. Maps a move to the new value of a slider, dial, rating, resize handle or colour pad. `Forward`, `Up` and -- `craft_behavior::nav::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel event to the new value of a single-value control: one `notch` per event, up for positive scroll. +- `craft_behavior::nav::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries ## `craft_behavior::one_press` @@ -1326,6 +1410,7 @@ Where windows go on the desktop: where a saved window opens ([`place`]), which m - `pub fn new(size: [f32; 2], scale: f32) -> Self`. A window of `size` points, position unknown, on a monitor of `scale`, not maximized. - `pub fn repaired(&self) -> Option`. The record with out-of-range numbers repaired, or `None` when its size is no size. - `pub fn position(&self) -> Option<[f32; 2]>`. The outer top-left corner in desktop points at the saved scale, where the position is known. +- `craft_behavior::placement::capped`: `pub fn capped(size: Vec2, monitor: &Monitor, frame: Vec2, min: Vec2) -> Vec2`. `size` at least `min` and at most the monitor's usable area less `frame`; the cap wins over the minimum. - `craft_behavior::placement::cascade`: `pub fn cascade(previous: Rect, size: Vec2, bounds: Rect, step: f32) -> Rect`. Where a window of `size` opens after the one at `previous`: one `step` right and down. An axis on which that - `craft_behavior::placement::cascade_rects`: `pub fn cascade_rects(area: Rect, size: Vec2, n: usize, step: f32) -> Vec`. `n` windows of `size` in a cascade inside `area`: the first at its top left, each next one [`cascade`]d from the - `craft_behavior::placement::monitor_of`: `pub fn monitor_of(monitors: &[Monitor], window_px: Rect) -> Option<&Monitor>`. The monitor the window at `window_px` (desktop pixels) is on: the one showing most of it or, when none shows it, @@ -1345,7 +1430,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn delta(mut self, delta: Vec2) -> Self`. The pointer movement of the pass. - `pub const fn cancel(mut self, cancel: Option) -> Self`. A reason the captured press ends now. - `craft_behavior::press::PointerButton`: `pub enum PointerButton { Primary, Secondary, Middle, Extra1, Extra2 }`. A pointer button. -- `craft_behavior::press::PointerEvent`: `pub enum PointerEvent { Moved(Pos2), Pressed { button: PointerButton, pos: Pos2, time: f64, clicks: u32 }, Released { button: PointerButton, pos: Pos2 }, Gone }`. A button event of one pass, in the order it arrived. The press lifecycle follows the primary button and the +- `craft_behavior::press::PointerEvent`: `pub enum PointerEvent { Moved { at: Pos2, sample: Option }, Pressed { button: PointerButton, pos: Pos2, time: f64, clicks: u32 }, Released { button: PointerButton, pos: Pos2 }, Gone }`. A button event of one pass, in the order it arrived. The press lifecycle follows the primary button and the + - `pub const fn moved(at: Pos2, sample: Option) -> Self`. The pointer moved to `at`, with the pen's reading for the move when the runtime has one. - `pub const fn pressed(pos: Pos2, time: f64, clicks: u32) -> Self`. The primary button going down at `pos`, `time`, as the `clicks`th press in a row. - `pub const fn released(pos: Pos2) -> Self`. The primary button going up at `pos`. - `pub const fn pressed_by(button: PointerButton, pos: Pos2, time: f64, clicks: u32) -> Self`. `button` going down at `pos`, `time`, as the `clicks`th press in a row. @@ -1353,7 +1439,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `craft_behavior::press::PointerKind`: `pub enum PointerKind { Mouse, Pen, Touch }`. What kind of device the pointer is. - `craft_behavior::press::PointerSample`: `pub struct PointerSample { pub pressure: f32, pub tilt: [f32; 2], pub rotation: f32, pub eraser: bool }`. Pressure and tilt of the current contact. - `pub const fn new(pressure: f32) -> Self`. A sample with no tilt or rotation. -- `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed }`. Why a captured press ended without a release. + - `pub fn sanitized(self) -> Self`. The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value +- `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed, Host }`. Why a captured press ended without a release. - `craft_behavior::press::PressMachine`: `pub struct PressMachine`. The press lifecycle of one root: the press winner it picked, kept until release or cancel. - `pub const fn new() -> Self`. A machine with no press. - `pub fn target(&self) -> Option`. The target of the open press. @@ -1361,7 +1448,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn dragging(&self) -> bool`. Whether a drag holds the pointer. - `pub fn release_held(&self) -> bool`. Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` -- `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. +- `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart, pos: Pos2 }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. - `pub const fn is_press(&self) -> bool`. A press is in progress or just ended: not `Idle` or `Hover`. - `pub const fn start(&self) -> Option`. The press the phase belongs to. - `pub const fn button_down(&self) -> bool`. Whether the button is down: `Down`, `Held`, `DragStart` or `Drag`. @@ -1378,7 +1465,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn captured(mut self, captured: bool) -> Self`. Whether a drag holds the pointer. - `pub const fn double_pressed(&self) -> bool`. Whether the phase is the `Down` of the second press of a double click: true once, false while the button is - `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option }`. What one pass did to the press. -- `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32)>, pos: Pos2, time: f64, slop: f32) -> u32`. The click count of a press at `pos` and `time`, given the previous press `(pos, time, clicks)`: one more when +- `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32`. The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, ## `craft_behavior::quantity` @@ -1497,7 +1584,7 @@ Selection models: what a collection's selection holds and how a change applies t The library's sense set, for a root or a part. -- `craft_behavior::sense::Sense`: `pub struct Sense: u16 (flag set)`. What a root or a part senses. The egui adapter maps the root's sense to egui's. +- `craft_behavior::sense::Sense`: `pub struct Sense: u32 (flag set)`. What a root or a part senses. The egui adapter maps the root's sense to egui's. - `pub const PRESS: Sense`. The bits that make a shape a press candidate. - `pub const WHEELS: Sense`. The bits that make a shape register a wheel taker. - `pub const fn takes_press(self) -> bool`. Whether a press can start on a shape with this sense. @@ -1539,9 +1626,10 @@ The library's sense set, for a root or a part. - `pub fn codec(&self) -> &C`. The codec. - `pub fn shown(&self, run: &EditRun, value: &C::Value) -> String`. The text to show: the draft, else the value's text. - `pub fn open(&self, run: &mut EditRun, start: &C::Value)`. Opens the run on `start` when none is open. - - `pub fn edit(&self, run: &mut EditRun, start: &C::Value, text: &str) -> Typed`. The draft is now `text`: characters the codec refuses and characters past the limit drop out. + - `pub fn edit(&self, run: &mut EditRun, start: &C::Value, text: &str) -> (Typed, bool)`. The draft is now `text`: characters the codec refuses and characters past the limit drop out. The `bool` + - `pub fn rewrite(&self, run: &mut EditRun) -> bool`. Replaces the draft with the codec's normal form of the value it reads (`Codec::normalise`, as a commit - `pub fn commit(&self, run: &mut EditRun) -> Ended`. Commits the draft: a value closes the run, a draft that is no value keeps it open. - - `pub fn commit_tagged(&self, run: &mut EditRun) -> (Ended, Option)`. [`commit`](Self::commit), with the tag of the unit the committed text named (`Codec::parse_tagged`). + - `pub fn commit_tagged(&self, run: &mut EditRun) -> (Ended, ParseNote)`. [`commit`](Self::commit), with the note of the committed text (`Codec::parse_tagged`); the default note for a - `pub fn cancel(&self, run: &mut EditRun) -> Option`. Closes the run without a commit and returns the value from before it; `None` when no run was open. - `pub fn escape(&self, run: &mut EditRun) -> Escaped`. Applies the escape rule. A codec that refuses the empty text keeps the cleared draft open under @@ -1550,7 +1638,7 @@ The library's sense set, for a root or a part. The value core of chapter 10: the bound every value type meets, `Mixed`, edit events and the list a pass's events - `craft_behavior::value::Applied`: `pub enum Applied { Changed, Unchanged, Restored }`. What applying an event did to a value. -- `craft_behavior::value::CancelReason`: `pub enum CancelReason { Refused, Dismissed, Escape, Blur, Removed, HostChanged, UndoDuringGesture }`. Why a gesture ended without a commit. +- `craft_behavior::value::CancelReason`: `pub enum CancelReason { Refused, Dismissed, Escape, Blur, Removed, HostChanged, UndoDuringGesture, Unchanged }`. Why a gesture ended without a commit. - `pub const fn document_moved(self) -> bool`. The document changed under the gesture, so the gesture's own edits stay and a revert would also take back the - `craft_behavior::value::EditEvent`: `pub enum EditEvent { Begin { id: GestureId, before: Mixed, label: Arc, doc_key: Option }, Update { id: GestureId, value: T }, Commit { id: GestureId, before: Mixed, after: T }, Cancel { id: GestureId, reason: CancelReason, before: Option> }, Set { before: Mixed, after: T, label: Arc, doc_key: Option } }`. One step of an edit. A pass raises several; [`EditEvents`] holds them in order. - `pub fn begin(id: GestureId, before: Mixed, label: Arc, doc_key: Option) -> Self`. A gesture began. @@ -1567,6 +1655,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub fn apply(&self, v: &mut T) -> Applied`. Applies the event to `v`: a proposal, commit or set writes its value, a cancel restores the value from before - `pub fn apply_mixed(&self, v: &mut Mixed) -> Applied`. Applies the event to a value that may be mixed: the written value is a concrete one. - `craft_behavior::value::EditEvents`: `pub struct EditEvents`. The edit events of one pass, in order. `push` folds what loses nothing, within one gesture: a later `Update`, + - `pub fn committed(&self) -> Option<&T>`. The value of the last `Commit` or `Set` in the events; `None` if there is none. - `pub fn new() -> Self`. No events. - `pub fn push(&mut self, event: EditEvent)`. Adds the next event of the pass, folding it with the one before when that loses nothing. - `pub fn is_empty(&self) -> bool`. No event happened. @@ -1581,20 +1670,27 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub fn map(self, f: impl Fn(T) -> U) -> EditEvents`. Maps the carried values of every event. - `pub fn filter_map(self, f: impl Fn(T) -> Option) -> EditEvents`. Maps the carried values of every event, dropping the events `f` has no value for. - `craft_behavior::value::EditPolicy`: `pub enum EditPolicy { WriteThrough, OnCommit }`. When a write-through source is written: on every proposal of a gesture or only on its commit. -- `craft_behavior::value::Gesture`: `pub struct Gesture { pub id: GestureId, pub before: Option>, pub proposal: Option, pub last_given: Option, pub emitted: Option, pub reported: Option, pub dead: bool, pub cancel_seen: u64, pub watched: bool }`. The running gesture of a value component, kept in shown memory under the component. Plain data; the pipeline +- `craft_behavior::value::Gesture`: `pub struct Gesture { pub id: GestureId, pub before: Option>, pub proposal: Option, pub last_given: Option, pub emitted: Option, pub reported: Option, pub dead: bool, pub cancel_seen: u64, pub watched: bool, pub wheel: bool, pub note: Option }`. The running gesture of a value component, kept in shown memory under the component. Plain data; the pipeline - `pub fn ended(&self, dead: bool) -> Gesture`. The gesture after it ended: no value, the id kept, and `dead` while the press that carried it is held. - `pub fn is_running(&self) -> bool`. A gesture is running. - `craft_behavior::value::GestureId`: `pub struct GestureId(pub u64)`. Names a gesture; ids grow in the order the gestures begin. - `pub const fn new(n: u64) -> GestureId`. The id numbered `n`. - `pub const fn next(self) -> GestureId`. The id of the gesture after this one. +- `craft_behavior::value::GestureNote`: `pub struct GestureNote`. A typed note a component sets on its running gesture for readers outside its pass, such as the guide a guides + - `pub fn new(note: N) -> Self`. A note holding `note`. + - `pub fn get(&self) -> Option<&N>`. The note, when it is an `N`. - `craft_behavior::value::GesturePhase`: `pub enum GesturePhase { Begin, Update, Commit, Cancel }`. Where a gesture stands in one pass. - `craft_behavior::value::Mixed`: `pub enum Mixed { Same(T), Mixed }`. A value that may differ across a multi-selection. - `pub const fn same(&self) -> Option<&T>`. The shared value, `None` while the items differ. - `pub const fn or<'a>(&'a self, start: &'a T) -> &'a T`. The shared value, or `start` while the items differ. - `pub fn each(values: [T; N]) -> [Mixed; N]`. Every part of `values` as a shared value: the per-part form of a composite value no part of which differs. - `pub fn parts(self) -> [Mixed; N]`. The per-part form of a composite value: a whole `Mixed` binding means every part differs. +- `craft_behavior::value::Preview`: `pub enum Preview { Unchanged, Shows(V), Ended }`. What one pass did to a live preview a component shows beside its value (the family under the pointer in a font + - `pub fn map(self, f: impl FnOnce(V) -> W) -> Preview`. The same change over the value `f` makes of the shown one. - `craft_behavior::value::Validity`: `pub enum Validity { Ok, Fix(T), Warn(M), Refuse(M), Error(M) }`. What a check says about a value. `M` is the message type: craft-ui exports the alias with its own `Message`. - `craft_behavior::value::Value`: `pub trait Value: Clone + PartialEq + Send + Sync + 'static`. What a bound value must be: cloneable, comparable and shareable across threads. +- `craft_behavior::value::same_in_f32`: `pub fn same_in_f32(proposed: f64, host: f64) -> bool`. Whether `host`, a number an app wrote back, is the proposal `proposed` as a host that keeps it in `f32` stores it: +- `craft_behavior::value::same_in_f32_at`: `pub fn same_in_f32_at(proposed: f64, host: f64, magnitude: f64) -> bool`. [`same_in_f32`] for a number the host computes in `f32` from terms as large as `magnitude`: a corner of a box it ## `craft_behavior::value_drag` @@ -1623,24 +1719,36 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub at: Option, pub zooms: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. + - `pub const fn touch_zoom(mut self, zoom: f32) -> Self`. The same gesture with the two-finger touch zoom factor `zoom`. + - `pub const fn rotation(mut self, radians: f32) -> Self`. The same gesture with rotation `radians`, clockwise on screen. + - `pub const fn touch_rotation(mut self, radians: f32) -> Self`. The same gesture with the two-finger touch rotation `radians`. + - `pub const fn source(mut self, source: WheelSource) -> Self`. The same gesture from `source`. - `pub const fn at(mut self, at: Pos2) -> Self`. The same gesture with the pointer at `at`. -- `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool }`. Who holds key focus, as the split reads it. +- `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool, pub by_position: bool }`. Who holds key focus, as the split reads it. - `pub const fn new(taker: Option) -> Self`. Focus on `taker`, or on nothing that takes the wheel. - `pub const fn app_field(mut self, on: bool) -> Self`. The same focus, in a text field the app drew itself when `on`. + - `pub const fn by_position(mut self, on: bool) -> Self`. The same focus, with the pointer over a layer that takes the wheel by position when `on` +- `craft_behavior::wheel::WheelGesture`: `pub struct WheelGesture { pub owner: Option, pub last: f64 }`. A wheel gesture: events closer than [`GESTURE_GAP`] seconds, or inside one device phase. `owner` is `None` while + - `pub fn runs(&self, now: f64) -> bool`. Whether an event at `now` continues the gesture: one is open, the device has not ended it and the gap since + - `pub fn end(&mut self, now: f64) -> Option`. Closes the gesture once `now - last` reaches [`GESTURE_GAP`], or at once after a device end, and returns the - `craft_behavior::wheel::WheelNotch`: `pub enum WheelNotch { Points(f32), ViewShare(f32) }`. The distance one wheel line scrolls a taker. - `pub const DEFAULT: WheelNotch`. The distance of a taker that states none. - `pub fn points(self, extent: f32) -> f32`. The notch in points, for a taker whose view is `extent` points along the axis. - `craft_behavior::wheel::WheelPhase`: `pub enum WheelPhase { Start, Move, End, Cancel }`. A wheel gesture's phase. - `craft_behavior::wheel::WheelRoom`: `pub struct WheelRoom { pub positive: Vec2, pub negative: Vec2 }`. The scroll left in a region, in points of wheel scroll: `positive` is what a wheel with positive `scroll` can - `pub const fn new(positive: Vec2, negative: Vec2) -> Self`. A room of `positive` and `negative` points. -- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option, pub zooms_view: bool, pub field: bool }`. A component that takes wheel input, as registered last pass. +- `craft_behavior::wheel::WheelSource`: `pub enum WheelSource { Unknown, Wheel, Trackpad, Momentum }`. The device a wheel event came from, where the system says (egui reports it on macOS only). + - `pub const fn fingers(self) -> bool`. Whether fingers drive the scroll: a trackpad or its momentum. +- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option, pub zooms_view: bool, pub field: bool, pub value: bool }`. A component that takes wheel input, as registered last pass. - `pub const fn new(owner: O, rect: Rect) -> Self`. A taker over `rect` that takes no axis yet. - `pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option`. The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll - `pub const fn zooms_view(mut self, on: bool) -> Self`. Whether it is a zoom zone (`WheelTaker::zooms_view`). - `pub const fn field(mut self, on: bool) -> Self`. Whether it is a value field (`WheelTaker::field`). + - `pub const fn value(mut self, on: bool) -> Self`. Whether it is a value control (`WheelTaker::value`). - `pub const fn horizontal(mut self, on: bool) -> Self`. Whether it takes horizontal scroll. - `pub const fn vertical(mut self, on: bool) -> Self`. Whether it takes vertical scroll. - `pub const fn zoom(mut self, on: bool) -> Self`. Whether it takes zoom. @@ -1650,12 +1758,14 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli - `pub const fn room(mut self, room: WheelRoom) -> Self`. The taker's scroll room: it passes a wheel on an axis it has no room left for to the next enclosing taker. - `pub fn points(&self, scroll: Vec2, unit: WheelUnit) -> Vec2`. `scroll`, given in `unit`s of the device, as points of this taker's view: a line is one notch, a page is - `craft_behavior::wheel::WheelUnit`: `pub enum WheelUnit { Point, Line, Page }`. How far one wheel event reaches. -- `craft_behavior::wheel::split`: `pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option) -> Vec<(O, Wheel)>`. The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes +- `craft_behavior::wheel::split`: `pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option, gesture: &mut WheelGesture, now: f64,) -> Vec<(O, Wheel)>`. The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes ## `craft_ui` The base of the craft UI library: runtime, style, fonts, primitives, the component contract, layout and the test +- `craft_ui::bind_tracked!`: `macro_rules! bind_tracked`. Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` +- `craft_ui::stays!`: `macro_rules! stays`. Types with no place: they stay as they are at any place. - `craft_ui::testing_registered!`: `macro_rules! testing_registered`. Writes `pub fn registered()` for the invoking package: its library crate's registrations in the running binary. - `craft_ui::InstallError`: re-export of `craft_ui::runtime::install::InstallError`. - `craft_ui::InstallSpec`: re-export of `craft_ui::runtime::install::InstallSpec`. @@ -1675,6 +1785,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `const MEMBERS: bool`. Whether the items are members of the collection's run instead of runs of their own. Each visible item is then - `fn items(&self) -> &CollectionProps`. Plain data: selection mode, reorder, rename, columns. - `fn selection(&mut self) -> Option>`. The selection binding; `None` keeps it in session memory. + - `fn column_layout(&mut self) -> Option>`. The column arrangement binding; `None` keeps it in the header's own memory. The header starts each pass from - `fn cell_space<'s>(&'s self, space: CellSpace<'s, Self::Key>) -> CellSpace<'s, Self::Key>`. The grid a model of cells selects in (17.7). The item step passes the grid it knows, the source's rows and the - `fn reveal(&self) -> Option<&Self::Key>`. A one-shot request to scroll an item into view. - `fn item_layout(&self, source: &dyn ItemSource, width: f32, cx: &StyleCx<'_>) -> Self::ItemLayout`. The layout of `source` at `width`. @@ -1683,7 +1794,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn dress_inputs(&self) -> u64`. What `dress` reads of the collection, hashed: a kept measure of the items serves only while it is the same. - `fn ideal_width(&self, _item: Option, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. - - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. + - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this - `fn rename_editor(&mut self, _ui: &mut Ui, _draft: Bind<'_, String>, _label: Rect, _name: &str) -> Option>`. The rename editor at `label`: the label rect the renaming item reports (`ItemOutput::label_rect`), else its row. - `fn rename_draft(&self, _key: &Self::Key) -> Option`. The text the rename field of the item `key` opens with; `None` for the item's own text. - `fn can_rename(&self, _key: &Self::Key) -> bool`. Whether the item `key` may be renamed; a rename request on another item does nothing. @@ -1692,12 +1803,13 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn drops(&self) -> &[DropKind<'_, Self::Key>]`. What the collection takes from drags that did not start in it, in order: the first kind that takes the drag's - `fn edge_press(&self) -> Option<&EdgePress<'_, Self::Key>>`. The press on the line between two adjacent rows the collection takes, reported as - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): it reports - - `fn empty_height(&self, width: f32, ui: &Ui, _cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The + - `fn empty_height(&self, width: f32, ui: &Ui, cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The - `fn empty(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>)`. The empty state at the rect the item step placed. The default shows `CollectionProps::empty`. - `craft_ui::contract::Component`: `pub trait Component: Meta + Sized`. The core trait: every UI type is a `Component`. - `const ROLE: Role`. The AccessKit role. - `const ALT_ROLES: &'static [Role]`. Roles `access` may pick per instance. - `const INPUT: Input`. How input reaches the component. + - `const ESCAPE: EscapeEdit`. What Escape does to the running gesture. - `const OVERLAYS: bool`. Whether the component hosts popups: `false` skips the overlay bookkeeping of steps 9, 10, 12, 15 and 16. - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except @@ -1725,7 +1837,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn same_value(&self, proposed: &ValueOf, host: &ValueOf) -> bool`. Whether `host`, a value the app wrote back, is the value `proposed` as the component holds values: a host that - `fn scrub(&self) -> Option>>`. Lets a drag on the scrub's sources (the side label, the body, a part) change the value; the pipeline runs the - `fn scroll(&mut self) -> Option>`. The scroll offset's owner when the app drives scrolling; `None` keeps it in session memory. The app restores a - - `fn content_env(&self, _cx: &Cx<'_, Self>, _values: &mut crate::runtime::env::AppValues)`. App values for content the component does not build: its body or its items. Runs once, at step 13. + - `fn content_env(&self, _cx: &Cx<'_, Self>, _values: &mut crate::runtime::env::AppValues)`. App values for content the component does not build: its body or its items. Runs at step 13, and in a measuring run of the body before it. - `fn update(&mut self, _cx: &mut Cx<'_, Self>)`. After sensing, before paint: value maths, memory, popup triggers. - `fn overlay(&mut self, _ui: &mut OverlayUi<'_>, _cx: &mut Cx<'_, Self>)`. Anchored popups. Runs before flags and paint. - `fn flags(&self) -> Flags`. Value-driven flags (checked, open, invalid, busy). @@ -1734,6 +1846,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn paint_over(&mut self, _ui: &mut PaintUi<'_>, _cx: &Cx<'_, Self>)`. Content above the body or items. - `fn access(&self, _access: &mut Access, _cx: &Cx<'_, Self>)`. Value, range, relations, sub-nodes and custom actions beyond role, label and flags. - `fn value_text(&self, _cx: &Cx<'_, Self>) -> Option`. The shown value as the component words it ("40.0", "20 to 60"), which assistive technology reads and a viewer + - `fn word_value(&self, _value: &ValueOf, _cx: &Cx<'_, Self>) -> Option`. Words `value` as the control shows it ("40.0", "20 to 60"); `None` for a component that words no value. The - `fn finish(self, cx: Cx<'_, Self>) -> Self::Output`. Builds the output from the finished context. - `craft_ui::contract::Container`: `pub trait Container: Component + HasProps + Meta`. A component whose caller supplies a body. - `fn open(&mut self) -> Option>`. The open state's owner: the caller's binding. `None`: a session slot under the id. @@ -1746,6 +1859,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn placement_changed(&mut self, _change: &overlay::PlacementChange)`. The user moved or resized the container's layer: by the move band, a grip or the keyboard Move and Size - `craft_ui::contract::ContentPainter`: `pub trait ContentPainter: Component`. Implemented by the allowlisted components that paint content with a raw painter (a preview, a waveform). - `craft_ui::contract::DisabledLook`: `pub enum DisabledLook { States, Faded }`. How a component that is not enabled looks (`Component::DISABLED`). Either way it takes no input, its access node +- `craft_ui::contract::EscapeEdit`: `pub enum EscapeEdit { Cancel, Commit }`. What Escape does to a value component's running gesture (step 9). - `craft_ui::contract::HasProps`: `pub trait HasProps`. Written by the derive from a `#[container]` field, for containers and collections. - `fn props(&self, _: Internal) -> &ContainerProps`. - `craft_ui::contract::IdSource`: `pub enum IdSource { Auto, Salt(IdSalt), Id(Id) }`. Where an element's id comes from. @@ -1796,14 +1910,19 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn given(v: impl Into>) -> Self`. A value in; every edit comes out as an event. - `pub fn bound(v: &'a mut T) -> Self`. Edits write through to `v`. - `pub fn bound_mixed(v: &'a mut Mixed) -> Self`. Edits write through to a field that may be mixed; an edit makes it concrete. - - `pub fn kept() -> Self`. No caller value: the component keeps it in session memory under its id. + - `pub fn kept() -> Self`. No caller value: the component keeps it in session memory under its id. Until something is stored, it reads - `pub fn saved(mut self, key: SaveKey) -> Self where T: Savable,`. A kept value that is also saved across runs under `key`. The `Savable` bound sits here; the pipeline reaches - `pub fn policy(mut self, policy: EditPolicy) -> Self`. When a write-through source is written. - - `pub fn check(mut self, check: impl Fn(&T) -> Validity + 'a) -> Self`. The check on a value: `Fix` replaces it; `Warn`, `Refuse` and `Error` set the component's state, and `Refuse` - - `pub fn reset(mut self, default: T) -> Self`. The value a reset gesture restores. + - `pub fn check(self, check: fn(&T) -> Validity) -> Self where T: 'a,`. The check on a value: `Fix` replaces it; `Warn`, `Refuse` and `Error` set the component's state, and `Refuse` + - `pub fn check_with(mut self, inputs: I, check: fn(&I, &T) -> Validity) -> Self where T: 'a,`. The check `check` on a value, reading `inputs` beside it (a limit, the names already taken). The inputs are + - `pub fn reset(mut self, default: T) -> Self`. The value a reset gesture restores, and the value a kept binding reads while nothing is stored. - `pub fn reborrowed(&mut self) -> Bind<'_, T>`. A binding with the same source, check, policy and reset that borrows this one, so a composite can hand its + - `pub fn value(&self) -> Option<&T>`. The one value the binding holds before this pass's edits; `None` for a mixed or kept binding. - `pub fn reborrow(&mut self) -> BindMut<'_, T>`. The binding as the pipeline reads and writes it. +- `craft_ui::contract::BindCheck`: `pub struct BindCheck<'c, T>`. A binding's check as props (`BindMut::check_of`): by the key of its inputs and its `fn`. + - `pub fn validity(&self, value: &T) -> Validity`. The check's verdict on `value`. - `craft_ui::contract::BindMut`: `pub struct BindMut<'a, T>`. A reborrow of a [`Bind`] the pipeline reads at steps 4, 11, 15 and 17. `Component::bind` returns it, and returns the + - `pub fn check_of(&self) -> BindCheck<'_, T>`. The binding's check, as the inputs of a child's check (`Bind::check_with`): a composite hands its own check to - `pub fn read(&self, cx: &mut impl StageAccess) -> Option>`. The binding's value for code that runs no pipeline step: a given or write-through value, or the kept value - `pub fn write(&mut self, cx: &mut impl StageAccess, event: &EditEvent) -> bool`. Writes `event` as the pipeline's apply step does: the check may replace the value (`Fix`) or refuse it - `craft_ui::contract::BodyCx`: `pub struct BodyCx<'a> { pub id: Id, pub env: EnvView<'a>, pub resolved: &'a Resolved<'a>, pub rect: Rect, pub memory: &'a mut MemoryStage }`. What a body closure and the header, footer and empty hooks read: a view over the pipeline's memory stage @@ -1821,10 +1940,12 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it -- `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]> } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. +- `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. - `pub const fn row() -> Self`. Children side by side from the start edge, with no wrap. - `pub fn grid(columns: impl Into>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass. + - `pub fn fit(self, fit: GridFit) -> Self`. A `Grid` with `fit`; any other layout is unchanged. + - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. @@ -1833,9 +1954,10 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn new() -> Self`. A collapsible body that starts open, animated. - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. -- `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection(SelectionChange), LeadMoved { key: K, by: LeadSource }, Activate(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option

+ Send + Sync + 'static) -> Self`. A row drag carries `map` of it, for the drop targets of type `P`; a row the map gives `None` for does not drag @@ -1906,12 +2028,14 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::Common`: `pub struct Common { pub label: Label, pub tooltip: Option, pub description: Option, pub selected: Option }`. What every component carries: the props the pipeline reads at step 1. - `pub const fn new() -> Common`. A `Common` with every prop unset, which the derive's constructors start from. - `craft_ui::contract::Component`: re-export of `craft_ui_macros::Component` (outside these crates). -- `craft_ui::contract::ContainerProps`: `pub struct ContainerProps { pub mount: Mount, pub surface: Option, pub pad: Pad, pub sizing: Sizing, pub room_height: Option, pub layout: BodyLayout, pub header: Option, pub scroll: Option, pub footer: Option, pub end: Option, pub help: Option