diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 7fa0422777..4704686970 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -544,7 +544,7 @@ const INV_PHI: f64 = 0.618_033_988_749_894_9; const PHI: f64 = 1.0 + INV_PHI; /// The composition guide drawn inside a crop frame, in Photoshop's menu order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropGuide { @@ -727,7 +727,7 @@ fn golden_spiral() -> Vec<[f64; 2]> { } /// When the guide shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum GuideShow { diff --git a/crates/color-ui/src/ui/eyedropper.rs b/crates/color-ui/src/ui/eyedropper.rs index 9a238c2863..4e17c7b572 100644 --- a/crates/color-ui/src/ui/eyedropper.rs +++ b/crates/color-ui/src/ui/eyedropper.rs @@ -61,7 +61,7 @@ craft_ui::words! { } /// How many pixels around the pointer the eyedropper averages: Photoshop's Sample Size list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSize { @@ -115,7 +115,7 @@ impl SampleSize { } /// Which layers the eyedropper reads: Photoshop's Sample list. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum SampleSource { @@ -172,7 +172,7 @@ impl SampleSource { } /// The Eyedropper's options bar values. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct EyedropperOptions { diff --git a/crates/color-ui/src/ui/gradient/editor/bar.rs b/crates/color-ui/src/ui/gradient/editor/bar.rs index ba55ee2823..394dcdfeab 100644 --- a/crates/color-ui/src/ui/gradient/editor/bar.rs +++ b/crates/color-ui/src/ui/gradient/editor/bar.rs @@ -845,7 +845,7 @@ impl Component for GradientBar<'_, P> { let edge_of = |m: StopRef| { if self.selected_marker == Some(m) { style.selected - } else if !dragging && cx.hover_pos(part_of(m)).is_some() { + } else if !dragging && cx.part_if_declared(part_of(m)).is_some_and(|result| result.hovered) { style.hovered } else { cx.resolve(&style.edge) diff --git a/crates/color-ui/src/ui/screen_picker/capture.rs b/crates/color-ui/src/ui/screen_picker/capture.rs index d25155f2ce..471ba62648 100644 --- a/crates/color-ui/src/ui/screen_picker/capture.rs +++ b/crates/color-ui/src/ui/screen_picker/capture.rs @@ -229,7 +229,7 @@ impl Component for CaptureView<'_> { .get_or_put(ctx, self.key, Revision::default(), || ColorImage::from_rgba_unmultiplied(image.size.map(|n| n as usize), &image.rgba)); let whole = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)); ui.draw().texture(cx.rect, texture.id, whole); - let Some(pointer) = cx.response.hover_pos().filter(|at| cx.rect.contains(*at)) else { return }; + let Some(pointer) = craft_ui::runtime::pointer::hover_point_in(ctx, cx.rect) else { return }; let Some((x, y)) = self.pixel(cx.rect, pointer) else { return }; self.loupe(ui, cx, pointer, (x, y)); } diff --git a/crates/color-ui/tests/it/color_parts.rs b/crates/color-ui/tests/it/color_parts.rs index 8bb2598d34..0a44f04ffa 100644 --- a/crates/color-ui/tests/it/color_parts.rs +++ b/crates/color-ui/tests/it/color_parts.rs @@ -210,7 +210,7 @@ fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec> let limits = |_: &usize| craft_ui::contract::SizeLimits::default(); let rules = craft_ui::docking::tree::FrameRules::new(&limits); let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0)); - let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| { + let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules, 0).show_at(ui, area, |ui, _| { let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui); }); let _ = craft_ui::buttons::Button::new("After").show(ui); diff --git a/crates/design-lint/src/contract/pointer.rs b/crates/design-lint/src/contract/pointer.rs index bc764fcec2..270e4e89e7 100644 --- a/crates/design-lint/src/contract/pointer.rs +++ b/crates/design-lint/src/contract/pointer.rs @@ -1,4 +1,4 @@ -//! `contract/pointer`: drag and click queries and press-origin reads outside `runtime::egui`. +//! `contract/pointer`: drag and click queries, press-origin reads and hover-position reads outside `runtime::egui`. use crate::report::Finding; @@ -7,6 +7,13 @@ use super::Cx; pub const ID: &str = "contract/pointer"; pub(super) fn check(cx: &Cx<'_>, out: &mut Vec) { + cx.flag_methods( + out, + ID, + ID, + "reads egui's pointer position; `Cx::hover_pos` and `pointer::hover_point_in` read it and mark what follows the pointer", + |name, args| matches!(name, "pointer_hover_pos" | "pointer_latest_pos" | "pointer_interact_pos") || (name == "hover_pos" && args.count == 0), + ); cx.flag_methods(out, ID, ID, "reads egui's pointer state; the pointer frame carries presses and drags", |name, _| { matches!( name, diff --git a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs index 17699b16f3..a382cbd7b3 100644 --- a/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs +++ b/crates/design-lint/tests/fixtures/egui-rules/reject/contract-pointer.rs @@ -1,4 +1,6 @@ -fn f(r: &Response) { +fn f(r: &Response, ctx: &Context) { if r.drag_started() || r.clicked() {} let _ = r.drag_delta(); + let _ = r.hover_pos(); + let _ = ctx.pointer_latest_pos(); } diff --git a/crates/draw/src/ui/crop/options.rs b/crates/draw/src/ui/crop/options.rs index 003ba54801..8e5cc3388c 100644 --- a/crates/draw/src/ui/crop/options.rs +++ b/crates/draw/src/ui/crop/options.rs @@ -24,7 +24,7 @@ pub const FIELD_MAX: f64 = 1e9; pub const LENGTH_MIN: f64 = 0.01; /// What the frame's proportions follow. -#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropRatio { @@ -55,7 +55,7 @@ impl CropRatio { } /// The resolution field's unit. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ResolutionUnit { @@ -68,7 +68,7 @@ pub enum ResolutionUnit { /// A length with the unit it was entered in: the W and H of W × H × Resolution mode keep what the user typed ("2 in" /// stays in inches when the document resizes). -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct CropLength { @@ -97,7 +97,7 @@ impl CropLength { /// The W, H and Resolution fields of W × H × Resolution mode. Unset W and H are `None`; the resolution is typed text /// ("300"), empty when unset. Perspective Crop's options bar uses the same fields. -#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct CropSizeFields { @@ -112,7 +112,7 @@ pub struct CropSizeFields { } /// What the area a turned or extending crop uncovers is filled with. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum CropFill { @@ -229,7 +229,7 @@ pub const CROP_SIZES: [CropSizePreset; 8] = [ /// options bar edits it in place, the tool reads it each pass and reports key changes (O, ⇧O, H, /// P, I, X) as [`CropEvent::Settings`](super::CropEvent::Settings). Every field defaults on its /// own, so older settings load. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct CropSettings { diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 5c08d39e94..5c9524af50 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -853,7 +853,7 @@ impl<'a> BezierOverlay<'a> { continue; } let Some(result) = cx.part_if_declared(item.part()) else { continue }; - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(item.part())); pressed |= press.phase.is_press(); if let Some(at) = hover { let rank = match item.kind { @@ -916,7 +916,7 @@ impl<'a> BezierOverlay<'a> { if matches!(self.tool, BezierTool::AddAnchor | BezierTool::DeleteAnchor) && let Some(result) = cx.part_if_declared(EMPTY) { - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(EMPTY)); // The part covers the canvas background, so it owns the cursor the host tool shows off the paths too. if hover.is_some() { let tool = if self.tool == BezierTool::AddAnchor { PathTool::AddAnchor } else { PathTool::DeleteAnchor }; diff --git a/crates/draw/src/ui/pen/options.rs b/crates/draw/src/ui/pen/options.rs index a616018e1a..ff745df7bf 100644 --- a/crates/draw/src/ui/pen/options.rs +++ b/crates/draw/src/ui/pen/options.rs @@ -38,7 +38,7 @@ pub const PATH_OPTIONS_COLOR_KEY: &str = "pathOptions.color"; /// The pen's Path Options, persisted by the app with its preferences (Photoshop's Pen gear popover). Serialised in /// camelCase; unknown fields are ignored and missing ones take their defaults. -#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct PathOptionsSettings { @@ -58,7 +58,7 @@ pub struct PathOptionsSettings { } /// How the direction handles' ends are drawn. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum HandleStyle { diff --git a/crates/draw/src/ui/shape/mod.rs b/crates/draw/src/ui/shape/mod.rs index 02995f04d8..5902f6a925 100644 --- a/crates/draw/src/ui/shape/mod.rs +++ b/crates/draw/src/ui/shape/mod.rs @@ -29,7 +29,7 @@ pub use stroke_cells::{StrokeCells, StrokeCellsOutput}; pub use words::ShapeWords; /// The drawing mode of the vector tools. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum VectorMode { diff --git a/crates/draw/src/ui/transform/session/settings.rs b/crates/draw/src/ui/transform/session/settings.rs index 72601b2bc3..3a779f3ba8 100644 --- a/crates/draw/src/ui/transform/session/settings.rs +++ b/crates/draw/src/ui/transform/session/settings.rs @@ -49,7 +49,7 @@ impl TransformPreset { /// How the transform resamples the moving pixels: PhotoCraft's three choices (LC11). The app maps /// them to its engine; [`id`](Self::id) gives PhotoCraft's ids. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Interpolation { @@ -100,7 +100,7 @@ pub enum TransformChoice { /// Free Transform's persisted section: the app keeps it with its preferences. Unknown fields are /// ignored, missing ones take their defaults. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct TransformSettings { diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index a7c7230f99..178084bdcc 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -842,7 +842,7 @@ impl<'a> TransformBox<'a> { let suspend = suspend_key(snap.as_ref()); for (reference, part) in self.pointer_parts() { let Some(result) = cx.part_if_declared(reference) else { continue }; - let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered)); + let (press, hover) = (result.press, cx.hover_pos(reference)); let mods = self.mods.unwrap_or(press.mods); let acting = drag_mods(mods, suspend); if let Some(pos) = hover diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 124c41610b..d6c5386309 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -734,7 +734,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: } }); over_rows = rows.response.contains_pointer(); - let pointer = ui.ctx().pointer_hover_pos(); + let pointer = craft_ui::runtime::pointer::hover_point_in(ui.ctx(), rows.response.rect); under_pointer = pointer.and_then(|at| rows.shown.iter().find(|row| row.rect.contains(at)).map(|row| row.key.clone())); events = rows.events; }); diff --git a/crates/imaging/src/ui/select/magnetic.rs b/crates/imaging/src/ui/select/magnetic.rs index 2f49645543..fe15487cd3 100644 --- a/crates/imaging/src/ui/select/magnetic.rs +++ b/crates/imaging/src/ui/select/magnetic.rs @@ -44,7 +44,7 @@ pub trait EdgeTracer { /// The Magnetic Lasso's options bar, persisted by the app (decisions §2.4). The options bar edits /// [`MagneticLassoTool::settings_mut`]; `[` and `]` change `width` ([`step_width`](Self::step_width)): the tool while an /// outline is open, the app's shortcuts otherwise. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::PlainData)] #[serde(rename_all = "camelCase", default)] #[non_exhaustive] pub struct MagneticSettings { diff --git a/crates/imaging/src/ui/warp/cylinder.rs b/crates/imaging/src/ui/warp/cylinder.rs index 5262295371..a11073363e 100644 --- a/crates/imaging/src/ui/warp/cylinder.rs +++ b/crates/imaging/src/ui/warp/cylinder.rs @@ -405,7 +405,7 @@ impl Component for CylinderWarp<'_> { results.push((handle, result.press)); } } - if let Some((hover_pos, press)) = cx.part_if_declared(BODY).map(|result| (result.hover_pos, result.press)) { + if let Some((hover_pos, press)) = cx.part_if_declared(BODY).map(|result| (cx.hover_pos(BODY), result.press)) { let on_surface = hover_pos.is_some_and(|at| self.mesh.surface_at(space.view.to_doc(at)).is_some()); if on_surface { cx.cursor(CursorIcon::Move, craft_behavior::CursorPriority::Part); diff --git a/crates/imaging/src/ui/warp/grid.rs b/crates/imaging/src/ui/warp/grid.rs index 46579dacc8..8f8a764cf3 100644 --- a/crates/imaging/src/ui/warp/grid.rs +++ b/crates/imaging/src/ui/warp/grid.rs @@ -288,7 +288,11 @@ impl<'a> WarpGrid<'a> { None => cx.part_if_declared(SURFACE), }; let Some(result) = found else { continue }; - let (hover_at, press) = (result.hover_pos, result.press); + let hover_at = match point { + Some(index) => cx.hover_pos(POINT.at(index as u64)), + None => cx.hover_pos(SURFACE), + }; + let press = result.press; if hover.is_none() && let Some(at) = hover_at { diff --git a/crates/imaging/src/ui/warp/pin/overlay.rs b/crates/imaging/src/ui/warp/pin/overlay.rs index 31605062b6..78cbfb7b92 100644 --- a/crates/imaging/src/ui/warp/pin/overlay.rs +++ b/crates/imaging/src/ui/warp/pin/overlay.rs @@ -353,7 +353,7 @@ impl PinWarp<'_> { fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, pins: &[Pin]) { for i in 0..pins.len() { let Some(result) = cx.part_if_declared(PIN.at(i as u64)) else { continue }; - let (press, hovered, hover_pos) = (result.press, result.hovered, result.hover_pos); + let (press, hovered, hover_pos) = (result.press, result.hovered, cx.hover_pos(PIN.at(i as u64))); if hovered { self.report.hovered = Some(i); self.report.pointer = hover_pos.map(|at| space.view.to_doc(at)); @@ -370,7 +370,7 @@ impl PinWarp<'_> { } } let Some(result) = cx.part_if_declared(MESH) else { return }; - let (press, hovered, hover_pos) = (result.press, result.hovered, result.hover_pos); + let (press, hovered, hover_pos) = (result.press, result.hovered, cx.hover_pos(MESH)); if hovered && self.report.pointer.is_none() { self.report.pointer = hover_pos.map(|at| space.view.to_doc(at)); } diff --git a/crates/layers/tests/it/panel_memo.rs b/crates/layers/tests/it/panel_memo.rs index 0de36e2fd3..e733658654 100644 --- a/crates/layers/tests/it/panel_memo.rs +++ b/crates/layers/tests/it/panel_memo.rs @@ -4,7 +4,7 @@ use craft_layers::ui::filter::{FilterBy, LayerFilter}; use craft_layers::ui::mock::FakeLayers; use craft_layers::ui::panel::{LayersEvent, LayersPanel}; use craft_ui::contract::{Bind, MemoProps, MemoView, Outbox, Tracked}; -use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, pointer, trial}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_runs, pointer, trial}; use egui::{Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -73,6 +73,11 @@ impl Rig { (count(MemoRun::Ran), count(MemoRun::Replayed)) } + /// The real runs in the last pass of the memoized views whose type name holds `name`. + fn real_runs(&self, name: &str) -> u32 { + last_pass_memo_runs(self.fixture.ctx()).iter().filter(|(ty, _, run)| ty.contains(name) && *run == MemoRun::Ran).count() as u32 + } + /// One frame with no input, after the edit of the trial. fn frame(&mut self) -> &mut Self { self.fixture.frame(Vec::new()); @@ -184,7 +189,9 @@ fn a_pointer_over_the_rows_replays_the_blend_rows() { } } -/// A new blend mode on the active layer runs the blend rows, so they never show a stale value. +/// A new blend mode on the active layer runs the blend rows, so they never show a stale value. The edit is a new +/// version of the panel's view, so the header measures its content afresh in the frame's one pass: the blend rows run +/// in that measuring run and once more in the real run. #[trial] fn the_active_layers_blend_mode_runs_the_blend_rows() { let mut rig = rig(FakeLayers::fifty()); @@ -195,7 +202,9 @@ fn the_active_layers_blend_mode_runs_the_blend_rows() { layer.info.blend_key = String::from("multiply"); } rig.frame(); - assert_eq!(rig.view_runs("BlendProps").0, 1, "the edit runs the blend rows"); + assert_eq!(rig.fixture.passes(), 1, "the edit runs one pass"); + assert_eq!(rig.real_runs("BlendProps"), 1, "the edit runs the blend rows in the real run"); + assert!(rig.view_runs("BlendProps").0 <= 2, "and at most once more, in the header's measuring run"); rig.frame(); assert_eq!(rig.host_runs(), (0, 1), "and the panel replays after it"); } diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 3d1204ce5e..a852119d72 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -202,7 +202,7 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { .zip(&labels.menus) .map(|((menu, title), level)| { // The commands the title holds, for the palette's callout; a built-in has no command of the app. - let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect(); + let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect::>(); let row = MenuTitle::new(title.label.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held); match title.hidden { Some(letter) => row.mnemonic(letter), diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 15543e8d97..8c1260f038 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -47,19 +47,22 @@ fn window(width: f32, pixels_per_point: f32) -> Fixture { let mut fixture = Fixture::new(move |ui| { let bar = Rc::clone(&bar); AppShell::new(WindowKey::main()) - .title_bar(move |ui, _, _: &mut ()| { - let bar = Rc::clone(&bar); - let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; - TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled( - ui, - Title::new(DOCUMENT), - move |ui, _| { - Picture::new("", 7, &brand).show(ui); - MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui); - }, - |_, _| {}, - ); - }) + .title_bar( + |_| None, + move |ui, _, _: &mut ()| { + let bar = Rc::clone(&bar); + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled( + ui, + Title::new(DOCUMENT), + move |ui, _| { + Picture::new("", 7, &brand).show(ui); + MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui); + }, + |_, _| {}, + ); + }, + ) .body(|ui, _, _| { ui.label("Document"); }) diff --git a/crates/pages/src/ui/table/size_picker.rs b/crates/pages/src/ui/table/size_picker.rs index edd1d67b6d..35e9304f07 100644 --- a/crates/pages/src/ui/table/size_picker.rs +++ b/crates/pages/src/ui/table/size_picker.rs @@ -186,7 +186,7 @@ impl Component for TableSizePicker { } fn update(&mut self, cx: &mut Cx<'_, Self>) { - let pointer = (0..ROWS * COLUMNS).find(|&index| cx.hover_pos(Self::part(index)).is_some()); + let pointer = (0..ROWS * COLUMNS).find(|&index| cx.part_if_declared(Self::part(index)).is_some_and(|result| result.hovered)); let focused = cx.active_part().and_then(|part| (0..ROWS * COLUMNS).find(|&index| Self::part(index) == part)).filter(|_| cx.focus_visible()); self.lead = pointer.or(focused).or_else(|| self.preset_index()); self.picked = (0..ROWS * COLUMNS).find(|&index| cx.part_activated(Self::part(index)).is_some()); diff --git a/crates/proof/src/tests.rs b/crates/proof/src/tests.rs index 15f3c3c75f..04da0307c8 100644 --- a/crates/proof/src/tests.rs +++ b/crates/proof/src/tests.rs @@ -627,11 +627,47 @@ fn mixed_language_paragraphs_check_each_run_in_its_language() { assert!(v.iter().all(|i| i.lang == ProofLang::It && i.message == "Possibile errore di ortografia"), "{v:?}"); } +/// Every [`ProofLang`], for `mixed_spans_never_panic` to draw from. `fr` stands for the +/// [`ProofLang::Pack`] languages (and runs the French grammar rules, which need no dictionary). +fn every_lang() -> Vec { + use ProofLang as L; + // Stops compiling when a language is added: add it to the list below too. + let _ = |l: L| match l { + L::En | L::EnGb | L::EnAu | L::EnCa | L::Pl | L::Bg | L::Pt | L::It | L::Hr | L::Tr | L::Ru | L::Cs | L::Id => (), + L::Es | L::EsMx | L::Es419 | L::EsUy | L::Gu | L::Hi | L::De | L::Pack(_) | L::Other => (), + }; + let fr = ProofLang::from_tag(Some("fr")); + assert!(matches!(fr, L::Pack(_)), "{fr:?}"); + vec![ + L::En, + L::EnGb, + L::EnAu, + L::EnCa, + L::Pl, + L::Bg, + L::Pt, + L::It, + L::Hr, + L::Tr, + L::Ru, + L::Cs, + L::Id, + L::Es, + L::EsMx, + L::Es419, + L::EsUy, + L::Gu, + L::Hi, + L::De, + fr, + L::Other, + ] +} + proptest::proptest! { #[test] - fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, 0u8..16), 0..6)) { - let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Hi, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; - let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), langs[l as usize % langs.len()])).collect(); + fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, proptest::sample::select(every_lang())), 0..6)) { + let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), l)).collect(); for i in check_text(&s, &spans) { proptest::prop_assert!(i.start <= i.end && i.end <= s.len()); } diff --git a/crates/text/src/ui/path_text.rs b/crates/text/src/ui/path_text.rs index 78debe5b01..8d494cc947 100644 --- a/crates/text/src/ui/path_text.rs +++ b/crates/text/src/ui/path_text.rs @@ -358,7 +358,7 @@ impl<'a> PathTextMarkers<'a> { let mut held: Option = *cx.press_slot::(); for (reference, part) in self.pointer_parts() { let Some(result) = cx.part_if_declared(reference) else { continue }; - let (press, hover) = (result.press, result.hover_pos.filter(|_| result.hovered)); + let (press, hover) = (result.press, cx.hover_pos(reference)); if let Some(pos) = hover && held.is_none() { diff --git a/crates/timeline/src/ui/panel.rs b/crates/timeline/src/ui/panel.rs index bb02570965..709dd4535f 100644 --- a/crates/timeline/src/ui/panel.rs +++ b/crates/timeline/src/ui/panel.rs @@ -602,7 +602,8 @@ impl Timeline<'_, M> { show_pane(ui, *side, indices); } if both { - let split = SplitArea::pair(words.tracks.clone(), Axis::Y, (Side::Upper, Side::Lower), share, rules) + // The rules read nothing that changes: their revision is fixed. + let split = SplitArea::pair(words.tracks.clone(), Axis::Y, (Side::Upper, Side::Lower), share, rules, 0) .divider_label(words.divider.clone()) .show(ui, |ui, body| { for (side, rect) in body.group_frames::() { diff --git a/crates/timeline/src/ui/view.rs b/crates/timeline/src/ui/view.rs index 47bee7cf0c..432e88e494 100644 --- a/crates/timeline/src/ui/view.rs +++ b/crates/timeline/src/ui/view.rs @@ -488,11 +488,10 @@ impl Component for TimelineView<'_> { return; } let mut next = target; - let pointer = cx.response.hover_pos().unwrap_or_else(|| cx.rect.center()); let left = cx.flow.span(self.inset(), width).left(); if let Some(wheel) = cx.take_wheel() { // The wheel's own point: over a child (the ruler) the view itself has no hover. - let pointer = wheel.at.unwrap_or(pointer); + let pointer = wheel.at.unwrap_or_else(|| cx.rect.center()); let at = next.time_at(pointer.x.max(left), left); self.wheel(wheel, &mut next, at, width); } diff --git a/crates/ui-canvas/src/canvas/crop/mod.rs b/crates/ui-canvas/src/canvas/crop/mod.rs index 1a6318a629..58c2b89713 100644 --- a/crates/ui-canvas/src/canvas/crop/mod.rs +++ b/crates/ui-canvas/src/canvas/crop/mod.rs @@ -744,7 +744,7 @@ impl Component for CropOverlay<'_> { None => craft_behavior::PartRef { key, index: None }, }; let Some(result) = cx.part_if_declared(part) else { continue }; - let (press, hover) = (result.press, result.hover_pos); + let (press, hover) = (result.press, cx.hover_pos(part)); let mods = press.mods; match press.phase { PressPhase::Down { start, .. } if start.button == PointerButton::Primary => { @@ -796,8 +796,10 @@ impl Component for CropOverlay<'_> { } self.report.hovered = (0..=8) .filter_map(frame_part) - .find(|part| cx.hover_pos(craft_behavior::PartRef { key: FRAME, index: Some(part.index()) }).is_some()) - .or_else(|| [TURN, OUTSIDE].into_iter().find_map(|key| cx.hover_pos(key)).map(|_| BoxPart::Outside)); + .find(|part| cx.part_if_declared(craft_behavior::PartRef { key: FRAME, index: Some(part.index()) }).is_some_and(|result| result.hovered)) + .or_else(|| { + [TURN, OUTSIDE].into_iter().any(|key| cx.part_if_declared(key).is_some_and(|result| result.hovered)).then_some(BoxPart::Outside) + }); self.run_keys(cx, &space, &frame, live.drag.is_some()); if live.drag.as_ref().is_some_and(|drag| matches!(drag.kind, Kind::Move)) { cx.cursor(CursorIcon::Grabbing, CursorPriority::Drag); diff --git a/crates/ui-canvas/src/canvas/crop/shield.rs b/crates/ui-canvas/src/canvas/crop/shield.rs index 3437a443d8..a5fb71890e 100644 --- a/crates/ui-canvas/src/canvas/crop/shield.rs +++ b/crates/ui-canvas/src/canvas/crop/shield.rs @@ -13,7 +13,7 @@ const SHIELD_OPACITY: f32 = 75.0; const SHIELD_EDITING: f32 = 0.5; /// The shield's colour. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ShieldColor { @@ -25,7 +25,7 @@ pub enum ShieldColor { } /// The crop gear menu's shield options. Photoshop's defaults: shown, enabled, Match Canvas, 75 %, Auto Adjust on. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, craft_ui_macros::PlainData)] #[serde(default)] #[non_exhaustive] pub struct CropShield { diff --git a/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs b/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs index 66aca9312e..6fa886e3b9 100644 --- a/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs +++ b/crates/ui-canvas/src/canvas/full_window_parts/canvas.rs @@ -273,7 +273,12 @@ impl<'a> FullWindowCanvas<'a> { let event = EditEvent::set(Mixed::Same(given), next, name.clone(), None); let _ = bind.write(cx, &event); } - let hover = output.response.hover_pos().filter(|_| output.response.hovered()).map(|at| next.view().to_doc(at)); + let hover = output + .response + .hovered() + .then(|| crate::runtime::pointer::hover_point_in(ui.ctx(), output.response.rect)) + .flatten() + .map(|at| next.view().to_doc(at)); FullWindowCanvasOutput { response: output.response, hover, tool: hosted } }); root.inner.unwrap_or_else(|| FullWindowCanvasOutput { response: root.output, hover: None, tool: ToolHostResponse::default() }) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 829a8d0052..5cf649d97b 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -960,7 +960,7 @@ impl ToolPass { /// in each pass the pointer should stay hidden, and stops asking when it moves. A measuring run publishes no pass, /// so only the real run asks. pub fn hide_pointer(&self, ui: &egui::Ui) { - if ui.ctx().pointer_hover_pos().is_some_and(|at| self.rect.contains(at)) { + if crate::runtime::pointer::hover_point_in(ui.ctx(), self.rect).is_some() { let hidden = craft_behavior::Cursor::Painted(craft_behavior::PaintedCursor::Hidden); crate::runtime::cursor::request(ui.ctx(), hidden, CursorPriority::Hidden); } diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 76f1c9c2aa..f9accf00ee 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -79,6 +79,10 @@ pub(super) struct BodyHooks<'b> { overflow: f32, /// The room the mount offers, in which a content-sized body runs. room: Vec2, + /// What the view of a scroll area around the container shows along x from the container's start + /// (`layout::view_room`), where that view scrolls along x and leaves the container's width unbounded: the rows of + /// its body shrink to it. + view_room: Option, open: bool, open_at_read: bool, open_bound: bool, @@ -205,6 +209,7 @@ impl<'b> BodyHooks<'b> { least_width: 0.0, overflow: 0.0, room: Vec2::ZERO, + view_room: None, open: true, open_at_read: true, open_bound: false, diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 8df6413bfd..fecf57cb3c 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -302,18 +302,17 @@ impl ShapeHooks for BodyHooks<'_> { self.overflow } - fn extent(&mut self, comp: &C, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { + fn extent(&mut self, comp: &C, ui: &Ui, env: &Env, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { let props = comp.props(Internal::new()); - self.room = self.mount_room(props, ui, id, at, scx.tokens); - let env = Env::of(ui); - self.given = self.given_axes(props, &env, at); + self.room = self.mount_room(props, (ui, env), id, at, scx.tokens); + self.given = self.given_axes(props, env, at); self.fixed_height = self.fixed_height(props, at); - self.passes = self.passes_width(props, &env, at); - self.held = self.held(props, &env); + self.passes = self.passes_width(props, env, at); + self.held = self.held(props, env); self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); - self.in_column = label::in_column(ui); + self.in_column = label::in_column(ui, env); self.egui_cell = env.egui_cell; - self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id); + self.given.1 |= self.given_room(props, env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; let room = self.room.x - 2.0 * self.pads(props, scx.tokens).x; @@ -382,10 +381,10 @@ impl ShapeHooks for BodyHooks<'_> { self.measured_footer = props.footer.as_ref().and_then(|_| took(sub(id, "footer"))).unwrap_or(Vec2::ZERO); self.measured_end = props.end.as_ref().and_then(|_| took(sub(id, "end"))); self.measured_controls = took(sub(id, "controls")); - self.extent(comp, at.ui, at.at, id, at.scx) + self.extent(comp, at.ui, at.place, at.at, id, at.scx) } - fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { let props = comp.props(Internal::new()); match self.sizing(props) { Sizing::Fill => { @@ -393,32 +392,32 @@ impl ShapeHooks for BodyHooks<'_> { // The available rect, not at least it: a fill child that took the whole room in an earlier pass (a // content-sized layer offers its whole room before the footer is known) must not keep its remembered // size once the room is less. - let room = crate::layout::flow_room(ui); + let room = crate::layout::flow_room(ui, place); let (x, y) = ( - crate::layout::fill_size(ui, id, Axis::X, size.x, room.x, self.given.0), - crate::layout::fill_size(ui, id, Axis::Y, size.y, room.y, self.given.1), + crate::layout::fill_size(ui, place, id, Axis::X, size.x, room.x, self.given.0), + crate::layout::fill_size(ui, place, id, Axis::Y, size.y, room.y, self.given.1), ); Vec2::new(x, y) } Sizing::FillWidth => { - let room = crate::layout::flow_fill_room(ui).x; + let room = crate::layout::flow_fill_room(ui, place).x; // A fill-width child held in a content column is not given the width (it never sets the column's // width) but shows across the column. It widens to the column it is held in, never past it, and only // where it is shown: its measure never sets the column's width. - let held = !self.given.0 && self.held(props, &Env::of(ui)); - let room = if held { room.min(crate::layout::flow_room(ui).x) } else { room }; + let held = !self.given.0 && self.held(props, place); + let room = if held { room.min(crate::layout::flow_room(ui, place).x) } else { room }; // Given the height of the row line it sits on, it fills that line (`given_axes`). let height = if self.given.1 { - crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, crate::layout::flow_room(ui).y, true) + crate::layout::fill_size(ui, place, id, craft_behavior::Axis::Y, size.y, crate::layout::flow_room(ui, place).y, true) } else { size.y }; - Vec2::new(crate::layout::fill_size(ui, id, craft_behavior::Axis::X, size.x, room, self.given.0 || held), height) + Vec2::new(crate::layout::fill_size(ui, place, id, craft_behavior::Axis::X, size.x, room, self.given.0 || held), height) } // Its content's width, and the height as `Fill` takes it. Sizing::FillHeight => { - let room = crate::layout::flow_room(ui); - Vec2::new(size.x, crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, room.y, self.given.1)) + let room = crate::layout::flow_room(ui, place); + Vec2::new(size.x, crate::layout::fill_size(ui, place, id, craft_behavior::Axis::Y, size.y, room.y, self.given.1)) } Sizing::Content => size, } @@ -523,7 +522,7 @@ impl ShapeHooks for BodyHooks<'_> { .vertical(vertical) .horizontal(horizontal) .scrolls(true) - .gated(crate::runtime::env::Env::of(pcx.ui).wheel == crate::runtime::env::WheelScope::Gated) + .gated(pcx.measure.scope.wheel == crate::runtime::env::WheelScope::Gated) .notch(notch) .room(WheelRoom::new(positive, negative)), ); @@ -960,7 +959,8 @@ impl BodyHooks<'_> { let props = Arc::clone(&self.props); let ctx = at.ui.ctx(); let pad = self.frame_size(&props, at.scx.tokens, top_band(&props, ctx, id, at.scx.tokens)); - let record = |key: Id, took: Vec2| layout_memory::emit_record(ctx, key, layout_memory::Measured::new(self.room, took)); + let room = self.keyed_room(); + let record = |key: Id, took: Vec2| layout_memory::emit_record(ctx, key, layout_memory::Measured::new(room, took)); record(id, self.body_size.unwrap_or(Vec2::ZERO)); if let Some(first) = self.first_line { record(sub(id, "first"), Vec2::new(0.0, first)); @@ -1637,12 +1637,10 @@ impl BodyHooks<'_> { let (ctx, id) = (run.ctx, run.id); 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); - } let extent = region_ui.min_rect().size(); if lays_out { let placed = crate::runtime::lazy::placed(ctx, id); + crate::contract::run::draw_bar_rules(®ion_ui, &placed.line); let keeps = !self.scroll_bound && !self.follows_end; follow_anchor(ctx, (&placed, scroll, keeps), (extent, seen.size()), (&mut self.offset, self.offset_at_read), &mut self.anchor); aim_glide(&mut self.glide, placed.reveal, shown, (extent, seen.size()), scroll); @@ -1900,7 +1898,7 @@ impl BodyHooks<'_> { _ => false, }; if !flows && at.ui.is_sizing_pass() { - return Err(self.extent(comp, at.ui, at.at, cx.core.id, at.scx)); + return Err(self.extent(comp, at.ui, at.place, at.at, cx.core.id, at.scx)); } let id = cx.core.id; let open = if self.open_given { self.open } else { open_now(comp, &mut *cx.core.memory, id, props) }; @@ -1933,8 +1931,9 @@ impl BodyHooks<'_> { self.least_width = least_of(&at.env.tokens, props.least_width); self.room = match at.width { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), - None => self.mount_room(&props, at.ui, id, at.at, at.scx.tokens), + None => self.mount_room(&props, (at.ui, at.place), id, at.at, at.scx.tokens), }; + self.view_room = crate::layout::view_room(at.ui, at.place, craft_behavior::Axis::X).filter(|_| self.room.x.is_infinite()); self.given = self.given_axes(&props, at.env, at.at); self.given.1 |= self.given_room(&props, at.env, at.at, at.ui.ctx(), id); self.fixed_height = self.fixed_height(&props, at.at); @@ -1945,27 +1944,28 @@ impl BodyHooks<'_> { if let Some(ColumnSweep::Column(_, width)) = at.env.column.filter(|_| self.across && at.width.is_none()) { self.room.x = width; } - self.in_column = label::in_column(at.ui); + self.in_column = label::in_column(at.ui, at.place); self.egui_cell = at.env.egui_cell; // A body that fills the main axis of the body it sits in is measured and shown at its share of it. The first // sweep of that body's measuring run only counts it: its contents run in the second sweep, at the share. let (x, y) = (craft_behavior::Axis::X, craft_behavior::Axis::Y); // Along an axis the flow does not bound it fills nothing (`sized`): it measures its content there. In a `Stack` // body that scrolls along y it shares what the view shows. - let bounded = crate::layout::flow_room(at.ui); - let scrolled_y = !bounded.y.is_finite() && crate::layout::shares_y(at.ui) && crate::layout::view_room(at.ui, y).is_some(); + let bounded = crate::layout::flow_room(at.ui, at.place); + let scrolled_y = !bounded.y.is_finite() && crate::layout::shares_y(at.place) && crate::layout::view_room(at.ui, at.place, y).is_some(); let (fills_x, fills_y) = (self.given.0 && bounded.x.is_finite(), self.given.1 && (bounded.y.is_finite() || scrolled_y)); if flows && at.ui.is_sizing_pass() - && ((fills_x && crate::layout::counting_fills(at.ui, x)) || (fills_y && crate::layout::counting_fills(at.ui, y))) + && ((fills_x && crate::layout::counting_fills(at.ui.ctx(), at.place, x)) + || (fills_y && crate::layout::counting_fills(at.ui.ctx(), at.place, y))) { return Err(Vec2::ZERO); } - if let Some(share) = crate::layout::fill_share(at.ui, x).filter(|_| flows && self.given.0) { + if let Some(share) = crate::layout::fill_share(at.place, x).filter(|_| flows && self.given.0) { self.room.x = share; } let mut scrolled_share = false; - if let Some(share) = crate::layout::fill_share(at.ui, y).filter(|_| flows && self.given.1) { + if let Some(share) = crate::layout::fill_share(at.place, y).filter(|_| flows && self.given.1) { self.room.y = share; scrolled_share = scrolled_y; } diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index b4d946fb53..cf105361db 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -15,8 +15,9 @@ use craft_behavior::layout_memory::measure_tolerance; use egui::{Context, Id, Rect, Ui, Vec2}; use std::sync::Arc; -/// The inputs a body's measuring run measures under. A later pass offering the same takes the body's kept -/// transcript (`layout_memory::kept_serves`); its real run checks that the content is the same. +/// The inputs a body's measuring run measures under, the content version of the memoized view it runs in among them +/// (`EnvFacts::view`). A later pass offering the same takes the body's kept transcript (`layout_memory::kept_serves`); +/// its real run checks that the content is the same. #[derive(Clone, PartialEq)] pub(super) struct MeasureKey { props: MeasuredProps, @@ -63,6 +64,8 @@ pub(crate) struct EnvFacts { measure: Option, grid: Option, egui_cell: bool, + /// The content version of the memoized view the body runs in (`Scoped::view_version`). + view: Option, } impl EnvFacts { @@ -84,6 +87,7 @@ impl EnvFacts { measure: env.measure, grid: env.grid, egui_cell: env.egui_cell, + view: env.view_version, } } } @@ -93,7 +97,7 @@ impl<'b> BodyHooks<'b> { pub(super) fn measure_key(&self, env: &Env, width: Option) -> MeasureKey { MeasureKey { props: MeasuredProps(Arc::clone(&self.props)), - room: self.room, + room: self.keyed_room(), given: self.given, wide: self.wide(), width, @@ -103,6 +107,15 @@ impl<'b> BodyHooks<'b> { } } + /// The room the body's measure keys on, its records and its kept transcript: the room the mount offers, and along + /// x, where that is unbounded in a view that scrolls along x, what the view shows from the container's start, to + /// which the rows of the body shrink before the view scrolls (`layout::view_room`). A measure laid out in another + /// view (a parent's measuring run in no room, a wider window) then serves only under the reuse rule + /// (`Measured::serves`): its content did not reach the view's room then and fits it now. + pub(super) fn keyed_room(&self) -> Vec2 { + Vec2::new(self.view_room.unwrap_or(self.room.x), self.room.y) + } + /// How the container's size follows its content here: a pane or a rect the host gives is filled; a layer sizes /// from its content until the user sizes it; an inline container follows its props. pub(super) fn sizing(&self, props: &ContainerProps) -> Sizing { @@ -230,8 +243,9 @@ impl<'b> BodyHooks<'b> { } /// What the regions took together, padding included, from the records a measuring run left in this pass, when they - /// serve a run offered `self.room`: on each axis the room equals the recorded one, or the container is not given - /// that axis, took less than the recorded room (the room did not bound it) and fits in the room now. + /// serve a run offered its keyed room (`keyed_room`): on each axis the room equals the recorded one, or the + /// container is not given that axis, took less than the recorded room (the room did not bound it) and fits in the + /// room now. pub(super) fn reusable(&self, props: &ContainerProps, ctx: &Context, id: Id, pad: Vec2, tolerance: f32) -> Option { let body = layout_memory::measured(ctx, id)?; let region = @@ -240,7 +254,8 @@ impl<'b> BodyHooks<'b> { (region("header", props.header.is_some()), region("footer", props.footer.is_some()), region("end", props.end.is_some())); let fits = |now: f32, was: f32, given: bool, took: f32| layout_memory::Measured::serves(now, was, given, took, tolerance); let full = self.regions_size(props, body.took, header, footer, end) + pad; - if !(fits(self.room.x, body.room.x, self.wide(), full.x) && fits(self.room.y, body.room.y, self.given.1, full.y)) { + let room = self.keyed_room(); + if !(fits(room.x, body.room.x, self.wide(), full.x) && fits(room.y, body.room.y, self.given.1, full.y)) { return None; } let body = if self.open { body.took } else { Vec2::ZERO }; @@ -305,13 +320,13 @@ impl<'b> BodyHooks<'b> { /// The room the mount offers: a layer's room, unless the host gives it a rect of its own size, else the rect the /// container is shown at, else the room of the flow. `tokens` are the container's own, as its token scope sets them: - /// the layer keeps the inset from the screen edge the host places it with. - pub(super) fn mount_room(&self, props: &ContainerProps, ui: &Ui, id: Id, at: ShowAt, tokens: &UiTokens) -> Vec2 { + /// the layer keeps the inset from the screen edge the host places it with. `env` is the env `ui`'s children are + /// placed under. + pub(super) fn mount_room(&self, props: &ContainerProps, (ui, env): (&Ui, &Env), id: Id, at: ShowAt, tokens: &UiTokens) -> Vec2 { match (overlay_of(props), self.fixed) { (Some(overlay), false) => { - let env = Env::of(ui); - let overlay = &overlay.opened_in(&env); - let room = Self::layer_room(ui.ctx(), &env, overlay).size(); + let overlay = &overlay.opened_in(env); + let room = Self::layer_room(ui.ctx(), env, overlay).size(); // An anchored layer's body runs in the room the anchor leaves on the side it takes, as the host // offers it: a body taller than that scrolls instead of covering the anchor. let ctx = ui.ctx(); @@ -319,7 +334,7 @@ impl<'b> BodyHooks<'b> { let rtl = env.layer_direction().is_rtl(); match crate::contract::overlay::measuring_room( ctx, - &env, + env, id, overlay, own, @@ -336,20 +351,20 @@ impl<'b> BodyHooks<'b> { (Mount::Pane(ShellPane { at: Some(rect), content_extent: true, .. }), _) => rect.size(), (_, ShowAt::Rect(rect)) => rect.size(), (_, ShowAt::Flow) => { - let room = crate::layout::flow_room(ui); + let room = crate::layout::flow_room(ui, env); // A row that shrinks its children to fit gives a body among them a width: it measures and shows // in that room. A body that fills a bounded row takes the rest of it instead. let fills = !self.sizing(props).content_width() && room.x.is_finite(); - let cap = match Env::of(ui).shrink { + let cap = match env.shrink { Some(crate::layout::Shrink::Apply(row)) if !fills => crate::layout::shrink_cap(ui.ctx(), row, id).map(|cap| cap.width), _ => None, }; // A body that fills the height of a `Stack` body that scrolls along y takes a share of what the view // shows (`layout::view_room`): it runs in that room, bounded like a body in a room that does not scroll. - let shares_view = !room.y.is_finite() && self.sizing(props).fills_height() && crate::layout::shares_y(ui); - let y = shares_view.then(|| crate::layout::view_room(ui, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y); + let shares_view = !room.y.is_finite() && self.sizing(props).fills_height() && crate::layout::shares_y(env); + let y = shares_view.then(|| crate::layout::view_room(ui, env, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y); // A body that fills the height of the row line it stands on runs in that line. - let y = self.line_height(props, &Env::of(ui), at).unwrap_or(y); + let y = self.line_height(props, env, at).unwrap_or(y); Vec2::new(cap.map_or(room.x, |cap| room.x.min(cap)), props.room_height.unwrap_or(y)) } }, diff --git a/crates/ui-contract/src/contract/cx/body.rs b/crates/ui-contract/src/contract/cx/body.rs index 4705042554..f776e87dd4 100644 --- a/crates/ui-contract/src/contract/cx/body.rs +++ b/crates/ui-contract/src/contract/cx/body.rs @@ -2,7 +2,7 @@ use crate::contract::label; use crate::contract::{Container, Resolved, Show, SideLabel}; -use crate::runtime::env::{EnvView, Label, Message}; +use crate::runtime::env::{Env, EnvView, Label, Message}; use crate::runtime::memory::{MemoryStage, StageAccess, sealed}; use crate::runtime::overlay::CloseReason; use egui::{Id, Rect, Ui}; @@ -132,7 +132,8 @@ impl<'a> BodyCx<'a> { /// the placement measured: the child (plus the label line when the label stacks), and the label when it is taller. /// `ui` is the body's `Ui`; `key` makes the child's id. pub fn labelled(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C) -> C::Output { - label::flow_leaf(ui, (self.id.with(key), self.resolved.id), (self.resolved.enabled, self.resolved.size), label, side, child, None) + let env = Env::of(ui); + label::flow_leaf((ui, env), (self.id.with(key), self.resolved.id), (self.resolved.enabled, self.resolved.size), label, side, child, None) } /// `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The @@ -160,14 +161,16 @@ impl<'a> BodyCx<'a> { Some(&super::Under::new(under.0, under.1)), ); let show = Box::new(move |ui: &mut Ui, rect: Rect| { + let place = Env::of(ui); let _ = crate::contract::run::show_leaf( &mut Some(crate::contract::Props::id(content, content_id)), ui, - crate::contract::run::ShowAt::Rect(rect), + (crate::contract::run::ShowAt::Rect(rect), place), None, ); }); - label::flow_leaf(ui, (id, self.resolved.id), under, label, side, child, Some(label::Trailing { size, show })) + let env = Env::of(ui); + label::flow_leaf((ui, env), (id, self.resolved.id), under, label, side, child, Some(label::Trailing { size, show })) } } diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index b3323c5ad9..bf269192e0 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -172,8 +172,6 @@ pub struct CxCore<'a> { pub(crate) reset_part: Option, /// The sense the root's egui widget carries, for the forwarding widget of a transformed body. pub(crate) root_sense: Sense, - /// The member of the container's roving group Tab arrives at, set by the group's pick. - 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`). @@ -321,9 +319,10 @@ impl Cx<'_, C> { } /// Names the member of this container's roving group (`ContainerProps.roving`) that Tab arrives at; the - /// first member when none is named. + /// first member when none is named. Called from `finish`, once the body's members have registered, so the arrival + /// is one of this run's members and the run's own record holds it. pub fn roving_arrival(&mut self, member: Id) { - self.core.roving_arrival = Some(member); + focus::name_group_arrival(&self.core.ctx, crate::contract::steps::body_group(self.core.id), (member, None)); } /// Names the member of this container's roving group that the next move starts from, in place of the focused one: diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index 240b1c4a0d..dde9cc0121 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -16,6 +16,9 @@ use std::hash::Hash; pub struct MeasureCx<'a, C: Component> { /// What the inherited context holds that component code may read. pub env: EnvView<'a>, + /// The env `env` views: the env installed for `ui`, in the component's own scope, so its layout facts are those of + /// the place `ui`'s children are shown in. + pub(crate) scope: &'a crate::runtime::env::Env, /// The component's cached style. pub style: &'a C::Style, /// `Common` after step 1. @@ -73,7 +76,7 @@ impl MeasureCx<'_, C> { // The column is an input of this measure call besides its room (step 5 opens the call), and of the calls // around it that measure it. let ctx = self.ui.ctx(); - let width = crate::layout::row_alone_room(self.ui).unwrap_or_else(|| crate::layout::flow_room(self.ui).x); + let width = crate::layout::row_alone_room(self.scope).unwrap_or_else(|| crate::layout::flow_room(self.ui, self.scope).x); let width = layout_memory::read_input(ctx, layout_memory::calls_from(ctx), self.id.with("column_room"), width); Some(width).filter(|width| width.is_finite()) }); @@ -86,7 +89,7 @@ impl MeasureCx<'_, C> { /// Whether the component is a direct child of a `Row` body, a bar's included. A component that could wrap into /// lines keeps its one-line least there, and the row's shrink step decides who gives way. pub fn in_row(&self) -> bool { - crate::layout::row_alone_room(self.ui).is_some() + crate::layout::row_alone_room(self.scope).is_some() } /// The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index 9f31c12991..bce2e0f7f0 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -21,9 +21,10 @@ pub trait Pointer { /// condition. fn part_if_declared(&self, part: impl Into) -> Option<&PartResult>; /// Where the pointer is over `part` this pass, in the component's layer space; `None` when `part` is not hovered. - fn hover_pos(&self, part: impl Into) -> Option { - self.part_if_declared(part).and_then(|result| result.hover_pos) - } + /// The read marks the part as following the pointer (`pointer::follows_pointer`): a memoized view around the + /// component runs on each move over the part, and the pointer-move gate runs a pass for it. A component that only + /// asks whether the part is hovered reads `PartResult::hovered`. + fn hover_pos(&self, part: impl Into) -> Option; /// The component's own press. fn press(&self) -> &PressState; /// The pointer is over the component's own shapes. @@ -110,6 +111,13 @@ impl Pointer for CxCore<'_> { self.results.get(&(part.key, part.index)) } + fn hover_pos(&self, part: impl Into) -> Option { + let result = self.part_if_declared(part)?; + let at = result.hover_pos?; + pointer::follows_part(&self.ctx, self.response.layer_id, result.rect); + Some(at) + } + fn press(&self) -> &PressState { &self.press } @@ -239,6 +247,10 @@ impl Pointer for Cx<'_, C> { self.core.part_if_declared(part) } + fn hover_pos(&self, part: impl Into) -> Option { + self.core.hover_pos(part) + } + fn press(&self) -> &PressState { self.core.press() } diff --git a/crates/ui-contract/src/contract/group.rs b/crates/ui-contract/src/contract/group.rs index 72a725788d..11d39c67e8 100644 --- a/crates/ui-contract/src/contract/group.rs +++ b/crates/ui-contract/src/contract/group.rs @@ -96,7 +96,7 @@ impl GroupHandle { self.with(|state| state.members.iter().find(|(_, member, enabled)| *member == id && *enabled).map(|(value, ..)| value.clone())) } - /// The id of the enabled member registered with `value` last pass. + /// The id of the enabled member registered with `value`: last pass's members until the body runs, this run's after. /// /// For the group form's own code, not for members or body code. #[doc(hidden)] diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index cabba801f8..fd3f6cbcd3 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -107,6 +107,10 @@ const SECTION: craft_behavior::PartKey = craft_behavior::PartKey::new("section") const EDGE: craft_behavior::PartKey = craft_behavior::PartKey::new("items_edge"); /// The sub-node of a toggle cell of an item row; the index is the hash of the row's key and the column. const TOGGLE_CELL: craft_behavior::PartKey = craft_behavior::PartKey::new("toggle_cell"); +/// The hover-only part over an item row's rect; the index is the hash of the row's key. The parts under the pointer +/// (`pointer::parts_under`) name the row it is over, under the row's own shapes, so a memoized view around the +/// collection replays while the pointer moves within one row. +const ROW: craft_behavior::PartKey = craft_behavior::PartKey::new("items_row"); /// The part an item row's own access node stands for in the collection: AccessKit requests on the row's node reach /// the collection under this part, the index being the hash of the row's key. const ITEM_NODE: craft_behavior::PartKey = craft_behavior::PartKey::new("item_node"); @@ -274,6 +278,9 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { pressed: Option<(usize, crate::contract::collection::RowPressed)>, /// The rows above and below the edge-press band declared this pass. edge: Option<(C::Key, C::Key)>, + /// The item rows that declare their `ROW` part this pass: the hash of the row's key, the row and its rect in the + /// rows' view. + row_parts: Vec<(u64, usize, Rect)>, } /// The primary-ness, click count, position in the layout's coordinates and scroll offset of a press on a row. @@ -338,6 +345,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { renaming_at_read: None, pressed: None, edge: None, + row_parts: Vec::new(), } } } diff --git a/crates/ui-contract/src/contract/items/edge.rs b/crates/ui-contract/src/contract/items/edge.rs index b3c6da9be4..a6225f5853 100644 --- a/crates/ui-contract/src/contract/items/edge.rs +++ b/crates/ui-contract/src/contract/items/edge.rs @@ -16,10 +16,15 @@ 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_raw(pcx.measure.ui.ctx()); - let (Some(pos), true) = (frame.pos, frame.mods == rule.mods()) else { return }; + let ctx = pcx.measure.ui.ctx().clone(); + if crate::runtime::pointer::frame_raw(&ctx).mods != rule.mods() { + return; + } let Some(layout) = self.layout.clone() else { return }; let view = self.below_header(pcx.content_rect); + // The band lies at the line nearest the pointer, which the rows then follow. + let screen = crate::runtime::egui::areas::layer_to_screen(&ctx, pcx.measure.ui.layer_id()) * view; + let Some(pos) = crate::runtime::pointer::hover_point_in(&ctx, screen) else { return }; let rtl = pcx.flow.is_rtl(); let at = self.xf.map_or(pos, |map| map.to_layer(pos)); if !view.contains(at) { diff --git a/crates/ui-contract/src/contract/items/geometry.rs b/crates/ui-contract/src/contract/items/geometry.rs index 469a228ced..cb3d61976b 100644 --- a/crates/ui-contract/src/contract/items/geometry.rs +++ b/crates/ui-contract/src/contract/items/geometry.rs @@ -1,9 +1,9 @@ //! Where rows sit: the rows' rect and scroll range, which rows a pass builds, and rows on the screen. -use super::ItemsHooks; -use crate::contract::{Collection, Cx}; -use craft_behavior::{Flow, ItemLayout, ScrollPos, SelectionModel}; -use egui::{Pos2, Rect}; +use super::{ItemsHooks, ROW}; +use crate::contract::{Collection, Cx, PartsCx}; +use craft_behavior::{Flow, HitLevel, HitPriority, ItemLayout, ScrollPos, SelectionModel}; +use egui::{Context, Id, Pos2, Rect}; impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { /// The rect of the rows: the content rect below the header row. @@ -15,6 +15,20 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { self.below_header(cx.core.content_rect) } + /// Declares each item row's `ROW` part over its rect in the rows' view: hover only, above the collection's + /// background and below its other parts and every row's own shapes. + pub(super) fn row_parts(&self, pcx: &mut PartsCx<'_, C>) { + for &(hash, _, rect) in &self.row_parts { + pcx.part(ROW.at(hash), rect).exact_hit().priority(HitPriority::new(HitLevel::Background, 1)); + } + } + + /// The item row whose `ROW` part, of the collection `id`, contains the pointer this pass, on top or not. + pub(super) fn row_under_pointer(&self, ctx: &Context, id: Id) -> Option { + let part = crate::runtime::pointer::parts_under(ctx, id).into_iter().find(|part| part.key == ROW)?; + self.row_parts.iter().find(|(hash, ..)| part.index == Some(*hash)).map(|&(_, at, _)| at) + } + /// Whether the scroll bar shows over the rows' rect `view`: the rows scroll and run past its height. pub(super) fn shows_bar(&self, view: Rect) -> bool { self.scrolls && self.content.y > view.height() diff --git a/crates/ui-contract/src/contract/items/header.rs b/crates/ui-contract/src/contract/items/header.rs index f3f9cdfdec..b14caee5d9 100644 --- a/crates/ui-contract/src/contract/items/header.rs +++ b/crates/ui-contract/src/contract/items/header.rs @@ -621,7 +621,7 @@ impl Header { } } 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())); + self.ask_menu(&ctx, Some(key.clone()), crate::runtime::pointer::frame_raw(&ctx).pos.unwrap_or(rect.left_bottom())); } if movable && primary && matches!(phase, PressPhase::DragStart { .. }) { cx.start_drag(ColumnDrag { table: id, key: key.clone() }, DragPreview::None); @@ -668,7 +668,7 @@ impl Header { && cx.part(ROOM).hovered && crate::runtime::pointer::frame_raw(&ctx).release == Some(PointerButton::Secondary) { - self.ask_menu(&ctx, None, ctx.pointer_latest_pos().unwrap_or(room.left_bottom())); + self.ask_menu(&ctx, None, crate::runtime::pointer::frame_raw(&ctx).pos.unwrap_or(room.left_bottom())); } self.column_drop(cx, id, rtl); self.keyboard_resize(cx); diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 128e3fe3b3..d2d58f3264 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -187,13 +187,13 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { Self::props_pad(comp, tokens) } - fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { let sizing = comp.props(Internal::new()).sizing; // A collection that measured its width from its content takes that width; the column it sits in holds it. let width = if self.content_sized(comp) || self.from_content.0 { size.x } else { - crate::layout::body::fill_size(ui, id, Axis::X, size.x, self.room.x, true) + crate::layout::body::fill_size(ui, place, id, Axis::X, size.x, self.room.x, true) }; let height = match (self.scrolls && self.room.y.is_finite(), sizing) { (true, Sizing::Fill | Sizing::FillHeight) if !self.from_content.1 && !self.capped => self.room.y, @@ -211,7 +211,14 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let mut layout = self.layout.take()?; Arc::make_mut(&mut layout).set_view(view.size(), offset); let (_, order) = self.built(&layout, view, offset); - let rects = order.into_iter().map(|at| (self.source.key(at), self.screen(&layout, view, at, offset, rtl))).collect(); + let rects: Vec<(C::Key, Rect)> = order.iter().map(|&at| (self.source.key(at), self.screen(&layout, view, at, offset, rtl))).collect(); + self.row_parts.clear(); + for (&at, (key, rect)) in order.iter().zip(&rects) { + let shown = rect.intersect(view); + if !self.source.section_stop(at) && shown.is_positive() { + self.row_parts.push((key_hash(key), at, shown)); + } + } self.layout = Some(layout); Some(Rc::new(Rows { rects, offset, view: clear })) } @@ -219,6 +226,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { fn parts(&mut self, comp: &mut C, _: Rect, pcx: &mut PartsCx<'_, C>) { self.header.parts(pcx, self.offset_x as f32); self.edge_parts(comp, pcx); + self.row_parts(pcx); self.notch = comp.items().wheel_notch(pcx.tokens.typography.body.line_height); if !self.scrolls { return; @@ -304,7 +312,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.marquee_step(comp, cx, &layout, (rect, offset, rtl), &props); } if props.hover_lead != HoverLead::Off { - self.hover_lead(comp, cx, &layout, seen, props.hover_lead); + self.hover_lead(comp, cx, &layout, props.hover_lead); } // The moves a control in the rows left that do not page them (an arrow a region's fallback collection takes) // navigate the rows as the collection's own keys do. @@ -332,7 +340,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.requested_rename(comp, cx, &props, &layout); self.requested_reveal(comp, &layout); self.type_ahead(comp, cx, &layout, lead_at); - self.rest_lead(cx, &layout, seen); + self.rest_lead(cx, &layout); let lead_now = self.lead.key.as_ref().and_then(|key| self.index_of(key)); request::record_lead(&cx.core.ctx, cx.core.id, lead_now); // A collection whose lead item shows the focus ring takes the ring around that item while it is shown, and @@ -454,8 +462,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { // The pointer counts as over a row only while the sensing pass puts it on this collection, so a popup or another // widget above it takes the hover as it does for the rows' parts. let outcome = crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)); - let hover_at = ctx.pointer_latest_pos().filter(|_| outcome.hover.any()); - let over_at = ctx.pointer_latest_pos().filter(|_| outcome.contains); + let under = self.row_under_pointer(&ctx, id); + let hover_at = under.filter(|_| outcome.hover.any()); + let over_at = under.filter(|_| outcome.contains); self.hovered = None; let menu_open = self.drags.menu.is_some() && crate::contract::overlay::container_open::opened_from(&ctx, cx.core.id); // A double click on a column's edge fits the column to its widest cell among the rows built here, in view. @@ -491,8 +500,8 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let state = RowState { dragging: self.drags.grabbed.as_ref() == Some(&key), drop_target: matches!(&self.drags.pending, Some(PendingDrop::Drop(DropAt::Onto(over))) if *over == key), - hovered: hover_at.is_some_and(|pos| row.contains(pos)), - pointer_over: over_at.is_some_and(|pos| row.contains(pos)), + hovered: hover_at == Some(at), + pointer_over: over_at == Some(at), pressed: self.pressed.as_ref().filter(|(held, _)| *held == at).map(|(_, pressed)| pressed.clone()), menu_open: self.drags.menu.as_ref().is_some_and(|request| request.key == key) && menu_open, activated_by_key: self.keyed_activation.as_ref() == Some(&key), @@ -1218,12 +1227,11 @@ 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 (ui, env, scx) = (measuring.ui, measuring.place, measuring.scx); let room = match measuring.at { ShowAt::Rect(rect) => rect.size(), - ShowAt::Flow => crate::layout::flow_room(ui), + ShowAt::Flow => crate::layout::flow_room(ui, env), }; - 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); @@ -1233,7 +1241,7 @@ impl ItemsHooks<'_, '_, C> { // 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); + let held = env.content_column || crate::layout::in_grid_content_column(ui.ctx(), env); 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); @@ -1242,7 +1250,7 @@ impl ItemsHooks<'_, '_, C> { // 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 asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, (ui, env), 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. @@ -1305,14 +1313,15 @@ impl ItemsHooks<'_, '_, C> { 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 }; + let wide = + if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, (ui, env), 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)) + asked.unwrap_or_else(|| self.width_from_content(comp, (ui, env), id, room, item, scx)) } else { 0.0 }; diff --git a/crates/ui-contract/src/contract/items/lead.rs b/crates/ui-contract/src/contract/items/lead.rs index 2a240ae0fd..767901dca5 100644 --- a/crates/ui-contract/src/contract/items/lead.rs +++ b/crates/ui-contract/src/contract/items/lead.rs @@ -193,13 +193,17 @@ 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_raw(&cx.core.ctx).pos.filter(|_| cx.core.response.hovered()) + /// The row under the pointer while it is over the collection and the row can be picked and shows: the row whose + /// `ROW` part contains it. + fn hovered_row(&self, cx: &Cx<'_, C>, layout: &C::ItemLayout) -> Option { + if !cx.core.response.hovered() { + return None; + } + self.row_under_pointer(&cx.core.ctx, cx.core.id).filter(|&row| self.source.enabled(row) && !self.source.is_section(row) && layout.shown(row)) } - /// The row under `pos` (screen space) in the rows' placement `at`: the pointer-to-row mapping of `hover_lead`, - /// which `hover_lead`, the rest check and the drag-select step all call. + /// The row under `pos` (screen space) in the rows' placement `at`: the drag-select step maps the drag session's + /// pointer with it. pub(super) fn row_under(&self, layout: &C::ItemLayout, at: Placement, pos: Pos2) -> Option { let Placement { rect, offset, rtl } = at; let pos = self.xf.map_or(pos, |map| map.to_layer(pos)); @@ -218,13 +222,13 @@ impl ItemsHooks<'_, '_, C> { /// The lead follows a moving pointer over the rows; with `HoverLead::LeadAndSelection` the selection follows the /// lead the way it does for the 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, hover: HoverLead) { + pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, hover: HoverLead) { let moved = crate::runtime::pointer::with_pass_raw(&cx.core.ctx, |pass| pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. }))); if !moved { return; } - let Some(row) = Self::hovered_pos(cx).and_then(|pos| self.row_under(layout, at, pos)) else { return }; + let Some(row) = self.hovered_row(cx, layout) else { return }; if self.lead.key.as_ref() != Some(&self.source.key(row)) { self.move_lead(row, LeadSource::Pointer); if hover == HoverLead::LeadAndSelection { @@ -235,9 +239,9 @@ impl ItemsHooks<'_, '_, C> { /// The pointer resting on the lead row for the tooltip delay reports `CollectionEvent::Rested`, once per lead /// change. Motion inside the row does not restart the timer, as for a tooltip. - pub(super) fn rest_lead(&mut self, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { + pub(super) fn rest_lead(&mut self, cx: &mut Cx<'_, C>, layout: &C::ItemLayout) { let lead = self.lead.key.clone(); - let over = Self::hovered_pos(cx).and_then(|pos| self.row_under(layout, at, pos)); + let over = self.hovered_row(cx, layout); let held = lead.is_some() && self.lead.rested != lead && over.is_some_and(|row| lead.as_ref() == Some(&self.source.key(row))); let (ctx, id) = (cx.core.ctx.clone(), cx.core.id); if crate::contract::overlay::dwell(&ctx, &mut *cx.core.memory, id, "rest", held, crate::contract::tooltip::DELAY) diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index d6f44a3e69..cd75ee16dc 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -40,17 +40,17 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { /// sized from its content: the header's least width, else its largest row's, at least the width it asks for /// (`Collection::ideal_width`), up to `room`. The column it sits in holds it at that width and shows it across /// the width the column settles on. - pub(super) fn width_from_content(&mut self, comp: &C, ui: &Ui, id: Id, room: Vec2, item: Option, scx: &StyleCx<'_>) -> f32 { - let rows = if self.header.has_columns() { self.header.least_width() } else { self.largest_in(comp, ui, id, room).x }; + pub(super) fn width_from_content(&mut self, comp: &C, at: (&Ui, &Env), id: Id, room: Vec2, item: Option, scx: &StyleCx<'_>) -> f32 { + let rows = if self.header.has_columns() { self.header.least_width() } else { self.largest_in(comp, at, id, room).x }; rows.max(comp.ideal_width(item, self.source.len(), scx)).min(room.x) } /// The largest ideal size of the rows in this pass, the sum of their ideal widths, and the widest cell each column's /// items reported: each row is built as `content` builds it, with its column cells at the widths the header /// resolves with no room to share (a fixed or toggle column at its own width), and measured without allocating. - fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { + fn largest_row(&mut self, comp: &C, (ui, env): (&Ui, &Env), id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { let ctx = ui.ctx().clone(); - crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, ui, id)) + crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, (ui, env), id)) } /// Builds the rows once to measure the largest and records it under `sub(id, "largest")` for `extent`, when this @@ -58,7 +58,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { pub(super) fn record_largest(&mut self, comp: &C, at: &Measuring<'_, '_>, id: Id) { let room = match at.at { ShowAt::Rect(rect) => rect.size(), - ShowAt::Flow => crate::layout::flow_room(at.ui), + ShowAt::Flow => crate::layout::flow_room(at.ui, at.place), }; let room = Self::inner_room(comp, &at.env.tokens, room); if self.source.is_empty() || (room.x.is_finite() && !self.content_sized(comp) && !comp.measures_items() && !self.header.has_content_columns()) @@ -66,14 +66,15 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { return; } self.header.measure(at.scx); - self.largest_in(comp, at.ui, id, room); + self.largest_in(comp, (at.ui, at.place), id, room); } /// The largest row in the room `room`: what a record of this pass under `sub(id, "largest")` found when it serves /// the room (`Measured::serves`), else what the measure kept from an earlier pass gives while the items' inputs /// hold, else the rows built and measured now, recorded there and kept. The widest cell of each `Content` column, /// or its header label when wider, is recorded with it (`header::content_id`). The caller measures the header first. - pub(super) fn largest_in(&mut self, comp: &C, ui: &Ui, id: Id, room: Vec2) -> Vec2 { + /// `env` is the env `ui`'s children are placed under. + pub(super) fn largest_in(&mut self, comp: &C, (ui, env): (&Ui, &Env), id: Id, room: Vec2) -> Vec2 { let ctx = ui.ctx().clone(); let key = sub(id, "largest"); let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); @@ -85,7 +86,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { return found.took; } // A kept measure serves only the outermost measuring run, which this opens when none is open. - let inputs = self.items_inputs(comp, ui, room); + let inputs = self.items_inputs(comp, env, room); if let Some(inputs) = &inputs && crate::runtime::measure::measuring(&ctx, || layout_memory::kept_serves(&ctx, key, inputs)) && let Some(found) = found(&ctx) @@ -98,10 +99,9 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { if inputs.is_some() { layout_memory::begin_measure(&ctx, key); } - let (largest, run, cells) = self.largest_row(comp, ui, id); + let (largest, run, cells) = self.largest_row(comp, (ui, env), id); layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(room, largest)); layout_memory::emit_record(&ctx, run_id(id), layout_memory::Measured::new(room, Vec2::new(run, 0.0))); - let env = Env::of(ui); let content: Vec<(usize, craft_behavior::ColumnKey)> = self.header.content_columns().map(|(at, key)| (at, key.clone())).collect(); for (at, column) in content { let widest = cells.iter().find(|(held, _)| *held == column).map_or(0.0, |(_, width)| *width); @@ -118,14 +118,14 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { /// What the items' measure reads besides the rows' content: the room, the item count, the env and what `dress` /// reads of the collection. `None` when the source declares no content version (rows stamp or revision): the rows /// may change unseen, so every pass measures them. - fn items_inputs(&self, comp: &C, ui: &Ui, room: Vec2) -> Option { + fn items_inputs(&self, comp: &C, env: &Env, room: Vec2) -> Option { let content = (comp.items().rows_stamp, self.source.revision()); (content.0.is_some() || content.1.is_some()).then(|| ItemsInputs { room, count: self.source.len(), content, dress: comp.dress_inputs(), - env: EnvFacts::of(&Env::of(ui)), + env: EnvFacts::of(env), }) } @@ -138,9 +138,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { .map_or(0.0, |found| found.took.x) } - fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { + fn largest_row_in(&mut self, comp: &C, (ui, env): (&Ui, &Env), id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let mut memory = MemoryStage::open_peek(&ctx, id); let cells: Vec<(craft_behavior::ColumnKey, Rect)> = self.header.columns(0.0).into_iter().map(|(key, width)| (key, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, 0.0)))).collect(); @@ -152,7 +151,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { continue; } 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)); + let (size, cells) = self.measure_row(comp, ui, (id, env.view(), env), &mut memory, row, |measure, _, _| measure(Proposal::Ideal)); largest = largest.max(size); run += size.x; for (column, width) in cells { diff --git a/crates/ui-contract/src/contract/items/press.rs b/crates/ui-contract/src/contract/items/press.rs index 09f7288dc5..b2566b5879 100644 --- a/crates/ui-contract/src/contract/items/press.rs +++ b/crates/ui-contract/src/contract/items/press.rs @@ -434,7 +434,7 @@ fn item_openers(ui: &Ui, ctx: &Context, id: Id, enabled: bool, openers: Vec(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided { // Read before the child measures: nothing it does there may count as a child placed in flow. - let in_column = in_column(ui); + let in_column = in_column(ui, env); // An egui grid's cell is as wide as the row takes, and the control shows at its ideal width there. let proposal = if at.egui_cell { craft_behavior::Proposal::Ideal } else { craft_behavior::Proposal::Min }; let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), proposal, Some(at.under)).x; @@ -335,13 +335,13 @@ fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: /// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. The first child of an /// unwrapped row that is itself a row of a vertical flow (`Scoped::column_row`) starts where that flow's rows start, -/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. -pub(crate) fn in_column(flow: &Ui) -> bool { +/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. `env` is the +/// env `flow`'s children are placed under. +pub(crate) fn in_column(flow: &Ui, env: &Env) -> bool { if !flow.layout().is_horizontal() { return true; } - let env = Env::of(flow); - env.column_row && crate::layout::at_flow_start(flow.ctx(), &env) + env.column_row && crate::layout::at_flow_start(flow.ctx(), env) } /// A control with its label after it that the label step moved into the control column (its `control` starts past @@ -361,7 +361,7 @@ pub(crate) fn report_after_reach(ctx: &egui::Context, env: &Env, side: &SideLabe /// child's id, `owner` the component whose eviction takes the label scope's facts, and `under` the enabled state and /// size the child inherits. `trailing` is content shown inside the label, after its text. pub(crate) fn flow_leaf( - ui: &mut Ui, + (ui, env): (&mut Ui, Env), (id, owner): (Id, Id), under: (bool, craft_theme::ControlSize), label: Label, @@ -371,28 +371,26 @@ pub(crate) fn flow_leaf( ) -> C::Output { // In a grid the row is the grid's next cell, read under its column's group, as `run` shows any other cell: the // room before the row is the whole grid's, and a row placed there would stand under the one before it. - match crate::layout::grid_cell(ui) { - Some((grid, column, sized)) => { - let ctx = ui.ctx().clone(); - crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || flow_leaf_row(ui, (id, owner), under, label, side, child, trailing, true)) - } - None => flow_leaf_row(ui, (id, owner), under, label, side, child, trailing, false), + let ctx = ui.ctx().clone(); + match crate::layout::grid_cell(&ctx, &env) { + Some((grid, column, sized)) => crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || { + flow_leaf_row((ui, env), (id, owner), under, label, side, child, (trailing, true)) + }), + None => flow_leaf_row((ui, env), (id, owner), under, label, side, child, (trailing, false)), } } -/// `flow_leaf` for a row in the flow of `ui`; `in_cell`: the row is the next cell of the grid around it. -#[expect(clippy::too_many_arguments, reason = "flow_leaf's arguments and whether its row is a grid cell")] +/// `flow_leaf` for a row in the flow of `ui`, whose children are placed under `env`; `in_cell`: the row is the next +/// cell of the grid around it. fn flow_leaf_row( - ui: &mut Ui, + (ui, env): (&mut Ui, Env), (id, owner): (Id, Id), under: (bool, craft_theme::ControlSize), label: Label, side: SideLabel, child: C, - trailing: Option>, - in_cell: bool, + (trailing, in_cell): (Option>, bool), ) -> C::Output { - let env = Env::of(ui); let mut child = child; let under = leaf_under(&env, &side, &child, under); let ideal = crate::contract::run::measure_under(&mut child, &*ui, Some(id), craft_behavior::Proposal::Ideal, Some(&under)); @@ -401,7 +399,7 @@ fn flow_leaf_row( } // A grid's cell; a probe offers it unbounded room, and the row then spans the grid's flow so it has an end edge. let flow = ui.available_rect_before_wrap(); - let avail = match crate::layout::flow_region(ui) { + let avail = match crate::layout::flow_region(ui, &env) { region if in_cell && region.width().is_finite() => region, region if in_cell => Rect::from_min_size(region.min, Vec2::new(flow.width(), region.height())), _ => flow, @@ -438,7 +436,8 @@ fn flow_leaf_row( // below it. let height = (decided_control.bottom().max(decided_label.bottom()) - row.top()).max(ideal.y); let first = decided_control.top() - row.top() + ideal.y / 2.0; - let took = crate::layout::place_in_cell(ui, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true }); + let took = + crate::layout::place_in_cell(ui, &env, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true }); let placed = show_leaf(ui, &env, &at, decided, took.top() - row.top(), trailing); let control = span(placed.control); // A control beside its label in a content-sized column reports how far it reaches past the label column, so @@ -451,10 +450,8 @@ fn flow_leaf_row( report_after_reach(ui.ctx(), &env, &side, (avail, control), extent); } // The child runs under the inside label its measures saw. - let installed = under - .inside - .clone() - .map(|inside| Env::install_for(ui, env.derive_local(|scoped| scoped.inside_label = Some(inside as crate::runtime::env::Held)))); + let inside = under.inside.clone().map(|inside| env.derive_local(|scoped| scoped.inside_label = Some(inside as crate::runtime::env::Held))); + let installed = inside.clone().map(|inside| Env::install_for(ui, inside)); // The control and its label are one member of a bar's line: judged together, and hidden together, as the label // step hid the label. let shown_clip = ui.clip_rect(); @@ -462,8 +459,13 @@ fn flow_leaf_row( if cut { ui.set_clip_rect(Rect::NOTHING); } - let output = - crate::contract::run::show_leaf(&mut Some(crate::contract::Props::id(child, id)), ui, crate::contract::run::ShowAt::Rect(control), None); + let place = inside.unwrap_or_else(|| env.clone()); + let output = crate::contract::run::show_leaf( + &mut Some(crate::contract::Props::id(child, id)), + ui, + (crate::contract::run::ShowAt::Rect(control), place), + None, + ); if cut { ui.set_clip_rect(shown_clip); } @@ -515,7 +517,7 @@ pub(crate) fn show_leaf_in_flow(mut child: C, ui: &mut Ui) -> C::Output let named_by_scope = env.arena.is_none() && scope::in_label(ui.ctx()); let shows = C::LABELLED_AFTER && child.shows_label() && child.common(crate::contract::Internal::new()).label != Label::Empty && !named_by_scope; if !shows { - return crate::contract::run::show_leaf(&mut Some(child), ui, crate::contract::run::ShowAt::Flow, None); + return crate::contract::run::show_leaf(&mut Some(child), ui, (crate::contract::run::ShowAt::Flow, env), None); } let label = std::mem::take(&mut child.common_mut(crate::contract::Internal::new()).label); let facts = crate::contract::run::TypeFacts::of::(); @@ -525,5 +527,6 @@ pub(crate) fn show_leaf_in_flow(mut child: C, ui: &mut Ui) -> C::Output Some(detail) => side.detail(detail), None => side, }; - flow_leaf(ui, (id, id), (env.enabled, env.size), label, side, child, None) + let under = (env.enabled, env.size); + flow_leaf((ui, env), (id, id), under, label, side, child, None) } diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 328fb86710..a89e495b67 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -62,27 +62,29 @@ impl Lazy { /// 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 { - match self.run_keyed(ui, "Lazy", Key::None, |ui, _| add(ui)) { + let env = Env::of(ui); + match self.run_keyed((ui, env), "Lazy", Key::None, |ui, _| add(ui)) { Shown::Ran(out) => Some(out), Shown::Replayed(..) | Shown::OutOfView => None, } } - /// The id of the child in `ui`: under its scroll area, or under `ui`'s scope outside every scroll area. - pub(super) fn id(&self, ui: &Ui) -> egui::Id { - match Env::of(ui).view().lazy_view() { + /// The id of the child in `ui`, whose children are placed under `env`: under its scroll area, or under `ui`'s scope + /// outside every scroll area. + pub(super) fn id(&self, ui: &Ui, env: &Env) -> egui::Id { + match env.view().lazy_view() { Some(view) => sub(view.owner, ("lazy", self.key)), None => sub(ui.scope_id(), ("lazy", self.key)), } } /// 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 { + /// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view. `env` is the + /// env installed for `ui`. + pub(super) fn run_keyed(self, (ui, env): (&mut Ui, Env), name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let view = env.view().lazy_view(); - let id = self.id(ui); + let id = self.id(ui, &env); let rtl = ui.layout().prefer_right_to_left(); let memo = matches!(key, Key::Memo(_)); let sizing = ui.is_sizing_pass(); @@ -94,7 +96,7 @@ impl Lazy { let share = env .shares() .filter(|axis| memo && real && lazy::fills(&ctx, id, sizing) == Some(*axis)) - .and_then(|axis| crate::layout::fill_share(ui, axis).map(|share| (axis, share))); + .and_then(|axis| crate::layout::fill_share(&env, axis).map(|share| (axis, share))); // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a @@ -106,10 +108,10 @@ impl Lazy { _ => None, }; let available = match share { - Some((axis, share)) => share_of(flow_region(ui), rtl, axis, share), - None => cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)), + Some((axis, share)) => share_of(flow_region(ui, &env), rtl, axis, share), + None => cap.map_or_else(|| flow_region(ui, &env), |cap| at_most(flow_region(ui, &env), rtl, cap.width)), }; - let available = if memo { on_row_line(ui, id, available) } else { available }; + let available = if memo { on_row_line(ui, &env, id, available) } else { available }; let owner = view.map(|view| view.owner); // 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)); @@ -122,7 +124,7 @@ impl Lazy { crate::contract::queue_child_reveal(&ctx, view.owner, id); } if let Decision::Skip(size) = lazy::decide(&ctx, id, &view, at, sizing, estimate) { - let (took, _) = take_in_flow(ui, size); + let (took, _) = take_in_flow(ui, &env, size); if real { layout_memory::backstop(&ctx, id, size); lazy::replay(&ctx, id); @@ -141,6 +143,7 @@ impl Lazy { layout, pixels_per_point: ctx.pixels_per_point(), atlas: ctx.fonts(|fonts| fonts.atlas_generation()), + access: crate::runtime::egui::access::builds_nodes(&ctx), opacity: ui.opacity(), env: env.key, flow: env.flow(), @@ -164,7 +167,7 @@ impl Lazy { // 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 fills = if memo && !real { lazy::fills(&ctx, id, sizing) } else { None }; - let took = place_unit(ui, (shrink, fills), id, rect, rtl); + let took = place_unit(ui, &env, (shrink, fills), id, rect, rtl); let kept = if real { layout_memory::backstop(&ctx, id, size); let kept = lazy::replay_settled(&ctx, id, &shift); @@ -200,14 +203,14 @@ impl Lazy { // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. The // content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their // line, cells and shrink step, and a memoized view starts its own room on top of it. - let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env, |child| add(child, &mut run))); + let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env.clone(), |child| add(child, &mut run))); let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); let fills = if memo { crate::layout::take_view_fill(&ctx, id) } else { None }; let record = run.recording.then(|| replay::close(&ctx, place.layer)); if let Some(shift) = audited { - return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); + return place_audit_run(ui, &env, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); } #[cfg(feature = "testing")] if let Some(record) = &record @@ -219,9 +222,9 @@ impl Lazy { layout_memory::backstop(&ctx, id, rect.size()); } if memo { - place_unit(ui, (shrink, fills.filter(|_| !real)), id, rect, rtl); + place_unit(ui, &env, (shrink, fills.filter(|_| !real)), id, rect, rtl); } else { - crate::layout::close_flow_start_in(ui); + crate::layout::close_flow_start(&ctx, &env); alloc::advance_past(ui, rect); } if view.is_some() || memo { @@ -251,11 +254,11 @@ impl Lazy { /// 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 { +fn place_audit_run(ui: &mut Ui, env: &Env, 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); + place_view(ui, env, rect); if let Some(view) = view { lazy::place(&ctx, &view, id, rect); } @@ -334,11 +337,10 @@ fn share_of(region: Rect, rtl: bool, axis: Axis, share: f32) -> Rect { /// Any other view reports its extent to the shrinking row around it: what it takes, in the row's counting sweep, and /// its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows from what it takes /// in no room down to what it takes with every leaf at its least. -fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: egui::Id, rect: Rect, rtl: bool) -> Rect { +fn place_unit(ui: &mut Ui, env: &Env, (shrink, fills): (Option, Option), id: egui::Id, rect: Rect, rtl: bool) -> Rect { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let Some(axis) = fills.filter(|axis| env.shares() == Some(*axis)) else { - let took = place_view(ui, rect); + let took = place_view(ui, env, rect); match shrink { Some(Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, rect.width(), rect.width(), None, (false, None)), Some(Shrink::Least(row)) => crate::layout::report_least(&ctx, row, id, rect.width()), @@ -347,10 +349,10 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: return took; }; let content = rect.size(); - let along = match crate::layout::fill_share(ui, axis) { + let along = match crate::layout::fill_share(env, axis) { Some(share) => Some(share), - None if crate::layout::counting_fills(ui, axis) && !env.least => { - crate::layout::count_fill_view(ui); + None if crate::layout::counting_fills(&ctx, env, axis) && !env.least => { + crate::layout::count_fill_view(&ctx, env); Some(0.0) } None => None, @@ -360,7 +362,7 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: (_, Some(along)) => Vec2::new(content.x, along), (_, None) => content, }; - let took = place_view(ui, Rect::from_min_size(at_start(rect, rtl, size), size)); + let took = place_view(ui, env, Rect::from_min_size(at_start(rect, rtl, size), size)); if let (Axis::X, Some(Shrink::Count(row))) = (axis, shrink) { crate::layout::report_shrink(&ctx, row, id, size.x, size.x, Some((size.x, size.x)), (false, None)); } @@ -370,9 +372,9 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: /// 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() { - crate::layout::close_flow_start_in(ui); +fn place_view(ui: &mut Ui, env: &Env, rect: Rect) -> Rect { + if take_cell(ui, env, rect.size()).is_none() { + crate::layout::close_flow_start(ui.ctx(), env); alloc::advance_past(ui, rect); } rect @@ -381,11 +383,11 @@ fn place_view(ui: &mut Ui, rect: Rect) -> Rect { /// The room of the memoized view `id` in the flow region `room` of `ui`. Its content starts a layout room of its own /// (`Env::start_room`), so it would sit at the top of the unwrapped `Row` around it; as a child placed in flow /// (`place_in_cell`), a view of one line sits with its centre on the row's line instead: its room moves down by the -/// whole pixels that put the centre of the extent it took (in this pass's measuring run, else its last run) there. A -/// view taller than that reaches, and a view no run showed yet, stays at the row's top. The room keeps its size, so a +/// whole pixels that put the centre of the extent it took (in this pass's measuring run, else its last real run) there. +/// A view taller than that reaches, and a view no run measured yet, stays at the row's top. The room keeps its size, so a /// kept run replays moved with it. -fn on_row_line(ui: &Ui, id: egui::Id, room: Rect) -> Rect { - let Some(centre) = Env::of(ui).row_line.and_then(|line| line.centre) else { +fn on_row_line(ui: &Ui, env: &Env, id: egui::Id, room: Rect) -> Rect { + let Some(centre) = env.row_line.and_then(|line| line.centre) else { return room; }; let Some(size) = lazy::last_extent(ui.ctx(), id) else { diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 9734c96127..4b0ac8520d 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -376,6 +376,8 @@ pub struct MemoKey { /// 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, + /// An input the key cannot follow was fed (`changes_every_pass`). + every_pass: bool, } impl std::fmt::Debug for MemoKey { @@ -419,9 +421,20 @@ impl MemoKey { if let Some(ctx) = &self.context { let pass = ctx.cumulative_pass_nr(); self.write(&pass.to_le_bytes()); + self.every_pass = true; } } + /// Whether the key follows every input fed into it: none was fed through `changes_every_pass`. + pub(crate) const fn follows(&self) -> bool { + !self.every_pass + } + + /// Takes the inputs `child` (from `child`) fed that the key cannot follow, once its hash is fed. + pub(crate) fn absorb(&mut self, child: &MemoKey) { + self.every_pass |= child.every_pass; + } + /// Feeds `bytes`. pub fn write(&mut self, bytes: &[u8]) { self.hasher.write(bytes); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index 46a1150b02..5bbb950eb0 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -59,6 +59,11 @@ use std::sync::Arc; /// - 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 key is also its content's version: a container inside measures under it, so a run with a new key measures its +/// bodies afresh, in the first pass, instead of taking what they measured under the last key. A run with the same key +/// (input reached it) takes those measures. A key that holds an input it cannot follow (`changes_every_pass`) gives +/// no version: the containers inside measure as outside any view. +/// /// Its content is a layout room of its own, as a pane's is: the flow of the body around it (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. In a shrinking `Row` it is a unit the row narrows @@ -124,17 +129,29 @@ impl MemoVie let MemoView { lazy, mut props, show } = self; let ctx = ui.ctx().clone(); // In the counting sweep of a shrinking row the view reports what it takes in no room, as a leaf there does. - let counting = matches!(Env::of(ui).shrink, Some(Shrink::Count(_))); - let unbounded = counting.then(|| Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.unbounded.0 = true))); let env = Env::of(ui); - let id = lazy.id(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| { + let (env, unbounded) = if matches!(env.shrink, Some(Shrink::Count(_))) { + let env = env.derive_local(|scoped| scoped.unbounded.0 = true); + let installed = Env::install_for(ui, env.clone()); + (env, Some(installed)) + } else { + (env, None) + }; + let id = lazy.id(ui, &env); + let (key, follows) = Self::key(&ctx, &env, &props, show); + let shown = lazy.run_keyed((ui, env.clone()), 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. It keeps how // that body sizes from its content, whether its leaves fit their room and which axis it shares among the // children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the // same content shown without the view would. - let installed = Env::install_for(ui, env.derive_local(|scoped| scoped.start_view_room(id))); + // Its key is its content's version: a body inside measures under it (`Scoped::view_version`). + let installed = Env::install_for( + ui, + env.derive_local(|scoped| { + scoped.start_view_room(id); + scoped.view_version = follows.then_some(key); + }), + ); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); @@ -159,16 +176,18 @@ impl MemoVie /// 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 { + /// one address differ in their props type or show the same. The flag says whether the key follows every input it + /// holds (`MemoKey::follows`). + fn key(ctx: &egui::Context, env: &Env, props: &P, show: fn(&mut P, &mut Ui) -> R) -> (u128, bool) { 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()); + let (scope, scope_follows) = env.scope_key(); + key.write(&scope.to_le_bytes()); props.key(&mut key); #[cfg(feature = "testing")] crate::runtime::measure::count_memo_key_bytes(ctx, key.bytes()); - key.finish() + (key.finish(), scope_follows && key.follows()) } } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 67e371e030..73411ddff7 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -116,6 +116,7 @@ pub use settle::SettleCx; pub use text::EDIT_MENU; pub use values::{Bind, BindCheck, BindMut, EditResponse, Hover, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed, response_of}; +use crate::runtime::env::Env; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, Flags, StyleCx, StyleKey}; @@ -132,7 +133,6 @@ pub use craft_behavior::ColumnKey; pub use craft_behavior::DropOperation; pub use craft_behavior::MiddleButton; pub use craft_behavior::ReorderKeys; -pub(crate) use run::BarRules; pub(crate) use run::measure_under; #[cfg(feature = "testing")] pub(crate) use steps::queue_reveal; @@ -401,8 +401,9 @@ pub trait Component: Meta + Sized { const BINDS_VIEW: bool = false; /// How a disabled instance looks: token states (the default), or its enabled look faded. const DISABLED: DisabledLook = DisabledLook::States; - /// Whether the component is a rule between groups of members (a divider). In a bar's line a rule shows only when - /// the member after it shows: a rule before a member the bar hides, or with no member after it, is taken back. + /// Whether the component is a rule between groups of members (a divider). In a bar's line the bar draws it, as a + /// divider line along the axis the rule fills, only when the member after it shows: a rule before a member the bar + /// hides, or with no member after it, is not drawn. const RULE: bool = false; /// The style type. @@ -800,17 +801,20 @@ pub trait Show: Component + Meta + sealed::Show { /// Shows the component at `rect`, with no allocation. fn show_at(self, ui: &mut Ui, rect: Rect) -> Self::Output { - run::show_leaf(&mut Some(self), ui, ShowAt::Rect(rect), None) + let place = Env::of(ui); + run::show_leaf(&mut Some(self), ui, (ShowAt::Rect(rect), place), None) } /// Shows the component with rich tooltip content from the same call. fn show_with_tip(self, ui: &mut Ui, tip: impl FnOnce(&mut Ui)) -> Self::Output { - run::show_leaf(&mut Some(self), ui, ShowAt::Flow, Some(Box::new(tip))) + let place = Env::of(ui); + run::show_leaf(&mut Some(self), ui, (ShowAt::Flow, place), Some(Box::new(tip))) } /// Shows the component at `rect` with rich tooltip content. fn show_at_with_tip(self, ui: &mut Ui, rect: Rect, tip: impl FnOnce(&mut Ui)) -> Self::Output { - run::show_leaf(&mut Some(self), ui, ShowAt::Rect(rect), Some(Box::new(tip))) + let place = Env::of(ui); + run::show_leaf(&mut Some(self), ui, (ShowAt::Rect(rect), place), Some(Box::new(tip))) } /// Measures without allocating: steps 1 to 5 under the id `show` would use next. It registers no id, opens no @@ -824,12 +828,14 @@ pub trait Show: Component + Meta + sealed::Show { pub trait ShowContainer: Container + sealed::ShowContainer { /// Shows the container in the flow of `ui`. fn show(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Flow, &mut body, None) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Flow, place), &mut body, None) } /// Shows the container at `rect`, with no allocation: a frame over a split or a layer the parent places. fn show_at(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), &mut body, None) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Rect(rect), place), &mut body, None) } /// Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies @@ -847,7 +853,8 @@ pub trait ShowContainer: Container + sealed::ShowContainer { /// Shows the container with rich tooltip content. fn show_with_tip(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Flow, &mut body, Some(Box::new(tip))) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Flow, place), &mut body, Some(Box::new(tip))) } /// Shows the container at `rect` with rich tooltip content. @@ -858,7 +865,8 @@ pub trait ShowContainer: Container + sealed::ShowContainer { mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui), ) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), &mut body, Some(Box::new(tip))) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Rect(rect), place), &mut body, Some(Box::new(tip))) } } diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index c44e356766..3f9eb1bbbe 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -171,7 +171,9 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U placed.at += nudge.offset(); } let tier = overlay.tier(ctx); - if (sized || layer.size.is_some()) && areas::layer_rect(ctx, area).is_none() { + // A toast or a tooltip shows first at its room, never in egui's hidden sizing pass; a container's layer starts its + // `Area` at its measured size (`LayerSpec::size`). + if sized && areas::layer_rect(ctx, area).is_none() { areas::seed_area(ctx, areas::layer_of(tier, area), placed.at, placed.room); } // A modal's cover: it takes the presses below the modal while the modal is open, and paints the scrim if it has one. @@ -190,7 +192,14 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U }; let parent = overlay::drawing_parent(ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); - let mut spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + let mut spec = LayerSpec { + id: area, + tier, + at: placed.at, + size: layer.size.and(size), + interactable: overlay.rank != Rank::Tooltip && !layer.exiting, + root: None, + }; // A popup's or a modal's layer, and any layer while it fades out, has a root node, made before its `Area` shows so // egui hangs the layer's content below it. A sizing pass of the `Area` reports nothing. if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { @@ -387,7 +396,14 @@ fn show_in_popup( // The layer's content starts from its opener's env, on the popup window's own root: its scale and window facts. let opener = layer.env.capture().env(); let env = Env::root_of(&ctx).map_or_else(|| opener.clone(), |root| opener.rebase(&root)); - let mut spec = LayerSpec { id: area, tier, at: window.min, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + let mut spec = LayerSpec { + id: area, + tier, + at: window.min, + size: layer.size.map(|size| Vec2::new(size.x.max(min_width), size.y)), + interactable: overlay.rank != Rank::Tooltip && !layer.exiting, + root: None, + }; // The layer's root node, made before its `Area` shows, as in `host`. if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { spec.root = areas::content_rect(&ctx, &spec).map(|rect| access::report_layer(&ctx, layer.id, rect, layer.exiting)); diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs index 5ab8b28c67..d11d5f79f7 100644 --- a/crates/ui-contract/src/contract/pages.rs +++ b/crates/ui-contract/src/contract/pages.rs @@ -41,10 +41,10 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { pub fn show(self, ui: &mut Ui, mut page: impl FnMut(&mut Ui, &K) -> R) -> R { let ctx = ui.ctx().clone(); let base = sub(ui.scope_id(), ("pages", self.salt)); - let region = flow_region(ui); - let layout = *ui.layout(); // Each page runs in the env of `ui`, as the direct children of the body around it. let env = Env::of(ui); + let region = flow_region(ui, &env); + 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 kept = lazy::measured(&ctx, id).map(|(size, reads)| { diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 0605417b82..a0a7b6b922 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -211,10 +211,11 @@ impl PaintUi<'_> { } None => env, }; - let installed = Env::install_for(kids, env); + let installed = Env::install_for(kids, env.clone()); // The child sits in a rect its owner chose, and the owner's own measure answers for it: no body's transcript // holds it. - let output = layout_memory::boundary(&ctx, true, || run::show_leaf(&mut Some(super::Props::id(child, id)), kids, ShowAt::Rect(rect), tip)); + let output = + layout_memory::boundary(&ctx, true, || run::show_leaf(&mut Some(super::Props::id(child, id)), kids, (ShowAt::Rect(rect), env), tip)); Env::restore(&ctx, installed); output } diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index bd30301c91..a60b6e138b 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -13,6 +13,7 @@ use crate::runtime::access::{self, Politeness, Role, SetPosition, scope}; use crate::runtime::commands::ResolvedCommand; use crate::runtime::env::{AppValues, ColumnSweep, Env, EnvView, ThemeScope}; use crate::runtime::layout_memory::{Call, Inputs}; +use crate::runtime::lazy::LineItem; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::overlay::CloseReason; use crate::runtime::reads::{self, BindKey, Sample}; @@ -20,7 +21,7 @@ use crate::runtime::{commands, focus, inspect, keys, memory}; use crate::style::{Ink, StateSet, StyleCx, StyleView, UiTokens}; use craft_behavior::{Flow, Input, KeyRole, NavMove, PartRef, PressState, Proposal, Roving, Sense}; use craft_theme::Variant; -use egui::{Context, Id, IdMap, Pos2, Rect, Response, Ui, Vec2}; +use egui::{Context, Id, Pos2, Rect, Response, Ui, Vec2}; use std::any::TypeId; use std::cell::RefCell; use std::collections::HashMap; @@ -85,6 +86,8 @@ pub(crate) struct Measuring<'a, 's> { pub at: ShowAt, /// The width a `Proposal::Width` sets: the room is that wide and unbounded in height. pub width: Option, + /// The env the component's parent installed for `ui`, under which `ui`'s children are placed. + pub place: &'a Env, pub env: &'a Env, pub scx: &'a StyleCx<'s>, pub resolved: &'a Resolved<'s>, @@ -126,8 +129,9 @@ pub(crate) trait ShapeHooks { } /// The size step 6 allocates, from the measured `size`: a body that fills reads the available rect of `ui`: the - /// parent's at step 5, and the host's at step 6 when the host runs the pass in a `Ui` of its own. - fn sized(&self, _comp: &C, _ui: &Ui, _id: Id, size: Vec2) -> Vec2 { + /// parent's at step 5, and the host's at step 6 when the host runs the pass in a `Ui` of its own. `place` is the + /// env `ui`'s children are placed under. + fn sized(&self, _comp: &C, _ui: &Ui, _place: &Env, _id: Id, size: Vec2) -> Vec2 { size } @@ -210,8 +214,9 @@ pub(crate) trait ShapeHooks { 0.0 } - /// What the shape adds to the content size at step 5, before padding and `min_size`. - fn extent(&mut self, _comp: &C, _ui: &Ui, _at: ShowAt, _id: Id, _scx: &StyleCx<'_>) -> Vec2 { + /// What the shape adds to the content size at step 5, before padding and `min_size`. `place` is the env the parent + /// `ui`'s children are placed under. + fn extent(&mut self, _comp: &C, _ui: &Ui, _place: &Env, _at: ShowAt, _id: Id, _scx: &StyleCx<'_>) -> Vec2 { Vec2::ZERO } @@ -219,13 +224,13 @@ pub(crate) trait ShapeHooks { /// inputs only: a body runs its regions in an invisible sizing pass and measures what they took. The default is /// `extent`. fn measured_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Vec2 { - self.extent(comp, at.ui, at.at, cx.core.id, at.scx) + self.extent(comp, at.ui, at.place, at.at, cx.core.id, at.scx) } /// A real pass's step 5 for a body or an item shape: what the shape adds to the content size, from a measuring run /// of its contents in this pass (or the record one left in this pass). The default is `extent`. fn pass_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, _style: &C::Style, _shown: Option>>) -> Vec2 { - self.extent(comp, at.ui, at.at, at.resolved.id, at.scx) + self.extent(comp, at.ui, at.place, at.at, at.resolved.id, at.scx) } /// The width by which the shape's content wants to be wider than the size it measured to, because the room cut @@ -327,15 +332,15 @@ impl ShapeHooks for LeafHooks { (scope != crate::runtime::focus::FocusPolicy::NONE).then_some(scope) } - fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { use craft_behavior::Axis; - let room = crate::layout::leaf_fill_room(ui); + let room = crate::layout::leaf_fill_room(ui, place); // A leaf is given an axis its enclosing body does not size from its content: there it fills, elsewhere it keeps // its measured size, so it never sets that size. - let content = Env::of(ui).content; + let content = place.content; let fill = |measured: f32, offered: f32, along: Axis| { let given = if along == Axis::X { !content.0 } else { !content.1 }; - crate::layout::fill_size(ui, id, along, measured, offered, given) + crate::layout::fill_size(ui, place, id, along, measured, offered, given) }; // The control beside an inspector's label fills the cell the label leaves, unless its caller sized it to its // content. @@ -343,7 +348,7 @@ impl ShapeHooks for LeafHooks { if sizing == Some(super::Sizing::Fill) { return Vec2::new(fill(size.x, room.x, Axis::X), fill(size.y, room.y, Axis::Y)); } - let in_cell = Env::of(ui).cell_fills && sizing != Some(super::Sizing::Content); + let in_cell = place.cell_fills && sizing != Some(super::Sizing::Content); match comp.fills().or(in_cell.then_some(Axis::X)) { Some(Axis::X) => Vec2::new(fill(size.x, room.x, Axis::X), size.y), Some(Axis::Y) => Vec2::new(size.x, fill(size.y, room.y, Axis::Y)), @@ -412,7 +417,6 @@ fn blank_core<'a>( toggles: Vec::new(), reset_part: None, root_sense: Sense::empty(), - roving_arrival: None, roving_lead: None, collection_events: None, visible_rows: 0..0, @@ -535,9 +539,9 @@ pub(crate) trait Erased { fn fills_width(&self) -> bool; /// How much wider than the size it measured to the shape's content wants to be (`ShapeHooks::overflow`). fn overflow(&self) -> f32; - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2; + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2; fn arena(&self) -> bool; - fn extent(&mut self, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2; + fn extent(&mut self, ui: &Ui, place: &Env, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2; fn pad(&self, tokens: &UiTokens) -> f32; fn host(&mut self, at: HostCx<'_>) -> Box; fn record(&mut self, stage: &mut MemoryStage, ctx: &Context, id: Id); @@ -560,6 +564,8 @@ pub(crate) trait ErasedPass<'a> { /// Whether the component is bound, and whether its binding has a reset value. fn bound(&mut self) -> (bool, bool); fn paint_outset(&self, tokens: &crate::style::UiTokens) -> f32; + /// The axis the component fills (`Component::fills`). + fn fills(&self) -> Option; /// `Component::padding` at `rect`. fn padding(&self, rect: Rect) -> craft_behavior::Insets; /// Step 7: the component's parts, then the shape's. @@ -598,7 +604,7 @@ pub(crate) trait ErasedPass<'a> { fn in_flow(&self) -> bool; fn regions(&self, id: Id) -> Vec<(Id, Vec2)>; fn focus(&self) -> Option; - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2; + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2; fn fills_width(&self) -> bool; fn first_line(&self, ctx: &Context, id: Id, height: f32) -> Option; fn first_is_row_line(&self) -> bool; @@ -656,6 +662,8 @@ struct Pass<'p, 'r, 'a> { p: &'p mut dyn ErasedPass<'a>, facts: &'r TypeFacts, env: &'r Env, + /// The env the parent installed for the parent `Ui`. + place: &'r Env, style: &'r dyn StyleView, resolved: &'r Resolved<'r>, trace: Trace<'r>, @@ -834,8 +842,9 @@ fn sense_root(ui: &Ui, member: Option, spec: RootS } } -/// Step 6: the rect the root takes in `ui`, and whether it is a fill-width root held at its measured width. -fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Vec2, inert: bool, rtl: bool) -> (Rect, bool) { +/// Step 6: the rect the root takes in `ui`, whose children are placed under `place`, and whether it is a fill-width +/// root held at its measured width. +fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, (at, place): (ShowAt, &Env), env: &Env, size: Vec2, inert: bool, rtl: bool) -> (Rect, bool) { let (ctx, id) = (ui.ctx().clone(), p.resolved.id); if p.dropped { return (Rect::from_min_size(ui.cursor().min, Vec2::ZERO), false); @@ -845,16 +854,16 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve // the column settles on, so it never sets that width. let held = !inert && matches!(at, ShowAt::Flow) - && ((env.content_column && p.p.fills_width()) || (crate::layout::in_grid_content_column(ui) && p.p.fills_width_only())); + && ((env.content_column && p.p.fills_width()) || (crate::layout::in_grid_content_column(&ctx, place) && p.p.fills_width_only())); let rect = if held { // The column's settled width, read before the child takes its place in it. A sizing or measuring run has no // settled width yet: there the child shows at its own size. let column = (!ui.is_sizing_pass() && !crate::runtime::measure::active(ui.ctx())) - .then(|| crate::layout::flow_room(ui).x) + .then(|| crate::layout::flow_room(ui, place).x) .filter(|width| width.is_finite()) .unwrap_or(0.0); let line = p.p.first_is_row_line(); - let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); + let flowed = steps::place(ui, place, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); // The column's first sweep learns which of its held children measured narrower than it settles on. if let Some(ColumnSweep::Count(column)) = env.column { crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Fill, flowed.width()); @@ -864,7 +873,7 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve } else { let fill = p.p.fills_width() && !p.p.fills_width_only(); let size = if inert { Vec2::ZERO } else { size }; - let placed = steps::place(ui, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); + let placed = steps::place(ui, place, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); // A picture its measure held (`MeasureCx::picture_size`) reports its placed width, padding included. if let Some(ColumnSweep::Count(column)) = env.column && crate::layout::held_kind(&ctx, column, id) == Some(crate::layout::HeldKind::Picture) @@ -897,7 +906,9 @@ fn create_node(ctx: &Context, ui: &Ui, id: Id, member: bool, role: Role) -> bool fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, host_env: Option<&Env>) { 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) { + // A host that runs the pass in a `Ui` of its own installs the env it gives for it; else the pass runs in the parent. + let place = host_env.unwrap_or(p.place); + if let Some(mut h) = sense_steps(p, ui, (host_at, place), env) { update_steps(p, env, &h); overlay_step(p, ui, env, &h); state_steps(p, ui, env, &h); @@ -938,7 +949,7 @@ struct HostStep { /// still offers the redirected action. report_sense: Sense, member: Option, - /// The bar line whose rules wait for this member. + /// The bar line the member sits in, in the run that paints: a rule notes itself to it instead of painting. line: Option, /// A bar's view cut the member: it shows nothing until the clip is restored. cut: bool, @@ -955,15 +966,15 @@ struct HostStep { /// inert component. // 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 sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, env: &Env) -> Option> { +fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, (host_at, place): (Option, &Env), env: &Env) -> Option> { let ctx = p.p.core_ref().ctx.clone(); let (id, rtl) = (p.resolved.id, p.env.direction.is_rtl()); let (resolved, inert, facts) = (p.resolved, p.inert, p.facts); // 6 place let at = host_at.unwrap_or(p.at); // A root that fills takes the room of the `Ui` its host runs it in: a pane's or a layer's own, not its parent's. - let size = if ui.scope_id() == p.parent { p.size } else { p.p.sized(ui, id, p.measured) }; - let (rect, held) = place_root(p, ui, at, env, size, inert, rtl); + let size = if ui.scope_id() == p.parent { p.size } else { p.p.sized(ui, place, id, p.measured) }; + let (rect, held) = place_root(p, ui, (at, place), env, size, inert, rtl); p.trace.mark(Step::Place); // What the content wants past the room counts where the root's width comes from its content: a content-sized // root, or a fill-width one held at its measured width. A root that fills the flow keeps to the room it fills, and @@ -1047,7 +1058,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e let shown_clip = ui.clip_rect(); let judged = e.member() && matches!(at, ShowAt::Flow) && !scope::in_label(&ctx); let cut = judged && bar_member(&ctx, env, hit, facts.rule); - // Rules wait for their member only in the run that paints. + // A bar's line takes its rules only in the run that paints. let line = bar_line(env).filter(|_| judged && !crate::runtime::measure::active(&ctx)); if cut { ui.set_clip_rect(Rect::NOTHING); @@ -1201,13 +1212,7 @@ fn update_steps(p: &mut Pass<'_, '_, '_>, env: &Env, h: &HostStep) { Some(lead) => group.lead((lead, None)), None => group, }; - focus::register_group( - ctx, - match core.roving_arrival { - Some(arrival) => group.selected((arrival, None)), - None => group, - }, - ); + focus::register_group(ctx, group); } } @@ -1259,22 +1264,32 @@ fn paint_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &mut HostStep p.trace.mark(Step::Paint); let e = &mut *p.p; let fade = steps::fade(ui, env, e.core()); - let rule_from = h.line.filter(|_| p.facts.rule && !h.cut).map(|line| (line, steps::next_shape(ui))); - steps::paint_surface(ui, env, e.core_ref(), p.style); - steps::paint_part_layers(ui, env, e.core_ref()); + // A rule in a bar's line is the bar's to draw, with the member after it (`draw_bar_rules`). + let bar_rule = h.line.filter(|_| p.facts.rule && !h.cut); + if bar_rule.is_none() { + steps::paint_surface(ui, env, e.core_ref(), p.style); + steps::paint_part_layers(ui, env, e.core_ref()); + } // Paint and content stay inside the rect (grown by the type's declared outset), however small the room is. h.outer_clip = ui.clip_rect(); h.inside = e.core_ref().rect.expand(e.paint_outset(&env.tokens)).intersect(h.outer_clip); ui.set_clip_rect(h.inside); - e.paint(ui, env); + match bar_rule { + Some(line) => { + let rect = e.core_ref().rect; + let axis = e.fills().unwrap_or(craft_behavior::Axis::Y); + let look = crate::style::rule_look(&env.tokens, crate::primitives::RuleKind::Divider); + let item = LineItem::Rule { rect, clip: crate::runtime::Clip::new(h.inside), axis, look }; + crate::runtime::lazy::note_line(&h.ctx, line, item); + } + None => e.paint(ui, env), + } // The content's values may read what `paint` found this pass. e.content_env(&mut h.values); steps::unfade(ui, e.core(), fade); ui.set_clip_rect(h.outer_clip); - steps::paint_focus(ui, e.core_ref(), p.style, e.shape() != ShapeKind::Item); - // A rule a bar's view shows waits for the member after it. - if let Some((line, from)) = rule_from { - hold_rule(ui, line, from); + if bar_rule.is_none() { + steps::paint_focus(ui, e.core_ref(), p.style, e.shape() != ShapeKind::Item); } ui.set_clip_rect(h.inside); } @@ -1398,61 +1413,44 @@ fn bar_line(env: &Env) -> Option { /// Judges a member of a bar's line whose hit target is `hit` (a control with the label it claims): whether its view /// shows it only in part. Such a member is not shown until a scroll brings it in whole; it keeps its stop, so Tab -/// reaches it and the reveal scrolls it in. In the run that paints, the rules before a member that is not itself a -/// `rule` show with it, or are taken back with it. Outside a bar's line nothing is cut. +/// reaches it and the reveal scrolls it in. In the run that paints, a member that is not itself a `rule` is noted to +/// the line, so the rules before it show with it or not (`draw_bar_rules`). Outside a bar's line nothing is cut. pub(crate) fn bar_member(ctx: &Context, env: &Env, hit: Rect, rule: bool) -> bool { let Some(line) = bar_line(env) else { return false }; let cut = cut_by_bar_view(env, hit); if !rule && !crate::runtime::measure::active(ctx) { - settle_rules(ctx, line, cut); + crate::runtime::lazy::note_line(ctx, line, LineItem::Member { cut }); } cut } -/// The rules a bar line shows this pass that wait for the member after them: the shapes each painted, by line. -#[derive(Default)] -pub(crate) struct BarRules(IdMap>); - -/// A rule's paint: `shapes` of the paint list of `layer`, in the pass `pass`. -struct HeldRule { - layer: crate::runtime::egui::areas::Layer, - shapes: std::ops::Range, - pass: u64, -} - -/// Holds the shapes a rule of `line` painted since `from` until the member after it settles them. -fn hold_rule(ui: &Ui, line: Id, from: usize) { - let rule = HeldRule { layer: ui.layer_id(), shapes: from..steps::next_shape(ui), pass: ui.ctx().cumulative_pass_nr() }; - crate::runtime::pass_state::with::(ui.ctx(), |rules| rules.0.entry(line).or_default().push(rule)); -} - -/// Settles the rules of `line` that wait for a member: a member shown keeps them, a member `cut` takes them back. -fn settle_rules(ctx: &Context, line: Id, cut: bool) { - let Some(held) = crate::runtime::pass_state::with::(ctx, |rules| rules.0.remove(&line)) else { return }; - if cut { - take_back(ctx, &held); - } -} - -/// Closes the line of the bar body `line`: a rule no member came after is taken back. -pub(crate) fn close_bar_line(ctx: &Context, line: Id) { - if let Some(held) = crate::runtime::pass_state::with::(ctx, |rules| rules.0.remove(&line)) { - take_back(ctx, &held); - } -} - -/// 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(); - ctx.graphics_mut(|layers| { - for rule in held.iter().filter(|rule| rule.pass == pass) { - let list = layers.entry(rule.layer); - for at in rule.shapes.clone() { - list.reset_shape(egui::layers::ShapeIdx(at)); +/// Closes a bar's line in `ui`, the line's own: draws each rule of `line` (what its run and the replays in it noted, in +/// run order) that a member the view shows comes after, in the look, clip and place the rule had. A rule before a +/// member the view cut, or with no member after it, is not drawn. +pub(crate) fn draw_bar_rules(ui: &Ui, line: &[LineItem]) { + let mut waiting = Vec::new(); + for item in line { + match item { + LineItem::Rule { .. } => waiting.push(item), + LineItem::Member { cut } => { + if !cut { + waiting.iter().for_each(|rule| draw_bar_rule(ui, rule)); + } + waiting.clear(); } } - }); + } +} + +/// Draws the rule `rule` of a bar's line in `ui`. +fn draw_bar_rule(ui: &Ui, rule: &LineItem) { + let LineItem::Rule { rect, clip, axis, look } = rule else { return }; + let (from, to) = match axis { + craft_behavior::Axis::X => (rect.left_center(), rect.right_center()), + _ => (rect.center_top(), rect.center_bottom()), + }; + let painter = ui.painter().with_clip_rect(clip.rect()); + painter.extend(crate::primitives::Rule::shapes(look, from, to, painter.pixels_per_point())); } /// Whether `rect`, in the scrolling body of a bar, lies partly outside the body's view along x. A member wider than the @@ -1475,30 +1473,30 @@ fn measured(t: &mut dyn Erased, input: &MeasureIn<'_>, style: &dyn StyleView, re /// The pipeline: steps 1 to 17 for one component, whatever its type and shape. A component that takes a cell of a /// `Grid` runs under the column group of its cell's column (`ColumnGroup::cell`). -pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { +/// Runs `t` in `ui`, whose children are placed under `place`: the env its parent installed for it, which every step +/// of the run reads the place from. +pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, place: Env) { if crate::runtime::pass_state::in_component_tree() { - return run_in_context(t, ui, at, tip); + return run_in_context(t, ui, at, tip, place); } let ctx = ui.ctx().clone(); - crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip)); + crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip, place)); } -fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { - let cell = (matches!(at, ShowAt::Flow) && t.in_flow()).then(|| crate::layout::grid_cell(ui)).flatten(); +fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, place: Env) { + let ctx = ui.ctx().clone(); + let cell = (matches!(at, ShowAt::Flow) && t.in_flow()).then(|| crate::layout::grid_cell(&ctx, &place)).flatten(); match cell { - Some((grid, column, sized)) => { - let ctx = ui.ctx().clone(); - crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip)); - } - None => run_steps(t, ui, at, tip), + Some((grid, column, sized)) => crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip, place)), + None => run_steps(t, ui, at, tip, place), } } /// Steps 1 to 17 of `run`. A component's children run inside step 5 (a body's measuring run) and inside the passes /// of steps 6 to 16, so the frames on that path keep only what the run reads after them: each step runs in its own /// function, and `run_steps` holds what steps 1 to 5 found. -fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { - let begun = begin(t, ui); +fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, place: Env) { + let begun = begin(t, ui, place); let mut stage = begun.open_stage(t); let mixed = value_step(t, &begun, &mut stage); let resolved = begun.resolved(t); @@ -1525,7 +1523,9 @@ struct Begun { sizing: bool, /// The inspector records this run; read once per run. recording: bool, - /// The env of the parent `Ui`, which the style reads. + /// The env the parent installed for the parent `Ui`, under which the run is placed. + place: Env, + /// The place env in the component's token scope, which the style reads. env: Env, /// The env with the component's own command instance, when it has one. own_env: Option, @@ -1564,7 +1564,7 @@ impl Begun { /// Steps 1 to 3: env, style and id. // 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 begin(t: &mut dyn Erased, ui: &Ui) -> Box { +fn begin(t: &mut dyn Erased, ui: &Ui, place: Env) -> Box { let ctx = ui.ctx().clone(); let facts = t.facts(); crate::runtime::measure::count_run(&ctx, facts.name); @@ -1579,7 +1579,7 @@ fn begin(t: &mut dyn Erased, ui: &Ui) -> Box { let recording = !sizing && inspect::recording(&ctx); // 1 env: `Common` moves out of the component; `Resolved` borrows it. A themed component resolves its own look in its // scope, and everything it shows inherits it. - let env = scoped_env(&ctx, Env::of(ui), t.theme_scope()); + let env = scoped_env(&ctx, place.clone(), t.theme_scope()); let common: Common = t.take_common(); let step1 = steps::env(&ctx, &env, &common, t.variants(common.variant, &env)); // 2 style @@ -1595,7 +1595,7 @@ fn begin(t: &mut dyn Erased, ui: &Ui) -> Box { } // The command instance the component is, which steps 4 to 17 run under. let own_env = t.instance_scope().map(|scope| env.derive_local(|scoped| scoped.inherited_mut().commands = scoped.commands.pushed(scope, id))); - Box::new(Begun { ctx, facts, shape, sizing, recording, env, own_env, common, step1, style, id }) + Box::new(Begun { ctx, facts, shape, sizing, recording, place, env, own_env, common, step1, style, id }) } /// Step 4, value: returns whether the binding holds a mixed value. A sizing pass reads the cancel and ends nothing: @@ -1647,7 +1647,7 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { { Some(width) } - _ => Some(crate::layout::flow_room(ui).x) + _ => Some(crate::layout::flow_room(ui, &begun.place).x) .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(ctx))), }, }; @@ -1656,7 +1656,7 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { // room (`mount_room`). A body that fills the width of a bounded room takes the room or its share of it (`sized`), // so it is no unit. let in_flow = matches!(at, ShowAt::Flow) && t.fills().is_none(); - let fill_body = shape == ShapeKind::Body && in_flow && t.in_flow() && t.fills_width() && crate::layout::flow_room(ui).x.is_finite(); + let fill_body = shape == ShapeKind::Body && in_flow && t.in_flow() && t.fills_width() && crate::layout::flow_room(ui, &begun.place).x.is_finite(); let shrink = env.shrink.filter(|_| in_flow && (shape == ShapeKind::Leaf || (shape == ShapeKind::Body && t.in_flow() && !fill_body))); let given = match shrink { Some(crate::layout::Shrink::Apply(row)) => crate::layout::shrink_cap(ctx, row, id), @@ -1693,10 +1693,10 @@ fn extent_step( } let scx = steps::style_cx(ctx, &begun.env, &begun.step1); if sizing || matches!(shape, ShapeKind::Body | ShapeKind::Item) { - let measuring = Measuring { ui, at, width: None, env, scx: &scx, resolved, command: begun.step1.command.clone(), mixed }; + let measuring = Measuring { ui, at, width: None, place: &begun.place, env, scx: &scx, resolved, command: begun.step1.command.clone(), mixed }; if sizing { t.measured_extent(&measuring, stage) } else { t.pass_extent(&measuring) } } else { - t.extent(ui, at, id, &scx) + t.extent(ui, &begun.place, at, id, &scx) } } @@ -1729,7 +1729,9 @@ fn measure_step( let fills = |axis: craft_behavior::Axis| t.fills() == Some(axis) || begun.common.sizing == Some(super::Sizing::Fill); let tells_least = shape == ShapeKind::Leaf && matches!(at, ShowAt::Flow) - && [craft_behavior::Axis::X, craft_behavior::Axis::Y].into_iter().any(|axis| fills(axis) && crate::layout::counting_fills(ui, axis)); + && [craft_behavior::Axis::X, craft_behavior::Axis::Y] + .into_iter() + .any(|axis| fills(axis) && crate::layout::counting_fills(ctx, &begun.place, axis)); let min = (in_label || tells_least).then(|| { let (took, inputs) = ask(&mut *t, Proposal::Min, None, Vec2::ZERO); Call { proposal: Proposal::Min, room: None, inputs, took } @@ -1777,8 +1779,9 @@ fn measure_step( } false => cap, }; - let fit_room = - (leaf_in_flow && shrink == Some(crate::layout::Shrink::Fit)).then(|| crate::layout::flow_room(ui).x).filter(|room| room.is_finite()); + let fit_room = (leaf_in_flow && shrink == Some(crate::layout::Shrink::Fit)) + .then(|| crate::layout::flow_room(ui, &begun.place).x) + .filter(|room| room.is_finite()); let cap = match fit_room.filter(|room| size.x > *room) { Some(room) => Some(cap.map_or(room, |cap| cap.min(room)).max(least(&mut *t))), None => cap, @@ -1788,7 +1791,7 @@ fn measure_step( let measured = size; // A component on a layer or in a window of its own takes no room in the parent's flow: the parent neither sizes it // nor counts it among the children that share its room. Its host sizes it in its own `Ui`. - let size = if t.in_flow() { t.sized(ui, id, size) } else { size }; + let size = if t.in_flow() { t.sized(ui, &begun.place, id, size) } else { size }; match shrink { Some(crate::layout::Shrink::Count(row)) if shape == ShapeKind::Leaf => { // The `Ideal` size in no room, and the least width at which its content shows whole. @@ -1873,6 +1876,7 @@ fn passes<'a>( p: e, facts: &begun.facts, env: begun.env(), + place: &begun.place, style: &*begun.style, resolved, trace: begun.trace(), @@ -1948,9 +1952,11 @@ pub(super) fn measure_shape( purpose: MeasureFor, ) -> Vec2 { let facts = t.facts(); + // The one walk of a measure: what follows reads the place from it. + let place = Env::of(ui); let env = match under { - Some(under) => super::cx::child_env(&Env::of(ui), under), - None => Env::of(ui), + Some(under) => super::cx::child_env(&place, under), + None => place.clone(), }; let env = scoped_env(ui.ctx(), env, t.theme_scope()); let id = id.unwrap_or_else(|| steps::id(ui, &t.common().id, false, false, facts.style_key, facts.name)); @@ -1971,7 +1977,7 @@ pub(super) fn measure_shape( Vec2::ZERO } else { let mut stage = MemoryStage::open_peek(ui.ctx(), id); - let measuring = Measuring { ui, at, width, env: &env, scx: &scx, resolved: &resolved, command: step1.command.clone(), mixed }; + let measuring = Measuring { ui, at, width, place: &place, env: &env, scx: &scx, resolved: &resolved, command: step1.command.clone(), mixed }; t.measured_extent(&measuring, &mut stage) }; let ask = |t: &mut dyn Erased, proposal: Proposal| measured(t, &MeasureIn { ui, env: &env, proposal, room: None }, &*style, &resolved, extent); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index c3e9e325e1..c7e6bab1ce 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -234,16 +234,16 @@ impl Erased for Typed<'_, '_, C> { self.hooks.overflow() } - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2 { - self.hooks.sized(self.comp.get_ref(), ui, id, size) + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { + self.hooks.sized(self.comp.get_ref(), ui, place, id, size) } fn arena(&self) -> bool { self.hooks.arena(self.comp.get_ref()) } - fn extent(&mut self, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { - self.hooks.extent(self.comp.get_ref(), ui, at, id, scx) + fn extent(&mut self, ui: &Ui, place: &Env, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { + self.hooks.extent(self.comp.get_ref(), ui, place, at, id, scx) } fn pad(&self, tokens: &UiTokens) -> f32 { @@ -309,6 +309,10 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { C::paint_outset(tokens) } + fn fills(&self) -> Option { + self.comp.fills() + } + fn padding(&self, rect: Rect) -> craft_behavior::Insets { self.comp.padding(rect, self.cx.style) } @@ -448,8 +452,8 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { self.hooks.focus(self.comp) } - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2 { - self.hooks.sized(self.comp, ui, id, size) + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { + self.hooks.sized(self.comp, ui, place, id, size) } fn fills_width(&self) -> bool { @@ -541,15 +545,16 @@ fn measure_shape( super::measure_shape(&mut Typed::new(Held::Lent(comp), hooks), ui, id, proposal, under, purpose) } +/// Shows a leaf in `ui`, whose children are placed under `place` (the env installed for it). pub(crate) fn show_leaf>( slot: &mut Option, ui: &mut Ui, - at: ShowAt, + (at, place): (ShowAt, Env), tip: Option>, ) -> C::Output { let mut hooks = LeafHooks { scope: held(slot).common(Internal::new()).command_scope }; let mut typed = Typed::owned(slot, &mut hooks); - super::run(&mut typed, ui, at, tip); + super::run(&mut typed, ui, at, tip, place); typed.output() } @@ -561,16 +566,18 @@ pub(crate) fn show_container_taking( rect: Rect, body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { - let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); - crate::layout::close_flow_start_in(ui); + let place = Env::of(ui); + let shown = show_container(slot, ui, (ShowAt::Rect(rect), place.clone()), body, None); + crate::layout::close_flow_start(ui.ctx(), &place); crate::runtime::egui::alloc::advance_past(ui, rect); shown } +/// Shows a container in `ui`, whose children are placed under `place` (the env installed for it). pub(crate) fn show_container( slot: &mut Option, ui: &mut Ui, - at: ShowAt, + (at, place): (ShowAt, Env), body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: Option>, ) -> Inner { @@ -586,7 +593,7 @@ pub(crate) fn show_container( }; let mut hooks = crate::contract::body::BodyHooks::of(held(slot), &mut call); let mut typed = Typed::owned(slot, &mut *hooks); - super::run(&mut typed, ui, at, tip); + super::run(&mut typed, ui, at, tip, place); let output = typed.output(); let id = crate::contract::Outcome::response(&output).id; let settle = ran.then(|| crate::contract::settle::SettleAt { ctx: ui.ctx().clone(), body: sub(id, "body"), owner: id }); @@ -638,7 +645,8 @@ pub(crate) fn show_items<'r, C: Collection>( ) -> C::Output { let mut hooks = crate::contract::items::ItemsHooks::::new(source, item); let mut typed = Typed::owned(slot, &mut hooks); - super::run(&mut typed, ui, ShowAt::Flow, None); + let place = Env::of(ui); + super::run(&mut typed, ui, ShowAt::Flow, None, place); typed.output() } diff --git a/crates/ui-contract/src/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 54099c36cb..d38707a71c 100644 --- a/crates/ui-contract/src/contract/steps.rs +++ b/crates/ui-contract/src/contract/steps.rs @@ -30,7 +30,7 @@ pub(super) use id::measuring; pub(crate) use id::{claim_id, draft, id, keeping_ids}; pub(crate) use label::scrub_by_label; pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx, padding, whole}; -pub(crate) use paint::{Fade, UnderVeil, fade, next_shape, paint_focus, paint_part_layers, paint_surface, surface_ink, unfade}; +pub(crate) use paint::{Fade, UnderVeil, fade, paint_focus, paint_part_layers, paint_surface, surface_ink, unfade}; #[cfg(feature = "testing")] pub(crate) use parts::declares_none; pub(crate) use parts::{PartsStep, check_parts}; diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6ccec0dbf7..3d0fd033fe 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -78,6 +78,7 @@ pub(crate) fn measure_cx<'a, C: Component>( let padding = padding(ComponentStyle::metrics(style).padding, resolved.pad); MeasureCx { env: input.env.view(), + scope: input.env, style, resolved, proposal: input.proposal, diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index 083f7c1616..d7752fc02b 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -73,7 +73,7 @@ pub(crate) fn unfade(ui: &Ui, core: &mut CxCore<'_>, fade: Option) { } /// The index the next shape `ui` paints gets in its layer's paint list. -pub(crate) fn next_shape(ui: &Ui) -> usize { +fn next_shape(ui: &Ui) -> usize { ui.ctx().graphics(|layers| layers.get(ui.layer_id()).map_or(0, |list| list.next_idx().0)) } diff --git a/crates/ui-contract/src/contract/steps/place.rs b/crates/ui-contract/src/contract/steps/place.rs index c6df925f75..cfdc257fd1 100644 --- a/crates/ui-contract/src/contract/steps/place.rs +++ b/crates/ui-contract/src/contract/steps/place.rs @@ -2,10 +2,17 @@ use egui::{Rect, Ui, Vec2}; -/// Step 6, place: in flow one allocation with no widget, at a rect none. -pub(crate) fn place(ui: &mut Ui, at: crate::contract::run::ShowAt, size: Vec2, child: crate::layout::InFlow) -> Rect { +/// Step 6, place: in flow one allocation with no widget, at a rect none. `place` is the env `ui`'s children are placed +/// under. +pub(crate) fn place( + ui: &mut Ui, + place: &crate::runtime::env::Env, + at: crate::contract::run::ShowAt, + size: Vec2, + child: crate::layout::InFlow, +) -> Rect { match at { - crate::contract::run::ShowAt::Flow => crate::layout::place_in_cell(ui, size, child), + crate::contract::run::ShowAt::Flow => crate::layout::place_in_cell(ui, place, size, child), crate::contract::run::ShowAt::Rect(rect) => rect, } } diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index d7cfe572c9..5a7b1873fc 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -115,7 +115,7 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> let resolved = core.resolved; // Before any return: a component without an AccessKit node (merged, or AccessKit off) still records its command // for the inspected region, which keytips place their badges by. - inspect::note_command(ctx, id, core.command.as_deref().map(|command| command.command.clone())); + inspect::note_command(ctx, id, core.command.as_deref().map(|command| (*command.command).clone())); let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 9bbf1478ab..12b7cf7f43 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -458,8 +458,16 @@ fn prepare(core: &mut CxCore<'_>, ui: &mut Ui, decl: &TextPart, state: &mut Text let pointer = !scrubs || in_edit_before || (focused && !core.press.phase.is_drag()); core.text_takes_pointer = pointer; let read_only = core.resolved.read_only || !enabled; - let ink = decl.options.ink.map_or(ink, |own| crate::style::ink_color(&crate::runtime::env::Env::of(ui).tokens, own)); - let ink = if enabled { ink } else { crate::style::rgba_color(crate::runtime::env::Env::of(ui).tokens.color.text.disabled) }; + // The tokens of the place the field is shown in, read only for an ink of its own or a disabled field. + let place = (decl.options.ink.is_some() || !enabled).then(|| crate::runtime::env::Env::of(ui)); + let ink = match (decl.options.ink, &place) { + (Some(own), Some(place)) => crate::style::ink_color(&place.tokens, own), + _ => ink, + }; + let ink = match &place { + Some(place) if !enabled => crate::style::rgba_color(place.tokens.color.text.disabled), + _ => ink, + }; let held = core.popup(EDIT_MENU).is_open_in(core); // The text the part shows now: its resting text while it is idle and has one, else the value's own. let current = decl.options.resting.as_deref().filter(|_| !focused && !held && state.draft.is_none()).unwrap_or(&decl.shown); diff --git a/crates/ui-contract/src/layout/arrange.rs b/crates/ui-contract/src/layout/arrange.rs index 8a6b9b1704..c90c8bce25 100644 --- a/crates/ui-contract/src/layout/arrange.rs +++ b/crates/ui-contract/src/layout/arrange.rs @@ -59,7 +59,8 @@ impl<'c> Placed<'c> { /// is mirrored through the env's direction when the layout mirrors, so no arrangement reads the direction. /// Returns the rect the placement took. pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_>]) -> Rect { - let rtl = Env::of(ui).direction.is_rtl(); + let env = Env::of(ui); + let rtl = env.direction.is_rtl(); let room = ui.available_rect_before_wrap(); let base = ui.scope_id(); let ids: Vec = children.iter().map(|placed| (placed.id)(base)).collect(); @@ -71,7 +72,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_> placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect))); } let whole = flow.to_physical(Rect::from_min_size(room.min, taken)); - super::close_flow_start_in(ui); + super::close_flow_start(ui.ctx(), &env); alloc::advance_past(ui, whole); whole } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index b9732e0fb3..dd6e424734 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -350,11 +350,6 @@ pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { } } -/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`. -pub(crate) fn close_flow_start_in(ui: &Ui) { - close_flow_start(ui.ctx(), &Env::of(ui)); -} - /// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or /// run under way, and the rect of the row's last child in flow, by the row's layout id. #[derive(Default)] @@ -415,9 +410,8 @@ enum MainFill { /// /// `given` is the caller's own fact: whether the child is given `axis` (a leaf where its body does not size from its /// content, a container given the axis or held across its column, a collection where it fills). `offered` is the room -/// the flow offers it along `axis`, `measured` what it measured. -pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32, given: bool) -> f32 { - let env = Env::of(ui); +/// the flow offers it along `axis`, `measured` what it measured. `env` is the env `ui`'s children are placed under. +pub(crate) fn fill_size(ui: &Ui, env: &Env, id: Id, axis: Axis, measured: f32, offered: f32, given: bool) -> f32 { // Across an unwrapped row's content-height line a child that fills is shown across the line the row settled on in // its measuring run, where the child measured at its own size. if axis == Axis::Y @@ -434,8 +428,8 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 } // In a body that shares the axis and scrolls along it, a share never cuts the child's content: what is past the // view scrolls. - if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, axis).is_some() { - return match main_fill(ui, id, axis) { + if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, env, axis).is_some() { + return match main_fill(ui, env, id, axis) { MainFill::Measuring => 0.0, MainFill::Share(share, _) => measured.max(share), MainFill::Room(_) => measured, @@ -444,7 +438,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 if !offered.is_finite() { return measured; } - match main_fill(ui, id, axis) { + match main_fill(ui, env, id, axis) { MainFill::Measuring => 0.0, MainFill::Share(share, least) => least.max(share), MainFill::Room(least) => least.max(offered), @@ -453,8 +447,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 /// What the child `id` of `ui`'s body that fills along `axis` takes there, with its least along it /// (`layout_memory::fill_least`). Called once per such child and run. -fn main_fill(ui: &Ui, id: Id, axis: Axis) -> MainFill { - let env = Env::of(ui); +fn main_fill(ui: &Ui, env: &Env, id: Id, axis: Axis) -> MainFill { let Some((body, _)) = env.fill_body.filter(|(_, along)| *along == axis) else { return MainFill::Room(0.0) }; layout_memory::leaf_fill(ui.ctx(), id, body, axis); if let Some(share) = env.fill_share { @@ -472,11 +465,12 @@ fn count_fill(ctx: &egui::Context, body: Id) { pass_state::with::(ctx, |counts| *counts.0.entry(body).or_insert(0) += 1); } -/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it, in the -/// first sweep of the body's measuring run (`counting_fills`), as a child shown there directly is counted. -pub(crate) fn count_fill_view(ui: &Ui) { - if let Some((body, _)) = Env::of(ui).fill_body { - count_fill(ui.ctx(), body); +/// Counts the memoized view whose content fills the main axis of the sharing body that places children under `env` as +/// one child that fills it, in the first sweep of the body's measuring run (`counting_fills`), as a child shown there +/// directly is counted. +pub(crate) fn count_fill_view(ctx: &egui::Context, env: &Env) { + if let Some((body, _)) = env.fill_body { + count_fill(ctx, body); } } @@ -491,18 +485,16 @@ pub(crate) fn take_view_fill(ctx: &egui::Context, view: Id) -> Option { pass_state::with::(ctx, |fills| fills.0.remove(&view)) } -/// The share a child of `ui`'s body that fills along `axis` takes there, once its body knows it: the room the child -/// is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike. -pub(crate) fn fill_share(ui: &Ui, axis: Axis) -> Option { - let env = Env::of(ui); +/// The share a child placed under `env` that fills its body along `axis` takes there, once its body knows it: the room +/// the child is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike. +pub(crate) fn fill_share(env: &Env, axis: Axis) -> Option { env.fill_body.filter(|(_, along)| *along == axis).and(env.fill_share) } -/// Whether `ui` runs the first sweep of a measuring run of a body that shares its main axis: a child that fills along -/// `axis` is only counted there, and its contents run in the second sweep, at its share. -pub(crate) fn counting_fills(ui: &Ui, axis: Axis) -> bool { - let env = Env::of(ui); - measure::active(ui.ctx()) && env.fill_body.is_some_and(|(_, along)| along == axis) && env.fill_share.is_none() +/// Whether the children placed under `env` run in the first sweep of a measuring run of a body that shares its main +/// axis: a child that fills along `axis` is only counted there, and its contents run in the second sweep, at its share. +pub(crate) fn counting_fills(ctx: &egui::Context, env: &Env, axis: Axis) -> bool { + measure::active(ctx) && env.fill_body.is_some_and(|(_, along)| along == axis) && env.fill_share.is_none() } /// What a unit of a shrinking row reported in the first sweep: its id, the width it took there, the width it asks for @@ -653,17 +645,18 @@ pub fn plan_levels(units: &[Vec], room: f32) -> Vec { /// centred row in it centres across its column, not in the view the row scrolls in. pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(&mut Ui, usize)) { let ctx = ui.ctx().clone(); - let shrink = Env::of(ui).shrink; + let env = Env::of(ui); + let shrink = env.shrink; + let rtl = env.direction.is_rtl(); // The unit's content is no unit of the row: it runs in a room of its own, on the row's line only to fill it. Its // children take no slots on the line and report nothing to the row: the unit's block is what stands in the row. - let line = Env::of(ui).row_line.map(|line| RowLine { places: false, ..line }); - let own_room = Env::of(ui).derive_local(|scoped| { + let line = env.row_line.map(|line| RowLine { places: false, ..line }); + let own_room = env.derive_local(|scoped| { scoped.start_room(); scoped.row_line = line; }); match shrink { Some(Shrink::Count(row)) => { - let rtl = Env::of(ui).direction.is_rtl(); let mut widths = Vec::with_capacity(levels); let mut widest = Vec2::ZERO; // Each level measures at what it takes in no room: unbounded along x, in a region as wide as the row's, @@ -698,7 +691,6 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(& let level = level.min(levels.saturating_sub(1)); match width { Some(width) => { - let rtl = Env::of(ui).direction.is_rtl(); let bounded = own_room.derive_local(|scoped| scoped.unbounded.0 = false); // Half a pixel past the width the level measured at, as a bounded re-run of a measured body is given: // content that took exactly that width lays out the same here, never wrapping on a rounding. @@ -932,11 +924,12 @@ fn shrink_widths_in_turn(units: &[ShrinkUnit], first: &[bool], fixed: f32, room: /// the bodies' leasts. It records the width `shrink_in_turns` gives each unit for the rest of the pass, and when a unit /// took another width there, or the row probed, it sweeps them again at those widths. The real run shows each unit at /// most at its width. Every sweep runs in a child of `ui` with its layout, so the children get the same ids in each, -/// and the records a measuring run leaves are the ones the real run's children read and check. -fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> R { +/// and the records a measuring run leaves are the ones the real run's children read and check. `place` is the env +/// installed for `ui`. +fn run_shrinking(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); let layout = *ui.layout(); - let mut env = Env::of(ui); + let mut env = place.clone(); let inherited = (env.unbounded.0, env.least); let rank_short = env.rank_short; let mut sweep = |ui: &mut Ui, shrink: Shrink, body: &mut dyn FnMut(&mut Ui) -> R| { @@ -954,9 +947,9 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> if !measure::active(&ctx) { return child::block(ui, None, layout, |ui| sweep(ui, Shrink::Apply(id), &mut body)).0; } - let room = shrink_room(ui); - let order = if Env::of(ui).values.get::().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even }; - let (drops, gap) = (view_room(ui, Axis::X).is_none(), ui.spacing().item_spacing.x); + let room = shrink_room(ui, place); + let order = if place.values.get::().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even }; + let (drops, gap) = (view_room(ui, place, Axis::X).is_none(), ui.spacing().item_spacing.x); // Records the width each unit gets, and returns whether one took another width in the first sweep. The levelled // units take their levels first, in the room the continuous units leave at their least; the continuous units then // narrow by their own rule with the levelled units' widths held. A row without levelled units holds nothing more. @@ -1058,8 +1051,7 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> /// In a body that scrolls along `axis`, what its view shows along it from the start of the rest of `ui`'s layout: along /// x the width a row there shrinks to fit and a child that fills its width fills, along y the height the children that /// fill a `Stack` there share. `None` outside such a body. -pub(crate) fn view_room(ui: &Ui, axis: Axis) -> Option { - let env = Env::of(ui); +pub(crate) fn view_room(ui: &Ui, env: &Env, axis: Axis) -> Option { let scrolls = |view: &crate::runtime::lazy::View| if axis == Axis::X { env.unbounded.0 && view.axes.0 } else { env.unbounded.1 && view.axes.1 }; env.lazy.filter(scrolls).map(|view| { let start = view.start_of(ui.available_rect_before_wrap()); @@ -1071,14 +1063,14 @@ pub(crate) fn view_room(ui: &Ui, axis: Axis) -> Option { /// The width the leaves of a row in `ui` shrink to fit: the row's flow room, except in a body that scrolls along x, /// where it is what the view shows from the row's start. There the leaves narrow to their least before the body /// scrolls, and when even their least does not fit they keep their natural widths and the body scrolls. -fn shrink_room(ui: &Ui) -> f32 { - view_room(ui, Axis::X).unwrap_or_else(|| flow_room(ui).x) +fn shrink_room(ui: &Ui, env: &Env) -> f32 { + view_room(ui, env, Axis::X).unwrap_or_else(|| flow_room(ui, env).x) } /// Runs `body` as the content of the `Stack` (along y) or unwrapped `Row` (along x) body `id` in `ui`, the block /// it is placed in, when the body is given that axis. A measuring run is `measure_sharing`'s; the real run gives each -/// child that fills the share its record holds. -fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R { +/// child that fills the share its record holds. `body` gets the env installed for the `Ui` it runs in. +fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, mut body: impl FnMut(&mut Ui, &Env) -> R) -> R { let ctx = ui.ctx().clone(); if measure::active(&ctx) { let (inner, rect) = measure_sharing(ui, env, id, axis, layout, &mut body); @@ -1086,11 +1078,11 @@ fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo return inner; } if !shares_along(env, axis) { - return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), body)).0; + return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), |ui| body(ui, env))).0; } let key = sub(id, "share"); child::block(ui, None, layout, |ui| { - let room = share_room(ui, axis); + let room = share_room(ui, env, axis); let share = layout_memory::measured(&ctx, key) .filter(|found| found.took.y >= 1.0 && room.is_finite()) .map(|found| ((room - found.took.x) / found.took.y).max(0.0)); @@ -1113,20 +1105,20 @@ fn shares_along(env: &Env, axis: Axis) -> bool { /// The room along `axis` the children that fill a body in `ui` share. In a body that scrolls along the axis they share /// what the view shows: shorter than the view, the content leaves them its rest; longer, they take their least and the /// body scrolls (`MainFill::Share`). -fn share_room(ui: &Ui, axis: Axis) -> f32 { - view_room(ui, axis).unwrap_or_else(|| { +fn share_room(ui: &Ui, env: &Env, axis: Axis) -> f32 { + view_room(ui, env, axis).unwrap_or_else(|| { let size = ui.available_rect_before_wrap().size(); if axis == Axis::Y { size.y } else { size.x } }) } /// One sweep of the children of the sharing body `id` in `ui`, each child that fills `axis` given `share`. -fn share_sweep(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option, body: &mut dyn FnMut(&mut Ui) -> R) -> R { +fn share_sweep(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option, body: &mut dyn FnMut(&mut Ui, &Env) -> R) -> R { let scoped = env.local_mut(); scoped.fill_body = Some((id, axis)); scoped.fill_share = share; let installed = Env::install_for(ui, env.clone()); - let inner = body(ui); + let inner = body(ui, env); Env::restore(ui.ctx(), installed); inner } @@ -1137,11 +1129,11 @@ fn share_sweep(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option< /// The first sweep counts the children that fill at no extent and records what the others and the gaps took with the /// number that fill. With a child that fills, a second sweep replaces it under the same ids: the others reuse what the /// first recorded, and each child that fills is measured once, at its equal share of the rest. -fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Rect) { +fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui, &Env) -> R) -> (R, Rect) { let ctx = ui.ctx().clone(); - let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| { + let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui, &Env) -> R| { let mut child = laid_out_child(ui, layout); - let inner = Env::run_in(&mut child, env.clone(), body); + let inner = Env::run_in(&mut child, env.clone(), |ui| body(ui, env)); (inner, child.min_rect()) }; if !shares_along(env, axis) { @@ -1153,7 +1145,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: let first = crate::contract::keeping_ids(&ctx, || { let (inner, rect, room) = { let mut first = laid_out_child(ui, layout); - let room = share_room(&first, axis); + let room = share_room(&first, env, axis); pass_state::with::(&ctx, |counts| counts.0.insert(id, 0)); let inner = share_sweep(&mut first, &mut sweep_env, id, axis, None, body); (inner, first.min_rect(), room) @@ -1165,7 +1157,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: ((inner, rect, share), share.is_some()) }); match first { - (_, _, Some(share)) => in_child(ui, &mut |ui| share_sweep(ui, &mut sweep_env, id, axis, Some(share), body)), + (_, _, Some(share)) => in_child(ui, &mut |ui, _| share_sweep(ui, &mut sweep_env, id, axis, Some(share), body)), (inner, rect, None) => (inner, rect), } } @@ -1185,11 +1177,11 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: // PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse // rule: a container that reused its content-sized record there would be laid out across in the real run under records // not made across. -fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R { +fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: impl FnMut(&mut Ui, &Env) -> R) -> R { let ctx = ui.ctx().clone(); let key = sub(id, "column"); let column_env = |column: Option| env.derive_local(|scoped| scoped.column = column); - let sweep = |ui: &mut Ui, column: Option, body: &mut dyn FnMut(&mut Ui) -> R| { + let sweep = |ui: &mut Ui, column: Option, body: &mut dyn FnMut(&mut Ui, &Env) -> R| { let env = column_env(column); let installed = Env::install_for(ui, env.clone()); let inner = run_sharing(ui, &env, id, Axis::Y, layout, body); @@ -1198,7 +1190,7 @@ fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: }; if !measure::active(&ctx) { let across = this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.0); - let column = across.then(|| ColumnSweep::Column(id, flow_room(ui).x)); + let column = across.then(|| ColumnSweep::Column(id, flow_room(ui, env).x)); return sweep(ui, column, &mut body); } let (inner, rect, again) = crate::contract::keeping_ids(&ctx, || { @@ -1353,10 +1345,10 @@ impl Spread { /// records the natural width and count, and the leasts (none for a row that fits). The real run, including one a kept /// transcript serves, builds the same cursor from those records, so each child measures in the same room in both. /// Every sweep runs in a child of `ui` with its layout, so the children get the same ids in each. -fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { +/// `env` is the row's env, installed for `ui`. +fn run_spread(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); let layout = child::row_layout(rtl, false); - let env = Env::of(ui); let sweep = |ui: &mut Ui, env: &Env, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { let flow = Flow::new(ui.available_rect_before_wrap(), rtl); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe)))); @@ -1374,13 +1366,13 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize); let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect(); let last = this_pass(&ctx, false, id); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, last, leasts, false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, env, last, leasts, false, body)).0; return (inner, natural(&spread)); } let room = ui.available_rect_before_wrap().size(); let ((inner, spread), rect, short) = crate::contract::keeping_ids(&ctx, || { let mut first = laid_out_child(ui, layout); - let (inner, spread) = sweep(&mut first, &env, None, Vec::new(), false, body); + let (inner, spread) = sweep(&mut first, env, None, Vec::new(), false, body); // Half a point: less than a pixel shows at any scale the box runs. let short = spread.as_ref().is_some_and(|spread| spread.count >= 2 && room.x.is_finite() && spread.natural > room.x + 0.5); (((inner, spread), first.min_rect(), short), short) @@ -1400,7 +1392,7 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( }); (leasts, true) }); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, None, leasts.clone(), false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, env, None, leasts.clone(), false, body)).0; (inner, spread, leasts) } else { ui.advance_cursor_after_rect(rect); @@ -1454,13 +1446,13 @@ fn one_line(first: Option, height: f32) -> Option { /// sits at the vertical centre of its cell. #[doc(hidden)] pub fn place_in_flow(ui: &mut Ui, size: Vec2) -> Rect { - place_in_cell(ui, size, InFlow { fill: false, first: Some(size.y / 2.0), line: false }) + let env = Env::of(ui); + place_in_cell(ui, &env, size, InFlow { fill: false, first: Some(size.y / 2.0), line: false }) } /// `place_in_flow` for a child that is `child`. In a measuring run the child reports its line to the row around it -/// and its first line to the container whose header or body it starts. -pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { - let env = Env::of(ui); +/// and its first line to the container whose header or body it starts. `env` is the env `ui`'s children are placed under. +pub(crate) fn place_in_cell(ui: &mut Ui, env: &Env, size: Vec2, child: InFlow) -> Rect { let (line, target) = (env.row_line.filter(|line| line.places), env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its @@ -1472,11 +1464,11 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); // A child of a wrapping row takes the height of its line; a one-line child sits at its middle. - let wrapped = if line.is_none() { wrap_line(ui, &env, size) } else { None }; + let wrapped = if line.is_none() { wrap_line(ui, env, size) } else { None }; let height = line.and_then(|line| line.height).or(wrapped); let slot = Vec2::new(size.x, height.map_or(above + size.y, |height| height.max(above + size.y))); - let (rect, in_cell) = take_in(ui, &env, slot); - wrap_took(ui, &env, rect); + let (rect, in_cell) = take_in_flow(ui, env, slot); + wrap_took(ui, env, rect); let placed = if child.fill && in_cell { rect } else { @@ -1508,10 +1500,15 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { placed } -/// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the -/// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. -pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { - take_in(ui, &Env::of(ui), size) +/// Takes `size` in flow in `ui`, whose children are placed under `env`: the next cell of the `Grid` or spread `Row` body +/// that encloses it directly, else the next allocation of `ui`'s layout; the body's flow start closes. Returns the rect +/// taken and whether it is a cell. +pub(crate) fn take_in_flow(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { + close_flow_start(ui.ctx(), env); + match cell_in(ui, env.grid, size) { + Some(cell) => (cell, true), + None => (alloc::space(ui, size), false), + } } /// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it. @@ -1521,27 +1518,16 @@ pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { - take_in(ui, &env, Vec2::ZERO); - } -} - -/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start -/// closes. -fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { - close_flow_start(ui.ctx(), env); - match cell_in(ui, env.grid, size) { - Some(cell) => (cell, true), - None => (alloc::space(ui, size), false), + take_in_flow(ui, &env, Vec2::ZERO); } } /// 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 { - let env = Env::of(ui); +/// it; `None`, taking nothing, outside such a body. `env` is the env `ui`'s children are placed under. +pub(crate) fn take_cell(ui: &mut Ui, env: &Env, size: Vec2) -> Option { let cell = cell_in(ui, env.grid, size); if cell.is_some() { - close_flow_start(ui.ctx(), &env); + close_flow_start(ui.ctx(), env); } cell } @@ -1553,31 +1539,31 @@ fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { } /// 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 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); +/// spread `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. `env` is the env `ui`'s children are +/// placed under, as for every helper here that takes one. +pub(crate) fn flow_region(ui: &Ui, env: &Env) -> Rect { + let cell = env.grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); cell.unwrap_or_else(|| ui.available_rect_before_wrap()) } -/// The width a child of the `Row` body that encloses `ui` directly takes alone in it: the room the row is offered, +/// The width a child placed under `env` takes alone in the `Row` body that places it: the room the row is offered, /// whatever its earlier children took, unbounded in a body that scrolls along x. `None` outside such a row. -pub(crate) fn row_alone_room(ui: &Ui) -> Option { - let env = Env::of(ui); +pub(crate) fn row_alone_room(env: &Env) -> Option { env.row_room.map(|room| if env.unbounded.0 { f32::INFINITY } else { room }) } /// The room a child shown in flow in `ui` measures and sizes in: the room 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_room(ui: &Ui) -> Vec2 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); - cell.unwrap_or_else(|| open_room(ui)) +pub(crate) fn flow_room(ui: &Ui, env: &Env) -> Vec2 { + let cell = env.grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); + cell.unwrap_or_else(|| open_room(ui, env)) } /// The rest of `ui`'s layout (the room offered to the container, less the earlier siblings and gaps; a whole line in a row /// that wraps); unbounded along the axes of the scrolling body that encloses it, whose region is only as large as egui /// can make it. -fn open_room(ui: &Ui) -> Vec2 { - let (x, y) = Env::of(ui).unbounded; +fn open_room(ui: &Ui, env: &Env) -> Vec2 { + let (x, y) = env.unbounded; let mut room = ui.available_size_before_wrap(); // In a row that wraps, a child that does not fit the rest of the line goes on the next one: its room is a line. let layout = ui.layout(); @@ -1586,7 +1572,6 @@ fn open_room(ui: &Ui) -> Vec2 { } // A body sized from its content offers its children the width it was offered, and a row body that placed its // block behind a lead the width of its band; either less what they took. - let env = Env::of(ui); if let Some(offered) = env.offered.or(env.row_room) { room.x += offered - ui.max_rect().width(); } @@ -1595,39 +1580,38 @@ fn open_room(ui: &Ui) -> Vec2 { /// The room a child that fills its width fills in `ui`: `flow_room`, except that in a `Content` column of a `Grid` it /// is the column's width, so the child never measures as the room and pushes the next column out of it. -pub(crate) fn flow_fill_room(ui: &Ui) -> Vec2 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); - cell.unwrap_or_else(|| open_room(ui)) +pub(crate) fn flow_fill_room(ui: &Ui, env: &Env) -> Vec2 { + let cell = env.grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); + cell.unwrap_or_else(|| open_room(ui, env)) } /// `flow_fill_room` for a leaf that fills: along x in a body that scrolls along x it is what the view shows from the /// leaf's start, so the leaf fills the view and what is past it scrolls; along y the same in a `Stack` body that /// scrolls along y, whose children that fill share it. -pub(crate) fn leaf_fill_room(ui: &Ui) -> Vec2 { - let room = flow_fill_room(ui); - let x = view_room(ui, Axis::X).filter(|_| room.x.is_infinite()); - let y = view_room(ui, Axis::Y).filter(|_| room.y.is_infinite() && shares_y(ui)); +pub(crate) fn leaf_fill_room(ui: &Ui, env: &Env) -> Vec2 { + let room = flow_fill_room(ui, env); + let x = view_room(ui, env, Axis::X).filter(|_| room.x.is_infinite()); + let y = view_room(ui, env, Axis::Y).filter(|_| room.y.is_infinite() && shares_y(env)); Vec2::new(x.unwrap_or(room.x), y.unwrap_or(room.y)) } -/// Whether the children in flow in `ui` are the children of a `Stack` body that shares its height among those that fill. -pub(crate) fn shares_y(ui: &Ui) -> bool { - Env::of(ui).fill_body.is_some_and(|(_, along)| along == Axis::Y) +/// Whether the children placed under `env` are the children of a `Stack` body that shares its height among those that +/// fill. +pub(crate) fn shares_y(env: &Env) -> bool { + env.fill_body.is_some_and(|(_, along)| along == Axis::Y) } -/// Whether the next child shown in flow in `ui` goes in a `Content` column of the `Grid` body that encloses `ui` -/// directly: like a content-sized column, a child that fills its width is placed at its measured width there. -pub(crate) fn in_grid_content_column(ui: &Ui) -> bool { - Env::of(ui) - .grid - .is_some_and(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) +/// Whether the next child placed under `env` goes in a `Content` column of the `Grid` body that places it: like a +/// content-sized column, a child that fills its width is placed at its measured width there. +pub(crate) fn in_grid_content_column(ctx: &egui::Context, env: &Env) -> bool { + env.grid.is_some_and(|body| pass_state::with::(ctx, |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) } -/// The cell the next child shown in flow in `ui` takes, when the body that encloses `ui` directly is a `Grid`: the -/// grid's body, the cell's column and whether the column is a `Content` one. -pub(crate) fn grid_cell(ui: &Ui) -> Option<(Id, usize, bool)> { - let grid = Env::of(ui).grid?; - pass_state::with::(ui.ctx(), |cursors| { +/// The cell the next child placed under `env` takes, when the body that places it is a `Grid`: the grid's body, the +/// cell's column and whether the column is a `Content` one. +pub(crate) fn grid_cell(ctx: &egui::Context, env: &Env) -> Option<(Id, usize, bool)> { + let grid = env.grid?; + pass_state::with::(ctx, |cursors| { let cursor = cursors.0.get(&grid)?; Some((grid, cursor.grid_column()?, cursor.in_content_column())) }) @@ -1914,8 +1898,8 @@ fn open_sweep(ctx: &egui::Context, target: Option, row: Option, least: f /// Records the line of the unwrapped `Row` body `id` from what its children took in `ui`, the block they ran in, /// with the line `shared` it shares with its container's regions; a real run records nothing. The last sweep of a /// measuring run gives the line. The block takes the row's height once its children sit on the line, and the row -/// reports its line to the target its body reports a first line to. -fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option) { +/// reports its line to `target`, the container its body reports a first line to. +fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option, target: Option) { if !sizing { return; } @@ -1933,7 +1917,7 @@ fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option) { } let top = ui.max_rect().top(); alloc::reach_down_to(ui, top + height); - if let Some(target) = Env::of(ui).first_line { + if let Some(target) = target { report_first_line(&ctx, target, took.centre.map(|_| top + centre)); } } @@ -2027,8 +2011,10 @@ fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> scoped.stack_gap = Some((at.id, at.gap.y)); }); let installed = Env::install_for(ui, env.clone()); + let mut body = body; + let body = move |ui: &mut Ui, _: &Env| body(ui); // A held child of a column whose own room is unbounded keeps the width it measured at. - let inner = if env.content_column && flow_room(ui).x.is_finite() { + let inner = if env.content_column && flow_room(ui, &env).x.is_finite() { run_column(ui, &env, at.id, child::column_layout(at.rtl), body) } else { run_sharing(ui, &env, at.id, Axis::Y, child::column_layout(at.rtl), body) @@ -2043,19 +2029,17 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m let RowIn { id, gap, shared, sizing, rtl } = *at; let (inner, _) = child::block(ui, None, child::row_layout(rtl, false), |ui| { let line = on_line(id, row_line(&ctx, sizing, id, shared), shared); - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - scoped.grid = Some(id); - scoped.grid_top = false; - scoped.row_line = Some(line); - scoped.first_line = None; - scoped.flow_body = Some(id); - }), - ); - let inner = run_spread(ui, id, gap.x, rtl, &mut body); + let row = env.derive_local(|scoped| { + scoped.grid = Some(id); + scoped.grid_top = false; + scoped.row_line = Some(line); + scoped.first_line = None; + scoped.flow_body = Some(id); + }); + let installed = Env::install_for(ui, row.clone()); + let inner = run_spread(ui, &row, id, gap.x, rtl, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared); + record_line(ui, sizing, id, shared, env.first_line); inner }); inner @@ -2067,19 +2051,17 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu let RowIn { id, shared, sizing, rtl, .. } = *at; let room = ui.available_rect_before_wrap(); let line = on_line(id, row_line(&ctx, sizing, id, shared), shared); - run_sharing(ui, env, id, Axis::X, child::row_layout(rtl, false), |ui| { - let installed = Env::install_for( - ui, - Env::of(ui).derive_local(|scoped| { - scoped.row_room = Some(room.width()); - scoped.row_line = Some(line); - scoped.first_line = None; - scoped.flow_body = Some(id); - }), - ); - let inner = run_shrinking(ui, id, &mut body); + run_sharing(ui, env, id, Axis::X, child::row_layout(rtl, false), |ui, sweep| { + let row = sweep.derive_local(|scoped| { + scoped.row_room = Some(room.width()); + scoped.row_line = Some(line); + scoped.first_line = None; + scoped.flow_body = Some(id); + }); + let installed = Env::install_for(ui, row.clone()); + let inner = run_shrinking(ui, &row, id, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared); + record_line(ui, sizing, id, shared, env.first_line); inner }) } @@ -2103,7 +2085,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign RowAlign::Center | RowAlign::End => { let last = this_pass(&ctx, sizing, id); // In a body that scrolls along x the band is the width its view shows, not the scroll region. - let band = if Env::of(ui).unbounded.0 { shrink_room(ui) } else { room.width() }; + let band = if env.unbounded.0 { shrink_room(ui, env) } else { room.width() }; // Without a measuring run, or in a band without an end, the block is placed as `Start`. last.filter(|last| band.is_finite() && last.x > 0.0 && last.x < band).map(|last| { let spare = band - last.x; @@ -2120,31 +2102,29 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign // line of its own. let block_layout = if wrap && env.least { child::column_layout(rtl) } else { child::row_layout(rtl, wrap) }; let (inner, took) = child::block(ui, rect, block_layout, |ui| { - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - scoped.row_room = Some(room.width()); - scoped.row_line = line; - scoped.flow_body = Some(id); - if line.is_some() { - scoped.first_line = None; - } - // A leaf wider than a whole line takes the line, never below its least, as in a stack. - if wrap { - scoped.shrink = Some(Shrink::Fit); - } - }), - ); + let row = env.derive_local(|scoped| { + scoped.row_room = Some(room.width()); + scoped.row_line = line; + scoped.flow_body = Some(id); + if line.is_some() { + scoped.first_line = None; + } + // A leaf wider than a whole line takes the line, never below its least, as in a stack. + if wrap { + scoped.shrink = Some(Shrink::Fit); + } + }); + let installed = Env::install_for(ui, row.clone()); if lines { open_wraps(&ctx, sizing, id); } - let inner = if wrap { body(ui) } else { run_shrinking(ui, id, &mut body) }; + let inner = if wrap { body(ui) } else { run_shrinking(ui, &row, id, &mut body) }; if lines { close_wraps(&ctx, sizing, id, room.size()); } Env::restore(&ctx, installed); if !wrap { - record_line(ui, sizing, id, shared); + record_line(ui, sizing, id, shared, env.first_line); } inner }); diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 157cfd5bf5..56f35ae858 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,7 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills, + BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start, count_fill_view, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index b2d1f5c9d3..e25eaaeffe 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -36,8 +36,9 @@ pub struct PartResult { pub press: PressState, /// The pointer is over it and nothing above takes the hover. pub hovered: bool, - /// The pointer's position while `hovered`, in the owner's layer space. - pub hover_pos: Option, + /// The pointer's position while `hovered`, in the owner's layer space: read through `Cx::hover_pos`, which marks the + /// part as following the pointer. + pub(crate) hover_pos: Option, /// The value flags the component set on the part. pub flags: Flags, /// What the part senses, as declared. diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 12d4c0985f..87e8a6d6dc 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -413,7 +413,7 @@ impl Shown { /// The entry `reader` keeps for `command`. fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option { let ids = self.by_reader.get(reader)?.get(&number)?; - ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| entry.kept.resolved.command == *command)) + ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| *entry.kept.resolved.command == *command)) } /// Keeps `kept` for `reader`, in place of what it kept for the same command. @@ -848,7 +848,7 @@ impl Board { hint_alone: state.is_some_and(CommandState::is_hint_alone), kind: def.map_or(CommandKind::Command, |def| def.kind.clone()), edit: self.registry.edit_of(&command.id).is_some(), - command: command.clone(), + command: Arc::new(command.clone()), instance, }; (resolved, key) @@ -1816,7 +1816,10 @@ pub(crate) fn fire_resolved(ctx: &Context, command: &ResolvedCommand, source: Fi if !command.enabled || !crate::runtime::measure::effect(ctx, "board::fire_resolved") { return false; } - queue(ctx, Fired { target: command.instance, ..Fired::new(command.command.clone(), source, FirePhase::Press, pass::now(ctx)) }.mods(mods)); + queue( + ctx, + Fired { target: command.instance, ..Fired::new(CommandRef::clone(&command.command), source, FirePhase::Press, pass::now(ctx)) }.mods(mods), + ); true } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index dc6a98264b..f95bf0bde8 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -407,7 +407,8 @@ pub struct ResolvedCommand { /// The command is an edit a focused component takes as its own (it has an `EditCommand` link): a control bound to /// it keeps the focus where it is on a press, so the edit reaches the focused component. pub edit: bool, - pub(crate) command: CommandRef, + /// Shared by every fact that shows this resolution, so a settled view's facts copy no command. + pub(crate) command: Arc, /// Something besides the command's own state refuses it: the gate, the modal rule, the instance's liveness or a /// focused component whose edit does nothing now. A key whose app-scope command its state alone disables is /// declined (`FrameOutput::declined`); a refused one is not. @@ -781,7 +782,7 @@ struct ShownFact { /// What a [`ShownFact`] shows: a bound component's command, or the commands a container holds. #[derive(Clone, Debug, PartialEq)] enum ShownCommands { - Bound(CommandRef), + Bound(Arc), Held(Arc<[CommandRef]>), } @@ -789,7 +790,7 @@ impl ShownFact { /// Whether the fact shows `command`. fn shows(&self, command: &CommandRef) -> bool { match &self.commands { - ShownCommands::Bound(bound) => bound == command, + ShownCommands::Bound(bound) => **bound == *command, ShownCommands::Held(held) => held.contains(command), } } @@ -813,17 +814,17 @@ fn register_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label /// Records that a container at `rect` holds `commands`, for this pass and viewport. Not [`CommandInput::holds`], which /// turns hold bindings on. -pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &[CommandRef], label: Label) { +pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &Arc<[CommandRef]>, label: Label) { if !commands.is_empty() { - register_shown(ctx, layer, rect, label, ShownCommands::Held(commands.into())); + register_shown(ctx, layer, rect, label, ShownCommands::Held(Arc::clone(commands))); } } /// Records that the bound component of `command` was shown at `rect` in `layer`, with `label`, for this pass and /// viewport: the report step calls it for a component wholly inside its clip. // PLAN: the caller is the report step (menus-w3); until it lands nothing in this crate calls it. -pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label, command: &CommandRef) { - register_shown(ctx, layer, rect, label, ShownCommands::Bound(command.clone())); +pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label, command: &Arc) { + register_shown(ctx, layer, rect, label, ShownCommands::Bound(Arc::clone(command))); } /// How many shown-command registrations the running viewport's last pass made: one per bound component and one per @@ -831,7 +832,23 @@ pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label #[cfg(feature = "testing")] #[doc(hidden)] pub fn shown_registrations(ctx: &Context) -> usize { - Facts::::of_last_pass(ctx).len() + Facts::::with_last_pass(ctx, <[ShownFact]>::len) +} + +/// The commands the bound components of the running viewport's last pass showed, in registration order: the values +/// the facts hold, so two passes that copied no command give the same allocations. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn shown_commands(ctx: &Context) -> Vec> { + Facts::::with_last_pass(ctx, |facts| { + facts + .iter() + .filter_map(|fact| match &fact.commands { + ShownCommands::Bound(command) => Some(Arc::clone(command)), + ShownCommands::Held(_) => None, + }) + .collect() + }) } /// Where `command` was shown in the last pass: a bound component's clipped rect or a holder's rect. `None` unless it @@ -839,11 +856,14 @@ pub fn shown_registrations(ctx: &Context) -> usize { pub fn shown(ctx: &Context, command: &CommandRef) -> Option { let viewport = pass::current_viewport(ctx); let scrim = overlay::top_modal_in(ctx, viewport).and_then(|top| top.cover); - Facts::::of_last_pass(ctx) - .into_iter() - .filter(|fact| fact.shows(command)) - .find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect))) - .map(|fact| Shown { rect: fact.rect, viewport, label: fact.label, holder: matches!(fact.commands, ShownCommands::Held(_)) }) + // The rects over a fact are read outside the facts' record, which `with_last_pass` holds. + let showing: Vec = Facts::::with_last_pass(ctx, |facts| facts.iter().filter(|fact| fact.shows(command)).cloned().collect()); + showing.into_iter().find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect))).map(|fact| Shown { + rect: fact.rect, + viewport, + label: fact.label, + holder: matches!(fact.commands, ShownCommands::Held(_)), + }) } /// Where a command was shown, from [`shown`]. diff --git a/crates/ui-contract/src/runtime/cursor.rs b/crates/ui-contract/src/runtime/cursor.rs index 2f9d38a509..713b79b204 100644 --- a/crates/ui-contract/src/runtime/cursor.rs +++ b/crates/ui-contract/src/runtime/cursor.rs @@ -1,6 +1,7 @@ //! The cursor service (8.5): requests of a pass collect here, the end hook picks the winner and records it, and a //! painted winner reaches the window as its cursor image where the window shows one. +use crate::runtime::Shift; use crate::runtime::egui::areas::LayerKey; use crate::runtime::egui::{output, pass, viewports}; use crate::runtime::frame::PerViewport; @@ -50,6 +51,19 @@ pub struct CursorRegion { pub clip: Rect, } +impl Shift for CursorRegion { + fn shifted(&self, by: &egui::RecordShift) -> Self { + CursorRegion { layer: self.layer, clip: crate::runtime::Clip::new(self.clip).shifted(by).rect() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + CursorRegion { layer: self.layer, clip: self.clip.snapped(&to.clip, within) } + } +} + +// A cursor is drawn at the pointer, wherever the record that asked for it replays. +crate::stays!(Cursor, CursorPriority); + impl CursorRegion { /// The region of `clip` on `layer`. pub fn new(layer: LayerKey, clip: Rect) -> Self { @@ -83,7 +97,13 @@ pub fn request_within(ctx: &Context, cursor: Cursor, priority: CursorPriority, r push(ctx, cursor, priority, Some(region)); } +/// A request is a registration of the pass: a settled view's replay requests its cursor again. fn push(ctx: &Context, cursor: Cursor, priority: CursorPriority, region: Option) { + crate::runtime::replay::journal( + ctx, + || (cursor.clone(), priority, region), + |ctx, (cursor, priority, region)| push(ctx, cursor.clone(), *priority, *region), + ); PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { state.requests.push((cursor, priority)); state.regions.push(region); diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index d13d63ef46..11964c3484 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -140,6 +140,11 @@ pub(crate) fn create_node(ctx: &Context, id: Id) -> bool { ctx.accesskit_node_builder(id, |_| ()).is_some() } +/// Whether this pass builds AccessKit nodes: AccessKit was on when the pass began. Reads only, unlike `create_node`. +pub(crate) fn builds_nodes(ctx: &Context) -> bool { + ctx.with_accesskit_parents(|_| ()).is_some() +} + /// Whether AccessKit is running and the widget `id` is visible: nodes are built only then. Creates the node of `id`. pub(crate) fn enabled(ctx: &Context, id: Id) -> bool { create_node(ctx, id) diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index 7e873c8a77..6774467e4d 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -249,6 +249,9 @@ pub(crate) struct LayerSpec { pub tier: Tier, /// The physical left-top of the layer. pub at: Pos2, + /// The size the layer's content takes in this pass, when the host knows it before the layer shows (a container's + /// measured size). egui's `Area` otherwise starts the pass at the size it kept from the last pass. + pub size: Option, /// Whether the layer takes input; a tooltip and the ghost layer never do. pub interactable: bool, /// The accessibility node the layer's content hangs under, created before the layer shows: egui attaches the @@ -265,8 +268,21 @@ pub(crate) struct LayerShown { } /// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. The motion -/// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off. +/// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off. A layer of known +/// size (`spec.size`) starts its `Area` at that size, so egui senses the layer's background over the rect it shows in +/// this pass, from its first pass on. pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut egui::Ui)) -> LayerShown { + if let Some(size) = spec.size { + let kept = egui::AreaState::load(ctx, spec.id); + let state = egui::AreaState { + pivot_pos: Some(spec.at), + pivot: egui::Align2::LEFT_TOP, + size: Some(size), + interactable: kept.is_some_and(|state| state.interactable), + last_became_visible_at: kept.and_then(|state| state.last_became_visible_at), + }; + ctx.memory_mut(|memory| memory.areas_mut().set_state(layer_of(spec.tier, spec.id), state)); + } let mut sizing = false; let mut area = egui::Area::new(spec.id) .fade_in(false) @@ -292,7 +308,7 @@ pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut /// The rect the content of the layer `spec` shows takes in this pass, before the layer shows: its left-top and the size /// egui keeps for its `Area`. `None` when the layer shows in an egui sizing pass, which paints and reports nothing. pub(crate) fn content_rect(ctx: &Context, spec: &LayerSpec) -> Option { - egui::AreaState::load(ctx, spec.id).and_then(|state| state.size).map(|size| Rect::from_min_size(spec.at, size)) + spec.size.or_else(|| egui::AreaState::load(ctx, spec.id).and_then(|state| state.size)).map(|size| Rect::from_min_size(spec.at, size)) } /// What an overlay layer's `Area` keeps in egui's memory for a pass it shows in: its egui layer, its left-top in diff --git a/crates/ui-contract/src/runtime/egui/pass.rs b/crates/ui-contract/src/runtime/egui/pass.rs index cfcbaa3c77..f3a7d6f928 100644 --- a/crates/ui-contract/src/runtime/egui/pass.rs +++ b/crates/ui-contract/src/runtime/egui/pass.rs @@ -5,7 +5,13 @@ use egui::{Context, ViewportId}; /// The pass number of `viewport`; it counts every pass, discard passes included. pub(crate) fn pass_nr(ctx: &Context, viewport: ViewportId) -> u64 { - match frame::running(ctx) { + pass_nr_beside(ctx, frame::running(ctx), viewport) +} + +/// The pass number of `viewport` while `running` is the running pass: for a sweep over the records of every viewport, +/// which reads the running pass once. +pub(crate) fn pass_nr_beside(ctx: &Context, running: Option, viewport: ViewportId) -> u64 { + match running { Some(facts) if facts.viewport == viewport => facts.pass_nr, _ => ctx.cumulative_pass_nr_for(viewport), } diff --git a/crates/ui-contract/src/runtime/egui/response.rs b/crates/ui-contract/src/runtime/egui/response.rs index 3a4a3bedc8..2179582534 100644 --- a/crates/ui-contract/src/runtime/egui/response.rs +++ b/crates/ui-contract/src/runtime/egui/response.rs @@ -102,7 +102,8 @@ pub(crate) fn member(ui: &Ui, id: Id, rect: Rect, enabled: bool, view: MemberVie fn member_on(ctx: &egui::Context, layer_id: LayerId, clip: Rect, id: Id, rect: Rect, enabled: bool, view: MemberView) -> Response { let mut flags = Flags::empty(); let hovered = enabled && view.hovered; - // egui gives the interaction position through the pass the press ends in. + // egui gives the interaction position through the pass the press ends in. A hover position goes through + // `Cx::hover_pos`, which marks what reads it as following the pointer. let mine = enabled && (view.press.pressed || view.press.drag_stopped || view.press.clicked); if enabled { flags |= Flags::ENABLED; @@ -117,7 +118,7 @@ fn member_on(ctx: &egui::Context, layer_id: LayerId, clip: Rect, id: Id, rect: R rect, interact_rect: rect.intersect(clip), sense: egui::Sense::hover(), - interact_pointer_pos_or_nan: if hovered || mine { view.pointer.unwrap_or(Pos2::NAN) } else { Pos2::NAN }, + interact_pointer_pos_or_nan: if mine { view.pointer.unwrap_or(Pos2::NAN) } else { Pos2::NAN }, intrinsic_size_or_nan: Vec2::NAN, flags, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 0f16b57d56..dea72c2f8a 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -112,7 +112,11 @@ pub struct Scoped { #[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, + scope_key: std::sync::OnceLock<(u128, bool)>, + /// The key of the memoized view whose content the scope runs in, when that key follows every input of the view + /// (`MemoKey::follows`): its content version. A body inside measures under it (`EnvFacts`), so a run of the view + /// with other inputs measures afresh instead of taking a transcript its last inputs left. + pub(crate) view_version: Option, /// 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`. @@ -566,8 +570,9 @@ impl Scoped { /// the flow facts, 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), the command chain, motion, the host's formats and date, and every - /// app value. Computed once per scope, on the first view that asks; the bytes it fed are counted then. - pub(crate) fn scope_key(&self) -> u128 { + /// app value. Computed once per scope, on the first view that asks; the bytes it fed are counted then. The flag says + /// whether the key follows every input it holds (`MemoKey::follows`). + pub(crate) fn scope_key(&self) -> (u128, bool) { *self.scope_key.get_or_init(|| { use crate::contract::{MemoKey, MemoProps as _}; let mut key = MemoKey::of_view(&self.ctx); @@ -597,7 +602,7 @@ impl Scoped { crate::runtime::measure::count_memo_key_bytes(&self.ctx, key.bytes() + value_bytes); #[cfg(not(feature = "testing"))] let _ = value_bytes; - key.finish() + (key.finish(), key.follows()) }) } @@ -728,6 +733,7 @@ impl Env { }), key, scope_key: std::sync::OnceLock::new(), + view_version: None, ink: Ink::default(), surface: SurfaceKind::Background, size: ControlSize::Md, @@ -791,6 +797,8 @@ impl Env { /// /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes. pub fn of(ui: &Ui) -> Env { + #[cfg(feature = "testing")] + WALKS.with(|walks| walks.set(walks.get() + 1)); let ctx = ui.ctx(); let viewport = pass::current_viewport(ctx); // The root env stands for an entry above the whole stack. @@ -962,6 +970,18 @@ impl Env { } } +#[cfg(feature = "testing")] +thread_local! { + static WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times this thread walked a `Ui` stack for its env (`Env::of`). +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn env_walks() -> u64 { + WALKS.with(std::cell::Cell::get) +} + /// One viewport's env entries by the `Ui` they are installed for, and its root env. The lock is held only to /// install or look up an entry or clone an `Arc`. #[derive(Default)] diff --git a/crates/ui-contract/src/runtime/env/app_values.rs b/crates/ui-contract/src/runtime/env/app_values.rs index 41cb894ea6..f7c0197544 100644 --- a/crates/ui-contract/src/runtime/env/app_values.rs +++ b/crates/ui-contract/src/runtime/env/app_values.rs @@ -102,6 +102,7 @@ impl AppValues { keyer(&**value, &mut one); sum = sum.wrapping_add(one.finish()); bytes += one.bytes(); + key.absorb(&one); } key.write(&sum.to_le_bytes()); bytes diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 357f85b1f0..bb40e701e8 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -124,7 +124,7 @@ impl EnvValue for craft_behavior::ZoomScheme { } /// What a number counts. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum UnitKind { diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 38a1b88494..64263b8989 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -173,7 +173,7 @@ impl EnvValue for craft_theme::ComponentSet { impl super::StyleValue for craft_theme::ComponentSet {} /// Where a shell pane sits. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub enum PaneEdge { /// What the edge panes leave. diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index e74ae68240..86e6a45f53 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -617,6 +617,16 @@ pub(crate) fn register_group(ctx: &Context, group: Group) { }); } +/// Names the member Tab arrives at in the roving group `group` registered in the running pass, once its members have +/// registered. A group not registered in this pass is left as it is. +pub(crate) fn name_group_arrival(ctx: &Context, group: Id, member: StopKey) { + with(ctx, |state| { + if let Some(group) = state.groups.get_mut(&group) { + group.selected = Some(member); + } + }); +} + /// Registers the row groups `ids` of the collection `owner` for the running pass. pub(crate) fn register_row_groups(ctx: &Context, owner: Id, rtl: bool, mut ids: Vec) { ids.sort_unstable_by_key(|id| id.value()); diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 4baa04d629..bcb8b6947c 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -2,7 +2,6 @@ use crate::runtime::commands::{self, CommandInput, CommandSet as _, Fired}; use crate::runtime::egui::input::{self as raw_input, Arrived, HeldInput, RawInput}; -use crate::runtime::egui::memory as store; use crate::runtime::egui::{clipboard, pass, scale, style}; use crate::runtime::env::{AltCodePages, Env, RootEnv, WheelSpeed, WindowKey}; use crate::runtime::pass_state; @@ -14,7 +13,6 @@ use craft_keymap::Mods; use craft_theme::{AppSizes, Appearance, Contrast, HitSizes, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, builtins, resolve_sized}; use egui::{Context, Id, Ui, ViewportId}; use std::any::TypeId; -use std::cell::RefCell; use std::collections::HashMap; use std::sync::Arc; @@ -275,18 +273,18 @@ impl PerViewport { } } -/// Where the records of a [`PerViewport`] type live: a context service unless the type is pass-local -/// (`runtime::pass_state`), which overrides these. +/// Where the records of a [`PerViewport`] type live: in the context's pass state, a field of it for the types the +/// runtime names there (`runtime::pass_state`, which overrides these), else by type beside the fields. #[doc(hidden)] pub trait Stored: Default + Send + 'static { /// Runs `f` on the records of this type. fn records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { - store::with::, R>(ctx, f) + pass_state::with_records::(ctx, f) } /// Runs `f` on the stamped records of this type. fn stamped(ctx: &Context, f: impl FnOnce(&mut PerViewport>) -> R) -> R { - store::with::>, R>(ctx, f) + pass_state::with_records::, R>(ctx, f) } } @@ -681,14 +679,6 @@ struct ViewportRecord { impl Stored for ViewportRecord {} -/// What the begin hook read of the running pass; steps read it, none writes it. -#[derive(Clone)] -struct RunningPass { - /// The context the pass runs in. Another context on the same thread, and a pass a panic left open, read none of these. - ctx: Context, - facts: PassFacts, -} - /// What a pass fixes for every step: its viewport, numbers and time. #[derive(Clone, Copy)] #[doc(hidden)] @@ -703,15 +693,11 @@ pub struct PassFacts { pub elapsed: f64, } -thread_local! { - /// The passes between their begin and end hooks on this thread, innermost last: nested viewport passes stack. - static RUNNING: RefCell> = const { RefCell::new(Vec::new()) }; -} - -/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. +/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. The begin hook +/// reads them; steps read them, none writes them. #[doc(hidden)] pub fn running(ctx: &Context) -> Option { - RUNNING.with(|running| running.borrow().iter().rev().find(|pass| pass.ctx == *ctx).map(|pass| pass.facts)) + pass_state::running(ctx) } /// The facts of the innermost running pass of `ctx`, or outside every pass of it, what the context says of its @@ -840,13 +826,8 @@ pub(crate) fn begin_pass(ui: &mut Ui) { let elapsed = record.now.replace(now).map_or(0.0, |previous| (now - previous).max(0.0)); (elapsed, std::mem::take(&mut record.press_cancelled)) }); - RUNNING.with(|running| { - let mut running = running.borrow_mut(); - // A pass of this viewport that never ended (a panic unwound through it) is not still running. - running.retain(|pass| !(pass.ctx == ctx && pass.facts.viewport == viewport)); - running.push(RunningPass { ctx: ctx.clone(), facts: PassFacts { viewport, pass_nr, frame_nr, now, elapsed } }); - }); pass_state::hold(&ctx); + pass_state::begin_running(&ctx, PassFacts { viewport, pass_nr, frame_nr, now, elapsed }); if root_pass.is_some() && pass::first_of_frame(&ctx) { prune_closed(&ctx); } @@ -916,11 +897,6 @@ pub(crate) fn end_pass(ui: &mut Ui) { pass_state::with::(&ctx, |state| state.passes_open = state.passes_open.saturating_sub(1)); #[cfg(feature = "testing")] crate::runtime::egui::access::check_parents_acyclic(&ctx); - RUNNING.with(|running| { - let mut running = running.borrow_mut(); - if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) { - running.remove(at); - } - }); + pass_state::end_running(&ctx); pass_state::release(&ctx); } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index db7583281b..2b5285431a 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -23,6 +23,7 @@ use crate::runtime::inputs::{self, Input}; use crate::runtime::layout_memory; use crate::runtime::reads::BindKey; use crate::runtime::replay::{self, Record}; +use crate::runtime::{Clip, Shift}; use crate::style::EnvKey; use egui::emath::GuiRounding as _; use egui::{Context, Id, IdMap, IdSet, Layout, RecordShift, Rect, Vec2}; @@ -85,7 +86,7 @@ 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)] +#[derive(Clone, 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 @@ -99,6 +100,36 @@ pub(crate) struct Placed { pub(crate) first: Option<(Id, Vec2)>, /// The place of the child the area glides to, when the run reached it. pub(crate) reveal: Option, + /// When the area is a bar's line, its rules and members in run order (`note_line`). + pub(crate) line: Vec, +} + +/// What a bar's line holds, in run order: a rule (`Component::RULE`) is the bar's to draw, and shows only when the member +/// after it shows. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum LineItem { + /// A rule: a line in `look` along `axis` through the middle of `rect`, in `clip`, as the rule had them. + Rule { rect: Rect, clip: Clip, axis: craft_behavior::Axis, look: crate::style::RuleLook }, + /// A member that is not a rule; `cut` when the bar's view shows it only in part, so it does not show. + Member { cut: bool }, +} + +impl Shift for LineItem { + fn shifted(&self, by: &RecordShift) -> Self { + match self { + LineItem::Rule { rect, clip, axis, look } => LineItem::Rule { rect: rect.shifted(by), clip: clip.shifted(by), axis: *axis, look: *look }, + LineItem::Member { cut } => LineItem::Member { cut: *cut }, + } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + match (self, to) { + (LineItem::Rule { rect, clip, axis, look }, LineItem::Rule { rect: to_rect, clip: to_clip, .. }) => { + LineItem::Rule { rect: rect.snapped(to_rect, within), clip: clip.snapped(to_clip, within), axis: *axis, look: *look } + } + _ => self.clone(), + } + } } impl Placed { @@ -140,6 +171,8 @@ struct Entry { /// 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], + /// The pass of the last measuring run in `sizes`. + measuring_pass: u64, /// 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. @@ -172,8 +205,8 @@ pub(crate) struct Measured { pub(crate) fills: Option, } -/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, flow and environment, -/// and its record moves with the room's position (`Place::shift_to`). +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, AccessKit state, opacity, flow +/// 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. @@ -185,6 +218,9 @@ pub(crate) struct Place { /// 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, + /// Whether the pass built AccessKit nodes (`access::builds_nodes`): a run with AccessKit off keeps no nodes, which a + /// pass with it on must show, and AccessKit turns on mid-session (a screen reader starts, automation reads the tree). + pub(crate) access: bool, /// The opacity everything painted in the room is faded to (`Ui::opacity`, a layer fading in or out): the run's /// colours hold it. pub(crate) opacity: f32, @@ -212,7 +248,8 @@ struct Moved { 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, opacity, flow and environment are the ones the run had. A record + /// its size, the layer, layout, scale, font atlas, AccessKit state, opacity, flow and environment are the ones the run + /// had. A record /// that shows an overlay replays only at the room and clip of its run (`Record::pinned`). Any other 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 (`Record::movable`: no paint @@ -231,6 +268,7 @@ impl Place { && now.layout == self.layout && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas + && now.access == self.access && now.opacity == self.opacity && now.env == self.env && now.flow == self.flow; @@ -281,8 +319,12 @@ struct Settled { place: Place, /// The rect its content took. rect: Rect, - /// The pointer was over it, or one of its stops held focus: it runs again to show that they left. + /// A press held that started in it, or one of its stops was the target of a focus request: it runs again to show + /// that they ended. engaged: bool, + /// What pointer sensing gave it (`pointer::Sensed`) and the hover point, screen points, when it ran. + sensed: crate::runtime::pointer::Sensed, + pointer: Option, /// What it ran for: its props key after the run. key: Key, /// The pass it ran in. @@ -423,22 +465,25 @@ fn write(ctx: &Context, id: Id, f: impl FnOnce(&mut Store, u64, u64) -> R) -> 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. +/// Decides whether the child `id`, whose content starts at `at` in this run, runs this pass. It runs when its shown +/// extent placed at `at` meets the view, or when one of its stops holds focus or is the target of a focus request. Its +/// shown extent is the one its last real run showed it at, else the one a measuring run found, 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. The answer does not depend on which kind of run decides: a child whose real extent is +/// more than its content's (a card its grid row stretches) meets the view by its shown extent in both. 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); 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. + // A skipped child takes this kind of run's extent in flow; one the other kind of run showed last takes that one. 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, _ => { + let shown = entry.sizes[1].or(entry.sizes[0]).map_or(estimate, |measured| measured.size); let focus = entry.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); - let skip = !focus && !at(size).intersects(view.rect); + let skip = !focus && !at(shown).intersects(view.rect); entry.decided = Some((pass_nr, skip)); skip } @@ -450,9 +495,12 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - /// 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| { + write(ctx, id, |store, pass_nr, frame| { let entry = store.touch(owner, id, frame); entry.sizes[usize::from(!sizing)] = Some(measured); + if sizing { + entry.measuring_pass = pass_nr; + } if let Some(registered) = registered { entry.focus = Arc::new(registered); } @@ -466,10 +514,14 @@ pub(crate) fn fills(ctx: &Context, id: Id, sizing: bool) -> Option Option { - with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[1].map(|measured| measured.size))) + with(ctx, |store, pass_nr, _| { + let entry = store.entries.get(&id)?; + let measured = entry.sizes[0].filter(|_| entry.measuring_pass == pass_nr); + measured.or(entry.sizes[1]).map(|measured| measured.size) + }) } /// Registers what the skipped child `id` registered with the focus service in the last real run that showed it, in @@ -494,8 +546,15 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// 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 or an overlay layer it shows, no press started on either and none of its widgets is -/// dragged, and none of that held in its last run; +/// - what pointer sensing gives it is what its run saw (`pointer::Sensed`: the hover, part and pointer-over facts of +/// the components whose shapes it registered and of its egui widgets), so a move within one part of it, a +/// collection's row among them, leaves it alone, and a move onto another part, in or out runs it; while it is under +/// the pointer, the modifiers are the ones its run saw; the pointer did not move in a rect its run follows the +/// pointer in (`pointer::follows_pointer`, which a hover position read marks), now or then; no wheel share or owed +/// ease of this pass goes to a taker it registered; no tap of this pass lies in it; while a drag session runs, the +/// pointer is not over it or an overlay layer it shows; +/// - no press that is held started on it or an overlay layer it shows, none of its widgets is dragged, and none of +/// that held in its last run; /// - the focus is where its run left it (`replay::Held`: the same stop and egui widget of it, or none), and while the /// focus is in it no key, text, IME, clipboard or AccessKit event came (`Input::Sent`, which such a run reads); /// - none of its stops is the target of a focus request, now or in its last run; @@ -504,7 +563,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - 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; /// - the call's key is the one of its last run (its props key after that run), and its environment (theme, density, -/// scale, language, window active) and the flow of the body around it (`Flow`) the ones it ran in; +/// scale, language, window active), the flow of the body around it (`Flow`) and whether the pass builds AccessKit +/// nodes the ones 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 @@ -595,7 +655,9 @@ pub(crate) fn settled( // 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), &settled.record.facts.overlays) + let shown = rect.intersect(shift.clip); + if pressed(ctx, settled.place.layer, shown, &settled.record.facts.overlays) + || pointer_reaches(ctx, &settled, shown, shift.offset) || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) || moved(ctx, &settled, view) { @@ -624,16 +686,40 @@ fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option bool { - let over = |layer: Layer, rect: Rect| { +/// Whether a press that is held started in `rect` (shown) on `layer` or in one of the overlay layers `overlays` shown, +/// with the layer the top layer at its origin, so a press on an overlay above the view leaves it alone. +fn pressed(ctx: &Context, layer: Layer, rect: Rect, overlays: &[replay::ShownLayer]) -> bool { + let Some(origin) = input_state::held_press_origin(ctx) else { return false }; + let on = |layer: Layer, rect: Rect| { 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) && ctx.layer_id_at(origin) == Some(layer)) + screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer) }; - over(layer, rect) || overlays.iter().any(|shown| over(shown.layer, shown.rect)) + on(layer, rect) || overlays.iter().any(|shown| on(shown.layer, shown.rect)) +} + +/// Whether the pointer input of this pass reaches the kept run `settled`, which replays at `rect` (shown), moved by +/// `offset`: the pointer rules of `settled`. +fn pointer_reaches(ctx: &Context, settled: &Settled, rect: Rect, offset: Vec2) -> bool { + let facts = &settled.record.facts; + let sensed = crate::runtime::pointer::sensed(ctx, &facts.sensors, &settled.record.widgets); + let changed = |input: Input| inputs::generation(ctx, input) != settled.seen[input as usize]; + let hover = crate::runtime::pointer::hover_point(ctx); + let follows = changed(Input::Pointer) + && facts + .follows + .iter() + .any(|ran| hover.is_some_and(|at| ran.translate(offset).contains(at)) || settled.pointer.is_some_and(|at| ran.contains(at))); + let layer = settled.place.layer; + let over = |layer: Layer, rect: Rect| ctx.rect_contains_pointer(layer, rect); + let dragged = crate::runtime::drag::running(ctx) && (over(layer, rect) || facts.overlays.iter().any(|shown| over(shown.layer, shown.rect))); + let tapped = crate::runtime::pointer::with_frame(ctx, |frame, _| frame.and_then(|frame| frame.multi_tap)) + .is_some_and(|tap| ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect).contains(tap.at)); + sensed != settled.sensed + || (!sensed.is_empty() && changed(Input::Modifiers)) + || follows + || crate::runtime::wheel::reaches(ctx, &facts.takers) + || dragged + || tapped } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` @@ -655,8 +741,10 @@ pub(crate) fn audit( 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() { + // A pass that turned to discard during the audit run paints nothing: its run is no shown run to compare with. A + // discard layout memory asked for (a layout entry the run placed by was gone or moved) reaches egui only in the end + // hook. + if ctx.will_discard() || crate::runtime::layout_memory::discard_pending(ctx) { return; } let Some(kept) = with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.clone())) else { return }; @@ -702,8 +790,11 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec let revealed = focus::targets(ctx)[1]; let engaged_now = record.focus.stop_ids().any(|stop| revealed == Some(stop)); 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), &settled.record.facts.overlays); + let sensed = crate::runtime::pointer::sensed(ctx, &record.facts.sensors, &record.widgets); + let pointer = crate::runtime::pointer::hover_point(ctx); + let mut settled = + Settled { record, frame: 0, place, rect, engaged: engaged_now, sensed, pointer, key, pass: 0, edits, output, lives, seen, view }; + settled.engaged |= pressed(ctx, place.layer, rect.intersect(place.clip), &settled.record.facts.overlays); with(ctx, |store, pass_nr, frame| { settled.frame = frame; settled.pass = pass_nr; @@ -797,6 +888,20 @@ fn note_place(ctx: &Context, owner: Id, id: Id, rect: Rect) { }); } +/// Notes, in the real run that lays out the bar line `owner`, its next rule or member `item`. A settled run around it +/// that is replayed later notes it again, moved with the run, so the bar draws the rules its replayed members hold; a +/// line inside the replayed run does not lay out in that pass, and its record holds the rules it drew. +pub(crate) fn note_line(ctx: &Context, owner: Id, item: LineItem) { + replay::journal(ctx, || (owner, item.clone()), |ctx, (owner, item)| note_line(ctx, *owner, item.clone())); + with(ctx, |store, _, _| { + if let Some(placed) = store.placed.get_mut(&owner) + && placed.view.is_some() + { + placed.line.push(item); + } + }); +} + /// What the children of the area `owner` reported since `begin`. pub(crate) fn placed(ctx: &Context, owner: Id) -> Placed { with(ctx, |store, _, _| store.placed.remove(&owner).unwrap_or_default()) diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index b0da0f3da0..c4927a38c1 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -326,8 +326,9 @@ fn end_lives(reg: &mut Registry, owners: impl IntoIterator) { pub(crate) fn evict(ctx: &Context) { let now = frame::clock(ctx); let live = pass::live_viewports(ctx); + let running = frame::running(ctx); pass_state::with::(ctx, |reg| { - let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr(ctx, r.viewport), now, live.contains(&r.viewport)); + let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr_beside(ctx, running, r.viewport), now, live.contains(&r.viewport)); let dead: IdSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect(); if dead.is_empty() { return; @@ -949,17 +950,22 @@ impl Facts { Self::with_record(ctx, |record| record.this.push(fact)); } - /// The facts the running viewport's previous pass registered, in registration order. + /// `f` on the facts the running viewport's previous pass registered, in registration order. `f` reaches no + /// service: the record is held while it runs. #[doc(hidden)] - pub fn of_last_pass(ctx: &Context) -> Vec { - Self::with_record(ctx, |record| record.last.clone()) + pub fn with_last_pass(ctx: &Context, f: impl FnOnce(&[T]) -> R) -> R { + Self::with_record(ctx, |record| f(&record.last)) } fn with_record(ctx: &Context, f: impl FnOnce(&mut FactRecord) -> R) -> R { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); let advance = |record: &mut FactRecord, step: PassStep| match step { - PassStep::Next => record.last = std::mem::take(&mut record.this), + // The buffers swap, so a pass reuses the room the pass before it grew. + PassStep::Next => { + std::mem::swap(&mut record.last, &mut record.this); + record.this.clear(); + } PassStep::Skipped => { record.last.clear(); record.this.clear(); diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 2ac5ad08b6..aec0b13902 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -10,9 +10,10 @@ //! context runs. Another thread can't reach the state while a pass holds it: the runtime touches these services only //! from the thread that runs the pass. -use crate::runtime::egui::memory::Service; -use crate::runtime::frame::{self, PerViewport, Stamped, Stored}; +use crate::runtime::egui::memory::{FastMap, Service}; +use crate::runtime::frame::{PassFacts, PerViewport, Stamped, Stored}; use egui::{Context, IdSet}; +use std::any::{Any, TypeId}; use std::cell::{Cell, RefCell}; use std::sync::Arc; @@ -33,6 +34,9 @@ macro_rules! pass_state { $($(#[$service_attr])* $service: RefCell<$service_ty>,)* $($record: RefCell>,)* $($stamped: RefCell>>,)* + /// The per-viewport records of the types with no field here (generic ones, and those of crates above the + /// runtime), by type: each value is a `RefCell>`. + others: RefCell>>, } $($(#[$service_attr])* impl PassLocal for $service_ty { @@ -93,7 +97,6 @@ pass_state! { least_reports: crate::layout::body::LeastReports, fill_leasts: crate::layout::body::FillLeasts, row_shortfalls: crate::layout::body::RowShortfalls, - bar_rules: crate::contract::BarRules, surface_frames: crate::primitives::SurfaceFrames, fill_counts: crate::layout::body::FillCounts, view_fills: crate::layout::body::ViewFills, @@ -163,6 +166,15 @@ pass_state! { struct Held { ctx: Context, state: Box, + /// The context's passes between their begin and end hooks on this thread, innermost last: nested viewport passes + /// stack. A pass a panic unwound through stays until a pass of its viewport begins again. + passes: RefCell>, +} + +impl Held { + fn running(&self) -> bool { + !self.passes.borrow().is_empty() + } } struct HeldStates { @@ -178,13 +190,13 @@ impl HeldStates { /// Service reads in the same context reuse its slot. A nested context or a swap on release /// can change the slot, so verify its owner before reusing it. - fn get(&self, ctx: &Context) -> Option<&PassState> { + fn get(&self, ctx: &Context) -> Option<&Held> { if let Some(entry) = self.entries.get(self.current.get()).filter(|entry| entry.ctx == *ctx) { - return Some(&entry.state); + return Some(entry); } let at = self.entries.iter().position(|entry| entry.ctx == *ctx)?; self.current.set(at); - Some(&self.entries[at].state) + Some(&self.entries[at]) } } @@ -214,7 +226,7 @@ pub(crate) fn with_component_tree(ctx: &Context, run: impl FnOnce()) { impl Drop for Restore { fn drop(&mut self) { if let Some(entry) = self.0.take() { - if frame::running(&entry.ctx).is_some() { + if entry.running() { keep(entry); } else { park(entry); @@ -249,34 +261,103 @@ impl Default for Parked { pub(crate) fn with(ctx: &Context, f: impl FnOnce(&mut S) -> R) -> R { #[cfg(feature = "testing")] crate::runtime::layout_memory::guard::touch::(); + with_state(ctx, |state| f(&mut S::cell(state).borrow_mut())) +} + +/// Runs `f` on the context's records of `T`, one per viewport, for a type with no field in [`PassState`]. `f` makes +/// no call that reaches the context, so no other record of this kind is first used inside it. +pub(crate) fn with_records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { + with_state(ctx, |state| { + let key = TypeId::of::>(); + if !state.others.borrow().contains_key(&key) { + state.others.borrow_mut().insert(key, Box::new(RefCell::new(PerViewport::::default()))); + } + let others = state.others.borrow(); + #[expect(clippy::expect_used, reason = "the entry under a type's id is created above with that type")] + let records = others.get(&key).and_then(|records| records.downcast_ref::>>()).expect("the records of the type"); + f(&mut records.borrow_mut()) + }) +} + +/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. +pub(crate) fn running(ctx: &Context) -> Option { + if RUNNING.is_set() + && let Some(facts) = RUNNING.with(|entry| (entry.ctx == *ctx).then(|| entry.passes.borrow().last().copied())) + { + return facts; + } + note_unbound(); + HELD.with(|held| held.borrow().get(ctx).and_then(|entry| entry.passes.borrow().last().copied())) +} + +/// Puts the pass the begin hook starts on the running stack of `ctx`, whose state this thread holds: a pass of the +/// same viewport still there never ended (a panic unwound through it). +pub(crate) fn begin_running(ctx: &Context, facts: PassFacts) { + let held = with_entry(ctx, |entry| { + let mut passes = entry.passes.borrow_mut(); + passes.retain(|pass| pass.viewport != facts.viewport); + passes.push(facts); + }); + debug_assert!(held.is_some(), "the begin hook holds the context's pass state"); +} + +/// Takes the innermost pass of `ctx` off its running stack: the end hook. +pub(crate) fn end_running(ctx: &Context) { + with_entry(ctx, |entry| entry.passes.borrow_mut().pop()); +} + +/// Runs `f` on the entry of `ctx` this thread holds, bound or not. +fn with_entry(ctx: &Context, f: impl FnOnce(&Held) -> R) -> Option { + if bound(ctx) { + return Some(RUNNING.with(f)); + } + HELD.with(|held| held.borrow().get(ctx).map(f)) +} + +/// Runs `f` on the context's pass state: inside its component tree, straight from the binding. +fn with_state(ctx: &Context, f: impl FnOnce(&PassState) -> R) -> R { let mut call = Some(f); + if RUNNING.is_set() + && let Some(out) = RUNNING.with(|entry| if entry.ctx == *ctx { call.take().map(|f| f(&entry.state)) } else { None }) + { + return out; + } + note_unbound(); let mut out = None; visit(ctx, &mut |state| { if let Some(f) = call.take() { - out = Some(f(&mut S::cell(state).borrow_mut())); + out = Some(f(state)); } }); #[expect(clippy::expect_used, reason = "visit calls its callback once on both the held and parked paths")] out.expect("the pass state was visited") } -/// The thread-local lookup and the parked-state slow path are shared by every service and caller. +#[cfg(feature = "testing")] +thread_local! { + static UNBOUND: Cell = const { Cell::new(0) }; +} + +/// How many reads of a pass state this thread made outside the component tree that binds it. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn unbound_reads() -> u64 { + UNBOUND.with(Cell::get) +} + +#[inline] +fn note_unbound() { + #[cfg(feature = "testing")] + UNBOUND.with(|reads| reads.set(reads.get() + 1)); +} + +/// The state of a context its component tree does not bind: the thread's held entry, else the parked state, held for +/// this read alone. Shared by every service and caller. fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) { - if RUNNING.is_set() - && RUNNING.with(|entry| { - if entry.ctx != *ctx { - return false; - } - f(&entry.state); - true - }) - { - return; - } let found = HELD.with(|held| { let held = held.borrow(); - let Some(state) = held.get(ctx) else { return false }; - f(state); + let Some(entry) = held.get(ctx) else { return false }; + f(&entry.state); true }); if !found { @@ -292,8 +373,8 @@ fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) { HELD.with(|held| { let held = held.borrow(); #[expect(clippy::expect_used, reason = "`hold` has just moved the context's state into this thread")] - let state = held.get(ctx).expect("the state was just taken"); - f(state) + let entry = held.get(ctx).expect("the state was just taken"); + f(&entry.state) }) } } @@ -304,8 +385,7 @@ pub(crate) fn hold(ctx: &Context) { if bound(ctx) { return; } - let stale: Vec = - HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && frame::running(&entry.ctx).is_none()).collect()); + let stale: Vec = HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && !entry.running()).collect()); for held in stale { park(held); } @@ -315,15 +395,19 @@ pub(crate) fn hold(ctx: &Context) { let state = Service::::run(ctx, |parked| parked.0.take()); debug_assert!(state.is_some(), "another thread holds this context's pass state"); let state = state.unwrap_or_default(); - keep(Held { ctx: ctx.clone(), state }); + keep(Held { ctx: ctx.clone(), state, passes: RefCell::new(Vec::new()) }); } /// Moves the context's state back into its context data unless a pass of it still runs on this thread: the end hook. pub(crate) fn release(ctx: &Context) { - if bound(ctx) || frame::running(ctx).is_some() { + if bound(ctx) { return; } - if let Some(held) = HELD.with(|held| held.borrow_mut().take(ctx)) { + let idle = HELD.with(|held| { + let mut held = held.borrow_mut(); + if held.get(ctx).is_some_and(Held::running) { None } else { held.take(ctx) } + }); + if let Some(held) = idle { park(held); } } @@ -334,14 +418,13 @@ fn park(held: Held) { #[cfg(all(feature = "testing", any(test, feature = "suite")))] pub(crate) mod binding_tests { - use super::{PassState, bound, hold, in_component_tree, visit, with_component_tree}; + use super::{PassState, begin_running, bound, end_running, hold, in_component_tree, release, running, with_component_tree, with_state}; + use crate::runtime::frame::PassFacts; use crate::testing::trial; - use egui::Context; + use egui::{Context, ViewportId}; fn address(ctx: &Context) -> *const PassState { - let mut address = std::ptr::null(); - visit(ctx, &mut |state| address = std::ptr::from_ref(state)); - address + with_state(ctx, std::ptr::from_ref) } #[trial] @@ -349,11 +432,14 @@ pub(crate) mod binding_tests { let outer = Context::default(); let inner = Context::default(); hold(&outer); + begin_running(&outer, PassFacts { viewport: ViewportId::ROOT, pass_nr: 7, frame_nr: 7, now: 0.0, elapsed: 0.0 }); let original = address(&outer); let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { with_component_tree(&outer, || { assert!(bound(&outer)); assert!(!bound(&inner)); + assert_eq!(running(&outer).map(|facts| facts.pass_nr), Some(7), "the tree reads its pass from the binding"); + assert!(running(&inner).is_none(), "a nested context has no pass running"); assert_ne!(address(&inner), original); assert_eq!(address(&outer), original); std::panic::resume_unwind(Box::new("component unwound")); @@ -362,5 +448,9 @@ pub(crate) mod binding_tests { assert!(unwound.is_err_and(|reason| reason.downcast_ref::<&str>() == Some(&"component unwound"))); assert!(!in_component_tree()); assert_eq!(address(&outer), original); + assert_eq!(running(&outer).map(|facts| facts.pass_nr), Some(7), "the running pass outlives the unwound tree"); + end_running(&outer); + release(&outer); + assert!(running(&outer).is_none()); } } diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index bb7d81ce9a..3324e4c897 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -248,6 +248,9 @@ pub(crate) struct Shapes { /// What lies under the pass's hover point, found over `last` at the begin hook with the pass's egui targets: /// every root's hover reads it, and a press at the same point and targets reuses it. hover: Option<(Pos2, PressTargets, Under)>, + /// The egui widgets under the pass's hover point in the last finished pass, with the click and drag targets there + /// (`Context::widgets_at`), found once at the begin hook for every view's `sensed`. + hover_widgets: Option<(Vec, Option, Option)>, /// A press was open when the pass began: only its target hovers. captured: bool, /// The pass's tap went to a component. @@ -376,7 +379,9 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if events { inputs::bump(ctx, Input::Pointer); } - // A press or release, or an outside press the layer stack's input hook took before egui saw it. + // A press or release, or an outside press the layer stack's input hook took before egui saw it. The buttons + // held are part of the press state ([`press_state`]) too. + inputs::observe(ctx, Input::Press, frame.buttons); if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() { inputs::bump(ctx, Input::Press); } @@ -407,8 +412,10 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { let hover_targets = PressTargets { click: hits.0, drag: hits.1 }; let hover = hover_at.map(|at| (at, hover_targets, find_under(ctx, viewport, at, hover_targets, false))); let captured = press_captured(ctx); + let hover_widgets = hover_at.and_then(|at| ctx.widgets_at(viewport, at)); PerViewport::::with(ctx, viewport, |shapes| { shapes.hover = hover; + shapes.hover_widgets = hover_widgets; shapes.captured = captured; shapes.pressed_parts.clear(); }); @@ -476,7 +483,8 @@ pub(crate) fn with_frame(ctx: &Context, f: impl FnOnce(Option<&PointerFrame>, } /// 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`]. +/// pointer changes. A view that reads only the modifiers reads [`mods`], one that reads only the buttons, presses and +/// releases [`press_state`]. pub fn frame(ctx: &Context) -> PointerFrame { crate::runtime::replay::note_input(ctx, Input::Pointer); frame_raw(ctx) @@ -489,6 +497,32 @@ pub fn mods(ctx: &Context) -> Mods { with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods)) } +/// The press state of a pass: the buttons held, and the primary press and the release the pass brought. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct PressState { + /// The buttons held (`PointerFrame::buttons`). + pub buttons: Buttons, + /// The primary press of the pass (`PointerFrame::press`). + pub press: Option, + /// The button released in the pass (`PointerFrame::release`). + pub release: Option, +} + +/// The press state of the running pass. A tracked input (`Input::Press`): a memoized view that reads it runs on a +/// press or a release, and a pointer move leaves it alone. A view that needs the pointer's position reads [`frame`]. +pub fn press_state(ctx: &Context) -> PressState { + crate::runtime::replay::note_input(ctx, Input::Press); + with_pass_raw(ctx, |pointer| { + let frame = pointer.frame.as_ref(); + PressState { + buttons: frame.map_or(Buttons::empty(), |frame| frame.buttons), + press: frame.and_then(|frame| frame.press), + release: frame.and_then(|frame| frame.release), + } + }) +} + /// Where the primary press of the running pass started. A tracked input (`Input::Press`): a layer's dismissal decides by /// it, so a memoized view that shows a layer runs on a press anywhere, and a pointer move leaves it alone. pub(crate) fn primary_press(ctx: &Context) -> Option { @@ -637,6 +671,7 @@ pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer /// `record_shapes_in` with no note in the run records, for a caller whose own note makes the shapes again: shapes at /// stack positions a replay takes from the arena it joins (`sensing`), not from the recorded run. pub(crate) fn add_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, clip: Rect, shapes: Vec>) { + crate::runtime::replay::note_sensors(ctx, shapes.iter().map(|shape| shape.owner)); PerViewport::::with(ctx, viewport, |record| { let order = record.next; record.next += 1; @@ -671,11 +706,32 @@ pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) { /// Records that what the running pass shows in `rect` (screen points) follows the pointer: a cursor drawn at the /// pointer, a readout of the point under it. A pointer move into, out of or within `rect` runs a pass even when /// nothing under the pointer changes ([`gate_pointer_moves`]). +/// +/// A memoized view whose run marked a rect runs on each pointer move into, out of or within it (`runtime::lazy`). pub fn follows_pointer(ctx: &Context, rect: Rect) { crate::runtime::replay::journal(ctx, || rect, |ctx, &rect| follows_pointer(ctx, rect)); + crate::runtime::replay::note_follows(ctx, rect); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| record.this_follows.push(rect)); } +/// The running pass's hover point (screen points) when it lies in `rect` (screen points), for code that shows what +/// it reads there (a readout, a cursor drawn at the point, a band at the line nearest it): `rect` then follows the +/// pointer ([`follows_pointer`]). The one way component code reads where the pointer hovers. +pub fn hover_point_in(ctx: &Context, rect: Rect) -> Option { + let at = with_frame(ctx, |_, hover| hover).filter(|at| rect.contains(*at))?; + follows_pointer(ctx, rect); + Some(at) +} + +/// Marks the hit area of a part with the bounds `rect` on `layer` (layer space) as following the pointer: its owner +/// read the hover position there (`Cx::hover_pos`). The area is the bounds grown to the least hit size across, as +/// sensing grows them. +pub(crate) fn follows_part(ctx: &Context, layer: Layer, rect: Rect) { + let target = with_frame(ctx, |frame, _| frame.map_or(0.0, |frame| frame.target)); + let grow = (Vec2::splat(target) - rect.size()).max(Vec2::ZERO) / 2.0; + follows_pointer(ctx, areas::layer_to_screen(ctx, layer) * rect.expand2(grow)); +} + /// Lets a pointer move run no pass when nothing it would change differs: egui's gate /// ([`egui::Context::set_pointer_move_gate`]) answers [`move_needs_pass`]. An app opts in once; without it every move /// runs a pass. @@ -1003,6 +1059,11 @@ pub(crate) struct Under { pub hover_top: Option<(Winner, Id)>, /// Every root with a shape under the point, on top or not: the roots that contain the pointer. pub over: SmallVec<[Id; 4]>, + /// Every component (root or member) that owns a shape under the point, on top or not. + pub owners: SmallVec<[Id; 4]>, + /// The roots' own parts with a shape under the point, on top or not, each with its root: a collection's row that + /// contains the pointer under the row's own shapes. + pub parts: SmallVec<[(Id, PartRef); 4]>, } impl Under { @@ -1056,6 +1117,78 @@ pub(crate) fn with_hover(ctx: &Context, viewport: ViewportId, f: impl FnOnce( PerViewport::::with(ctx, viewport, |record| f(record.hover.as_ref().map(|(_, _, under)| under), record.captured)) } +/// A shape a memoized view's run sensed ([`Sensed::hover`]): its kind, root, owner and part. +type SensedShape = (u8, Id, Id, Option); + +/// What pointer sensing gives a memoized view's run in the running pass (`runtime::lazy`): of the components that own +/// shapes the run registered (arena roots and members) and of its egui widgets, the ones under the pass's hover point +/// and what they win there. A component's facts are its own: a member's view sees a move over a sibling member or its +/// root as nothing. Equal answers in two passes mean every hover, part and pointer-over fact the run's components read +/// is the same; a hover position is not part of it, as the code that reads one marks itself ([`follows_pointer`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Sensed { + /// The press winners and the shape that hovers beside them (`Under`), each as its kind, root, owner and part, of + /// the run's components. None while a press is open: only the press's target hovers, and the press runs it. + hover: SmallVec<[SensedShape; 3]>, + /// The run's components with a shape under the point. + over: SmallVec<[Id; 4]>, + /// The own parts of the run's roots with a shape under the point (`Under::parts`). + parts: SmallVec<[(Id, PartRef); 4]>, + /// The run's egui widgets that contain the point, then its click and drag targets there. + widgets: SmallVec<[Id; 4]>, +} + +impl Sensed { + /// Nothing of the run lies under the pointer. + pub(crate) fn is_empty(&self) -> bool { + self.hover.is_empty() && self.over.is_empty() && self.parts.is_empty() && self.widgets.is_empty() + } +} + +/// What pointer sensing gives the components `sensors` and egui widgets `widgets` of a run in the running pass +/// ([`Sensed`]): read from the pass's one resolution at the hover point. +pub(crate) fn sensed(ctx: &Context, sensors: &IdSet, widgets: &IdSet) -> Sensed { + PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { + let mut sensed = Sensed::default(); + if let Some((_, _, under)) = &record.hover + && !sensors.is_empty() + { + if !record.captured { + let found = [under.press.click, under.press.drag, under.hover_top]; + for (kind, (winner, root)) in (0u8..).zip(found).filter_map(|(kind, found)| Some((kind, found?))) { + if sensors.contains(&winner.owner) { + sensed.hover.push((kind, root, winner.owner, winner.part)); + } + } + } + sensed.over.extend(under.owners.iter().copied().filter(|owner| sensors.contains(owner))); + sensed.parts.extend(under.parts.iter().copied().filter(|(root, _)| sensors.contains(root))); + } + if let Some((contains, click, drag)) = &record.hover_widgets + && !widgets.is_empty() + { + sensed.widgets.extend(contains.iter().chain(click).chain(drag).copied().filter(|widget| widgets.contains(widget))); + } + sensed + }) +} + +/// The running pass's hover point, screen points; `None` while the pointer is not in the window. +pub(crate) fn hover_point(ctx: &Context) -> Option { + with_frame(ctx, |_, hover| hover) +} + +/// The own parts of the root `root` with a shape under the running pass's hover point, on top or not +/// (`Under::parts`), by the pass's one resolution: the parts that contain the pointer. +pub(crate) fn parts_under(ctx: &Context, root: Id) -> SmallVec<[PartRef; 4]> { + PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { + record + .hover + .as_ref() + .map_or_else(SmallVec::new, |(_, _, under)| under.parts.iter().filter(|(owner, _)| *owner == root).map(|(_, part)| *part).collect()) + }) +} + /// Whether a shape the component `id` registered shows hover in the running pass, by the pass's one resolution of /// what lies under the pointer: it takes the press there, or it is the topmost shape and takes none. A /// container reads it for the components in its body before they run. While a press is open it holds for none: only @@ -1124,6 +1257,17 @@ fn find_under(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTarge if !under.over.contains(&root) { under.over.push(root); } + for &index in &kept { + let shape = &entry.shapes[index]; + if !under.owners.contains(&shape.owner) { + under.owners.push(shape.owner); + } + if let Some(part) = shape.part.filter(|_| shape.owner == root) + && !under.parts.contains(&(root, part)) + { + under.parts.push((root, part)); + } + } // The winner among the shapes at `indices` by `kind`, with its rank. let pick = |indices: &[usize], kind: ResolveFor| { let mut shapes: Vec> = indices.iter().map(|&index| entry.shapes[index].clone()).collect(); diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 68213a9c3b..2adadc14b6 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -24,10 +24,10 @@ use crate::runtime::reads::BindKey; use crate::runtime::shift::Shift; use egui::{Context, IdSet, RecordShift, Rect}; use std::any::Any; +use std::cell::Cell; use std::collections::HashSet; use std::fmt; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; /// A registration of the recorded run: the call that makes it again and what it is called with. Two entries are equal /// when they come from the same call (the same `again` of [`journal`]) with equal arguments. @@ -108,8 +108,17 @@ impl fmt::Debug for Entry { } } -/// Records open across all contexts, so a registration made while none is open takes no lock. -static OPEN: AtomicUsize = AtomicUsize::new(0); +thread_local! { + /// The records open on this thread, so a registration made while none is open reads no pass state. Records are + /// open only around runs of a pass, on the pass's own thread: a job's thread (a finished job's wake, a progress + /// report) has none, and never takes the pass state the pass's thread holds. + static OPEN: Cell = const { Cell::new(0) }; +} + +/// Whether a record is open on this thread. +fn any_open() -> bool { + OPEN.with(Cell::get) > 0 +} /// The journal of the running pass while a record is open, and the records open around the running code. #[derive(Default)] @@ -184,6 +193,13 @@ pub(crate) struct Facts { pub(crate) overlays: Vec, /// The layer stack entries the run recorded (`note_layer`): a close queued for one is taken only by a run. pub(crate) layers: Vec, + /// The components (arena roots and members) that own shapes the run registered (`note_sensors`): what pointer + /// sensing gives them is what the run saw of the pointer (`pointer::Sensed`), with the run's egui widgets. + pub(crate) sensors: IdSet, + /// The screen rects the run's content follows the pointer in (`pointer::follows_pointer`). + pub(crate) follows: Vec, + /// The wheel takers the run registered (`wheel::register`): a share of the wheel for one runs it. + pub(crate) takers: Vec, } /// An overlay layer a run showed: its egui layer and its rect in screen space. @@ -246,7 +262,7 @@ impl Record { /// 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()) + any_open() && pass_state::with::(ctx, |recorder| !recorder.open.is_empty()) } /// Opens a record around the real run of a region, which `close` ends. A run inside an open label scope cannot be @@ -263,7 +279,7 @@ pub(crate) fn open_in_pass(ctx: &Context) { 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); + OPEN.with(|open| open.set(open.get() + 1)); } /// Opens a record around a run of the replay audit, which `close` ends as any other. @@ -275,13 +291,13 @@ pub(crate) fn open_audit(ctx: &Context) { /// 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)) + any_open() && 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 a layer that is neither `layer` nor /// an overlay the run showed block it. pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { - OPEN.fetch_sub(1, Ordering::AcqRel); + OPEN.with(|open| open.set(open.get().saturating_sub(1))); let (open, journal) = pass_state::with::(ctx, |recorder| { // A close with no open record ends one that holds nothing and is never replayed. let open = recorder.open.pop().unwrap_or_else(|| { @@ -306,6 +322,9 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.instances.extend(open.facts.instances.iter().copied()); outer.facts.overlays.extend(open.facts.overlays.iter().copied()); outer.facts.layers.extend(open.facts.layers.iter().copied()); + outer.facts.sensors.extend(open.facts.sensors.iter().copied()); + outer.facts.follows.extend(open.facts.follows.iter().copied()); + outer.facts.takers.extend(open.facts.takers.iter().copied()); } else { recorder.journal.clear(); } @@ -458,10 +477,8 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { } fn with_open(ctx: &Context, f: impl FnOnce(&mut Facts)) { - // Records are open only around runs of a pass on its own thread. A job's thread (a finished job's wake, a progress - // report) runs no pass of `ctx`: it has no record to note into and must not take the pass state that the pass's - // thread holds. - if OPEN.load(Ordering::Acquire) > 0 && frame::running(ctx).is_some() { + // A record open on this thread is one of a running pass: of `ctx`, or of another context this thread runs. + if any_open() && frame::running(ctx).is_some() { pass_state::with::(ctx, |recorder| { if let Some(open) = recorder.open.last_mut() { f(&mut open.facts); @@ -518,7 +535,7 @@ where /// Notes that the running code read the value `key`. pub(crate) fn note_read(ctx: &Context, key: BindKey) { - if OPEN.load(Ordering::Acquire) > 0 && frame::running(ctx).is_some() { + if any_open() && frame::running(ctx).is_some() { pass_state::with::(ctx, |recorder| { if let Some(open) = recorder.open.last_mut() && (!open.kept || !matches!(key, BindKey::Place(..))) @@ -555,6 +572,21 @@ pub(crate) fn note_overlay(ctx: &Context, layer: Layer, rect: Rect) { with_open(ctx, |facts| facts.overlays.push(ShownLayer { layer, rect })); } +/// Notes that the running code registered shapes owned by the components `owners`, by a run or a replay. +pub(crate) fn note_sensors(ctx: &Context, owners: impl IntoIterator) { + with_open(ctx, |facts| facts.sensors.extend(owners)); +} + +/// Notes that what the running code shows in the screen rect `rect` follows the pointer, by a run or a replay. +pub(crate) fn note_follows(ctx: &Context, rect: Rect) { + with_open(ctx, |facts| facts.follows.push(rect)); +} + +/// Notes that the running code registered the wheel taker `owner`, by a run or a replay. +pub(crate) fn note_taker(ctx: &Context, owner: egui::Id) { + with_open(ctx, |facts| facts.takers.push(owner)); +} + /// Notes that the running code recorded the layer stack entry `id`, by a run or a replay. pub(crate) fn note_layer(ctx: &Context, id: egui::Id) { with_open(ctx, |facts| facts.layers.push(id)); diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index e2dc2aebf2..7f253e1d3a 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -163,6 +163,7 @@ pub(crate) fn register(ctx: &Context, taker: WheelTaker) { return; } crate::runtime::replay::journal(ctx, || taker, |ctx, &taker| register(ctx, taker)); + crate::runtime::replay::note_taker(ctx, taker.owner); let layer = crate::runtime::overlay::drawing_parent(ctx); PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { state.this_layers.insert(taker.owner, layer); @@ -333,6 +334,16 @@ pub(crate) fn begin(ctx: &Context, pointer_scoped_field_wheel: bool) { } } +/// Whether this pass's wheel reaches one of `takers`: a share of it goes to one, or one's ease owes motion it pays in +/// this pass. +pub(crate) fn reaches(ctx: &Context, takers: &[Id]) -> bool { + !takers.is_empty() + && PerViewport::::with(ctx, pass::current_viewport(ctx), |state| { + state.shares.iter().any(|(owner, _)| takers.contains(owner)) + || state.eases.iter().any(|(owner, ease)| ease.owes() && takers.contains(owner)) + }) +} + /// The component's share of this pass's wheel, left in place. pub(crate) fn peek(ctx: &Context, id: Id) -> Option { PerViewport::::with(ctx, pass::current_viewport(ctx), |state| state.shares.iter().find(|(owner, _)| *owner == id).map(|share| share.1)) diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index 6ddd4c814d..161ed8061a 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -92,8 +92,11 @@ pub(crate) struct Shared { desktop: Option, /// Whether the root window had focus in the last root pass. root_focused: bool, - /// The app's state when the last frame's windows had all reported, which its palettes follow. + /// The app's state as the last root frame's windows reported it, which its palettes follow. app: AppState, + /// The windows [`show_viewport`] showed in this root frame: with the root's, the app's windows. [`follow_activity`] + /// takes them at the end of the root pass, inside which every child window's pass ran. + shown: Vec, /// Whether a palette window stood lowered under an app-modal layer in this frame. lowered: bool, /// Where the raise of the modal's window above the palettes it lowered stands. @@ -557,7 +560,7 @@ fn in_family(ctx: &Context, viewport: ViewportId, window: ViewportId) -> bool { false } -/// Whether no window of the app has focus, as the last frame's windows reported. +/// Whether no window of the app has focus, as the last root frame's windows reported ([`follow_activity`]). pub(crate) fn app_away(ctx: &Context) -> bool { shared(ctx, |shared| shared.app.away) } @@ -681,27 +684,28 @@ fn flush_store(ctx: &Context) { /// Keeps the app's state and the stacking order of its windows current from the windows' facts. A palette's window /// level and visibility follow the state: the mounts build their viewports with the state of the moment, and a change /// asks for the next frame. Runs at the end of the root pass, inside which every child window's pass of the frame -/// has run, so each window's focus is the one its own pass reported after its input batch. The root input's list of -/// windows holds each child as of its previous pass, so it is not read for focus. The app is inactive when no -/// window reports focus: the batch that took focus from one window gave it to no other. +/// has run, so each window's focus is the one its own pass reported after its input batch. The app's windows are the +/// root's and those the mounts showed in this frame, a window opened in it included. The app is away when every one +/// of them reports that it has no focus: the batch that took focus from one window gave it to no other. A window +/// with no facts yet is unknown, and the app is not away while one is. /// /// Once a palette has stood lowered under an app-modal layer, the modal's window is raised above it, once per modal. /// A window that has the keyboard when a modal comes to block it drops the keys the modal needs, so the modal's window /// takes the keyboard from it ([`focus_modal`]). fn follow_activity(ctx: &Context) { - let windows = viewports::reported(ctx); - let focused: Vec = windows - .iter() - .map(|(viewport, _)| *viewport) - .filter(|viewport| PerViewport::::with(ctx, *viewport, |record| record.facts.is_some_and(|facts| facts.focused))) - .collect(); + let shown = shared(ctx, |shared| std::mem::take(&mut shared.shown)); + let windows: Vec = std::iter::once(ViewportId::ROOT).chain(shown).collect(); + let focus: Vec> = + windows.iter().map(|viewport| PerViewport::::with(ctx, *viewport, |record| record.facts.map(|facts| facts.focused))).collect(); + let away = focus.iter().all(|focus| *focus == Some(false)); + let focused: Vec = windows.iter().zip(&focus).filter(|(_, focus)| **focus == Some(true)).map(|(viewport, _)| *viewport).collect(); let modal = overlay::app_modal_viewport(ctx); let minimized = viewports::current(ctx).minimized; let now = pass::now(ctx); let (repaint, raise) = shared(ctx, |shared| { - shared.stacking.retain(|viewport| windows.iter().any(|(open, _)| open == viewport) && !focused.contains(viewport)); + shared.stacking.retain(|viewport| windows.contains(viewport) && !focused.contains(viewport)); shared.stacking.extend(&focused); - let app = AppState { away: focused.is_empty(), modal, minimized }; + let app = AppState { away, modal, minimized }; let lowered = std::mem::take(&mut shared.lowered); let modal_changed = app.modal != shared.app.modal; if modal_changed { @@ -731,12 +735,12 @@ fn follow_activity(ctx: &Context) { /// Gives the window of `modal`, the app's top modal, the OS focus when one of `windows` that it blocks still has it /// [`MODAL_FOCUS_WAIT`] after the modal opened; once per modal. With the focus elsewhere by then (in the modal's own /// window, in an OS dialog, in another app) nothing is sent. -fn focus_modal(ctx: &Context, modal: ViewportId, windows: &[(ViewportId, viewports::Facts)]) { +fn focus_modal(ctx: &Context, modal: ViewportId, windows: &[ViewportId]) { let Some(due) = shared(ctx, |shared| shared.modal_focus) else { return }; let blocked = |viewport: ViewportId| overlay::modal_viewport(ctx, viewport) == Some(modal) && !in_family(ctx, viewport, modal); let wait = due - pass::now(ctx); if wait > 0.0 { - if windows.iter().any(|(viewport, _)| blocked(*viewport)) { + if windows.iter().any(|viewport| blocked(*viewport)) { repaint::request_after(ctx, ViewportId::ROOT, wait); } return; @@ -745,7 +749,7 @@ fn focus_modal(ctx: &Context, modal: ViewportId, windows: &[(ViewportId, viewpor let focused = |viewport: ViewportId| { PerViewport::::with_existing(ctx, viewport, |record| record.facts.is_some_and(|facts| facts.focus_reported)).unwrap_or(false) }; - if !focused(modal) && windows.iter().any(|(viewport, _)| focused(*viewport) && blocked(*viewport)) { + if !focused(modal) && windows.iter().any(|viewport| focused(*viewport) && blocked(*viewport)) { act(ctx, modal, WindowAction::Focus); } } diff --git a/crates/ui-contract/src/runtime/windows/spec.rs b/crates/ui-contract/src/runtime/windows/spec.rs index 95115c0597..ef97167950 100644 --- a/crates/ui-contract/src/runtime/windows/spec.rs +++ b/crates/ui-contract/src/runtime/windows/spec.rs @@ -22,10 +22,10 @@ pub enum WindowLevel { AlwaysOnTop, } -/// The app's state that its palettes follow, as its windows reported it in the last frame. +/// The app's state that its palettes follow, as its windows reported it in the last root frame. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) struct AppState { - /// No window of the app has focus. + /// Every window of the app reported that it has no focus. pub away: bool, /// The window that holds an app-modal layer, which blocks the app's other windows. pub modal: Option, diff --git a/crates/ui-contract/src/runtime/windows/viewport.rs b/crates/ui-contract/src/runtime/windows/viewport.rs index c669d95fde..a717ebb6f0 100644 --- a/crates/ui-contract/src/runtime/windows/viewport.rs +++ b/crates/ui-contract/src/runtime/windows/viewport.rs @@ -47,6 +47,11 @@ pub(crate) struct ViewportOpen<'a> { /// resizable window's size goes out only to open it (`ViewportOpen::follows_size`). pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: impl FnMut(&mut Ui)) { let viewport = viewports::viewport_id(open.id); + shared(ctx, |shared| { + if !shared.shown.contains(&viewport) { + shared.shown.push(viewport); + } + }); let opened = PerViewport::::with(ctx, viewport, |record| record.seen.is_some()); let (size, pos) = saved_geometry(ctx, open, opened).map_or((open.size, None), |(size, pos)| (Some(size), pos)); let pos = pos.or(open.position); diff --git a/crates/ui-contract/src/style/paint.rs b/crates/ui-contract/src/style/paint.rs index 02e467d3f6..6165f0628b 100644 --- a/crates/ui-contract/src/style/paint.rs +++ b/crates/ui-contract/src/style/paint.rs @@ -27,7 +27,7 @@ pub struct RuleLook { } /// The width of a rule. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub enum RuleWidth { /// One physical pixel at every scale. diff --git a/crates/ui-contract/src/testing/memory.rs b/crates/ui-contract/src/testing/memory.rs index 5f029eb593..e2f9745b87 100644 --- a/crates/ui-contract/src/testing/memory.rs +++ b/crates/ui-contract/src/testing/memory.rs @@ -95,7 +95,7 @@ pub fn register_fact(ctx: &Context) -> Vec { - Facts::of_last_pass(ctx) + Facts::with_last_pass(ctx, <[T]>::to_vec) } /// Runs `f` on a child `Ui` of `ui`. diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index d6acf5d4f5..42225ed3dd 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -52,6 +52,8 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat pub use crate::fonts::document::set_budget as document_face_budget; pub use crate::runtime::audit::{in_run as in_audit_run, set as audit_replays}; #[cfg(feature = "testing")] +pub use crate::runtime::env::env_walks; +#[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; @@ -61,6 +63,8 @@ pub use crate::runtime::measure::{ last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, last_pass_tip_texts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, }; +#[cfg(feature = "testing")] +pub use crate::runtime::pass_state::unbound_reads as unbound_pass_state_reads; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; pub use frames::Frames; diff --git a/crates/ui-contract/src/testing/stage.rs b/crates/ui-contract/src/testing/stage.rs index c295901d24..81fe0954e9 100644 --- a/crates/ui-contract/src/testing/stage.rs +++ b/crates/ui-contract/src/testing/stage.rs @@ -35,8 +35,9 @@ pub fn stage(ui: &mut Ui) -> Rect { /// The height of the room `ui` offers a story whose root has no content height and fills it (a window, a full-window /// canvas): the room its card's view gives, or the stage height where the room is unbounded. pub fn room_height(ui: &Ui) -> f32 { - let room = flow_room(ui).y; - if room.is_finite() { room } else { stage_height(&Env::of(ui).tokens) } + let env = Env::of(ui); + let room = flow_room(ui, &env).y; + if room.is_finite() { room } else { stage_height(&env.tokens) } } /// Allocates a stage as wide as [`stage`]'s and as tall as the story's content at that width, which `height` gives, @@ -49,8 +50,9 @@ pub fn stage_fitting(ui: &mut Ui, height: impl FnOnce(f32) -> f32) -> Rect { /// The width of the stage [`stage_fitting`] allocates: the width left in `ui` between the least and greatest stage /// width. A story whose content measures itself at a width (through `ui`) reads it before allocating. pub fn stage_width(ui: &Ui) -> f32 { - let tokens = &Env::of(ui).tokens; - let room = flow_room(ui).x; + let env = Env::of(ui); + let tokens = &env.tokens; + let room = flow_room(ui, &env).x; let room = if room.is_finite() { room } else { ui.available_width() }; room.clamp(least_stage_width(tokens), WIDTH_MAX_IN_CONTROLS * tokens.size.control.md) } diff --git a/crates/ui-contract/tests/it/body/placement.rs b/crates/ui-contract/tests/it/body/placement.rs index 836f66048d..744e341fab 100644 --- a/crates/ui-contract/tests/it/body/placement.rs +++ b/crates/ui-contract/tests/it/body/placement.rs @@ -7,8 +7,8 @@ use craft_behavior::{GesturePhase, Sense}; use craft_theme::{Contrast, Mode}; use craft_ui::contract::overlay::{Anchor, DragBounds, FloatPlace, Place, PlacementChange, PlacementKind}; use craft_ui::contract::{ - BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Mount, Overlay, Props as _, Role, Show as _, - ShowContainer as _, Sizing, + BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, MemoProps, MemoView, Mount, Overlay, Props as _, Role, + Show as _, ShowContainer as _, Sizing, }; use craft_ui::layout::BodyLayout; use craft_ui::runtime::commands::{self, CommandSet, FireSource, WindowCommand}; @@ -16,7 +16,7 @@ use craft_ui::runtime::env::{Direction, with_env}; use craft_ui::style::StyleCx; use craft_ui::testing::input::key_press; use craft_ui::testing::layout::allocate; -use craft_ui::testing::{Frames, pointer, trial}; +use craft_ui::testing::{Frames, MemoRun, audit_replays, last_frame_memo_runs, pointer, trial}; use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen}; use egui::{Align2, Key, Modifiers, Pos2, Rect, Response, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -499,3 +499,35 @@ fn an_open_layer_takes_the_side_its_host_asks_for_now() { frames.idle(4, &mut show); assert!(shown.get().bottom() <= anchor.top() + SLACK, "asked for Above again, the layer sits above: {:?}", shown.get()); } + +/// A memoized view holding a layer whose body is `width` points wide. +#[derive(MemoProps)] +struct HeldLayer { + width: f32, +} + +fn held_layer(held: &mut HeldLayer, ui: &mut Ui) { + let log = RefCell::new(Vec::new()); + let props = ContainerProps::new().mount(Mount::Layer(Overlay::floating().modeless().placed_at(START.min))).sizing(Sizing::Content); + let width = held.width; + Pane { common: Common::new(), props, log: &log }.id_salt("held").show(ui, |ui, _| allocate(ui, Vec2::new(width, BODY.y))); +} + +/// A layer that grows inside a memoized view senses its background over the rect it shows from the run that grows it, +/// so that run's record is what the view replays: the replay audit finds the replay the same as a run. egui's `Area` +/// started each pass at the size it kept from the last one, so the run that grew the layer kept its background at the +/// old size (a canvas task bar showing new members). +#[trial] +fn a_memoized_layer_that_grows_replays_as_it_runs() { + let width = Cell::new(BODY.x); + let mut frames = Frames::new(); + audit_replays(&frames.ctx, true); + let mut show = |ui: &mut Ui| { + MemoView::new("held layer", HeldLayer { width: width.get() }, held_layer).show(ui); + }; + frames.idle(4, &mut show); + width.set(2.0 * BODY.x); + frames.idle(4, &mut show); + let runs = last_frame_memo_runs(&frames.ctx); + assert!(runs.iter().any(|(name, _, run)| name.contains("HeldLayer") && *run == MemoRun::Replayed), "the grown layer's view replays: {runs:?}"); +} diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index 6fbdd01099..ec0a5926ba 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -10,7 +10,7 @@ use craft_ui::layout::{BodyLayout, RowAlign}; use craft_ui::runtime::env::{Direction, with_env}; use craft_ui::style::{ComponentStyle, StyleCx}; use craft_ui::testing::layout::{Block, body}; -use craft_ui::testing::{Fixture, Frames, is_measuring, trial}; +use craft_ui::testing::{Fixture, Frames, audit_replays, is_measuring, trial}; use craft_ui_test_kit::contract::{Panel, PlainStyle, Probe, Seen}; use egui::{Rect, Response, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -542,29 +542,82 @@ fn short(_: &mut Short, ui: &mut Ui) -> Rect { Block::new(Vec2::new(40.0, 10.0)).show(ui).rect } -/// A memoized view in a row sits on the row's line, as the one-line child beside it does, also while it replays. Its -/// content starts a layout room of its own, which left it at the row's top (a menu bar beside an app icon, -/// storytold/photocraft#16113). +/// A row of a tall block and the memoized short view beside it: the block's rect and the view's. +fn row_of_short(ui: &mut Ui) -> (Rect, Rect) { + let rects = Cell::new((Rect::NOTHING, Rect::NOTHING)); + Panel::new().layout(BodyLayout::row()).id_salt("row").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; + let view = MemoView::new("short", Short {}, short).show(ui); + rects.set((tall, view.unwrap_or(Rect::NOTHING))); + }); + rects.get() +} + +/// A memoized view that holds the row. +#[derive(MemoProps)] +struct HeldRow {} + +fn held_row(_: &mut HeldRow, ui: &mut Ui) { + row_of_short(ui); +} + +/// A memoized view in a row sits on the row's line, as the one-line child beside it does, from the first pass that +/// shows it and while it replays. Its content starts a layout room of its own, which left it at the row's top (a menu +/// bar beside an app icon, storytold/photocraft#16113); in its first pass it has no real run yet, so it sits by the +/// extent the row's measuring run found in that pass. A view around the row keeps that first run, and replays it. #[trial] fn a_memoized_view_sits_on_the_rows_line() { - let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let seen = Rc::new(RefCell::new(Vec::new())); let shown = Rc::clone(&seen); let mut fixture = Fixture::new(move |ui| { - Panel::new().layout(BodyLayout::row()).id_salt("row").show(ui, |ui, _| { - let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; - let view = MemoView::new("short", Short {}, short).show(ui); - if !is_measuring(ui.ctx()) { - shown.set((tall, view.unwrap_or(Rect::NOTHING))); - } - }); + let rects = row_of_short(ui); + if !is_measuring(ui.ctx()) && !ui.is_sizing_pass() { + shown.borrow_mut().push(rects); + } }); fixture.room(Vec2::splat(400.0)).settle(); - for frame in 0..3 { - let (tall, view) = seen.get(); - assert!(view.height() > 0.0, "frame {frame}: the view showed: {view:?}"); - assert!((view.center().y - tall.center().y).abs() < SLACK, "frame {frame}: the view {view:?} is off the line of {tall:?}"); + for _ in 0..3 { fixture.settle(); } + let seen = seen.borrow(); + assert!(seen.len() > 1, "the row showed in several passes: {seen:?}"); + for (pass, (tall, view)) in seen.iter().enumerate() { + assert!(view.height() > 0.0, "pass {pass}: the view showed: {view:?}"); + assert!((view.center().y - tall.center().y).abs() < SLACK, "pass {pass}: the view {view:?} is off the line of {tall:?}"); + } + // Held in a view of its own, the row's first run is what that view replays: the replay audit finds it the same as a + // run. + let mut fixture = Fixture::new(|ui| { + MemoView::new("held row", HeldRow {}, held_row).show(ui); + }); + audit_replays(fixture.ctx(), true); + fixture.room(Vec2::splat(400.0)).settle(); + for _ in 0..3 { + fixture.settle(); + } +} + +/// An unwrapped row in a row sits on the outer row's line by its own line, whatever its alignment: a row that places +/// its block from its start, at its end, centred or spread reports its line as its first line alike. +#[trial] +fn an_unwrapped_row_sits_on_the_outer_line_by_its_line_in_every_alignment() { + for align in [RowAlign::Start, RowAlign::SpaceBetween, RowAlign::Center, RowAlign::End] { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).id_salt("outer").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; + let short = Panel::new().layout(BodyLayout::row().align(align)).id_salt("inner").show(ui, |ui, _| Block::new(ITEM).show(ui).rect); + if !is_measuring(ui.ctx()) { + shown.set((tall, short.inner.unwrap_or(Rect::NOTHING))); + } + }); + }); + fixture.room(Vec2::splat(400.0)).settle(); + let (tall, short) = seen.get(); + assert!(short.height() > 0.0, "{align:?}: the inner row showed its block: {short:?}"); + assert!((short.center().y - tall.center().y).abs() < SLACK, "{align:?}: the inner row's block {short:?} is off the line of {tall:?}"); + } } /// A Row in right-to-left holding a vertically scrolling container (content-sized, then filling its height) beside a diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 5c0ba16b23..755fee0622 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -59,13 +59,45 @@ fn one_press_per_pass_and_a_discard_pass_gets_no_held_events() { assert_eq!(run(&mut frames, vec![], false), vec![Vec::<&str>::new()]); } -/// Pass-local state: inside a pass the pipeline looks up no service in context data per run, so a settled pass of -/// forty leaves makes as many lookups as one of ten. +/// Pass-local state: inside a pass the pipeline looks up no service in context data per run, and each run reaches the +/// pass state and the pass's facts through its component tree's binding, so a settled pass of forty command-bound +/// leaves (each registers the command it shows, a per-viewport record) makes as many lookups and unbound reads as one +/// of ten. #[trial] fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { use craft_ui::runtime::egui::memory::service_lookups; + use craft_ui::testing::unbound_pass_state_reads; use craft_ui_test_kit::contract::Panel; let settled_lookups = |leaves: usize| { + let mut frames = Frames::new(); + let mut show = |ui: &mut egui::Ui| { + Panel::new().id_salt("leaves").show(ui, |ui, _| { + for at in 0..leaves { + let seen = std::cell::RefCell::new(Seen::default()); + Probe::new(&seen).label(format!("Leaf {at}")).command(Shown::Apply).show(ui); + } + }); + }; + for _ in 0..3 { + frames.frame(vec![], &mut show); + } + let (lookups, unbound) = (service_lookups(), unbound_pass_state_reads()); + frames.frame(vec![], &mut show); + (service_lookups() - lookups, unbound_pass_state_reads() - unbound) + }; + let ((ten, ten_unbound), (forty, forty_unbound)) = (settled_lookups(10), settled_lookups(40)); + assert_eq!(ten, forty, "context-data lookups grow with the runs: {ten} for ten leaves, {forty} for forty"); + assert_eq!(ten_unbound, forty_unbound, "unbound pass-state reads grow with the runs: {ten_unbound} for ten leaves, {forty_unbound} for forty"); +} + +/// The place env: a run takes the env its parent installed for its `Ui` from its caller, or walks the `Ui` stack for it +/// once where app code shows it, and every step and layout helper of the run reads it from there. A pass of forty +/// leaves in a panel walks no more often per run than one of ten: at most once. +#[trial] +fn a_run_walks_its_ui_stack_for_its_env_at_most_once() { + use craft_ui::testing::{env_walks, last_pass_runs}; + use craft_ui_test_kit::contract::Panel; + let walks_and_runs = |leaves: usize| { let mut frames = Frames::new(); let mut show = |ui: &mut egui::Ui| { Panel::new().id_salt("leaves").show(ui, |ui, _| { @@ -78,12 +110,17 @@ fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { for _ in 0..3 { frames.frame(vec![], &mut show); } - let before = service_lookups(); - frames.frame(vec![], &mut show); - service_lookups() - before + let walks = env_walks(); + assert_eq!(frames.frame(vec![], &mut show), 1, "the settled frame is one pass"); + let runs: u32 = last_pass_runs(&frames.ctx).iter().map(|(_, runs)| runs).sum(); + (env_walks() - walks, u64::from(runs)) }; - let (ten, forty) = (settled_lookups(10), settled_lookups(40)); - assert_eq!(ten, forty, "context-data lookups grow with the runs: {ten} for ten leaves, {forty} for forty"); + let ((ten, ten_runs), (forty, forty_runs)) = (walks_and_runs(10), walks_and_runs(40)); + assert!(forty_runs > ten_runs, "the leaves run in the pass: {ten_runs} runs for ten leaves, {forty_runs} for forty"); + assert!( + forty - ten <= forty_runs - ten_runs, + "env walks grow faster than the runs: {ten} walks in {ten_runs} runs for ten leaves, {forty} in {forty_runs} for forty" + ); } /// The app command the settled view's probe is bound to; its modal rule is the default one, `Blocked`. diff --git a/crates/ui-contract/tests/it/runtime/pointer.rs b/crates/ui-contract/tests/it/runtime/pointer.rs index ac0c06eef2..9aee8f6ffd 100644 --- a/crates/ui-contract/tests/it/runtime/pointer.rs +++ b/crates/ui-contract/tests/it/runtime/pointer.rs @@ -1,9 +1,10 @@ //! The sensing core over probe roots: the press lifecycle, arenas, press targets, parts and the shape record. use craft_behavior::{CanvasTransform, HitLevel, PartKey, PointerButton, PressPhase, Sense}; +use craft_ui::contract::{MemoProps, MemoView}; use craft_ui::testing::pointer::{self, drag}; use craft_ui::testing::sensing::{ProbeMember, ProbePart, ProbeRoot, RootReport, SenseReport, egui_click_target, show}; -use craft_ui::testing::{Frames, trial}; +use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, trial}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -77,6 +78,42 @@ fn a_press_uses_its_event_modifiers_when_the_frame_has_released_them() { assert!(log.borrow().last().root.press.mods.shift, "the press reads Shift even after the frame has released it"); } +/// A view that shows whether a button is held, from the press state. +#[derive(MemoProps)] +struct Held {} + +fn held(_: &mut Held, ui: &mut Ui) { + let state = craft_ui::runtime::pointer::press_state(ui.ctx()); + ui.label(if state.buttons.is_empty() { "Up" } else { "Down" }); +} + +/// Whether the press-state reader ran in any pass of the last frame. +fn held_ran(frames: &Frames) -> bool { + last_frame_memo_runs(&frames.ctx).iter().any(|(name, _, run)| name.ends_with("Held") && *run == MemoRun::Ran) +} + +/// A view that reads the press state runs on a press and on a release, wherever they land, and replays while the +/// pointer only moves, with a button held or not. +#[trial] +fn a_press_state_reader_runs_on_a_press_or_release_and_replays_on_a_move() { + let mut show = |ui: &mut Ui| { + MemoView::new("held", Held {}, held).show(ui); + }; + let away = Pos2::new(300.0, 300.0); + let mut frames = Frames::new(); + frames.frame(vec![pointer::moved(away)], &mut show); + frames.idle(30, &mut show); + frames.frame(vec![pointer::moved(away + Vec2::new(20.0, 0.0))], &mut show); + assert!(!held_ran(&frames), "a pointer move replays the reader: {:?}", last_frame_memo_runs(&frames.ctx)); + frames.frame(vec![pointer::press(away)], &mut show); + assert!(held_ran(&frames), "a press runs the reader"); + frames.idle(2, &mut show); + frames.frame(vec![pointer::moved(away + Vec2::new(0.0, 20.0))], &mut show); + assert!(!held_ran(&frames), "a move with the button held replays the reader: {:?}", last_frame_memo_runs(&frames.ctx)); + frames.frame(vec![pointer::release(away + Vec2::new(0.0, 20.0))], &mut show); + assert!(held_ran(&frames), "a release runs the reader"); +} + /// A hover-revealed part must remain identifiable when a drag leaves its shape. #[trial] fn active_part_survives_a_drag_outside_its_shape() { @@ -890,6 +927,85 @@ fn a_move_that_changes_nothing_under_the_pointer_needs_no_pass() { assert!(needs(None, inside), "the pointer coming in runs a pass"); } +/// The part of `Knob` over its start half. +const KNOB: PartKey = PartKey::new("knob"); + +/// A leaf whose knob part covers its start half, and which logs where the pointer hovers on the knob each pass +/// (`Cx::hover_pos`). +#[derive(craft_ui::contract::Component)] +struct Knob<'a> { + #[common] + common: craft_ui::contract::Common, + seen: &'a RefCell>>, +} + +impl craft_ui::contract::Component for Knob<'_> { + const ROLE: craft_ui::contract::Role = craft_ui::contract::Role::GROUP; + type Style = craft_ui_test_kit::contract::PlainStyle; + type Output = egui::Response; + + fn style(_: &craft_ui::style::StyleCx<'_>, _: KnobStyleKey) -> Self::Style { + craft_ui_test_kit::contract::PlainStyle::min(Vec2::new(200.0, 40.0)) + } + + fn parts(&mut self, rect: Rect, cx: &mut craft_ui::contract::PartsCx<'_, Self>) { + cx.part(KNOB, Rect::from_min_max(rect.min, rect.center_bottom())); + } + + fn update(&mut self, cx: &mut craft_ui::contract::Cx<'_, Self>) { + use craft_ui::contract::Pointer as _; + self.seen.borrow_mut().push(cx.hover_pos(KNOB)); + } + + fn finish(self, cx: craft_ui::contract::Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +/// The knob at `KNOB_AT`, logging into `seen`. +fn show_knob(seen: &RefCell>>) -> impl FnMut(&mut Ui) + '_ { + use craft_ui::contract::Show as _; + move |ui: &mut Ui| { + Knob { common: craft_ui::contract::Common::new(), seen }.show_at(ui, KNOB_AT); + } +} + +const KNOB_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(300.0, 140.0) }; + +/// `Cx::hover_pos` gives the hover point while the part is hovered, and nothing over the rest of the component. +#[trial] +fn hover_pos_reads_the_point_over_its_part_only() { + let seen = RefCell::new(Vec::new()); + let mut show = show_knob(&seen); + let mut frames = Frames::new(); + frames.idle(2, &mut show); + let on_knob = Pos2::new(130.0, 120.0); + frames.frame(vec![pointer::moved(on_knob)], &mut show); + assert_eq!(seen.borrow().last(), Some(&Some(on_knob)), "the point over the knob, in the component's layer space"); + frames.frame(vec![pointer::moved(Pos2::new(260.0, 120.0))], &mut show); + assert_eq!(seen.borrow().last(), Some(&None), "no point over the rest of the component"); +} + +/// A component that read the hover position on its part follows the pointer there: a move within the part needs a +/// pass (`move_needs_pass`); over the rest of the component, which it read nothing on, a move needs none. +#[trial] +fn a_hover_position_read_follows_the_pointer() { + use craft_ui::runtime::pointer::move_needs_pass; + let seen = RefCell::new(Vec::new()); + let mut show = show_knob(&seen); + let mut frames = Frames::new(); + frames.idle(2, &mut show); + let (on_knob, off_knob) = (Pos2::new(130.0, 120.0), Pos2::new(260.0, 120.0)); + let step = Vec2::new(5.0, 0.0); + frames.frame(vec![pointer::moved(on_knob)], &mut show); + assert!(move_needs_pass(&frames.ctx, egui::ViewportId::ROOT, Some(on_knob), on_knob + step), "a move within the read part runs a pass"); + frames.frame(vec![pointer::moved(off_knob)], &mut show); + assert!( + !move_needs_pass(&frames.ctx, egui::ViewportId::ROOT, Some(off_knob), off_knob + step), + "a move over the rest of the component, which read no position, runs none" + ); +} + /// Two overlapping parts of one root that hit both points of a move, where the nearest centre picks another part at /// the end: the hover changes, so the move runs a pass. #[trial] diff --git a/crates/ui-contract/tests/it/runtime/shown.rs b/crates/ui-contract/tests/it/runtime/shown.rs index f74d64a108..835a7639b2 100644 --- a/crates/ui-contract/tests/it/runtime/shown.rs +++ b/crates/ui-contract/tests/it/runtime/shown.rs @@ -1,8 +1,14 @@ //! Where commands were shown (`commands::holds`, `commands::shown`). +use craft_ui::contract::{CommandSet, MemoProps, MemoView, Props as _, Show as _}; use craft_ui::runtime::commands::{self, CommandRef}; use craft_ui::runtime::env::Label; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, trial}; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::sync::Arc; /// A container that holds a hundred commands, as a menu title holds its menu's, registers once per pass: a replay of /// the menu bar then makes one registration per title, not one per command (photocraft#15493). Each command is still @@ -10,7 +16,7 @@ use craft_ui::testing::{Fixture, trial}; #[trial] fn a_container_registers_its_commands_once() { let held: Vec = (0..100).map(|i| CommandRef::new(format!("test.held{i}"))).collect(); - let shown = held.clone(); + let shown: Arc<[CommandRef]> = held.clone().into(); let mut fixture = Fixture::new(move |ui| { let rect = egui::Rect::from_min_size(ui.max_rect().min, egui::vec2(40.0, 20.0)); commands::holds(ui.ctx(), ui.layer_id(), rect, &shown, Label::from("Image")); @@ -24,3 +30,52 @@ fn a_container_registers_its_commands_once() { } assert!(commands::shown(fixture.ctx(), &CommandRef::new("test.other")).is_none(), "a command nothing holds is not shown"); } + +/// The command every probe of the leaves view is bound to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "shownTrial")] +#[non_exhaustive] +enum Bound { + #[command(label = "Apply")] + Apply, +} + +/// A memoized view of `count` probes bound to `Bound::Apply`. +#[derive(MemoProps)] +struct Leaves { + count: usize, +} + +fn leaves(props: &mut Leaves, ui: &mut Ui) { + for _ in 0..props.count { + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).command(Bound::Apply).show(ui); + } +} + +/// A settled view's replay registers where its bound components show their commands with the very commands the run +/// registered, so a settled pass copies no command, however many it shows. +#[trial] +fn a_settled_pass_shows_its_commands_without_copying_them() { + for count in [10, 40] { + let mut frames = Frames::new(); + frames.screen(Vec2::new(400.0, 1400.0)); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(200.0, 1300.0)), |ui| { + MemoView::new("leaves", Leaves { count }, leaves).show(ui); + }); + }; + frames.idle(30, &mut show); + frames.frame(vec![], &mut show); + let before = commands::shown_commands(&frames.ctx); + frames.frame(vec![], &mut show); + let after = commands::shown_commands(&frames.ctx); + assert!(last_frame_memo_runs(&frames.ctx).iter().all(|(_, _, run)| *run != MemoRun::Ran), "the view of {count} probes is settled"); + assert_eq!(before.len(), count, "each of the {count} probes is shown"); + assert_eq!(after.len(), count, "the settled pass registers each of the {count} probes again"); + assert!( + before.iter().zip(&after).all(|(before, after)| Arc::ptr_eq(before, after)), + "a settled pass of {count} probes shows the commands the pass before it showed, not copies" + ); + } +} diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 6527e24fa1..565b797534 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -358,7 +358,11 @@ fn an_app_modal_takes_the_keyboard_from_a_window_it_blocks() { let windows = on_x11(); windows.root_info(focus(root)); windows.child_info(focus(float)); - let frame = || windows.frame(vec![], vec![], |ui| ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |_, _| {})); + let frame = || { + windows.frame(vec![], vec![], |ui| { + Palette::new("float", Some(WindowSpec::tool())).show(ui, |_, _| {}); + }) + }; for _ in 0..4 { frame(); } @@ -450,6 +454,26 @@ fn a_popup_window_of_the_modals_window_keeps_the_keyboard() { assert_eq!(outs.iter().map(|out| focus_requests(out, palette)).sum::(), 0, "the modal's window leaves it there"); } +/// A popup window opened in a palette's first frames stays open while the palette's window has the focus: the +/// palette counts among the app's windows from the frame it opened in, before the main window's input lists it, so +/// the app is not away. +#[trial] +fn a_popup_window_opened_with_its_palette_stays_open() { + let windows = on_x11(); + windows.root_info(focus(false)); + windows.child_info(focus(true)); + let frame = || { + windows.frame(vec![], vec![], |ui| { + Palette::new("tool", Some(WindowSpec::tool())).show(ui, |ui, _| { + Modal { common: Common::new(), props: menu_layer() }.id_salt("popup").show(ui, |_, _| {}); + }); + }) + }; + let outs: Vec = (0..4).map(|_| frame()).collect(); + let palette = builder_titled(&outs[0], "tool").0; + assert!(popup_window(&outs[3], palette).is_some(), "the layer opened with its palette still shows in its popup window"); +} + /// A layer in a popup window keeps the scroll that a focus move below its view gave it while it is open, and starts at /// the top when it opens again. #[trial] diff --git a/crates/ui-gallery/src/chrome/shell.rs b/crates/ui-gallery/src/chrome/shell.rs index f46c1aad30..7ccc434a91 100644 --- a/crates/ui-gallery/src/chrome/shell.rs +++ b/crates/ui-gallery/src/chrome/shell.rs @@ -202,7 +202,7 @@ impl ShellApp for Gallery { let in_theme = self.viewer.workspace == Workspace::Theme; let shell = |ui: &mut Ui, viewer: &mut Viewer| { AppShell::new(WindowKey::main()) - .options_bar(true, |ui, _, viewer: &mut Viewer| options_bar(ui, viewer)) + .options_bar(true, |_| None, |ui, _, viewer: &mut Viewer| options_bar(ui, viewer)) .body_label("Gallery") .body(body) .show(ui, viewer); diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index cb265feb59..0855af602c 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -80,9 +80,9 @@ impl<'a> EditorMock<'a> { let window = WindowKey::new(format!("mock-{:x}-{}", ui.scope_id().value(), label.as_str())); let shell = AppShell::embedded(window) .screen_mode(screen_mode) - .title_bar_if(true, |ui, _, state: &mut MockState| title_bar(ui, state)) - .options_bar(true, |ui, _, state: &mut MockState| options_bar(ui, state)) - .status(true, |ui, _, state: &mut MockState| status_bar(ui, state)) + .title_bar_if(true, |_| None, |ui, _, state: &mut MockState| title_bar(ui, state)) + .options_bar(true, |_| None, |ui, _, state: &mut MockState| options_bar(ui, state)) + .status(true, |_| None, |ui, _, state: &mut MockState| status_bar(ui, state)) .body_label(label) .body(|ui, cx, state: &mut MockState| body(ui, cx, state)); match at { @@ -309,7 +309,7 @@ fn status_bar(ui: &mut Ui, state: &mut MockState) { Link::new(words.cpu_rendering.clone()).tone(Tone::Warn).show(ui); }) .show(ui, |ui, _| { - chosen = StatusReadout::new(craft_ui::contract::bind_tracked!(document.view), document.size, *status_item, &values).show(ui).item; + chosen = StatusReadout::new(craft_ui::contract::bind_tracked!(document.view => zoom), document.size, *status_item, &values).show(ui).item; Divider::vertical().show(ui); Text::new(words.color_mode.clone()).show(ui); Divider::vertical().show(ui); diff --git a/crates/ui-gallery/tests/it/overview.rs b/crates/ui-gallery/tests/it/overview.rs index 0dbf7c6e29..d05ef0e44b 100644 --- a/crates/ui-gallery/tests/it/overview.rs +++ b/crates/ui-gallery/tests/it/overview.rs @@ -231,10 +231,11 @@ fn a_storys_dialog_closed_by_its_own_button_opens_again_by_the_opener() { assert!(painted_times(&fixture, "Save PDF") > closed, "the opener opens the dialog again"); } -/// A story whose dialog is open runs in every frame: the dialog paints on a layer of its own, which a replay can't add, -/// so the shell counts the dialog in every pass and the card keeps the story in place of its opener. +/// A story whose dialog is open replays in a settled frame: the dialog's layer is part of the story's run, which a +/// replay shows again where it ran. The dialog stays painted, the card keeps the story in place of its opener, and the +/// story does not run. #[trial] -fn a_story_with_its_dialog_open_runs_every_frame_and_keeps_the_dialog_counted() { +fn a_story_with_its_dialog_open_replays_in_settled_frames_and_keeps_the_dialog_open() { let mut gallery = gallery_filtered(level_of("FindReplaceDialog"), "FindReplaceDialog"); let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); fixture.room(Vec2::new(1400.0, 900.0)).settle(); @@ -247,12 +248,13 @@ fn a_story_with_its_dialog_open_runs_every_frame_and_keeps_the_dialog_counted() .expect("an opener"); fixture.click(&opener).settle(); let open = painted_times(&fixture, "Find what:"); + assert!(open > 0, "the opener opens the dialog"); for frame in 0..3 { fixture.idle(1); let stories = last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(ty, _, run)| ty.contains("::StoryProps") && *run == MemoRun::Ran).count(); - assert!(stories >= 1, "idle frame {frame}: the story with its dialog open ran"); - assert_eq!(openers(&fixture), closed - 1, "idle frame {frame}: the card keeps the story, its dialog counted"); + assert_eq!(stories, 0, "idle frame {frame}: the story with its dialog open replays"); + assert_eq!(openers(&fixture), closed - 1, "idle frame {frame}: the card keeps the story in place of its opener"); assert_eq!(painted_times(&fixture, "Find what:"), open, "idle frame {frame}: the dialog stays open"); } } diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index fdc5d6d350..b5c0c419ad 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -105,9 +105,10 @@ pub fn derive_plain_data(input: TokenStream) -> TokenStream { /// `#[memo_props(address = "why")]` and feeds where it points. A field another field of the same variant stands for (a /// closure a generation counter covers) carries `#[memo_props(covered_by = "", reason = "why")]` and feeds /// nothing; the named field must exist and feed the key itself. A type parameter is bound by `MemoProps`, except one -/// marked `#[memo_props(stateless)]`: the type of a callback held as `Stateless`, which no fn item or closure -/// implements `MemoProps` for, is bound by `'static` only (`struct Bar<#[memo_props(stateless)] E> { english: -/// Stateless }`). A type that is a handle to state written during the pass, or a context rebuilt each pass, carries +/// that only `covered_by` fields name, which feeds nothing and takes no bound (the app state `&mut S` a shell slot's view +/// holds), one that only `hash` fields name, bound by `Hash + Sync`, and one marked `#[memo_props(stateless)]`: the type +/// of a callback held as `Stateless`, which no fn item or closure implements `MemoProps` for, is bound by `'static` +/// only (`struct Bar<#[memo_props(stateless)] E> { english: Stateless }`). A type that is a handle to state written during the pass, or a context rebuilt each pass, carries /// `#[memo_props(every_pass = "why")]`: it feeds no field, and a view whose key holds it runs in every pass. #[proc_macro_derive(MemoProps, attributes(memo_props))] pub fn derive_memo_props(input: TokenStream) -> TokenStream { diff --git a/crates/ui-macros/src/memo.rs b/crates/ui-macros/src/memo.rs index cf5813ef3d..9ed0446dde 100644 --- a/crates/ui-macros/src/memo.rs +++ b/crates/ui-macros/src/memo.rs @@ -91,7 +91,8 @@ fn is_static_ref(ty: &syn::Type) -> bool { } /// The field escapes of `MemoProps`: `hash` binds a type parameter only such fields name by what `MemoKey::feed_hash` -/// needs (a dock's panel type); `address` and `covered_by` fields are not checked and keep the trait's bound. +/// needs (a dock's panel type); a `covered_by` field feeds nothing, so a type parameter only such fields name takes no +/// bound (the app state a shell slot's view holds); `address` fields are not checked and keep the trait's bound. struct MemoEscapes; impl EscapeRule for MemoEscapes { @@ -99,7 +100,8 @@ impl EscapeRule for MemoEscapes { Ok(match feed_of(field)? { Feed::Props => None, Feed::Hash => Some(Some(quote!(::core::hash::Hash + ::core::marker::Sync))), - Feed::Address | Feed::Covered(_) => Some(None), + Feed::Covered(_) => Some(Some(TokenStream::new())), + Feed::Address => Some(None), }) } } diff --git a/crates/ui-macros/src/plain.rs b/crates/ui-macros/src/plain.rs index db9f01288d..f4b8ebafd1 100644 --- a/crates/ui-macros/src/plain.rs +++ b/crates/ui-macros/src/plain.rs @@ -46,7 +46,7 @@ pub(crate) struct Escape { /// Which fields a derive does not check, and what a type parameter that only those fields name is bound by. pub(crate) trait EscapeRule { /// `None` when `field` is checked; else `Some(bound)`: what a type parameter that only escaped fields name is bound - /// by instead of the derive's trait (`None` keeps the trait). + /// by instead of the derive's trait (`None` keeps the trait, an empty bound leaves the parameter unbound). fn escape(&self, field: &syn::Field) -> syn::Result>>; } @@ -129,7 +129,9 @@ pub(crate) fn field_checks( param.attrs.clear(); let ident = ¶m.ident; let only_escaped = named_escaped.0.contains(ident) && !named.0.contains(ident); - let escape_bound = escaped_bounds.iter().find(|(named, _)| named == ident).map(|(_, bound)| bound); + // The first escaped field's bound that binds anything; an empty one (no bound) only when no other is given. + let bounds = || escaped_bounds.iter().filter(|(named, _)| named == ident).map(|(_, bound)| bound); + let escape_bound = bounds().find(|bound| !bound.is_empty()).or_else(|| bounds().next()); let bound = match (param_escape, escape_bound) { (Some(ParamEscape { bound, .. }), _) if escaped => quote!(#bound), (_, Some(bound)) if only_escaped => quote!(#bound), diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 2629923a03..3ab9079c2e 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -41,7 +41,7 @@ const EDGE: PartKey = PartKey::new("edge"); /// Where a column's bar is. A dock column and a floating window are both one column; the window's title row is the /// bar of the column it holds. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ColumnBar { /// The column shows its own bar (the double arrow and the band that moves the column and opens its menu), the diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 0f52e151b8..67c842b256 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -757,8 +757,9 @@ impl Container for /// on it comes out of its outbox. A titled group shows the shown panel's title, count and close button in place of /// the tab row. fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { - for (command, state) in self.command_states.drain(..) { - cx.publish(command, state); + // A measuring run of the header comes before the real one in some passes: both read the states. + for (command, state) in &self.command_states { + cx.publish(*command, state.clone()); } while let Some((command, _)) = cx.take_command::() { self.reported.commands.push(command); diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index a7d8192942..77cc4da605 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -68,13 +68,13 @@ pub use iconic::{FlyoutResize, IconGroupSeparator, IconicColumn, IconicColumnOut pub use window_menu::{WindowMenuRows, WindowMenuRowsOutput}; use crate::contract::{ - Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Edit as _, EditResponse, Focus as _, Outcome, Pad, PaintUi, - PartsCx, Pointer as _, Props as _, Role, Sizing, WordSetCx as _, + Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Edit as _, EditResponse, Focus as _, MemoKey, MemoProps as _, + Outcome, Pad, PaintUi, PartsCx, Pointer as _, Props as _, Role, Sizing, WordSetCx as _, }; use crate::runtime::commands::CommandRef; -use crate::runtime::env::Label; +use crate::runtime::derived::derived; +use crate::runtime::env::{AppValues, EnvValue, Label}; use crate::runtime::focus::KeyUse; -use crate::runtime::memory::sub; use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::dock::{DockEdge, Layout, Node, SplitSize}; use craft_behavior::{Axis, EditEvents, Flow, Metrics, PartKey, Sense}; @@ -294,7 +294,8 @@ impl Outcome for SplitAreaOutput

))] pub struct SplitArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { @@ -304,53 +305,141 @@ pub struct SplitArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { props: ContainerProps, layout: Bind<'a, Layout

>, rules: FrameRules<'a, P>, + revision: u128, /// The accessibility name of the area's dividers, for a split whose dividers are not "Resize panels": "Resize /// preview", "Resize timeline". #[prop(into)] divider_label: Option

>, rules: FrameRules<'a, P>) -> Self { + /// A split area named `label` over `layout`, sized by `rules`. `revision` is the caller's revision of the layout + /// and of everything the rules read: it moves whenever either changes. A mixed layout shows no handles. + pub fn new(label: impl Into

>, rules: FrameRules<'a, P>, revision: u128) -> Self { let props = ContainerProps::new().arena(true).sizing(Sizing::Fill).pad(Pad::None); - SplitArea { common: Common::new(), props, layout, rules, divider_label: None, declared: Vec::new() }.label(label) + SplitArea { common: Common::new(), props, layout, rules, revision, divider_label: None, declared: Vec::new(), frames: None }.label(label) } /// A two-body area: `bodies.0` first along `axis` and `bodies.1` after it, with one divider between them. The first /// body takes `share` of the room left after the divider; the area's response reports the divider's drags and keys /// as [`SplitAreaOutput::share`], and the host hands the share back in the next pass. The body reads each body's - /// rect with [`SplitFramesCx::group_frames`]. - pub fn pair(label: impl Into

, rect: Rect, sizes: &DockSizes, rtl: bool) -> Arc> { + if let Some(frames) = &self.frames { + return Arc::clone(frames); + } + let key = FramesKey { revision: self.revision, rect, sizes: *sizes, rtl }; + derived(ctx, id.with("frames"), &key, || SplitFrames::of(layout, rect, sizes, &self.rules, rtl)) } } -/// The groups of the layout with the frames the area gave them this pass, for the body. -#[derive(Clone)] -struct PassFrames

(Vec<(P, Rect)>); +/// What a split area's frames are built from: the caller's revision of the layout and rules, the room, the sizes and +/// the direction. +#[derive(crate::contract::MemoProps)] +struct FramesKey { + revision: u128, + rect: Rect, + sizes: DockSizes, + rtl: bool, +} -impl

Default for PassFrames

{ - fn default() -> Self { - PassFrames(Vec::new()) +/// A split area's layout laid out in its rect: each group as its anchor panel and rect, each dock as its window edge +/// and rect, and each handle with the range its divider can travel. +struct SplitFrames { + groups: SplitGroups

, + docks: SplitDocks, + handles: Vec<(SplitHandle, (f32, f32))>, +} + +impl SplitFrames

{ + fn of(layout: &Layout

, rect: Rect, sizes: &DockSizes, rules: &FrameRules<'_, P>, rtl: bool) -> Self { + let Some(root) = layout.root.as_ref() else { return Self::none() }; + let frames = tree::frames(root, rect, sizes, rules, rtl); + let (anchors, rects): (Vec

, Vec) = frames.groups.iter().filter_map(|group| Some((group.anchor()?.clone(), group.rect))).unzip(); + let (edges, dock_rects): (Vec, Vec) = frames + .groups + .iter() + .filter_map(|group| match group.node { + Node::Dock { side, .. } => Some((*side, group.rect)), + _ => None, + }) + .unzip(); + let handles = frames + .handles + .into_iter() + .map(|handle| { + let range = tree::drag_range(root, rect, sizes, rules, &handle.path); + (handle, range) + }) + .collect(); + SplitFrames { + groups: SplitGroups { anchors: Arc::from(anchors), rects: Arc::from(rects) }, + docks: SplitDocks { edges: Arc::from(edges), rects: Arc::from(dock_rects) }, + handles, + } + } + + fn none() -> Self { + SplitFrames { groups: SplitGroups::empty(), docks: SplitDocks::root(), handles: Vec::new() } } } -/// The docks of the layout with the frames the area gave them this pass, for the body. -#[derive(Clone, Default)] -struct PassDocks(Vec<(DockEdge, Rect)>); +/// The groups of the innermost split area, each anchor panel with its rect, as the area lays them out in the run its +/// body runs in: at the measuring run's rect, or at the real run's after its divider edits. +#[derive(Clone, PartialEq, crate::contract::MemoProps)] +struct SplitGroups { + #[memo_props(hash = "a split area's anchors are plain panel values it keys by their hash")] + anchors: Arc<[P]>, + rects: Arc<[Rect]>, +} -const FRAMES: &str = "split_frames"; -const DOCKS: &str = "split_docks"; +impl SplitGroups

{ + fn empty() -> Self { + SplitGroups { anchors: Arc::from(Vec::new()), rects: Arc::from(Vec::new()) } + } +} + +impl EnvValue for SplitGroups

{ + fn root() -> Self { + Self::empty() + } +} + +/// The docks of the innermost split area, each window edge with its rect, laid out as [`SplitGroups`] are. +#[derive(Clone, PartialEq, crate::contract::MemoProps)] +struct SplitDocks { + #[memo_props(hash = "a dock edge is a plain enum")] + edges: Arc<[DockEdge]>, + rects: Arc<[Rect]>, +} + +impl EnvValue for SplitDocks { + fn root() -> Self { + SplitDocks { edges: Arc::from(Vec::new()), rects: Arc::from(Vec::new()) } + } +} /// What a split area's body reads of the area's frames, on its `BodyCx`. pub trait SplitFramesCx { /// The groups of the split area this body belongs to, each as its anchor panel and its rect, with this pass's /// resize edits applied: a panel placed at its group's rect sits against the handle in the same pass. - fn group_frames(&self) -> Vec<(P, Rect)>; + fn group_frames(&self) -> Vec<(P, Rect)>; /// The docks of the split area this body belongs to, each as its window edge and its rect, with this pass's /// resize edits applied. @@ -358,38 +447,23 @@ pub trait SplitFramesCx { } impl SplitFramesCx for BodyCx<'_> { - fn group_frames(&self) -> Vec<(P, Rect)> { - self.memory.recall::>(sub(self.id, FRAMES)).0 + fn group_frames(&self) -> Vec<(P, Rect)> { + let groups = self.env.get::>(); + groups.anchors.iter().cloned().zip(groups.rects.iter().copied()).collect() } fn dock_frames(&self) -> Vec<(DockEdge, Rect)> { - self.memory.recall::(sub(self.id, DOCKS)).0 + let docks = self.env.get::(); + docks.edges.iter().copied().zip(docks.rects.iter().copied()).collect() } } -/// The dividers of the layout's docked tree in `rect`, each with the handle that names its split. -fn handles

(layout: &Layout

, rect: Rect, sizes: &DockSizes, rules: &FrameRules<'_, P>, rtl: bool) -> Vec { - layout.root.as_ref().map_or_else(Vec::new, |root| tree::frames(root, rect, sizes, rules, rtl).handles) -} - -/// The divider of `handle` in reading order. With `ranged`, the range it can travel is the tree's; without, it is -/// where it stands, which is all its part and face need. -fn divider_of

( - layout: &Layout

, - handle: &SplitHandle, - rect: Rect, - sizes: &DockSizes, - rules: &FrameRules<'_, P>, - rtl: bool, - ranged: bool, -) -> Divider { +/// The divider of `handle` in reading order, which can travel `range` from where it stands; `(0.0, 0.0)` where only +/// its place matters, as for its part and face. +fn divider_of(handle: &SplitHandle, range: (f32, f32), rect: Rect, sizes: &DockSizes, rtl: bool) -> Divider { let flow = Flow::new(rect, rtl); let (centre, split) = (flow.to_physical(handle.divider).center(), flow.to_physical(handle.split)); let at = if handle.axis == Axis::X { centre.x } else { centre.y }; - let range = match layout.root.as_ref() { - Some(root) if ranged => tree::drag_range(root, rect, sizes, rules, &handle.path), - _ => (0.0, 0.0), - }; Divider::new(handle.axis, at, split, (at + range.0, at + range.1), sizes.reach) } @@ -434,28 +508,28 @@ impl Component for SplitAr fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let Some(layout) = cx.value() else { return }; let (sizes, rtl) = (cx.style.sizes, cx.flow.is_rtl()); - let handles = handles(layout, rect, &sizes, &self.rules, rtl); - for (at, handle) in handles.iter().enumerate() { - let divider = divider_of(layout, handle, rect, &sizes, &self.rules, rtl, false); + let frames = self.frames_of(cx.ui.ctx(), cx.id, layout, rect, &sizes, rtl); + for (at, (handle, _)) in frames.handles.iter().enumerate() { + let divider = divider_of(handle, (0.0, 0.0), rect, &sizes, rtl); divider::declare(cx, rect, HANDLE, at as u64, ÷r); } - self.declared = handles.into_iter().map(|handle| handle.path).collect(); + self.declared = frames.handles.iter().map(|(handle, _)| handle.path.clone()).collect(); + self.frames = Some(frames); } fn update(&mut self, cx: &mut Cx<'_, Self>) { - let Some(layout) = cx.value().cloned() else { - cx.core.memory.shown::>(sub(sub(cx.core.id, "body"), FRAMES)).0.clear(); - return; - }; + let Some(layout) = cx.value().cloned() else { return }; let (rect, rtl, sizes, rules) = (cx.rect, cx.flow.is_rtl(), cx.style.sizes, self.rules); - let handles = handles(&layout, rect, &sizes, &rules, rtl); - for (at, handle) in handles.iter().enumerate() { - let divider = divider_of(&layout, handle, rect, &sizes, &rules, rtl, false); + let frames = self.frames_of(&cx.core.ctx, cx.core.id, &layout, rect, &sizes, rtl); + let mut edited = false; + for (at, (handle, _)) in frames.handles.iter().enumerate() { + let divider = divider_of(handle, (0.0, 0.0), rect, &sizes, rtl); match divider::pointer(cx, HANDLE, at as u64, ÷r) { Some(Drag::Start) => cx.begin(), Some(Drag::To(coord)) => { if let Some(next) = moved(&layout, rect, &sizes, &rules, handle, coord - divider.at) { cx.propose(next); + edited = true; } } Some(Drag::Release) => cx.commit(), @@ -464,33 +538,40 @@ impl Component for SplitAr } let focused = cx.active_part().filter(|part| part.key == HANDLE).and_then(|part| part.index); if let Some(index) = focused - && let Some(handle) = handles.get(index as usize) + && let Some((handle, range)) = frames.handles.get(index as usize) { - let divider = divider_of(&layout, handle, rect, &sizes, &rules, rtl, true); + let divider = divider_of(handle, *range, rect, &sizes, rtl); if let Some((_, coord)) = divider::keys(cx, HANDLE, &[(index, divider)], sizes.step, sizes.jump) && let Some(next) = moved(&layout, rect, &sizes, &rules, handle, coord - divider.at) { cx.set(next); + edited = true; } } - let frames = cx.value().and_then(|shown| shown.root.as_ref()).map(|root| tree::frames(root, rect, &sizes, &rules, rtl)); - let groups = frames.iter().flat_map(|frames| frames.groups.iter()).filter_map(|group| Some((group.anchor()?.clone(), group.rect))).collect(); - let docks = frames - .iter() - .flat_map(|frames| frames.groups.iter()) - .filter_map(|group| match group.node { - Node::Dock { side, .. } => Some((*side, group.rect)), - _ => None, - }) - .collect(); - cx.core.memory.shown::(sub(sub(cx.core.id, "body"), DOCKS)).0 = docks; - cx.core.memory.shown::>(sub(sub(cx.core.id, "body"), FRAMES)).0 = groups; + // The layout this pass edited lays out from its own frames, in this pass. + let frames = match cx.value() { + Some(shown) if edited => Arc::new(SplitFrames::of(shown, rect, &sizes, &rules, rtl)), + _ => frames, + }; + self.frames = Some(frames); + } + + /// The body lays the groups and docks out at the frames of this run: in a measuring run at its rect, in the real + /// run after `update`'s divider edits. + fn content_env(&self, cx: &Cx<'_, Self>, values: &mut AppValues) { + let frames = match cx.value() { + Some(layout) => self.frames_of(&cx.core.ctx, cx.core.id, layout, cx.rect, &cx.style.sizes, cx.flow.is_rtl()), + None => Arc::new(SplitFrames::none()), + }; + values.set(frames.groups.clone()); + values.set(frames.docks.clone()); } fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let Some(layout) = cx.value() else { return }; let (sizes, rtl) = (cx.style.sizes, cx.flow.is_rtl()); - for (at, handle) in handles(layout, cx.rect, &sizes, &self.rules, rtl).iter().enumerate() { + let frames = self.frames_of(&cx.core.ctx, cx.core.id, layout, cx.rect, &sizes, rtl); + for (at, (handle, _)) in frames.handles.iter().enumerate() { ui.face(HANDLE.at(at as u64), Splitter::new(handle.axis)); } } @@ -501,8 +582,9 @@ impl Component for SplitAr let words = cx.words::(); let given = self.divider_label.as_ref().map(|label| cx.env.resolve(label)); let name = given.as_ref().map_or_else(|| words.resize.as_str(), Label::as_str); - for (at, handle) in handles(layout, rect, &sizes, &self.rules, rtl).iter().enumerate() { - let divider = divider_of(layout, handle, rect, &sizes, &self.rules, rtl, true); + let frames = self.frames_of(&cx.core.ctx, cx.core.id, layout, rect, &sizes, rtl); + for (at, (handle, range)) in frames.handles.iter().enumerate() { + let divider = divider_of(handle, *range, rect, &sizes, rtl); divider::describe(access, HANDLE, at as u64, ÷r, name, sizes.step); } } diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index 953fb2ba1f..e1dcc2ac1f 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -59,7 +59,9 @@ impl> SpecSource

for Tracked { /// 2. Otherwise `group_header` once, inside the group's header before its tab strip, then `body` for the panels whose /// bodies are shown, and `footer` under the body of a shown panel whose spec has `PanelSpec::footer`. /// -/// Each of these runs every pass the group shows. A host memoizes inside them: a body or view shown through a +/// Each of these runs every pass the group runs. Where every shown panel of a column has a version +/// ([`content`](Self::content)), the column runs only when one of them, the arrangement, the specs or its place +/// changed, or input reached it. 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 ([`PanelSpecs`]), the arrangement and the look. @@ -83,10 +85,14 @@ pub trait DockPanels

{ /// spec has `PanelSpec::footer` (the default shows nothing). fn footer(&mut self, _panel: &P, _ui: &mut Ui, _cx: &mut BodyCx<'_>) {} - /// The version of the app data `panel`'s body shows that the framework does not track (a document's revision, a - /// job's progress). With one, the body settles (`Lazy::settles` with `Lazy::content`): it runs only when its - /// version, its room or something the framework tracks in it changed, the pointer is over it or focus is in it, and - /// otherwise repaints its last run. `None` (the default) runs the body every pass. + /// The version of the app data the host shows for `panel` that the framework does not track (a document's + /// revision, a job's progress): everything its `body` and `footer` show, and the `group_header`, `group_view` and + /// `rail_footer` of a group or rail whose shown panel it is. + /// + /// The dock shows each column, and its docked tree, as a memoized view keyed by the versions of the panels shown + /// in it, the arrangement, the specs and the place: while those hold and no input reaches it, the column repaints + /// its last run and calls none of these methods. A column or tree that shows a panel without a version (`None`, + /// the default) runs every pass. The host memoizes inside its bodies itself, for the passes a column runs. fn content(&self, _panel: &P) -> Option { None } diff --git a/crates/ui-panels/src/docking/sources.rs b/crates/ui-panels/src/docking/sources.rs index 1399c147bf..3a6fdcdf42 100644 --- a/crates/ui-panels/src/docking/sources.rs +++ b/crates/ui-panels/src/docking/sources.rs @@ -20,6 +20,18 @@ pub struct DockSource

{ pub id: Id, } +/// A replay of the view that drew a source at another place moves its rect; what it acts on, its OS window and its node +/// stay. +impl crate::runtime::Shift for DockSource

{ + fn shifted(&self, by: &egui::RecordShift) -> Self { + DockSource { rect: self.rect.shifted(by), ..self.clone() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + DockSource { rect: self.rect.snapped(&to.rect, within), ..self.clone() } + } +} + impl

DockSource

{ /// `kind` drawn at `rect` in the app window, with the node `id`. pub fn new(kind: SourceKind

, rect: Rect, id: Id) -> Self { diff --git a/crates/ui-panels/src/docking/stories.rs b/crates/ui-panels/src/docking/stories.rs index 1515988b56..5fec16652d 100644 --- a/crates/ui-panels/src/docking/stories.rs +++ b/crates/ui-panels/src/docking/stories.rs @@ -10,7 +10,7 @@ use super::{ }; use crate::buttons::Button; use crate::contract::SizeLimits; -use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, Tracked, Validity}; +use crate::contract::{Bind, MemoKey, Props as _, Show as _, ShowContainer as _, Tracked, Validity}; use crate::menu::{Menu, PanelRow}; use crate::runtime::commands::CommandRef; use crate::runtime::env::Message; @@ -43,10 +43,11 @@ fn titles(panels: &[usize]) -> Vec { panels.iter().map(|panel| title_of(*panel)).collect() } -fn dock(ui: &mut Ui, bind: Bind<'_, Layout>, shown: &Layout) -> StoryOutput { +/// The story's split area over `bind`, whose layout and rules the story data's `revision` covers. +fn dock(ui: &mut Ui, bind: Bind<'_, Layout>, shown: &Layout, revision: u128) -> StoryOutput { let limits = |_: &usize| SizeLimits::default(); let rules = FrameRules::new(&limits); - let area = SplitArea::new("Panels", bind, rules).show(ui, |ui, body| { + let area = SplitArea::new("Panels", bind, rules, revision).show(ui, |ui, body| { for (anchor, rect) in body.group_frames::() { let Some(Node::Tabs { panels, .. }) = shown.place(&anchor).and_then(|place| shown.node_of(&place)) else { continue }; let panels = titles(panels); @@ -66,25 +67,28 @@ 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 revision = MemoKey::of(&data.revision()); let (layout, layout_at) = data.value_at("dock", two_columns()); let shown = layout.clone(); - dock(ui, layout_at.bind(layout), &shown) + dock(ui, layout_at.bind(layout), &shown, revision) } #[story(SplitArea<'static, usize>, covers = [Mixed], drive = Drive::Custom(drag_handle))] fn layouts_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let revision = MemoKey::of(&data.revision()); let (layout, layout_at) = data.value_at("dock", Mixed::>::Mixed); - dock(ui, layout_at.bind_mixed(layout), &two_columns()) + dock(ui, layout_at.bind_mixed(layout), &two_columns(), revision) } #[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 revision = MemoKey::of(&data.revision()); 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, layout_at.bind(layout).check(needs_two), &shown) + dock(ui, layout_at.bind(layout).check(needs_two), &shown, revision) } #[story(DockGroup<'static, usize>, covers = [Default])] diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index a652d86ddd..0a4d9dbd4c 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -18,7 +18,7 @@ pub use craft_behavior::dock::{SIDE_ZONE_DEPTH_SHARE, SIDE_ZONE_FRACTION}; /// The sizes of a dock's drop bands and zones and of the windows it floats, resolved from the theme's tokens. /// A dock's component style calls [`Self::style`] from `Component::style`, so the sizes are cached with it. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub struct DockSizes { /// Depth of a group's side zones with `DockConfig::side_edge_zones` (the rail width). @@ -106,7 +106,7 @@ pub struct DockSizes { } /// Which docked columns a dock shows as cards ([`DockConfig::column_cards`](super::DockConfig::column_cards)). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] #[non_exhaustive] pub enum ColumnCards { /// None: every column fills its cell. diff --git a/crates/ui-panels/tests/it/focus/rings.rs b/crates/ui-panels/tests/it/focus/rings.rs index ab8d4b073b..1ad76afb32 100644 --- a/crates/ui-panels/tests/it/focus/rings.rs +++ b/crates/ui-panels/tests/it/focus/rings.rs @@ -146,7 +146,7 @@ fn a_focused_split_handle_and_stack_divider_show_the_focus_ring() { let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0usize], 0), Node::tabs(vec![1usize], 0)); let mut layout = Layout::new(Some(root), Vec::new()); let limits = |_: &usize| SizeLimits::default(); - SplitArea::new("Panels", Bind::bound(&mut layout), FrameRules::new(&limits)).show(ui, |_, _| ()); + SplitArea::new("Panels", Bind::bound(&mut layout), FrameRules::new(&limits), 0).show(ui, |_, _| ()); }); fixture.room(Vec2::new(400.0, 300.0)).settle(); let handle = tab_to_part(&mut fixture, "handle"); diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 31f310ed7c..111132029f 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -21,6 +21,7 @@ use crate::docking::{ use crate::layout_components::Stack; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::primitives::HostStyle; +use crate::runtime::Shift; use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within}; use crate::runtime::derived::derived; use crate::runtime::drag; @@ -288,6 +289,7 @@ struct Drops<'a, P> { permissions: &'a dyn Fn(&P) -> Permissions, config: &'a DockConfig, specs: &'a HashMap, + unnamed: &'a PanelSpec, hide: HidePanels<'a>, maximized: Option<&'a P>, rtl: bool, @@ -302,7 +304,7 @@ impl Drops<'_, P> { let shell = cx.env.get::().0; let bounds = inset_top(shell.as_ref().map_or(cx.rect, ShellCx::float_bounds), self.top_inset); let space = float_space(&ctx, bounds, &sizes, self.config, self.specs); - let spec = |panel: &P| spec_in(self.specs, panel); + let spec = |panel: &P| spec_in(self.specs, self.unnamed, panel).clone(); let protected = |panel: &P| (self.permissions)(panel).is_protected(); let prune = hide::Prune::new(self.layout, self.hide, shell.as_ref()); let mut target = DockDropTarget::new(&ctx, self.dock, self.layout, self.permissions); @@ -329,19 +331,88 @@ fn area_sizes(mut sizes: DockSizes, config: &DockConfig) -> DockSizes { struct Report

{ actions: Vec>, events: Vec>, - focused: Option

, pressed: Option

, picked: Option

, flyout: Vec>>, - placed: Vec<(P, Rect)>, + placed: Vec>, /// The OS windows the floating windows showed in, by their first panel. windows: Vec<(P, ViewportId)>, /// The files dropped on the floating windows that no target there took. files: Vec>, /// The gesture sources the parts drew, in the order they showed. sources: Vec>, - /// The groups shown this pass, by their shown panel, in the order they showed. - shown: Vec<(P, Rect)>, + /// The groups shown this pass, in the order they showed. + shown: Vec>, + /// The tab each `DockGroup` picked this pass (a click, or the host's focus request), by the group's id. + picks: Vec<(Id, P)>, + /// The divider edits of the docked tree this pass. + split: EditEvents>, +} + +/// A group the area showed: its shown panel, its rect and, where it is a `DockGroup` (not a host's view), its id. +#[derive(Clone, Debug, PartialEq)] +struct ShownGroup

{ + panel: P, + rect: Rect, + id: Option, +} + +impl Shift for ShownGroup

{ + fn shifted(&self, by: &egui::RecordShift) -> Self { + ShownGroup { rect: self.rect.shifted(by), ..self.clone() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + ShownGroup { rect: self.rect.snapped(&to.rect, within), ..self.clone() } + } +} + +/// Where a dock column was placed, named by a panel of its first group. +#[derive(Clone, Debug, PartialEq)] +struct Placed

{ + panel: P, + rect: Rect, +} + +impl Shift for Placed

{ + fn shifted(&self, by: &egui::RecordShift) -> Self { + Placed { rect: self.rect.shifted(by), ..self.clone() } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + Placed { rect: self.rect.snapped(&to.rect, within), ..self.clone() } + } +} + +/// What a column or the docked tree drew in its run that the area reports in every pass it shows: the gesture +/// sources, the groups and the placed dock columns. A view's replay returns its run's, moved with the record. +#[derive(Clone, Debug, PartialEq)] +struct Drawn

{ + sources: Vec>, + shown: Vec>, + placed: Vec>, +} + +impl Shift for Drawn

{ + fn shifted(&self, by: &egui::RecordShift) -> Self { + Drawn { sources: self.sources.shifted(by), shown: self.shown.shifted(by), placed: self.placed.shifted(by) } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + Drawn { + sources: self.sources.snapped(&to.sources, within), + shown: self.shown.snapped(&to.shown, within), + placed: self.placed.snapped(&to.placed, within), + } + } +} + +/// How far the report had grown when a view's run began ([`Pass::drawn_since`]). +#[derive(Clone, Copy)] +struct Mark { + sources: usize, + shown: usize, + placed: usize, } /// The inputs of the workspace's derived values: the workspace, the panels' specs and the lock. @@ -361,6 +432,8 @@ struct Scene<'s, P> { config: &'s DockConfig, layout: &'s Layout

, specs: &'s HashMap, + /// The spec of a panel the specs do not name. + unnamed: &'s PanelSpec, permissions: &'s HashMap, keys: &'s HashMap, space: &'s FloatSpace

, @@ -380,9 +453,9 @@ struct Scene<'s, P> { host_style: &'s HostStyle, } -/// The spec of `panel` in `specs`, or an unnamed one. -fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec { - specs.get(panel).cloned().unwrap_or_else(|| PanelSpec::new(Label::default())) +/// The spec of `panel` in `specs`, or `unnamed`. +fn spec_in<'s, P: Eq + Hash>(specs: &'s HashMap, unnamed: &'s PanelSpec, panel: &P) -> &'s PanelSpec { + specs.get(panel).unwrap_or(unnamed) } /// What an area derives from its workspace, its panels' specs and its lock, kept while none of them changes: whether @@ -391,6 +464,8 @@ fn spec_in(specs: &HashMap, panel: &P) -> PanelSpec struct DockModel

{ error: Option, specs: HashMap, + /// The spec of a panel `specs` does not name. + unnamed: PanelSpec, rights: HashMap, keys: HashMap, } @@ -409,6 +484,7 @@ impl DockModel

{ DockModel { error, specs: panels.iter().map(|panel| ((*panel).clone(), specs.spec(panel))).collect(), + unnamed: PanelSpec::new(Label::default()), rights, keys: panels.iter().map(|panel| (PanelKey::of(*panel), (*panel).clone())).collect(), } @@ -425,7 +501,7 @@ enum HostPart { View, } -impl Scene<'_, P> { +impl<'s, P: Clone + Eq + Hash> Scene<'s, P> { /// Runs `run`, which shows host code of `panel` as its `part`, on `ui`. Where the panel's body is the app's own egui /// code (`PanelSpec::host_body`), it runs with the style of the `Ui` the area was shown in, and only in the pass's /// real run: a measuring run takes what its last real run took (`HostStyle::show`). @@ -449,8 +525,8 @@ impl Scene<'_, P> { self.specs.get(panel).is_some_and(|spec| spec.host_body) } - fn spec(&self, panel: &P) -> PanelSpec { - spec_in(self.specs, panel) + fn spec(&self, panel: &P) -> &'s PanelSpec { + spec_in(self.specs, self.unnamed, panel) } fn permissions(&self, panel: &P) -> Permissions { @@ -464,7 +540,7 @@ impl Scene<'_, P> { /// Whether the docked `column` shows a rail of its icons beside it ([`IconicMode::Rail`]): an expanded column /// that collapses to icons. fn rail_beside(&self, column: &Column

) -> bool { - let spec = |panel: &P| self.spec(panel); + let spec = |panel: &P| self.spec(panel).clone(); let collapses = column.panels().all(|panel| self.permissions(panel).collapses); self.config.iconic_mode == IconicMode::Rail && !column.iconic @@ -474,7 +550,7 @@ impl Scene<'_, P> { /// The `(width, floor)` of each docked column of a dock, for [`fit_widths`]: a rail beside an expanded column adds /// its width to both. fn natural(&self, columns: &[Column

]) -> Vec<(f32, Option)> { - let spec = |panel: &P| self.spec(panel); + let spec = |panel: &P| self.spec(panel).clone(); let natural = self.sizes.natural(columns, &spec); columns .iter() @@ -490,6 +566,108 @@ impl Scene<'_, P> { } } +/// What the docks' geometry and the docked tree's frames follow besides their room: the pruned layout (with the specs +/// and the lock), the sizes and the config. +#[derive(crate::contract::MemoProps)] +struct GeometryKey<'k> { + view: u128, + sizes: DockSizes, + #[memo_props(hash = "the config derives `Hash` over every field")] + config: &'k DockConfig, +} + +/// The docks' columns as they lay out before the room shrinks them, derived per [`GeometryKey`]: for each dock, by its +/// window edge, each column's `(width, floor)` ([`Scene::natural`]) and its card's inset ([`DockSizes::card_place`]). +struct DockGeometry { + docks: Vec<(DockEdge, Vec, Vec>)>, +} + +/// A dock column's `(width, floor)` before the room shrinks it ([`Scene::natural`]). +type ColumnExtent = (f32, Option); + +impl DockGeometry { + fn of(scene: &Scene<'_, P>) -> Self { + let spec = |panel: &P| scene.spec(panel).clone(); + let docks = [DockEdge::Start, DockEdge::End] + .into_iter() + .filter_map(|edge| { + let path = scene.layout.dock_path(edge)?; + let Some(Node::Dock { columns, .. }) = node_at(scene.layout.root.as_ref()?, &path) else { return None }; + let cards = columns.iter().enumerate().map(|(at, column)| scene.sizes.card_place(at, column, &spec)).collect(); + Some((edge, scene.natural(columns), cards)) + }) + .collect(); + DockGeometry { docks } + } + + /// The `(width, floor)` and card place of each column of the dock at `edge`. + fn dock(&self, edge: DockEdge) -> (&[ColumnExtent], &[Option]) { + self.docks.iter().find(|(at, _, _)| *at == edge).map_or((&[], &[]), |(_, natural, cards)| (natural.as_slice(), cards.as_slice())) + } +} + +/// What a pass shows the docked tree with: the room, the docks' name, the open flyout, the shell and the docks' +/// geometry. +struct TreeAt

{ + room: Rect, + label: Label, + open: Option

, + shell: Option, + geometry: Arc, + /// The revision of the tree's frames: the layout, the specs, the sizes and the config ([`GeometryKey`]). + frames: u128, +} + +/// The docked tree as a memoized view: it replays while its key holds and no input reaches it. +#[derive(MemoProps)] +struct TreeView<'v, 's, P> { + /// [`Pass::tree_key`]. + key: u128, + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + rail_footer: Option

, + #[memo_props( + covered_by = "key", + reason = "the key holds the arrangement, the specs, the requests and the versions of every panel the tree shows" + )] + pass: &'v mut Pass<'s, P>, + #[memo_props(covered_by = "key", reason = "the key holds the room, the name, the open flyout, the shell's reveal and the geometry's key")] + at: TreeAt

, +} + +fn tree_view(view: &mut TreeView<'_, '_, P>, ui: &mut Ui) -> Drawn

{ + let mark = view.pass.mark(); + view.pass.show_tree(ui, &view.at); + view.pass.drawn_since(mark) +} + +/// A column as a memoized view: it replays while its key holds and no input reaches it. +#[derive(MemoProps)] +struct ColumnView<'v, 's, P> { + /// [`Pass::column_key`]. + key: u128, + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + first: P, + #[memo_props( + covered_by = "key", + reason = "the key holds the arrangement, the specs, the requests and the versions of the panels the column shows" + )] + pass: &'v mut Pass<'s, P>, + #[memo_props(covered_by = "key", reason = "the arrangement in the key holds the column")] + column: &'v Column

, + #[memo_props(covered_by = "key", reason = "the key holds the column's place")] + at: ColumnAt

, + name: Label, +} + +fn column_view(view: &mut ColumnView<'_, '_, P>, ui: &mut Ui) -> Drawn

{ + let mark = view.pass.mark(); + let cell = view.at.cell; + view.pass.column(ui, &view.name, view.column, view.at.clone()); + // The column takes no room in flow; the run covers its cell, so the pointer over it runs it again. + ui.expand_to_include_rect(cell); + view.pass.drawn_since(mark) +} + /// What the area reports from one pass. struct Passed

{ /// The divider sizes and window moves of `edit`, as actions on the workspace the pass started with. @@ -532,12 +710,16 @@ struct DockPlan<'p, P> { rect: Rect, flow: Flow, open: Option

, + /// Each column's `(width, floor)` and card place ([`DockGeometry::dock`]). + natural: &'p [(f32, Option)], + cards: &'p [Option], } /// Where and how a column shows: its rect; the edge it keeps to, a dock's window edge or the float area's edge a /// floating window keeps to; where its bar is; the rect its inner edge and flyouts stay within; and the open flyout. /// Its flyouts open away from its edge: towards the canvas for a dock column, towards the float area's room for a /// floating one. +#[derive(Clone)] struct ColumnAt

{ cell: Rect, edge: DockEdge, @@ -612,6 +794,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { permissions: &policy, config: &config, specs: &model.specs, + unnamed: &model.unnamed, hide, maximized: maximized.as_ref(), rtl, @@ -640,6 +823,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { current: ¤t, config: &config, specs: &model.specs, + unnamed: &model.unnamed, keys: &model.keys, hide, model: key, @@ -753,6 +937,7 @@ struct Input<'i, P> { current: &'i Arc>, config: &'i DockConfig, specs: &'i HashMap, + unnamed: &'i PanelSpec, keys: &'i HashMap, hide: HidePanels<'i>, model: ModelKey, @@ -802,6 +987,7 @@ fn show_area( current, config, specs, + unnamed, keys, hide, model, @@ -831,6 +1017,7 @@ fn show_area( config, layout, specs, + unnamed, permissions: rights, keys, space: &space, @@ -851,7 +1038,6 @@ fn show_area( report: Report { actions: Vec::new(), events: Vec::new(), - focused: None, pressed: None, picked: None, flyout: Vec::new(), @@ -860,41 +1046,19 @@ fn show_area( files: Vec::new(), sources: Vec::new(), shown: Vec::new(), + picks: Vec::new(), + split: EditEvents::new(), }, dock: id, }; - let limits = |panel: &P| scene.spec(panel).limits; - let dock_width = |columns: &[Column

]| scene.natural(columns).iter().map(|(width, _)| *width).sum::(); - let stripless = |panel: &P| scene.spec(panel).canvas; - let rules = FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless).dock_gap(scene.sizes.dock_gap); + let key = GeometryKey { view: scene.view, sizes, config }; + let docks = derived(ctx, id.with("geometry"), &key, || DockGeometry::of(&scene)); let label = Label::from(body.words::().panels.as_str().to_owned()); - let mut leaves: Vec<(Vec, Rect)> = Vec::new(); - let area = SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| { - DockTargets::

::register_room(ctx, id, split.rect); - for (anchor, rect) in split.group_frames::

() { - let Some(place) = scene.layout.place(&anchor) else { continue }; - let Some(node) = scene.layout.node_of(&place) else { continue }; - if let PanelPlace::Node(path) = &place { - leaves.push((path.clone(), rect)); - } - pass.leaf(ui, split, node, rect); - } - let flow = Flow::new(split.rect, rtl); - for (edge, rect) in split.dock_frames() { - 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()) { - 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() }); - } - }); - let splits = - area.output.dividers.iter().map(|(path, rect, node)| DockSource::new(SourceKind::Divider(DividerKind::Split(path.clone())), *rect, *node)); - pass.report.sources.extend(splits); - let mut edit = area.output.edit.events.map(|edited| { + let tree = TreeAt { room: body.rect, label, open: open.clone(), shell: shell.clone(), geometry: docks, frames: MemoKey::of(&key) }; + pass.tree(ui, tree); + let split = std::mem::take(&mut pass.report.split); + let mut edit = split.map(|edited| { let mut layout = current.layout().clone(); view.write_back(&edited, &mut layout); let resized = match (current.layout().root.as_ref(), layout.root.as_ref()) { @@ -910,7 +1074,6 @@ fn show_area( (Some(from), Some(to)) => split_changes(from, to).into_iter().map(|(path, size)| Action::resize_split(path, size)).collect(), _ => Vec::new(), }; - register_bands(&scene, ctx, body.rect, &leaves); let started = memory.moving.as_ref().map(|moving| moving.before.layout()); let moved = if prune.floating { pass.windows(ui, body, &open, started) } else { None }; let mut report = pass.report; @@ -953,16 +1116,26 @@ fn show_area( } } *body.memory::>() = memory; + // The group holding key focus, by the panel it shows, or the one it picked in this pass: a replayed group reports + // focus as a run does. + let focused = report + .shown + .iter() + .filter_map(|group| { + let id = group.id.filter(|id| focus_within(ctx, *id))?; + Some(report.picks.iter().find(|(picked, _)| *picked == id).map_or(&group.panel, |(_, panel)| panel).clone()) + }) + .last(); Passed { geometry, actions: report.actions, events: report.events, - focused: report.focused, + focused, pressed: report.pressed, picked: report.picked, edit, space: Some(space), - columns: report.placed, + columns: report.placed.into_iter().map(|placed| (placed.panel, placed.rect)).collect(), windows: report.windows, files: report.files, sources: report.sources, @@ -970,7 +1143,7 @@ fn show_area( } /// Registers the outer-edge bands and the new-dock bands as the dock's drop spots for the next pass, from the leaves -/// the split area placed this pass (each as its tree path and rect). A new-dock band runs along a start or end edge +/// the split area placed in this run (each as its tree path and rect). A new-dock band runs along a start or end edge /// that holds no dock. fn register_bands( scene: &Scene<'_, P>, @@ -1037,7 +1210,7 @@ fn panel_menu_rows( } let targets = scene.layout.move_targets(panel, |other| scene.permissions(other)); if scene.permissions(panel).movable && !targets.is_empty() { - let rows = targets.iter().enumerate().map(|(at, target)| PanelRow::Item(Entry::new(GroupItem::MoveTo(at), scene.spec(target).label))); + let rows = targets.iter().enumerate().map(|(at, target)| PanelRow::Item(Entry::new(GroupItem::MoveTo(at), scene.spec(target).label.clone()))); let name = Label::from(words.panel_move_to.as_str().to_owned()); group.push(PanelRow::Submenu(name, rows.collect())); } @@ -1214,13 +1387,13 @@ impl Pass<'_, P> { .iter() .map(|panel| { let spec = scene.spec(panel); - PanelTitle::new(PanelKey::of(panel), spec.label) + PanelTitle::new(PanelKey::of(panel), spec.label.clone()) .closable(scene.permissions(panel).closable) - .command(spec.command) + .command(spec.command.clone()) .count(spec.count) - .caption(spec.caption) + .caption(spec.caption.clone()) .swatch(spec.swatch) - .documents(spec.documents) + .documents(spec.documents.clone()) }) .collect(), ) @@ -1253,7 +1426,7 @@ impl Pass<'_, P> { let spec = scene.spec(&members[at]); if minimized { group = group.minimized(); - } else if !document(&spec) && !spec.host_body { + } else if !document(spec) && !spec.host_body { // The app's own egui body lays out in the whole body, as it did outside the dock. group = group.pad(Pad::Regular); } @@ -1284,7 +1457,13 @@ impl Pass<'_, P> { } GroupAt::Show(rect) => rect, }; - self.report.shown.push((shown.clone(), rect)); + // A measuring run of the container around the group draws it too; the group reports what it drew from the + // pass's real run only, once. + let reports = crate::runtime::measure::effect(ui.ctx(), "dock::group_report"); + let at_shown = self.report.shown.len(); + if reports { + self.report.shown.push(ShownGroup { panel: shown.clone(), rect, id: None }); + } // 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 @@ -1321,6 +1500,7 @@ impl Pass<'_, P> { let Some(output) = output else { if strip.is_positive() && let Some(node) = self.rail_grip(ui, anchor, shown, strip, rect.size()) + && reports { self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), strip, node)); } @@ -1335,12 +1515,14 @@ impl Pass<'_, P> { } }; let tabs = output.tabs.iter().filter_map(|(key, rect, node)| Some(DockSource::new(kind_of(*key)?, *rect, *node))); - self.report.sources.extend(tabs); - if let Some((rect, node)) = output.overflow { - self.report.sources.push(DockSource::new(SourceKind::Overflow(anchor.clone()), rect, node)); - } - if let Some((rect, node)) = output.grip { - self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), rect, node)); + if reports { + self.report.sources.extend(tabs); + if let Some((rect, node)) = output.overflow { + self.report.sources.push(DockSource::new(SourceKind::Overflow(anchor.clone()), rect, node)); + } + if let Some((rect, node)) = output.grip { + self.report.sources.push(DockSource::new(SourceKind::GroupBar(anchor.clone()), rect, node)); + } } // 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. @@ -1392,8 +1574,11 @@ impl Pass<'_, P> { self.report.pressed = Some(shown.clone()); } // A tab picked in this pass is the group's shown panel from now on, though this pass drew the one before. - if focus_within(ui.ctx(), output.response.id) { - self.report.focused = Some(picked.unwrap_or(shown).clone()); + if reports { + self.report.shown[at_shown].id = Some(output.response.id); + } + if let Some(panel) = picked { + self.report.picks.push((output.response.id, panel.clone())); } for panel in output.closed.into_iter().filter_map(|key| scene.panel(key)) { self.report.actions.push(Action::close(panel.clone())); @@ -1422,8 +1607,8 @@ impl Pass<'_, P> { /// The columns of a dock, from the window edge inwards. fn dock(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, plan: DockPlan<'_, P>) { - let scene = self.scene; - let widths = fit_widths(&scene.natural(plan.columns), plan.rect.width()); + let widths = fit_widths(plan.natural, plan.rect.width()); + let name = Label::from(body.words::().panels.as_str().to_owned()); let reading = plan.flow.to_physical(plan.rect); let start = plan.edge == DockEdge::Start; let mut cursor = if start { reading.left() } else { reading.right() }; @@ -1435,14 +1620,192 @@ impl Pass<'_, P> { // A docked column takes the dock's height, a stepped one (a tool rail) too: the references' docked // toolbar keeps its column's surface down to the dock's foot, with the tools at the top // (photocraft#16461). Content taller than the dock scrolls inside. Only a floating stepped window is as - // tall as its content. - self.report.placed.push((first.clone(), cell)); - let card = scene.sizes.card_place(at, column, &|panel: &P| scene.spec(panel)); + // tall as its content. A measuring run of the container around the dock places it too; the dock reports + // its columns from the pass's real run only, once. + if crate::runtime::measure::effect(ui.ctx(), "dock::placed_report") { + self.report.placed.push(Placed { panel: first.clone(), rect: cell }); + } + let card = plan.cards.get(at).copied().flatten(); + let place = ("docked", plan.edge, at); let at = ColumnAt { cell, edge: plan.edge, bar: ColumnBar::Own, within: body.rect, open: plan.open.clone(), card }; - self.column(ui, body, column, at); + self.shown_column(ui, &name, column, at, place); } } + /// Shows `column` at `at`: as a memoized view keyed by [`Pass::column_key`] where every panel it shows has a + /// version, else run in this pass. `place` names the column among the area's: its dock edge and index, or its + /// window, so the ids inside stay while its tabs move. + fn shown_column(&mut self, ui: &mut Ui, name: &Label, column: &Column

, at: ColumnAt

, place: impl Hash + Debug) { + let (Some(key), Some(first)) = (self.column_key(column, &at), column.panels().next().cloned()) else { + self.column(ui, name, column, at); + return; + }; + let id = self.dock.with(("column", place)); + let cell = at.cell; + let view = ColumnView { key, first, pass: &mut *self, column, at, name: name.clone() }; + // The view's room is the column's cell, so the pointer over the cell, and nowhere else, runs it. + let drawn = ui.scope_builder(UiBuilder::new().max_rect(cell), |ui| MemoView::new(id, view, column_view::

).show(ui)).inner; + if let Some(drawn) = drawn { + self.add_drawn(ui, drawn); + } + } + + /// The docked tree, with its docks: as a memoized view keyed by [`Pass::tree_key`] where every panel it shows has + /// a version, else run in this pass. + fn tree(&mut self, ui: &mut Ui, at: TreeAt

) { + let Some(key) = self.tree_key(&at) else { + self.show_tree(ui, &at); + return; + }; + let id = self.dock.with("docked tree"); + let rail_footer = self.scene.rail_footer.cloned(); + let view = TreeView { key, rail_footer, pass: &mut *self, at }; + if let Some(drawn) = MemoView::new(id, view, tree_view::

).show(ui) { + self.add_drawn(ui, drawn); + } + } + + /// The docked tree in a `SplitArea`: each group at its frame, each dock's columns, and the drop bands along the + /// area's edges. + fn show_tree(&mut self, ui: &mut Ui, at: &TreeAt

) { + let scene = self.scene; + let ctx = ui.ctx().clone(); + let limits = |panel: &P| scene.spec(panel).limits; + let dock_width = |columns: &[Column

]| scene.natural(columns).iter().map(|(width, _)| *width).sum::(); + let stripless = |panel: &P| scene.spec(panel).canvas; + let rules = FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless).dock_gap(scene.sizes.dock_gap); + let area = SplitArea::new(at.label.clone(), Bind::given(scene.layout.clone()), rules, at.frames).show(ui, |ui, split| { + DockTargets::

::register_room(&ctx, scene.dock, split.rect); + // The leaves of this run only: a measuring run of the area lays them out too, and registers nothing. + let mut leaves: Vec<(Vec, Rect)> = Vec::new(); + for (anchor, rect) in split.group_frames::

() { + let Some(place) = scene.layout.place(&anchor) else { continue }; + let Some(node) = scene.layout.node_of(&place) else { continue }; + if let PanelPlace::Node(path) = &place { + leaves.push((path.clone(), rect)); + } + self.leaf(ui, split, node, rect); + } + let flow = Flow::new(split.rect, scene.rtl); + for (edge, rect) in split.dock_frames() { + 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) = at.shell.as_ref().filter(|shell| shell.revealed()) { + shell.reveal_rect(&ctx, if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect); + } + let (natural, cards) = at.geometry.dock(edge); + self.dock(ui, split, DockPlan { edge, columns, rect, flow, open: at.open.clone(), natural, cards }); + } + register_bands(scene, &ctx, at.room, &leaves); + }); + let splits = area + .output + .dividers + .iter() + .map(|(path, rect, node)| DockSource::new(SourceKind::Divider(DividerKind::Split(path.clone())), *rect, *node)); + self.report.sources.extend(splits); + self.report.split = area.output.edit.events; + } + + /// A key fed with what every column and the docked tree read of the area: the pruned layout, the dock their spots + /// register in, the float bounds, the direction, the look and the host's requests. + fn area_key(&self, open: Option<&P>) -> MemoKey { + let scene = self.scene; + let mut key = MemoKey::new(); + scene.view.key(&mut key); + self.dock.key(&mut key); + scene.bounds.key(&mut key); + scene.rtl.key(&mut key); + scene.auto_collapse.key(&mut key); + key.feed_hash(scene.config); + scene.focus.map(PanelKey::of).key(&mut key); + scene.rail_footer.map(PanelKey::of).key(&mut key); + open.map(PanelKey::of).key(&mut key); + key + } + + /// The key of `column` shown at `at` ([`Pass::area_key`], its place and the versions of the panels it shows), or + /// `None` where one of those panels has no version ([`DockPanels::content`]). + fn column_key(&self, column: &Column

, at: &ColumnAt

) -> Option { + let mut key = self.area_key(at.open.as_ref()); + at.cell.key(&mut key); + at.within.key(&mut key); + key.feed_hash(&(at.edge, at.bar, at.card)); + self.feed_versions(&mut key, column_shows(column, [at.open.as_ref(), self.scene.rail_footer]))?; + Some(key.finish()) + } + + /// The key of the docked tree shown at `at` ([`Pass::area_key`], its room, name, the shell's reveal, its frames' + /// revision and the versions of every panel it shows), or `None` where one of those panels has no version. + fn tree_key(&self, at: &TreeAt

) -> Option { + let mut key = self.area_key(at.open.as_ref()); + at.room.key(&mut key); + at.label.key(&mut key); + at.shell.as_ref().map(ShellCx::revealed).key(&mut key); + at.frames.key(&mut key); + if let Some(root) = self.scene.layout.root.as_ref() { + self.feed_node(&mut key, root, at.open.as_ref())?; + } + Some(key.finish()) + } + + /// Feeds the versions of the panels `node` shows: each group's shown panel, each section and each dock column's + /// ([`column_shows`]). `None` where one has none. + fn feed_node(&self, key: &mut MemoKey, node: &Node

, open: Option<&P>) -> Option<()> { + match node { + Node::Split { first, second, .. } => { + self.feed_node(key, first, open)?; + self.feed_node(key, second, open) + } + Node::Tabs { panels, active, .. } => self.feed_versions(key, panels.get((*active).min(panels.len().saturating_sub(1))).into_iter()), + Node::Stack { entries, .. } => self.feed_versions(key, entries.iter().map(|entry| &entry.panel)), + Node::Dock { columns, .. } => { + for column in columns { + self.feed_versions(key, column_shows(column, [open, self.scene.rail_footer]))?; + } + Some(()) + } + _ => None, + } + } + + /// Feeds the host's version of each of `panels` ([`DockPanels::content`]); `None` where one has none. + fn feed_versions<'p>(&self, key: &mut MemoKey, panels: impl Iterator) -> Option<()> + where + P: 'p, + { + for panel in panels { + self.panels.content(panel)?.key(key); + } + Some(()) + } + + /// How far the report has grown, for [`Pass::drawn_since`]. + fn mark(&self) -> Mark { + Mark { sources: self.report.sources.len(), shown: self.report.shown.len(), placed: self.report.placed.len() } + } + + /// What the report gained since `mark`, taken out of it: what a view's run drew. + fn drawn_since(&mut self, mark: Mark) -> Drawn

{ + Drawn { + sources: self.report.sources.split_off(mark.sources), + shown: self.report.shown.split_off(mark.shown), + placed: self.report.placed.split_off(mark.placed), + } + } + + /// Adds what a view drew, by its run or its replay, to the report: in the pass's real run only. A measuring run's + /// replay returns the kept real run's report, which the real run adds once. + fn add_drawn(&mut self, ui: &Ui, drawn: Drawn

) { + if !crate::runtime::measure::effect(ui.ctx(), "dock::drawn_report") { + return; + } + self.report.sources.extend(drawn.sources); + self.report.shown.extend(drawn.shown); + self.report.placed.extend(drawn.placed); + } + /// The steps a resize `change` of the floating window of the stepped `column`, whose first panel is `first`, sets, /// and the window's rect at them: as wide as its steps and as tall as its chrome and its content at that width. /// `fitted` is the content's size under the chrome before the change, `chrome` the height above the window's body @@ -1461,7 +1824,7 @@ impl Pass<'_, P> { (fitted, chrome): (Vec2, f32), ) -> Option { let scene = self.scene; - let spec_of = |panel: &P| scene.spec(panel); + let spec_of = |panel: &P| scene.spec(panel).clone(); let (grid, steps) = scene.sizes.stepped(column, &spec_of)?; let by_height = match change.kind { PlacementKind::Size(grip) => matches!(grip, ResizeEdge::Top | ResizeEdge::Bottom), @@ -1492,7 +1855,7 @@ impl Pass<'_, P> { /// steps: what the column shows under its bar. `None` for any other column. fn stepped_height(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, width: f32, in_window: bool) -> Option { let scene = self.scene; - let spec = |panel: &P| scene.spec(panel); + let spec = |panel: &P| scene.spec(panel).clone(); if column.iconic || scene.sizes.stepped(column, &spec).is_none() { return None; } @@ -1507,7 +1870,7 @@ impl Pass<'_, P> { /// for. fn arrow_of(&self, column: &Column

) -> ColumnArrow { let scene = self.scene; - let spec = |panel: &P| scene.spec(panel); + let spec = |panel: &P| scene.spec(panel).clone(); ColumnArrow::of(column, &scene.sizes, &spec, column.panels().all(|panel| scene.permissions(panel).collapses)) } @@ -1526,10 +1889,9 @@ impl Pass<'_, P> { /// One column, docked or floating: its icons and their flyouts while it is collapsed, else its stacked groups, /// each group shown by `group_of`. What the user did on it becomes actions. - fn column(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, column: &Column

, at: ColumnAt

) { + fn column(&mut self, ui: &mut Ui, name: &Label, column: &Column

, at: ColumnAt

) { let scene = self.scene; - let spec = |panel: &P| scene.spec(panel); - let name = Label::from(body.words::().panels.as_str().to_owned()); + let spec = |panel: &P| scene.spec(panel).clone(); let dock = self.dock; let ColumnAt { mut cell, edge, bar, within, open, card } = at; let in_window = bar == ColumnBar::Window; @@ -1607,7 +1969,7 @@ impl Pass<'_, P> { self.report.actions.push(Action::resize_iconic(first.clone(), Some(width))); } } - let shown = DockColumn::new(name, dock, column, &spec) + let shown = DockColumn::new(name.clone(), dock, column, &spec) .edge(edge) .bar(bar) .arrow(self.arrow_of(column)) @@ -1621,8 +1983,10 @@ impl Pass<'_, P> { let output = shown.show_groups_at(ui, cell, |group, rect, ui, body| { self.group_of(ui, body, group, GroupAt::Show(rect), in_window); }); - let dividers = output.dividers.into_iter().map(|(divider, rect, node)| DockSource::new(SourceKind::Divider(divider), rect, node)); - self.report.sources.extend(dividers); + if crate::runtime::measure::effect(ui.ctx(), "dock::divider_report") { + let dividers = output.dividers.into_iter().map(|(divider, rect, node)| DockSource::new(SourceKind::Divider(divider), rect, node)); + self.report.sources.extend(dividers); + } let width = output.width.map(|width| width - inset); ColumnWork { iconic: output.iconic, picked: output.picked, resized: output.resized, width, flyout: None } }; @@ -1648,7 +2012,7 @@ impl Pass<'_, P> { self.report.actions.push(Action::resize_group(anchor, Some(height))); } let scene = self.scene; - let spec = |panel: &P| scene.spec(panel); + let spec = |panel: &P| scene.spec(panel).clone(); if let Some(width) = work.width { match scene.sizes.stepped(column, &spec) { // The edge of a stepped column moves in whole steps: the most that fit where it is dragged. @@ -1716,13 +2080,13 @@ impl Pass<'_, P> { let ctx = ui.ctx().clone(); let policy = |panel: &P| scene.permissions(panel); let protected = |panel: &P| scene.permissions(panel).is_protected(); - let spec_of = |panel: &P| scene.spec(panel); + let spec_of = |panel: &P| scene.spec(panel).clone(); let mut moved = None; for window in &scene.layout.floating { let Some(anchor) = window.panels().next().cloned() else { continue }; // The window's menu acts on the shown panel of its top group. let active = window.groups().first().and_then(Group::active_panel).cloned().unwrap_or_else(|| anchor.clone()); - let specs: Vec = window.panels().map(|panel| scene.spec(panel)).collect(); + let specs: Vec = window.panels().map(|panel| scene.spec(panel).clone()).collect(); let rights: Vec = window.panels().map(|panel| scene.permissions(panel)).collect(); let dock = scene.dock.with(("floating", window.id)); let group_id = dock.with("window"); @@ -1775,7 +2139,7 @@ impl Pass<'_, P> { WindowColumn::expanded(edge) } .arrow(self.arrow_of(&window.column)); - let mut group = FloatingGroup::new(spec.label, opening.rect) + let mut group = FloatingGroup::new(spec.label.clone(), opening.rect) .limits(scene.spec(&anchor).limits) .sized(Sizing::Fill) .column(shape) @@ -1825,7 +2189,8 @@ impl Pass<'_, P> { // in-app window's stay in the float area. let within = if opening.spec.is_some() { Rect::NOTHING } else { scene.bounds }; let at = ColumnAt { cell: body.rect, edge, bar: ColumnBar::Window, within, open: open.clone(), card: None }; - self.column(ui, body, &window.column, at); + let name = Label::from(body.words::().panels.as_str().to_owned()); + self.shown_column(ui, &name, &window.column, at, window.id); }); self.dock = area_dock; let output = shown.output; @@ -1844,8 +2209,8 @@ impl Pass<'_, P> { if !output.files.is_empty() { // The group under the drop, else the first group: a drop on the title row, or with no pointer known. let groups = &self.report.shown[first_group..]; - let under = output.files_at.and_then(|at| groups.iter().find(|(_, rect)| rect.contains(at))); - let panel = under.or(groups.first()).map_or_else(|| active.clone(), |(panel, _)| panel.clone()); + let under = output.files_at.and_then(|at| groups.iter().find(|group| group.rect.contains(at))); + let panel = under.or(groups.first()).map_or_else(|| active.clone(), |group| group.panel.clone()); self.report.files.push(WindowFiles { panel, files: output.files }); } if let Some(dropped) = dropped.into_inner() { @@ -1989,6 +2354,13 @@ fn window_edit( } } +/// The panels whose host views `column` shows: each group's shown panel, and each of `extra` (the open flyout's, the +/// rail footer's) that the column holds. +fn column_shows<'c, P: PartialEq>(column: &'c Column

, extra: [Option<&'c P>; 2]) -> impl Iterator { + let shown = column.groups.iter().filter_map(Group::active_panel); + shown.chain(extra.into_iter().flatten().filter(move |panel| column.panels().any(|held| held == *panel))) +} + /// Shows `panel`'s body in a group's body, in the host's style and once per pass where the body is the app's own egui /// code (`Scene::hosted`). It runs every pass the group shows; the host memoizes inside it. fn panel_body<'p, P: Clone + Eq + Hash>( diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index 83f61605ec..2081ba1515 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -1710,7 +1710,7 @@ pub(crate) fn edited_rows(params: &[Param], before: &DialogFields, after: &Dialo .iter() .filter(|param| { differs(¶m.key) - || param.unit_key().is_some_and(&differs) + || param.unit_key().is_some_and(differs) || matches!(¶m.kind, ParamKind::Custom(row) if row.companions.iter().any(|key| differs(key))) || (matches!(param.kind, ParamKind::Files { .. }) && (differs(¶m.folder_key()) || differs(¶m.use_folder_key()))) }) diff --git a/crates/ui-patterns/tests/it/docking/drop_session.rs b/crates/ui-patterns/tests/it/docking/drop_session.rs index 1185a6f271..6b2c65f59c 100644 --- a/crates/ui-patterns/tests/it/docking/drop_session.rs +++ b/crates/ui-patterns/tests/it/docking/drop_session.rs @@ -4,7 +4,9 @@ use craft_behavior::Axis; use craft_behavior::dock::{Layout, Node, Permissions, SplitSize, Workspace}; use craft_ui::contract::SizeLimits; -use craft_ui::contract::{Bind, BodyCx, Common, Component, Cx, MeasureCx, PlainData, Pointer as _, Role, Show as _, ShowContainer as _, Tracked}; +use craft_ui::contract::{ + Bind, BodyCx, Common, Component, Cx, MeasureCx, MemoKey, PlainData, Pointer as _, Role, Show as _, ShowContainer as _, Tracked, +}; use craft_ui::docking::tree::{self, FrameRules}; use craft_ui::docking::{ DockConfig, DockDropTarget, DockDropped, DockGroup, DockPanels, DockSizes, GroupDrag, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, @@ -131,13 +133,19 @@ fn bed(layout: Layout) -> Bed { Host { common: Common::new(), target: &target, seen: &shared_taken }.show(ui); let limits = |_: &String| SizeLimits::default(); let placed = placed_groups(&shown, origin); - SplitArea::new("Panels", Bind::given(shown.clone()), FrameRules::new(&limits)).show_at(ui, Rect::from_min_size(origin, AREA), |ui, _| { - for (anchor, panels, rect) in &placed { - let titles: Vec = panels.iter().map(|panel| PanelTitle::new(PanelKey::of(panel), panel.clone())).collect(); - let active = titles.first().map_or(PanelKey::new(0), |title| title.key); - DockGroup::new(anchor.clone(), Titles::from_content(titles.clone()), active).dock(dock_id()).show_at(ui, *rect, |_, _| ()); - } - }); + // The layout's saved form stands for it: the rules read nothing else. + let revision = MemoKey::of(&serde_json::to_value(&shown).expect("a layout saves")); + SplitArea::new("Panels", Bind::given(shown.clone()), FrameRules::new(&limits), revision).show_at( + ui, + Rect::from_min_size(origin, AREA), + |ui, _| { + for (anchor, panels, rect) in &placed { + let titles: Vec = panels.iter().map(|panel| PanelTitle::new(PanelKey::of(panel), panel.clone())).collect(); + let active = titles.first().map_or(PanelKey::new(0), |title| title.key); + DockGroup::new(anchor.clone(), Titles::from_content(titles.clone()), active).dock(dock_id()).show_at(ui, *rect, |_, _| ()); + } + }, + ); for dropped in shared_taken.borrow_mut().drain(..) { shared_layout.borrow_mut().apply_with_permissions(dropped.action, permissions).expect("the model takes what the dock accepted"); } diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index d79ba5fd4a..7247605e22 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -11,11 +11,12 @@ use craft_ui::docking::{DockConfig, DockPanels, PanelDrag, PanelSpec, PanelSpecs use craft_ui::menu::PanelRow; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; -use craft_ui::testing::in_audit_run; use craft_ui::testing::pointer::{moved, press}; use craft_ui::testing::{ - Fixture, MemoRun, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, trial, + Fixture, MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_derived_builds, last_pass_memo_key_bytes, last_pass_memo_runs, + last_pass_runs, trial, }; +use craft_ui::testing::{audit_replays, in_audit_run}; use egui::{Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -546,3 +547,153 @@ fn a_tab_picked_in_the_focused_group_is_the_focused_panel() { let at = reported.iter().position(|(_, picked)| *picked == Some(0)).expect("the click picks panel 0"); assert!(reported[at..].iter().all(|(focused, _)| *focused == Some(0)), "from the pick on, panel 0 is focused: {reported:?}"); } + +/// Panels whose bodies are memoized views and whose host views have versions ([`DockPanels::content`]), one per +/// panel, in a list a trial moves. +struct Versioned { + versions: Rc>>, +} + +impl DockPanels for Versioned { + fn body(&mut self, panel: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) { + let _ = MemoView::new(("body", *panel), BodyProps { panel: *panel }, panel_body).show(ui); + } + + fn content(&self, panel: &usize) -> Option { + self.versions.borrow().get(*panel).copied() + } + + fn panel_rows(&mut self, _: &usize) -> Vec { + vec![PanelRow::Separator] + } +} + +/// A settled dock over `layout` whose panels are [`Versioned`], with the versions and what each pass reported focused. +struct VersionedDock { + fixture: Fixture, + versions: Rc>>, + workspace: Rc>>>, + focused: Rc>>>, + /// How many docked columns and gesture sources each pass reported. + reported: Rc>>, +} + +fn versioned_dock(layout: Layout) -> VersionedDock { + let labels = Tracked::new(Labels((0..32).map(|panel| format!("Panel {panel}")).collect())); + let versions = Rc::new(RefCell::new(vec![0; 32])); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(layout)))); + let focused = Rc::new(RefCell::new(Vec::new())); + let reported = Rc::new(RefCell::new(Vec::new())); + let mut panels = Versioned { versions: Rc::clone(&versions) }; + let (shown, seen, counts) = (Rc::clone(&workspace), Rc::clone(&focused), Rc::clone(&reported)); + let mut fixture = Fixture::new(move |ui| { + let output = DockArea::new("Dock", Bind::bound(&mut *shown.borrow_mut()), &labels, &mut panels, DockConfig::default()).show(ui); + seen.borrow_mut().push(output.focused); + counts.borrow_mut().push((output.columns.len(), output.sources.len())); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle().idle(SETTLE); + body_runs(); + spec_reads(); + focused.borrow_mut().clear(); + VersionedDock { fixture, versions, workspace, focused, reported } +} + +/// The dock's containers: what a settled dock whose panels all have versions runs none of. +const CONTAINERS: [&str; 4] = ["SplitArea", "DockColumn", "DockGroup", "IconicColumn"]; + +/// At rest a dock whose panels all have versions runs none of its containers, whatever its groups and panels: the +/// docked tree replays as one record, and the floating window's column as its own. The replayed tabs still paint. +#[trial] +fn an_idle_versioned_dock_runs_no_dock_container() { + let twelve = Layout::new(Some(Node::tabs((0..12).collect(), 0)), Vec::new()); + for layout in [full(1), full(2), full(3), twelve] { + let VersionedDock { mut fixture, .. } = versioned_dock(layout); + fixture.frame(Vec::new()); + assert_eq!(runs_of(&fixture, &CONTAINERS), 0, "an idle dock ran containers: {:?}", last_pass_runs(fixture.ctx())); + assert_eq!(memo_of(&fixture, "TreeView"), (0, 1), "the docked tree replays: {:?}", memo_runs(&fixture)); + assert_eq!(body_runs(), Vec::::new(), "no body ran"); + assert!(fixture.texts().iter().any(|text| text.text == "Panel 0"), "the replayed tabs paint their titles"); + } + let VersionedDock { mut fixture, .. } = versioned_dock(full(2)); + fixture.frame(Vec::new()); + assert_eq!(memo_of(&fixture, "ColumnView"), (0, 1), "the floating window's column replays: {:?}", memo_runs(&fixture)); +} + +/// A new version of one docked column's panel runs that column and its group; the iconic column and the floating +/// window's column replay. +#[trial] +fn a_panel_version_change_runs_only_its_column() { + let VersionedDock { mut fixture, versions, .. } = versioned_dock(full(2)); + versions.borrow_mut()[20] += 1; + fixture.frame(Vec::new()); + assert_eq!(memo_of(&fixture, "ColumnView"), (1, 2), "only panel 20's column ran: {:?}", memo_runs(&fixture)); + assert_eq!(runs_of(&fixture, &["IconicColumn"]), 0, "the iconic column replays"); + fixture.frame(Vec::new()); + assert_eq!(runs_of(&fixture, &CONTAINERS), 0, "and the dock settles again: {:?}", last_pass_runs(fixture.ctx())); +} + +/// The pointer over a docked column's body runs that column and that body; the other columns and bodies replay. The +/// pointer over a group of the docked tree runs no column. +#[trial] +fn the_pointer_over_one_column_runs_only_that_column() { + let VersionedDock { mut fixture, .. } = versioned_dock(full(2)); + let tree = fixture.by_label("Body 0").expect("a tree group's body").center(); + fixture.frame(vec![moved(tree)]); + assert_eq!(memo_of(&fixture, "ColumnView").0, 0, "the pointer over the tree ran a column: {:?}", memo_runs(&fixture)); + body_runs(); + let body = fixture.by_label("Body 20").expect("the column's body").center(); + fixture.frame(vec![moved(body)]); + assert_eq!(memo_of(&fixture, "ColumnView"), (1, 2), "only the column under the pointer ran: {:?}", memo_runs(&fixture)); + // The tree body the pointer left runs once too; of the columns' bodies (panels 20 to 22) only panel 20's runs. + let columns: Vec = body_runs().into_iter().filter(|panel| *panel >= 20).collect(); + assert_eq!(columns, vec![20], "only panel 20's body ran of the columns' bodies"); +} + +/// A pass that runs the docked tree without changing it builds no derived value (the docks' geometry and the tree's +/// frames included); a column resize builds each of them once. +#[trial] +fn the_docks_geometry_builds_once_per_layout_change() { + let VersionedDock { mut fixture, workspace, .. } = versioned_dock(full(2)); + let body = fixture.by_label("Body 0").expect("a tree group's body").center(); + fixture.frame(vec![moved(body)]); + assert!(runs_of(&fixture, &["SplitArea"]) > 0, "the pointer over a tree group runs the tree"); + assert_eq!(last_pass_derived_builds(fixture.ctx()), Vec::new(), "an unchanged layout builds nothing"); + Arc::make_mut(&mut workspace.borrow_mut()).apply(Action::resize_column(20, 300.0), false, |_| Permissions::ALL).expect("the column resizes"); + fixture.frame(Vec::new()); + let builds = last_frame_derived_builds(fixture.ctx()); + assert!(!builds.is_empty() && builds.iter().all(|(_, count)| *count == 1), "the resize builds each value once: {builds:?}"); +} + +/// Key focus resting in a group of a dock that replays is still reported, pass after pass. +#[trial] +fn a_replayed_group_reports_the_focus_it_holds() { + let VersionedDock { mut fixture, focused, .. } = versioned_dock(side_by_side(2)); + for _ in 0..4 { + if focused.borrow().last() == Some(&Some(0)) { + break; + } + fixture.key(egui::Key::Tab, egui::Modifiers::NONE).idle(1); + } + assert_eq!(focused.borrow().last(), Some(&Some(0)), "Tab reaches the first group"); + focused.borrow_mut().clear(); + fixture.idle(3); + assert_eq!(runs_of(&fixture, &CONTAINERS), 0, "the focused dock replays"); + assert!(focused.borrow().iter().all(|panel| *panel == Some(0)), "every replay reports the focus: {:?}", focused.borrow()); +} + +/// The docked tree and its columns report each column and gesture source once in every pass, and replay what they +/// ran: the replay audit runs the tree in place of each replay, at rest and through new rooms, where the docks' split +/// area measures them before it shows them. +#[trial] +fn a_measured_versioned_dock_reports_each_column_and_source_once() { + let VersionedDock { mut fixture, reported, .. } = versioned_dock(full(2)); + let settled = *reported.borrow().last().expect("the dock reported"); + assert_eq!(settled.0, 2, "the dock's two columns are placed"); + audit_replays(fixture.ctx(), true); + reported.borrow_mut().clear(); + fixture.idle(4); + fixture.room(Vec2::new(1100.0, 600.0)).idle(4).room(Vec2::new(1200.0, 640.0)).idle(4); + audit_replays(fixture.ctx(), false); + let reported = reported.borrow(); + assert!(reported.iter().all(|counts| *counts == settled), "every pass reports {settled:?}: {reported:?}"); +} diff --git a/crates/ui-patterns/tests/it/panels/palette.rs b/crates/ui-patterns/tests/it/panels/palette.rs index ecfd5ea24a..4be3f59a23 100644 --- a/crates/ui-patterns/tests/it/panels/palette.rs +++ b/crates/ui-patterns/tests/it/panels/palette.rs @@ -14,6 +14,7 @@ use craft_ui::testing::{Fixture, Registry, trial}; use egui::{Key, Modifiers, Pos2, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; /// App commands with the default modal rule: blocked while a dialog is open. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] @@ -488,7 +489,7 @@ fn the_active_row_marks_its_shown_control_and_a_hidden_home_goes_to_the_footer() // Flip is held by a rect in the corner, the way a menu title holds its commands; Rotate has a bound button. let mut rig = rig(entries, Some(vec![TrialCommand::Flip.into()]), false, |ui| { let corner = egui::Rect::from_min_size(ui.max_rect().min, Vec2::new(60.0, 20.0)); - commands::holds(ui.ctx(), ui.layer_id(), corner, &[TrialCommand::Flip.into()], Label::from("Rail slot")); + commands::holds(ui.ctx(), ui.layer_id(), corner, &Arc::from([CommandRef::from(TrialCommand::Flip)]), Label::from("Rail slot")); ui.add_space(24.0); Button::command(TrialCommand::Rotate).show(ui); }); diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index f2a27ca6f2..984c07aeca 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -16,8 +16,8 @@ use super::title_bar::PageBand; use super::words::ShellWords; use crate::contract::overlay::{PopupRegion, Resize}; use crate::contract::{ - Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, DropZone, Mount, NoValue, Outcome, Overlay, PaneEdge, Props as _, - Remember as _, Role, ShellPane, ShowContainer as _, Sizing, + Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, DropZone, MemoView, Mount, NoValue, Outcome, Overlay, PaneEdge, + Props as _, Remember as _, Role, ShellPane, ShowContainer as _, Sizing, }; use crate::layout_components::Stack; use crate::notices::ToastStack; @@ -34,7 +34,7 @@ use crate::runtime::windows::{WindowAction, WindowHost}; use crate::shell::Slot; use crate::style::{ComponentStyle, StyleCx, SurfaceKind, UiTokens}; use craft_behavior::{EditEvent, Metrics, Mixed, Sense}; -use egui::{Context, Rect, Response, Ui, ViewportId, pos2}; +use egui::{Context, Rect, Response, Ui, UiBuilder, ViewportId, pos2}; use std::sync::Arc; /// The closure that fills a region. @@ -63,6 +63,134 @@ impl<'a, S> SlotBody<'a, S> { } } +/// The host's version of what a slot or the page shows, read from the app state at the slot's turn in the pass; `None` +/// runs the slot in every pass. +type VersionFn<'a, S> = Box Option + 'a>; + +/// Where and how one slot shows: everything its pane and its content take from the shell besides the app. +#[derive(Clone, crate::contract::MemoProps)] +struct SlotPlace { + key: SlotKey, + edge: PaneEdge, + /// The slot's extent along its edge, as it was laid out. + extent: f32, + /// The pane's rect, or for a slot sized by its content the room it can grow into. + room: Rect, + /// The slot is as large as its content ([`SlotSize::Content`]). + by_content: bool, + /// The title slot mirrors with the traffic lights at the right end. + mirrored: bool, + /// The floating options bar's top-left corner: the bar is a movable layer over the body, bounded by `room`. + floating: Option, + label: Option