mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
Merge pull request #3900 from aiongg/fw365-frame-floor
perf(ui): a settled frame replays more of the shell, dock and rows; four layout and focus fixes
This commit is contained in:
144 files changed
+4083
-1476
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -845,7 +845,7 @@ impl<P: Clone + Send + Sync + 'static> 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)
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -210,7 +210,7 @@ fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>>
|
||||
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);
|
||||
|
||||
@@ -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<Finding>) {
|
||||
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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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::<Vec<_>>();
|
||||
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),
|
||||
|
||||
@@ -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");
|
||||
})
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -358,7 +358,7 @@ impl<'a> PathTextMarkers<'a> {
|
||||
let mut held: Option<Grip> = *cx.press_slot::<Grip>();
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -602,7 +602,8 @@ impl<M: TimelineModel> 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::<Side>() {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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() })
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<f32>,
|
||||
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,
|
||||
|
||||
@@ -302,18 +302,17 @@ impl<C: Container> ShapeHooks<C> 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<C: Container> ShapeHooks<C> 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<C: Container> ShapeHooks<C> 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<C: Container> ShapeHooks<C> 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;
|
||||
}
|
||||
|
||||
@@ -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<f32>,
|
||||
grid: Option<Id>,
|
||||
egui_cell: bool,
|
||||
/// The content version of the memoized view the body runs in (`Scoped::view_version`).
|
||||
view: Option<u128>,
|
||||
}
|
||||
|
||||
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<f32>) -> 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<Vec2> {
|
||||
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))
|
||||
}
|
||||
},
|
||||
|
||||
@@ -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<C: Show>(&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 }))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -172,8 +172,6 @@ pub struct CxCore<'a> {
|
||||
pub(crate) reset_part: Option<PartRef>,
|
||||
/// 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<Id>,
|
||||
/// The member of the container's roving group that moves start from, set by `Cx::roving_lead`.
|
||||
pub(crate) roving_lead: Option<Id>,
|
||||
/// The component joined the roving group of the body it is shown in this pass (`Cx::join_roving`).
|
||||
@@ -321,9 +319,10 @@ impl<C: Component> 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:
|
||||
|
||||
@@ -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<C: Component> 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<C: Component> 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
|
||||
|
||||
@@ -21,9 +21,10 @@ pub trait Pointer {
|
||||
/// condition.
|
||||
fn part_if_declared(&self, part: impl Into<PartRef>) -> 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<PartRef>) -> Option<Pos2> {
|
||||
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<PartRef>) -> Option<Pos2>;
|
||||
/// 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<PartRef>) -> Option<Pos2> {
|
||||
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<C: Component> Pointer for Cx<'_, C> {
|
||||
self.core.part_if_declared(part)
|
||||
}
|
||||
|
||||
fn hover_pos(&self, part: impl Into<PartRef>) -> Option<Pos2> {
|
||||
self.core.hover_pos(part)
|
||||
}
|
||||
|
||||
fn press(&self) -> &PressState {
|
||||
self.core.press()
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ impl<G: GroupKind> GroupHandle<G> {
|
||||
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)]
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,10 +16,15 @@ impl<C: Collection> 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) {
|
||||
|
||||
@@ -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<usize> {
|
||||
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()
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -187,13 +187,13 @@ impl<C: Collection> ShapeHooks<C> 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<C: Collection> ShapeHooks<C> 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<C: Collection> ShapeHooks<C> 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<C: Collection> ShapeHooks<C> 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<C: Collection> ShapeHooks<C> 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<C: Collection> ShapeHooks<C> 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<C: Collection> ShapeHooks<C> 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<C: Collection> 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<C: Collection> 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<C: Collection> 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<C: Collection> 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
|
||||
};
|
||||
|
||||
@@ -193,13 +193,17 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer's position, in screen space, while it is over the collection.
|
||||
fn hovered_pos(cx: &Cx<'_, C>) -> Option<Pos2> {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
let Placement { rect, offset, rtl } = at;
|
||||
let pos = self.xf.map_or(pos, |map| map.to_layer(pos));
|
||||
@@ -218,13 +222,13 @@ impl<C: Collection> 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<C: Collection> 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)
|
||||
|
||||
@@ -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<Vec2>, 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<Vec2>, 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<ItemsInputs> {
|
||||
fn items_inputs(&self, comp: &C, env: &Env, room: Vec2) -> Option<ItemsInputs> {
|
||||
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 {
|
||||
|
||||
@@ -434,7 +434,7 @@ fn item_openers(ui: &Ui, ctx: &Context, id: Id, enabled: bool, openers: Vec<Item
|
||||
clicked: on_part(outcome.activated),
|
||||
..response::PressView::default()
|
||||
},
|
||||
pointer: ctx.pointer_latest_pos(),
|
||||
pointer: crate::runtime::pointer::frame_raw(ctx).pos,
|
||||
};
|
||||
let response = response::member(ui, opener_id(opener.item, opener.part), rect, enabled, view);
|
||||
Some((opener, response))
|
||||
|
||||
@@ -125,7 +125,7 @@ impl LeafPlaced {
|
||||
/// and calls `LeafPlaced::finish`.
|
||||
pub(crate) fn decide_leaf<C: Show>(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<C: Show>(
|
||||
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: Show>(
|
||||
) -> 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<C: Show>(
|
||||
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<Trailing<'_>>,
|
||||
in_cell: bool,
|
||||
(trailing, in_cell): (Option<Trailing<'_>>, 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<C: Show>(
|
||||
}
|
||||
// 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<C: Show>(
|
||||
// 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<C: Show>(
|
||||
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<C: Show>(
|
||||
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<C: Show>(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::<C>();
|
||||
@@ -525,5 +527,6 @@ pub(crate) fn show_leaf_in_flow<C: Show>(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)
|
||||
}
|
||||
@@ -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<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option<R> {
|
||||
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<R>(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown<R> {
|
||||
/// 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<R>(self, (ui, env): (&mut Ui, Env), name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown<R> {
|
||||
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<R>(ui: &mut Ui, audited: Audited<'_>, out: R, run: &Run) -> Shown<R> {
|
||||
fn place_audit_run<R>(ui: &mut Ui, env: &Env, audited: Audited<'_>, out: R, run: &Run) -> Shown<R> {
|
||||
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<Shrink>, Option<Axis>), id: egui::Id, rect: Rect, rtl: bool) -> Rect {
|
||||
fn place_unit(ui: &mut Ui, env: &Env, (shrink, fills): (Option<Shrink>, Option<Axis>), 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<Shrink>, Option<Axis>), 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<Shrink>, Option<Axis>), 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<Shrink>, Option<Axis>), 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 {
|
||||
|
||||
@@ -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<egui::Context>,
|
||||
/// 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);
|
||||
|
||||
@@ -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<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> 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::<P>(), 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::<P>(), 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<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> 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())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Shape = shape::Leaf> + 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<Shape = shape::Leaf> + sealed::Show {
|
||||
pub trait ShowContainer: Container + sealed::ShowContainer {
|
||||
/// Shows the container in the flow of `ui`.
|
||||
fn show<R>(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
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<R>(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner<Self::Output, R> {
|
||||
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<R>(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner<Self::Output, R> {
|
||||
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<Self::Output, R> {
|
||||
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)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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::layer_tier(ctx, overlay.rank);
|
||||
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 { .. }) {
|
||||
@@ -386,7 +395,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));
|
||||
|
||||
@@ -41,10 +41,10 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
|
||||
pub fn show<R>(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)| {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<f32>,
|
||||
/// 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<C: Component> {
|
||||
}
|
||||
|
||||
/// 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<C: Component> {
|
||||
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<C: Component> {
|
||||
/// 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<Arc<ValueOf<C>>>) -> 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<C: Component> ShapeHooks<C> 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<C: Component> ShapeHooks<C> 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<dyn Host>;
|
||||
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<craft_behavior::Axis>;
|
||||
/// `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<focus::FocusPolicy>;
|
||||
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<f32>;
|
||||
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<crate::runtime::env::ArenaId>, 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<ShowAt>, 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<crate::runtime::env::ArenaId>,
|
||||
/// 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<Id>,
|
||||
/// 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<ShowAt>, env: &Env) -> Option<Box<HostStep>> {
|
||||
fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, (host_at, place): (Option<ShowAt>, &Env), env: &Env) -> Option<Box<HostStep>> {
|
||||
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<ShowAt>, 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<Id> {
|
||||
|
||||
/// 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<Vec<HeldRule>>);
|
||||
|
||||
/// 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<usize>,
|
||||
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::<BarRules, _>(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::<BarRules, _>(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::<BarRules, _>(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<TipFn<'_>>) {
|
||||
/// 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<TipFn<'_>>, 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<TipFn<'_>>) {
|
||||
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<TipFn<'_>>, 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<TipFn<'_>>) {
|
||||
let begun = begin(t, ui);
|
||||
fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>, 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<Env>,
|
||||
@@ -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<Begun> {
|
||||
fn begin(t: &mut dyn Erased, ui: &Ui, place: Env) -> Box<Begun> {
|
||||
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<Begun> {
|
||||
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<Begun> {
|
||||
}
|
||||
// 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);
|
||||
|
||||
@@ -234,16 +234,16 @@ impl<C: Component> 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<craft_behavior::Axis> {
|
||||
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<C: Component>(
|
||||
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<C: Component + Meta<Shape = crate::contract::shape::Leaf>>(
|
||||
slot: &mut Option<C>,
|
||||
ui: &mut Ui,
|
||||
at: ShowAt,
|
||||
(at, place): (ShowAt, Env),
|
||||
tip: Option<TipFn<'_>>,
|
||||
) -> 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<C: Container, R>(
|
||||
rect: Rect,
|
||||
body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
) -> Inner<C::Output, R> {
|
||||
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<C: Container, R>(
|
||||
slot: &mut Option<C>,
|
||||
ui: &mut Ui,
|
||||
at: ShowAt,
|
||||
(at, place): (ShowAt, Env),
|
||||
body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R,
|
||||
tip: Option<TipFn<'_>>,
|
||||
) -> Inner<C::Output, R> {
|
||||
@@ -586,7 +593,7 @@ pub(crate) fn show_container<C: Container, R>(
|
||||
};
|
||||
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::<C>::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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -73,7 +73,7 @@ pub(crate) fn unfade(ui: &Ui, core: &mut CxCore<'_>, fade: Option<Fade>) {
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Id> = 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
|
||||
}
|
||||
@@ -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::<FillCounts, _>(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<Axis> {
|
||||
pass_state::with::<ViewFills, _>(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<f32> {
|
||||
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<f32> {
|
||||
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<f32>], room: f32) -> Vec<usize> {
|
||||
/// 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<R>(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<R>(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<R>(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::<InBar>().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::<InBar>().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<R>(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<f32> {
|
||||
let env = Env::of(ui);
|
||||
pub(crate) fn view_room(ui: &Ui, env: &Env, axis: Axis) -> Option<f32> {
|
||||
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<f32> {
|
||||
/// 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<R>(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<R>(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<R>(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<R>(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option<f32>, body: &mut dyn FnMut(&mut Ui) -> R) -> R {
|
||||
fn share_sweep<R>(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option<f32>, 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<R>(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<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Rect) {
|
||||
fn measure_sharing<R>(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<R>(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::<FillCounts, _>(&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<R>(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<R>(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<R>(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R {
|
||||
fn run_column<R>(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<ColumnSweep>| env.derive_local(|scoped| scoped.column = column);
|
||||
let sweep = |ui: &mut Ui, column: Option<ColumnSweep>, body: &mut dyn FnMut(&mut Ui) -> R| {
|
||||
let sweep = |ui: &mut Ui, column: Option<ColumnSweep>, 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<R>(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<R>(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option<f32>) {
|
||||
/// `env` is the row's env, installed for `ui`.
|
||||
fn run_spread<R>(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option<f32>) {
|
||||
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<Vec2>, leasts: Vec<f32>, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| {
|
||||
let flow = Flow::new(ui.available_rect_before_wrap(), rtl);
|
||||
pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe))));
|
||||
@@ -1374,13 +1366,13 @@ fn run_spread<R>(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<R>(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<f32>, height: f32) -> Option<f32> {
|
||||
/// 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::<Cursors, _>(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<Rect> {
|
||||
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<Rect> {
|
||||
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<Id>, size: Vec2) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// 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::<Cursors, _>(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::<Cursors, _>(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<f32> {
|
||||
let env = Env::of(ui);
|
||||
pub(crate) fn row_alone_room(env: &Env) -> Option<f32> {
|
||||
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::<Cursors, _>(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::<Cursors, _>(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::<Cursors, _>(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::<Cursors, _>(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::<Cursors, _>(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::<Cursors, _>(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::<Cursors, _>(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::<Cursors, _>(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<Id>, row: Option<Id>, 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<f32>) {
|
||||
/// 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<f32>, target: Option<Id>) {
|
||||
if !sizing {
|
||||
return;
|
||||
}
|
||||
@@ -1933,7 +1917,7 @@ fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option<f32>) {
|
||||
}
|
||||
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<R>(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<R>(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<R>(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<R>(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<R>(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
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Pos2>,
|
||||
/// 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<Pos2>,
|
||||
/// The value flags the component set on the part.
|
||||
pub flags: Flags,
|
||||
/// What the part senses, as declared.
|
||||
|
||||
@@ -413,7 +413,7 @@ impl Shown {
|
||||
/// The entry `reader` keeps for `command`.
|
||||
fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option<u64> {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<CommandRef>,
|
||||
/// 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<CommandRef>),
|
||||
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<CommandRef>) {
|
||||
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::<ShownFact>::of_last_pass(ctx).len()
|
||||
Facts::<ShownFact>::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<Arc<CommandRef>> {
|
||||
Facts::<ShownFact>::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<Shown> {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let scrim = overlay::top_modal_in(ctx, viewport).and_then(|top| top.cover);
|
||||
Facts::<ShownFact>::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<ShownFact> = Facts::<ShownFact>::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`].
|
||||
|
||||
@@ -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<CursorRegion>) {
|
||||
crate::runtime::replay::journal(
|
||||
ctx,
|
||||
|| (cursor.clone(), priority, region),
|
||||
|ctx, (cursor, priority, region)| push(ctx, cursor.clone(), *priority, *region),
|
||||
);
|
||||
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| {
|
||||
state.requests.push((cursor, priority));
|
||||
state.regions.push(region);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Vec2>,
|
||||
/// 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<Rect> {
|
||||
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
|
||||
|
||||
@@ -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<frame::PassFacts>, viewport: ViewportId) -> u64 {
|
||||
match running {
|
||||
Some(facts) if facts.viewport == viewport => facts.pass_nr,
|
||||
_ => ctx.cumulative_pass_nr_for(viewport),
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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<u128>,
|
||||
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<u128>,
|
||||
/// 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<u64> = 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)]
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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 {
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
@@ -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<Id>) {
|
||||
ids.sort_unstable_by_key(|id| id.value());
|
||||
|
||||
@@ -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<T: Default> PerViewport<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<R>(ctx: &Context, f: impl FnOnce(&mut PerViewport<Self>) -> R) -> R {
|
||||
store::with::<PerViewport<Self>, R>(ctx, f)
|
||||
pass_state::with_records::<Self, R>(ctx, f)
|
||||
}
|
||||
|
||||
/// Runs `f` on the stamped records of this type.
|
||||
fn stamped<R>(ctx: &Context, f: impl FnOnce(&mut PerViewport<Stamped<Self>>) -> R) -> R {
|
||||
store::with::<PerViewport<Stamped<Self>>, R>(ctx, f)
|
||||
pass_state::with_records::<Stamped<Self>, 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<Vec<RunningPass>> = 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<PassFacts> {
|
||||
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::<FrameState, _>(&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);
|
||||
}
|
||||
@@ -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<Vec2>,
|
||||
/// When the area is a bar's line, its rules and members in run order (`note_line`).
|
||||
pub(crate) line: Vec<LineItem>,
|
||||
}
|
||||
|
||||
/// 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<Measured>; 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<craft_behavior::Axis>,
|
||||
}
|
||||
|
||||
/// 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<egui::Pos2>,
|
||||
/// What it ran for: its props key after the run.
|
||||
key: Key,
|
||||
/// The pass it ran in.
|
||||
@@ -423,22 +465,25 @@ fn write<R>(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: Id, sizing: bool, measured: Measured, registered: Option<Transcript>) {
|
||||
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<craft_behavio
|
||||
with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[own].or(entry.sizes[other])).and_then(|measured| measured.fills))
|
||||
}
|
||||
|
||||
/// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it
|
||||
/// ran), at whatever room it had; `None` before any run showed it.
|
||||
/// The extent the child `id` took in this pass's measuring run once it ran, else in the last real run that showed it,
|
||||
/// at whatever room it had; `None` before any run showed it.
|
||||
pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option<Vec2> {
|
||||
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<View>, Option<Vi
|
||||
|| crate::runtime::overlay::close_queued(ctx, &facts.layers)
|
||||
}
|
||||
|
||||
/// Whether the pointer is over `rect` (shown) on `layer` or over one of the overlay layers `overlays` shown, or a
|
||||
/// press that is held started there. Both halves ask whether the layer is the top layer at the point, so a pointer or
|
||||
/// a press on an overlay above the view leaves it alone.
|
||||
fn engaged(ctx: &Context, layer: Layer, rect: Rect, overlays: &[replay::ShownLayer]) -> 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<crate::runtime::audit::SameOutput>,
|
||||
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())
|
||||
|
||||
@@ -326,8 +326,9 @@ fn end_lives(reg: &mut Registry, owners: impl IntoIterator<Item = Id>) {
|
||||
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::<Registry, _>(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<T: Clone + Send + Sync + 'static> Facts<T> {
|
||||
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<T> {
|
||||
Self::with_record(ctx, |record| record.last.clone())
|
||||
pub fn with_last_pass<R>(ctx: &Context, f: impl FnOnce(&[T]) -> R) -> R {
|
||||
Self::with_record(ctx, |record| f(&record.last))
|
||||
}
|
||||
|
||||
fn with_record<R>(ctx: &Context, f: impl FnOnce(&mut FactRecord<T>) -> R) -> R {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let pass_nr = pass::pass_nr(ctx, viewport);
|
||||
let advance = |record: &mut FactRecord<T>, 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();
|
||||
|
||||
@@ -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<PerViewport<$record_ty>>,)*
|
||||
$($stamped: RefCell<PerViewport<Stamped<$stamped_ty>>>,)*
|
||||
/// 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<PerViewport<_>>`.
|
||||
others: RefCell<FastMap<TypeId, Box<dyn Any + Send>>>,
|
||||
}
|
||||
|
||||
$($(#[$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<PassState>,
|
||||
/// 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<Vec<PassFacts>>,
|
||||
}
|
||||
|
||||
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<S: PassLocal, R>(ctx: &Context, f: impl FnOnce(&mut S) -> R) -> R {
|
||||
#[cfg(feature = "testing")]
|
||||
crate::runtime::layout_memory::guard::touch::<S>();
|
||||
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<T: Stored, R>(ctx: &Context, f: impl FnOnce(&mut PerViewport<T>) -> R) -> R {
|
||||
with_state(ctx, |state| {
|
||||
let key = TypeId::of::<PerViewport<T>>();
|
||||
if !state.others.borrow().contains_key(&key) {
|
||||
state.others.borrow_mut().insert(key, Box::new(RefCell::new(PerViewport::<T>::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::<RefCell<PerViewport<T>>>()).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<PassFacts> {
|
||||
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<R>(ctx: &Context, f: impl FnOnce(&Held) -> R) -> Option<R> {
|
||||
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<R>(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<u64> = 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> =
|
||||
HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && frame::running(&entry.ctx).is_none()).collect());
|
||||
let stale: Vec<Held> = 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::<Parked>::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());
|
||||
}
|
||||
}
|
||||
@@ -244,6 +244,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<Id>, Option<Id>, Option<Id>)>,
|
||||
/// A press was open when the pass began: only its target hovers.
|
||||
captured: bool,
|
||||
/// The pass's tap went to a component.
|
||||
@@ -372,7 +375,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);
|
||||
}
|
||||
@@ -403,8 +408,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::<Shapes>::with(ctx, viewport, |shapes| {
|
||||
shapes.hover = hover;
|
||||
shapes.hover_widgets = hover_widgets;
|
||||
shapes.captured = captured;
|
||||
shapes.pressed_parts.clear();
|
||||
});
|
||||
@@ -472,7 +479,8 @@ pub(crate) fn with_frame<R>(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)
|
||||
@@ -485,6 +493,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<PressStart>,
|
||||
/// The button released in the pass (`PointerFrame::release`).
|
||||
pub release: Option<PointerButton>,
|
||||
}
|
||||
|
||||
/// 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<Pos2> {
|
||||
@@ -633,6 +667,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<Shape<Id>>) {
|
||||
crate::runtime::replay::note_sensors(ctx, shapes.iter().map(|shape| shape.owner));
|
||||
PerViewport::<Shapes>::with(ctx, viewport, |record| {
|
||||
let order = record.next;
|
||||
record.next += 1;
|
||||
@@ -667,11 +702,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::<Shapes>::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<Pos2> {
|
||||
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.
|
||||
@@ -998,6 +1054,11 @@ pub(crate) struct Under {
|
||||
pub hover_top: Option<(Winner<Id>, 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 {
|
||||
@@ -1051,6 +1112,78 @@ pub(crate) fn with_hover<R>(ctx: &Context, viewport: ViewportId, f: impl FnOnce(
|
||||
PerViewport::<Shapes>::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<PartRef>);
|
||||
|
||||
/// 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::<Shapes>::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<Pos2> {
|
||||
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::<Shapes>::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
|
||||
@@ -1119,6 +1252,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<Shape<Id>> = indices.iter().map(|&index| entry.shapes[index].clone()).collect();
|
||||
|
||||
@@ -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<usize> = 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<ShownLayer>,
|
||||
/// The layer stack entries the run recorded (`note_layer`): a close queued for one is taken only by a run.
|
||||
pub(crate) layers: Vec<egui::Id>,
|
||||
/// 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<Rect>,
|
||||
/// The wheel takers the run registered (`wheel::register`): a share of the wheel for one runs it.
|
||||
pub(crate) takers: Vec<egui::Id>,
|
||||
}
|
||||
|
||||
/// 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::<Recorder, _>(ctx, |recorder| !recorder.open.is_empty())
|
||||
any_open() && pass_state::with::<Recorder, _>(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::<Recorder, _>(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::<Recorder, _>(ctx, |recorder| recorder.open.iter().any(|open| open.audit))
|
||||
any_open() && pass_state::with::<Recorder, _>(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::<Recorder, _>(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::<Recorder, _>(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::<Recorder, _>(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<Item = egui::Id>) {
|
||||
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));
|
||||
|
||||
@@ -163,6 +163,7 @@ pub(crate) fn register(ctx: &Context, taker: WheelTaker<Id>) {
|
||||
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::<State>::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::<State>::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<Wheel> {
|
||||
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| state.shares.iter().find(|(owner, _)| *owner == id).map(|share| share.1))
|
||||
|
||||
@@ -92,8 +92,11 @@ pub(crate) struct Shared {
|
||||
desktop: Option<Desktop>,
|
||||
/// 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<ViewportId>,
|
||||
/// 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<ViewportId> = windows
|
||||
.iter()
|
||||
.map(|(viewport, _)| *viewport)
|
||||
.filter(|viewport| PerViewport::<Record>::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<ViewportId> = std::iter::once(ViewportId::ROOT).chain(shown).collect();
|
||||
let focus: Vec<Option<bool>> =
|
||||
windows.iter().map(|viewport| PerViewport::<Record>::with(ctx, *viewport, |record| record.facts.map(|facts| facts.focused))).collect();
|
||||
let away = focus.iter().all(|focus| *focus == Some(false));
|
||||
let focused: Vec<ViewportId> = 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::<Record>::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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<ViewportId>,
|
||||
|
||||
@@ -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::<Record>::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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn register_fact<T: Clone + PartialEq + Debug + crate::runtime::Shift + Send
|
||||
|
||||
/// The facts the running viewport's previous pass registered.
|
||||
pub fn facts_of_last_pass<T: Clone + Send + Sync + 'static>(ctx: &Context) -> Vec<T> {
|
||||
Facts::of_last_pass(ctx)
|
||||
Facts::with_last_pass(ctx, <[T]>::to_vec)
|
||||
}
|
||||
|
||||
/// Runs `f` on a child `Ui` of `ui`.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -6,8 +6,8 @@ use craft_behavior::overlay::{Align, Side};
|
||||
use craft_behavior::{GesturePhase, Sense};
|
||||
use craft_ui::contract::overlay::{Anchor, 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};
|
||||
@@ -15,7 +15,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};
|
||||
@@ -398,3 +398,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:?}");
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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<Vec<Option<Pos2>>>,
|
||||
}
|
||||
|
||||
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<Vec<Option<Pos2>>>) -> 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]
|
||||
|
||||
@@ -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<CommandRef> = (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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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::<usize>(), 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<Out> = (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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user