mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:24:24 +00:00
Merge branch 'fw/speed1' into fw/mac1
# Conflicts: # crates/ui-patterns/src/patterns/dock/area.rs # crates/ui-shell/src/shell/app_shell.rs
This commit is contained in:
@@ -75,7 +75,7 @@ pub use navigate::{
|
||||
Autoscroll, FlickPan, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, TouchpadGlide, WheelAction, WheelInput, WheelNavigation, pan,
|
||||
};
|
||||
pub use rotate::{RotateView, RotateViewOutput, RotateViewStyle, ViewTurn};
|
||||
pub use tools::{HandTool, RotateViewTool, ViewCommands, ViewTarget, ZoomTool};
|
||||
pub use tools::{HandTool, LayerBounds, RotateViewTool, ViewCommands, ViewTarget, ZoomTool};
|
||||
pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag, easing_view};
|
||||
|
||||
mod rulers;
|
||||
@@ -157,13 +157,15 @@ pub struct Canvas<'a> {
|
||||
view: Option<Bind<'a, CanvasView>>,
|
||||
/// The view the binding held when the pass began.
|
||||
given: Option<CanvasView>,
|
||||
/// The document the view shows: its size in document units (a `Size` is enough), and the artboard, layer bounds
|
||||
/// and resolution some view commands need ([`ViewTarget`]). With a view and a document, the canvas fits a view
|
||||
/// The document the view shows: its size in document units (a `Size` is enough), and the artboard and resolution
|
||||
/// some view commands need ([`ViewTarget`]). With a view and a document, the canvas fits a view
|
||||
/// never shown, keeps the wheel's zoom inside the document's zoom range, keeps the document in view with Overscroll
|
||||
/// off, and applies the view commands routed to it ([`ViewCommands`]); without either, the view commands are
|
||||
/// disabled for it, and so is each command whose fact the target lacks.
|
||||
#[prop(into)]
|
||||
document: Option<ViewTarget>,
|
||||
/// The bounds Fit Layers on Screen shows ([`layer_bounds`](Self::layer_bounds)).
|
||||
layer_bounds: Option<LayerBounds<'a>>,
|
||||
/// The user's navigation options: how the wheel and a pinch move the view ([`WheelNavigation`]), whether a zoom
|
||||
/// eases (Animated Zoom) and whether the view may leave the document (Overscroll).
|
||||
#[prop]
|
||||
@@ -231,6 +233,7 @@ impl<'a> Canvas<'a> {
|
||||
view: None,
|
||||
given: None,
|
||||
document: None,
|
||||
layer_bounds: None,
|
||||
navigation: NavigationOptions::default(),
|
||||
show_rulers: false,
|
||||
keys_to_body: false,
|
||||
@@ -273,6 +276,14 @@ impl<'a> Canvas<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The bounds Fit Layers on Screen shows, asked only in the pass that runs the command. Without it Fit Layers is
|
||||
/// disabled for this canvas.
|
||||
#[must_use]
|
||||
pub fn layer_bounds(mut self, bounds: LayerBounds<'a>) -> Self {
|
||||
self.layer_bounds = Some(bounds);
|
||||
self
|
||||
}
|
||||
|
||||
/// Eases from `from`, the view the app drew last, to the view given this pass, as the canvas eases its own zoom
|
||||
/// commands: an app's zoom step made outside the canvas (a menu row, a Zoom tool click before the app's tools run
|
||||
/// on the tool host). `anchor` keeps a document point under a screen point along the way. With Animated Zoom off,
|
||||
@@ -306,13 +317,13 @@ impl<'a> Canvas<'a> {
|
||||
let pixels_per_point = cx.env.scale().0;
|
||||
let target = view.zip(self.document);
|
||||
for command in ViewCommands::ALL {
|
||||
let enabled = target.is_some_and(|(view, document)| command.available(&view, &document, pixels_per_point));
|
||||
let enabled = target.is_some_and(|(view, document)| command.available(&view, &document, self.layer_bounds, pixels_per_point));
|
||||
cx.publish(command, CommandState::new().enabled(enabled));
|
||||
}
|
||||
let (view, document) = target?;
|
||||
let (mut next, mut zoomed) = (view, false);
|
||||
while let Some((command, _)) = cx.take_command::<ViewCommands>() {
|
||||
zoomed |= command.apply(&mut next, &document, pixels_per_point) && command.zooms();
|
||||
zoomed |= command.apply(&mut next, &document, self.layer_bounds, pixels_per_point) && command.zooms();
|
||||
}
|
||||
(next != view).then_some((next, zoomed))
|
||||
}
|
||||
@@ -341,7 +352,7 @@ impl<'a> Canvas<'a> {
|
||||
let never_shown = !(view.rect.width() > 0.0 && view.rect.height() > 0.0);
|
||||
view.rect = area;
|
||||
if never_shown && let Some(document) = self.document {
|
||||
ViewCommands::FitOnScreen.apply(&mut view, &document, pixels_per_point);
|
||||
ViewCommands::FitOnScreen.apply(&mut view, &document, None, pixels_per_point);
|
||||
}
|
||||
}
|
||||
let mut jumped = false;
|
||||
|
||||
@@ -619,7 +619,7 @@ impl<'m> ToolHost<'m> {
|
||||
}
|
||||
}
|
||||
if requests.repaint {
|
||||
frame::request_repaint(&ctx);
|
||||
frame::request_own_repaint(&ctx);
|
||||
}
|
||||
for chord in claimed_chords(state.claims) {
|
||||
keys::claim(&ctx, canvas.response.id, chord);
|
||||
@@ -694,7 +694,7 @@ impl<'m> ToolHost<'m> {
|
||||
tool.cancel(reason, &mut cx);
|
||||
if let Some(view) = cx.take_requests().view {
|
||||
with_session(ctx, state_id(canvas), |state: &mut HostState| state.cancelled_view = Some(view));
|
||||
frame::request_repaint(ctx);
|
||||
frame::request_own_repaint(ctx);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -34,7 +34,8 @@ const SCREEN_PPI: f64 = 72.0;
|
||||
|
||||
/// What the view commands act on: the document's size and the facts some commands need. The app gives it to
|
||||
/// [`Canvas::document`](super::Canvas::document); a command whose fact is absent is disabled
|
||||
/// ([`ViewCommands::available`]).
|
||||
/// ([`ViewCommands::available`]). Fit Layers reads the layers' bounds from [`LayerBounds`] instead, which only the
|
||||
/// command runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ViewTarget {
|
||||
@@ -42,8 +43,6 @@ pub struct ViewTarget {
|
||||
pub document: Size,
|
||||
/// The artboard Fit Artboard on Screen shows (the active layer's board, else the last one), in document units.
|
||||
pub artboard: Option<Rect>,
|
||||
/// The bounds Fit Layer(s) on Screen shows (the selected layers' content), in document units.
|
||||
pub layers: Option<Rect>,
|
||||
/// The document's resolution in pixels per inch, for Print Size.
|
||||
pub ppi: Option<f64>,
|
||||
/// The screen resolution Print Size shows the document at, in pixels per inch (Preferences, Units & Rulers).
|
||||
@@ -52,9 +51,9 @@ pub struct ViewTarget {
|
||||
}
|
||||
|
||||
impl ViewTarget {
|
||||
/// A document of `size` with no artboard, no layer bounds and no resolution.
|
||||
/// A document of `size` with no artboard and no resolution.
|
||||
pub fn new(document: Size) -> Self {
|
||||
Self { document, artboard: None, layers: None, ppi: None, screen_ppi: SCREEN_PPI }
|
||||
Self { document, artboard: None, ppi: None, screen_ppi: SCREEN_PPI }
|
||||
}
|
||||
|
||||
/// The artboard Fit Artboard on Screen shows.
|
||||
@@ -64,13 +63,6 @@ impl ViewTarget {
|
||||
self
|
||||
}
|
||||
|
||||
/// The bounds Fit Layer(s) on Screen shows.
|
||||
#[must_use]
|
||||
pub fn layers(mut self, layers: Rect) -> Self {
|
||||
self.layers = Some(layers);
|
||||
self
|
||||
}
|
||||
|
||||
/// The document's resolution, for Print Size.
|
||||
#[must_use]
|
||||
pub fn ppi(mut self, ppi: f64) -> Self {
|
||||
@@ -97,6 +89,11 @@ impl From<Size> for ViewTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds Fit Layer(s) on Screen shows (the selected layers' content), in document units, asked only when the
|
||||
/// command runs: an app finds them by walking its layers' pixels, which no other pass needs. The app gives it to
|
||||
/// [`Canvas::layer_bounds`](super::Canvas::layer_bounds); `None` from it changes nothing.
|
||||
pub type LayerBounds<'a> = &'a dyn Fn() -> Option<Rect>;
|
||||
|
||||
/// A rect with area, or none.
|
||||
fn with_area(rect: Option<Rect>) -> Option<Rect> {
|
||||
rect.map(|rect| rect.abs()).filter(|rect| rect.width() > 0.0 && rect.height() > 0.0)
|
||||
@@ -167,9 +164,9 @@ impl ViewCommands {
|
||||
ViewCommands::ResetRotation,
|
||||
];
|
||||
|
||||
/// Applies the command to `view` for `target` at `pixels_per_point`. Returns whether the view changed: a command
|
||||
/// whose fact `target` lacks changes nothing.
|
||||
pub fn apply(self, view: &mut CanvasView, target: &ViewTarget, pixels_per_point: f32) -> bool {
|
||||
/// Applies the command to `view` for `target` and the layers' bounds `layers` at `pixels_per_point`. Returns whether
|
||||
/// the view changed: a command whose fact is absent changes nothing. Only Fit Layers asks `layers`.
|
||||
pub fn apply(self, view: &mut CanvasView, target: &ViewTarget, layers: Option<LayerBounds<'_>>, pixels_per_point: f32) -> bool {
|
||||
let before = *view;
|
||||
let size = target.document;
|
||||
let zoom_about_centre = |view: &mut CanvasView, device: f64| {
|
||||
@@ -198,7 +195,7 @@ impl ViewCommands {
|
||||
}
|
||||
}
|
||||
ViewCommands::FitLayers => {
|
||||
if let Some(bounds) = with_area(target.layers) {
|
||||
if let Some(bounds) = with_area(layers.and_then(|layers| layers())) {
|
||||
zoom::fit_rect(view, bounds, size, pixels_per_point, LAYERS_MARGIN);
|
||||
}
|
||||
}
|
||||
@@ -211,14 +208,15 @@ impl ViewCommands {
|
||||
*view != before
|
||||
}
|
||||
|
||||
/// Whether the command can run on `view` for `target`: Zoom In and Zoom Out stop at the ends of the zoom range,
|
||||
/// Print Size needs the document's resolution, Fit Artboard an artboard and Fit Layers the layers' bounds.
|
||||
pub fn available(self, view: &CanvasView, target: &ViewTarget, pixels_per_point: f32) -> bool {
|
||||
/// Whether the command can run on `view` for `target` and the layers' bounds `layers`: Zoom In and Zoom Out stop at
|
||||
/// the ends of the zoom range, Print Size needs the document's resolution, Fit Artboard an artboard and Fit Layers
|
||||
/// the layers' bounds, which it does not ask for here.
|
||||
pub fn available(self, view: &CanvasView, target: &ViewTarget, layers: Option<LayerBounds<'_>>, pixels_per_point: f32) -> bool {
|
||||
match self {
|
||||
ViewCommands::ZoomIn | ViewCommands::ZoomOut => self.apply(&mut view.clone(), target, pixels_per_point),
|
||||
ViewCommands::ZoomIn | ViewCommands::ZoomOut => self.apply(&mut view.clone(), target, None, pixels_per_point),
|
||||
ViewCommands::PrintSize => target.print_zoom().is_some(),
|
||||
ViewCommands::FitArtboard => with_area(target.artboard).is_some(),
|
||||
ViewCommands::FitLayers => with_area(target.layers).is_some(),
|
||||
ViewCommands::FitLayers => layers.is_some(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ pub fn easing_view(ctx: &Context, canvas: Id) -> Option<CanvasView> {
|
||||
/// tool host for a tool's view, the Navigator for a preview zoom. The canvas applies it in its next pass.
|
||||
pub(crate) fn steer(ctx: &Context, canvas: Id, steer: Steer) {
|
||||
with_session(ctx, ViewMotion::id(canvas), |slot: &mut ViewMotion| slot.steer = Some(steer));
|
||||
frame::request_repaint(ctx);
|
||||
frame::request_own_repaint(ctx);
|
||||
}
|
||||
|
||||
/// The Zoom tool's press held still: past [`DELAY`](Self::DELAY) it zooms in continuously about the press point (out
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft_ui::canvas::{
|
||||
Autoscroll, Canvas, CanvasScrollbars, CanvasTool, ContextRequest, CropOverlay, HandTool, Momentary, MomentaryCommands, MomentaryTool,
|
||||
NavigationOptions, Snap, StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer, canvas_space,
|
||||
};
|
||||
use craft_ui::contract::{Bind, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Lazy, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::Dialog;
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::primitives::Draw;
|
||||
@@ -19,6 +19,7 @@ use craft_ui::runtime::frame;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::style::DataColor;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::{Fixture, ToolFixture, pointer, trial};
|
||||
use egui::{Color32, Id, Key, Modifiers, Pos2, Rect, Shape, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -803,6 +804,80 @@ fn an_injected_pen_reading_reaches_the_tool() {
|
||||
assert!(pressures.len() == 2 && (pressures[0] - 0.3).abs() < 1e-4 && (pressures[1] - 0.7).abs() < 1e-4, "{pressures:?}");
|
||||
}
|
||||
|
||||
/// A tool that asks for a repaint in every drag, as a brush that previews its stroke does.
|
||||
#[derive(Default)]
|
||||
struct Painter {
|
||||
drags: usize,
|
||||
}
|
||||
|
||||
impl CanvasTool for Painter {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.drags += 1;
|
||||
cx.request_repaint();
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Freehand("the painter only asks for repaints")
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke on the canvas, whose tool asks for a repaint in every drag, runs neither of the settled panels beside it
|
||||
/// (each shows a content version), from its press to its release, and each of its move frames runs one pass.
|
||||
#[trial]
|
||||
fn a_stroke_runs_no_settled_panel_beside_the_canvas_and_one_pass_per_move() {
|
||||
let painter = Rc::new(RefCell::new(Painter::default()));
|
||||
let runs: Rc<[Cell<usize>; 2]> = Rc::default();
|
||||
let canvas = Rc::new(Cell::new(Id::NULL));
|
||||
let (shown_painter, shown_runs, shown_canvas) = (Rc::clone(&painter), Rc::clone(&runs), Rc::clone(&canvas));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let (side, document) = room.split_left_right_at_x(room.left() + 160.0);
|
||||
in_region(ui, side, |ui| {
|
||||
for (at, name) in ["Layers", "Navigator"].into_iter().enumerate() {
|
||||
Lazy::new(name, 0.0).settles(true).content(1).show(ui, |ui| {
|
||||
shown_runs[at].set(shown_runs[at].get() + 1);
|
||||
Text::new(name).show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
in_region(ui, document, |ui| {
|
||||
let view = CanvasView::new(document, Point::new(600.0, 450.0), 1.0);
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(view).show(ui, |_, _| {});
|
||||
shown_canvas.set(shown.output.response.id);
|
||||
let _ = ToolHost::new().run(ui, &shown.output, &mut *shown_painter.borrow_mut());
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
let at = fixture.by_role(Role::CANVAS)[0].rect.center();
|
||||
let ctx = fixture.ctx().clone();
|
||||
ToolHost::inject(&ctx, canvas.get(), ToolInput::down(PointerButton::Primary, at));
|
||||
for step in 1..=6 {
|
||||
ToolHost::inject(&ctx, canvas.get(), ToolInput::moved(at + Vec2::new(8.0 * step as f32, 4.0 * step as f32)));
|
||||
}
|
||||
ToolHost::inject(&ctx, canvas.get(), ToolInput::up(at + Vec2::new(48.0, 24.0)));
|
||||
let host = WindowHost::of(&ctx);
|
||||
let mut frames = Vec::new();
|
||||
while !host.injected_idle() && frames.len() < 64 {
|
||||
runs.iter().for_each(|runs| runs.set(0));
|
||||
fixture.frame(Vec::new());
|
||||
frames.push((fixture.passes(), [runs[0].get(), runs[1].get()]));
|
||||
}
|
||||
assert!(painter.borrow().drags > 0, "the moves reach the tool, which asks for repaints");
|
||||
assert!(frames.iter().all(|(_, runs)| *runs == [0, 0]), "no settled panel runs during the stroke: {frames:?}");
|
||||
let moves = &frames[1..frames.len() - 1];
|
||||
assert!(moves.iter().all(|(passes, _)| *passes == 1), "each move frame runs one pass: {frames:?}");
|
||||
}
|
||||
|
||||
/// A queued Space starts the momentary Hand as the real key does: the press it is held over pans the view, and the
|
||||
/// press after its release runs the selected tool.
|
||||
/// A canvas with the momentary set and `main` as the selected tool, zoomed in, so the document is larger than the
|
||||
|
||||
@@ -4,8 +4,10 @@ use craft_behavior::CanvasView;
|
||||
use craft_behavior::canvas::zoom;
|
||||
use craft_behavior::kurbo::Vec2 as DocVec;
|
||||
use craft_behavior::kurbo::{Point, Rect, Size};
|
||||
use craft_ui::canvas::{Canvas, CanvasTool, HandTool, NavigationOptions, RotateViewTool, ToolHost, ViewCommands, ViewTarget, ZoomTool};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::canvas::{Canvas, CanvasTool, HandTool, LayerBounds, NavigationOptions, RotateViewTool, ToolHost, ViewCommands, ViewTarget, ZoomTool};
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::commands::{self, FireSource};
|
||||
use craft_ui::testing::{Fixture, ToolFixture, pointer, trial};
|
||||
use egui::{Event, Modifiers, Pos2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -138,8 +140,10 @@ fn view_commands_run_with_their_facts_and_are_disabled_without() {
|
||||
let size = Size::new(4000.0, 3000.0);
|
||||
let board = Rect::new(2500.0, 400.0, 3500.0, 1200.0);
|
||||
let layers = Rect::new(100.0, 2000.0, 300.0, 2900.0);
|
||||
let full = ViewTarget::new(size).artboard(board).layers(layers).ppi(300.0);
|
||||
let full = ViewTarget::new(size).artboard(board).ppi(300.0);
|
||||
let bare = ViewTarget::from(size);
|
||||
let bounds = || Some(layers);
|
||||
let given: Option<LayerBounds<'_>> = Some(&bounds);
|
||||
let start = CanvasView::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0)), Point::new(2000.0, 1500.0), 0.1);
|
||||
let device = |view: &CanvasView| zoom::device(view, ppp);
|
||||
let shows = |view: &CanvasView, rect: Rect| {
|
||||
@@ -156,15 +160,15 @@ fn view_commands_run_with_their_facts_and_are_disabled_without() {
|
||||
];
|
||||
for (command, owed) in rows {
|
||||
let mut view = start;
|
||||
assert!(command.available(&start, &full, ppp), "{command:?} runs with its fact");
|
||||
assert!(command.apply(&mut view, &full, ppp) && owed(&view), "{command:?} gives {view:?}");
|
||||
assert!(command.available(&start, &full, given, ppp), "{command:?} runs with its fact");
|
||||
assert!(command.apply(&mut view, &full, given, ppp) && owed(&view), "{command:?} gives {view:?}");
|
||||
if command == ViewCommands::TwoHundredPercent {
|
||||
assert!(command.available(&start, &bare, ppp), "200% needs no fact");
|
||||
assert!(command.available(&start, &bare, None, ppp), "200% needs no fact");
|
||||
continue;
|
||||
}
|
||||
let mut view = start;
|
||||
assert!(!command.available(&start, &bare, ppp), "{command:?} is disabled without its fact");
|
||||
assert!(!command.apply(&mut view, &bare, ppp) && view == start, "{command:?} leaves the view without its fact");
|
||||
assert!(!command.available(&start, &bare, None, ppp), "{command:?} is disabled without its fact");
|
||||
assert!(!command.apply(&mut view, &bare, None, ppp) && view == start, "{command:?} leaves the view without its fact");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +291,7 @@ fn the_rotate_commands_step_fifteen_degrees_on_screen_in_a_flipped_view_too() {
|
||||
for (command, screen_turn) in [(ViewCommands::RotateClockwise, 15.0), (ViewCommands::RotateCounterclockwise, -15.0)] {
|
||||
let before = turned(room, 20.0, flip_x);
|
||||
let mut view = before;
|
||||
assert!(command.apply(&mut view, &target, 1.0), "{command:?} turns the view");
|
||||
assert!(command.apply(&mut view, &target, None, 1.0), "{command:?} turns the view");
|
||||
let turned_by = (angle(&view) - angle(&before) + 540.0).rem_euclid(360.0) - 180.0;
|
||||
assert!(
|
||||
(turned_by - screen_turn).abs() < 0.01,
|
||||
@@ -405,3 +409,35 @@ fn a_held_zoom_press_zooms_about_its_point_at_a_frame_rate_independent_rate() {
|
||||
rig.release(at + egui::vec2(100.0, 0.0), FRAME);
|
||||
assert!((rig.device() / device - 2.0).abs() < 1e-3, "a drag scrubs one doubling per 100 points: {}", rig.device() / device);
|
||||
}
|
||||
|
||||
/// A canvas asks the app for the layers' bounds only in the pass that runs Fit Layers: passes that only show the
|
||||
/// command enabled never walk the layers.
|
||||
#[trial]
|
||||
fn a_canvas_asks_for_the_layer_bounds_only_when_fit_layers_runs() {
|
||||
let size = Size::new(4000.0, 3000.0);
|
||||
let layers = Rect::new(100.0, 2000.0, 300.0, 2900.0);
|
||||
let unshown = CanvasView::new(egui::Rect::NOTHING, Point::new(2000.0, 1500.0), 1.0);
|
||||
let (asked, view) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(unshown)));
|
||||
let (shown_asked, shown_view) = (Rc::clone(&asked), Rc::clone(&view));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let bounds = || {
|
||||
shown_asked.set(shown_asked.get() + 1);
|
||||
Some(layers)
|
||||
};
|
||||
let mut held = shown_view.get();
|
||||
Canvas::new("Document").document(size).layer_bounds(&bounds).view(Bind::bound(&mut held)).show(ui, |_, _| {});
|
||||
shown_view.set(held);
|
||||
});
|
||||
fixture.settle();
|
||||
let canvas = fixture.by_role(Role::CANVAS)[0];
|
||||
fixture.click(&canvas).settle();
|
||||
assert_eq!(asked.get(), 0, "showing the canvas and its enabled commands asks for no bounds");
|
||||
let before = view.get();
|
||||
assert!(commands::fire(fixture.ctx(), ViewCommands::FitLayers, FireSource::Menu), "a menu row fires Fit Layers");
|
||||
fixture.frame(vec![]);
|
||||
assert!(asked.get() > 0, "the pass that runs Fit Layers asks for the bounds");
|
||||
assert_ne!(view.get(), before, "and fits them");
|
||||
let once = asked.get();
|
||||
fixture.idle(3);
|
||||
assert_eq!(asked.get(), once, "later passes ask no more");
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ pub struct Lazy {
|
||||
estimate: f32,
|
||||
reveal: bool,
|
||||
settles: bool,
|
||||
content: Option<u64>,
|
||||
}
|
||||
|
||||
impl Lazy {
|
||||
@@ -45,7 +46,7 @@ impl Lazy {
|
||||
use std::hash::Hasher;
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
key.hash(&mut hasher);
|
||||
Lazy { key: hasher.finish(), estimate, reveal: false, settles: false }
|
||||
Lazy { key: hasher.finish(), estimate, reveal: false, settles: false, content: None }
|
||||
}
|
||||
|
||||
/// When `reveal` holds, the scroll area glides until the child starts at the view's start (as far as the
|
||||
@@ -63,18 +64,30 @@ impl Lazy {
|
||||
/// - an animation in it is not at its end, something in it asked for a repaint, or a wake time it asked for came;
|
||||
/// - a bound value it read was written;
|
||||
/// - its place, room, clip or scale differs from its last run;
|
||||
/// - the frame or the one before had input other than pointer motion, the app asked for a repaint, or a given
|
||||
/// value was edited: the framework cannot see which children show plain app data, so every child runs then;
|
||||
/// - its [`content`](Self::content) version differs from its last run;
|
||||
/// - the app asked for a repaint outside every settling child (`frame::request_repaint`), or a given value was
|
||||
/// edited: the framework cannot see which children show that app data, so every child runs then;
|
||||
/// - for a child with no content version: the frame or the one before had input other than pointer motion, which
|
||||
/// may have changed app data it shows;
|
||||
/// - its last run showed an overlay or painted on another layer.
|
||||
///
|
||||
/// A bound value is known by where it lives, so a settled reader needs a binding that stays in place between
|
||||
/// frames: a value copied into a local each frame and bound there is a new place each frame, and an edit of it
|
||||
/// does not reach the reader until the next frame with input.
|
||||
/// does not reach the reader until the next frame it runs.
|
||||
pub fn settles(mut self, settles: bool) -> Lazy {
|
||||
self.settles = settles;
|
||||
self
|
||||
}
|
||||
|
||||
/// The version of the app data a settling child shows that the framework does not track (a document's revision,
|
||||
/// a job's progress): the child runs when it differs from the version of its last run. A child with a version
|
||||
/// does not run for input that reaches other parts of the window: what that input changes in the data it shows
|
||||
/// moves the version, or reaches it as a command or app repaint request.
|
||||
pub fn content(mut self, version: u64) -> Lazy {
|
||||
self.content = Some(version);
|
||||
self
|
||||
}
|
||||
|
||||
/// Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not
|
||||
/// run.
|
||||
pub fn show<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option<R> {
|
||||
@@ -115,7 +128,7 @@ impl Lazy {
|
||||
let layout = *ui.layout();
|
||||
let place = Place { room: available, clip: ui.clip_rect(), layer: ui.layer_id(), layout, pixels_per_point: ctx.pixels_per_point() };
|
||||
if self.settles
|
||||
&& let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place))
|
||||
&& let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place), self.content)
|
||||
{
|
||||
let (took, _) = take_in_flow(ui, size);
|
||||
if real {
|
||||
@@ -153,7 +166,7 @@ impl Lazy {
|
||||
lazy::place(&ctx, &view, id, rect);
|
||||
}
|
||||
if let Some(record) = record {
|
||||
lazy::ran(&ctx, id, record, place, rect);
|
||||
lazy::ran(&ctx, id, record, place, rect, self.content);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -11,8 +11,7 @@ use crate::runtime::overlay::{self, CloseReason};
|
||||
use crate::runtime::pass_state;
|
||||
use craft_behavior::Intent;
|
||||
use craft_behavior::{EditEvent, Mixed};
|
||||
use egui::{Context, Id};
|
||||
use std::collections::HashMap;
|
||||
use egui::{Context, Id, IdMap};
|
||||
|
||||
/// An id and a name; `Copy`, never a snapshot of the open state.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -77,7 +76,7 @@ pub(crate) struct Popups {
|
||||
pub(super) anchors: Vec<(Id, PopupShown)>,
|
||||
/// The opener that opened each layer with openers, by the layer's first opener: its id and trigger (two
|
||||
/// openers on one response differ by trigger) and how it fired.
|
||||
pub(super) opened_by: HashMap<Id, (Id, Trigger, Opening)>,
|
||||
pub(super) opened_by: IdMap<(Id, Trigger, Opening)>,
|
||||
/// The popups whose layer is a container running now (`OverlayUi::show_container`), innermost last.
|
||||
pub(super) layers: Vec<PopupLayer>,
|
||||
}
|
||||
@@ -159,7 +158,7 @@ pub(crate) fn popup_shown(ctx: &Context, owner: Id) -> bool {
|
||||
}
|
||||
|
||||
/// Step 10: the open state of every popup `owner` registered, with the closes `request_close` queued applied.
|
||||
pub(crate) fn open_map(stage: &mut MemoryStage, owner: Id) -> HashMap<Id, bool> {
|
||||
pub(crate) fn open_map(stage: &mut MemoryStage, owner: Id) -> IdMap<bool> {
|
||||
let ctx = stage.ctx().clone();
|
||||
let popups: Vec<Id> =
|
||||
with_popups(&ctx, |popups| popups.registered.iter().filter(|(registered, _)| *registered == owner).map(|(_, popup)| *popup).collect());
|
||||
|
||||
@@ -17,8 +17,7 @@ use crate::runtime::motion::{self};
|
||||
use crate::runtime::overlay::{self, CloseReason};
|
||||
use crate::style::SurfaceKind;
|
||||
use craft_behavior::PartRef;
|
||||
use egui::{Context, Id, Rect, Ui, UiBuilder};
|
||||
use std::collections::HashMap;
|
||||
use egui::{Context, Id, IdMap, Rect, Ui, UiBuilder};
|
||||
|
||||
/// What the `overlay` hook gets: one call per anchored popup of this component, built at step 10 with the open state
|
||||
/// of every popup `cx.popup` registered this pass.
|
||||
@@ -33,7 +32,7 @@ pub struct OverlayUi<'a> {
|
||||
pub(crate) to_screen: egui::emath::TSTransform,
|
||||
pub(crate) resolved: &'a Resolved<'a>,
|
||||
pub(crate) env: Env,
|
||||
pub(crate) open: HashMap<Id, bool>,
|
||||
pub(crate) open: IdMap<bool>,
|
||||
/// Popups whose dismissal or body request was decided in this pass; step 15 writes their slots.
|
||||
#[doc(hidden)]
|
||||
pub closed: Vec<(Id, CloseReason)>,
|
||||
@@ -49,7 +48,7 @@ pub(crate) struct OverlayOwner {
|
||||
}
|
||||
|
||||
impl<'a> OverlayUi<'a> {
|
||||
pub(crate) fn new(ctx: &'a Context, owner: OverlayOwner, ui: &'a mut Ui, resolved: &'a Resolved<'a>, env: Env, open: HashMap<Id, bool>) -> Self {
|
||||
pub(crate) fn new(ctx: &'a Context, owner: OverlayOwner, ui: &'a mut Ui, resolved: &'a Resolved<'a>, env: Env, open: IdMap<bool>) -> Self {
|
||||
let to_screen = areas::layer_to_screen(ctx, ui.layer_id());
|
||||
let OverlayOwner { id, anchor, parts } = owner;
|
||||
OverlayUi { ctx, ui, owner: id, anchor, to_screen, resolved, env, open, closed: Vec::new(), parts }
|
||||
|
||||
@@ -20,7 +20,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, Pos2, Rect, Response, Ui, Vec2};
|
||||
use egui::{Context, Id, IdMap, Pos2, Rect, Response, Ui, Vec2};
|
||||
use std::any::TypeId;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
@@ -1213,7 +1213,7 @@ pub(crate) fn bar_member(ctx: &Context, env: &Env, hit: Rect, rule: bool) -> boo
|
||||
|
||||
/// 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(HashMap<Id, Vec<HeldRule>>);
|
||||
pub(crate) struct BarRules(IdMap<Vec<HeldRule>>);
|
||||
|
||||
/// A rule's paint: `shapes` of the paint list of `layer`, in the pass `pass`.
|
||||
struct HeldRule {
|
||||
|
||||
@@ -4,15 +4,15 @@ use crate::contract::IdSource;
|
||||
use crate::runtime::egui::pass;
|
||||
use crate::runtime::frame::{PerViewport, Stamped};
|
||||
use crate::runtime::inspect;
|
||||
use egui::{Context, Id, Ui};
|
||||
use egui::{Context, Id, IdMap, IdSet, Ui};
|
||||
use std::any::TypeId;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// The `Auto` ordinals and the ids registered in one pass of one viewport.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IdPass {
|
||||
next: HashMap<(Id, TypeId), u32>,
|
||||
seen: HashSet<Id>,
|
||||
/// Under the scope's id joined with the component type's.
|
||||
next: IdMap<u32>,
|
||||
seen: IdSet,
|
||||
}
|
||||
|
||||
/// Runs `f` as a measuring run that leaves the `Auto` ordinals as it found them, so the run that follows in the same
|
||||
@@ -36,7 +36,7 @@ pub(crate) fn draft<R>(ctx: &Context, run: impl FnOnce() -> R, keep: impl FnOnce
|
||||
pub(crate) fn keeping_ids<R>(ctx: &Context, f: impl FnOnce() -> (R, bool)) -> R {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let pass_nr = pass::pass_nr(ctx, viewport);
|
||||
let ordinals = |take: Option<HashMap<(Id, TypeId), u32>>| {
|
||||
let ordinals = |take: Option<IdMap<u32>>| {
|
||||
PerViewport::<Stamped<IdPass>>::with_pass(
|
||||
ctx,
|
||||
viewport,
|
||||
@@ -80,7 +80,7 @@ pub(crate) fn id(ui: &Ui, source: &IdSource, register: bool, advance: bool, ty:
|
||||
pass_nr,
|
||||
|pass, _| *pass = IdPass::default(),
|
||||
|pass| {
|
||||
let slot = pass.next.entry((scope, ty)).or_insert(0);
|
||||
let slot = pass.next.entry(scope.with(ty)).or_insert(0);
|
||||
let n = *slot;
|
||||
if advance {
|
||||
*slot += 1;
|
||||
|
||||
@@ -9,9 +9,8 @@ use crate::runtime::measure;
|
||||
use crate::runtime::memory::sub;
|
||||
use crate::runtime::pass_state;
|
||||
use craft_behavior::{Axis, ColumnWidth, Flow, GridCursor, GridMeasure};
|
||||
use egui::{Id, Rect, Ui, Vec2};
|
||||
use egui::{Id, IdMap, Rect, Ui, Vec2};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// How a body lays out its children, in reading order: mirrored under a right-to-left direction.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -87,16 +86,16 @@ impl BodyLayout {
|
||||
|
||||
/// The cursors of the `Grid` and spread `Row` bodies running this pass, by body id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Cursors(HashMap<Id, Cursor>);
|
||||
pub(crate) struct Cursors(IdMap<Cursor>);
|
||||
|
||||
/// The number of children that fill the main axis of each `Stack` or `Row` body measured this pass, by body id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FillCounts(HashMap<Id, u32>);
|
||||
pub(crate) struct FillCounts(IdMap<u32>);
|
||||
|
||||
/// The narrowest width a held fill-width child of each content-sized `Stack` column measured at in the first sweep of
|
||||
/// the column's measuring run (`report_held`), by column id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HeldWidths(HashMap<Id, f32>);
|
||||
pub(crate) struct HeldWidths(IdMap<f32>);
|
||||
|
||||
/// Reports a held fill-width child of the content-sized column `column` in its first sweep: the `width` it measured
|
||||
/// at. A column with no first sweep open takes no report.
|
||||
@@ -112,11 +111,11 @@ pub(crate) fn report_held(ctx: &egui::Context, column: Id, width: f32) {
|
||||
/// of its first line's centre, or `None` for a child with no line of its own. A container's measuring sweep opens and
|
||||
/// closes its header's and body's targets; a body's sweep starts its own target afresh.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FirstLines(HashMap<Id, Option<f32>>);
|
||||
pub(crate) struct FirstLines(IdMap<Option<f32>>);
|
||||
|
||||
/// What the children of each unwrapped `Row` body took in the sweep of a measuring run running now, by body id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RowLines(HashMap<Id, LineTook>);
|
||||
pub(crate) struct RowLines(IdMap<LineTook>);
|
||||
|
||||
/// What the children of a row took about its line.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
@@ -279,11 +278,11 @@ impl ShrinkUnit {
|
||||
|
||||
/// The units each `Row` body counting this pass reported, in order, by body id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ShrinkReports(HashMap<Id, Vec<Reported>>);
|
||||
pub(crate) struct ShrinkReports(IdMap<Vec<Reported>>);
|
||||
|
||||
/// The least widths the body units of each `Row` body asking for them this pass reported, by row id.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LeastReports(HashMap<Id, HashMap<Id, f32>>);
|
||||
pub(crate) struct LeastReports(IdMap<IdMap<f32>>);
|
||||
|
||||
/// Reports the widths of the unit `leaf` of the row `row` that counts them: a leaf's whole and least widths, or `None`
|
||||
/// for a body.
|
||||
@@ -520,7 +519,7 @@ fn run_shrinking<R>(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) ->
|
||||
if probe {
|
||||
#[cfg(feature = "testing")]
|
||||
measure::count_least(&ctx, id);
|
||||
pass_state::with::<LeastReports, _>(&ctx, |reports| reports.0.insert(id, HashMap::new()));
|
||||
pass_state::with::<LeastReports, _>(&ctx, |reports| reports.0.insert(id, IdMap::default()));
|
||||
crate::contract::keeping_ids(&ctx, || {
|
||||
layout_memory::probing(&ctx, || {
|
||||
let mut least = ui.new_child(egui::UiBuilder::new().layout(layout));
|
||||
|
||||
@@ -20,7 +20,7 @@ use craft_behavior::{
|
||||
};
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::Flags;
|
||||
use egui::{Context, Id, Pos2, Rect, Response, Ui, ViewportId};
|
||||
use egui::{Context, Id, IdMap, Pos2, Rect, Response, Ui, ViewportId};
|
||||
use smallvec::SmallVec;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -243,7 +243,7 @@ struct ArenaState {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Arenas {
|
||||
by_root: HashMap<Id, ArenaState>,
|
||||
by_root: IdMap<ArenaState>,
|
||||
swept: u64,
|
||||
/// The end sweep is registered; the runtime layer below cannot register it at install.
|
||||
sweep_registered: bool,
|
||||
|
||||
@@ -8,8 +8,7 @@ use crate::runtime::egui::memory::Service;
|
||||
use crate::runtime::keys;
|
||||
use crate::runtime::memory::sub;
|
||||
use craft_behavior::{AccessRequest, PartKey, PartRef, TextPos};
|
||||
use egui::{Context, Id, Rect};
|
||||
use std::collections::HashMap;
|
||||
use egui::{Context, Id, IdMap, Rect};
|
||||
use std::ops::Range;
|
||||
|
||||
/// The part key of a run node, indexed in document order.
|
||||
@@ -58,7 +57,7 @@ struct Entry {
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Tables(HashMap<Id, Vec<Entry>>);
|
||||
struct Tables(IdMap<Vec<Entry>>);
|
||||
|
||||
pub(crate) fn run_id(owner: Id, line: usize, run: usize) -> Id {
|
||||
sub(owner, ("text_run", line, run))
|
||||
|
||||
@@ -10,10 +10,10 @@ mod text;
|
||||
mod tree;
|
||||
|
||||
use crate::runtime::pass_state;
|
||||
#[cfg(feature = "testing")]
|
||||
use egui::FullOutput;
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
#[cfg(feature = "testing")]
|
||||
use egui::{FullOutput, IdMap, IdSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::pass;
|
||||
|
||||
@@ -106,9 +106,9 @@ pub(crate) fn set_focus(ctx: &Context, id: Id) {
|
||||
#[derive(Default)]
|
||||
struct Emitted {
|
||||
order: HashMap<u64, usize>,
|
||||
written: HashSet<Id>,
|
||||
written: IdSet,
|
||||
/// Text widgets whose node folds into their owner's node, each with its owner.
|
||||
folded: HashMap<Id, Id>,
|
||||
folded: IdMap<Id>,
|
||||
/// Whether the runtime reported a focused node this pass.
|
||||
focus_set: bool,
|
||||
}
|
||||
@@ -182,7 +182,7 @@ pub(crate) fn order_children(ctx: &Context) {
|
||||
|
||||
/// While a modal layer is open in `viewport`, hides the nodes the runtime wrote on layers below it: what sits behind
|
||||
/// a modal is inert for assistive technology, as it is for the pointer and the keys.
|
||||
fn hide_behind_modal(ctx: &Context, viewport: ViewportId, written: &HashSet<Id>) {
|
||||
fn hide_behind_modal(ctx: &Context, viewport: ViewportId, written: &IdSet) {
|
||||
// Without a modal nothing is behind one; this spares reading every written node's response.
|
||||
if crate::runtime::commands::modal_root(ctx, viewport).is_none() {
|
||||
return;
|
||||
|
||||
@@ -395,10 +395,24 @@ pub(crate) fn announce(ctx: &Context, text: String) {
|
||||
pass_state::with::<FrameState, _>(ctx, |state| state.output.announcements.push(text));
|
||||
}
|
||||
|
||||
/// Asks for another pass of the viewport the running pass belongs to.
|
||||
/// Asks for another pass of the viewport the running pass belongs to. Asked inside a settling child
|
||||
/// (`Lazy::settles`), that child runs again; asked outside every one, the app says data it shows changed, so every
|
||||
/// settling child runs.
|
||||
#[doc(hidden)]
|
||||
pub fn request_repaint(ctx: &Context) {
|
||||
crate::runtime::lazy::unsettle(ctx);
|
||||
if crate::runtime::replay::recording(ctx) {
|
||||
crate::runtime::replay::note_unsettled(ctx);
|
||||
} else {
|
||||
crate::runtime::lazy::unsettle(ctx);
|
||||
}
|
||||
raw_input::request_repaint_of(ctx, pass::current_viewport(ctx));
|
||||
}
|
||||
|
||||
/// Asks for another pass of the viewport the running pass belongs to, to move what the caller itself shows (a tool's
|
||||
/// preview, a view that eases): no app data changed, so only the settling child it is asked in runs again.
|
||||
#[doc(hidden)]
|
||||
pub fn request_own_repaint(ctx: &Context) {
|
||||
crate::runtime::replay::note_unsettled(ctx);
|
||||
raw_input::request_repaint_of(ctx, pass::current_viewport(ctx));
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,7 @@ use crate::runtime::egui::sizing::{Rerun, request_discard};
|
||||
use crate::runtime::reads::{self, BindKey};
|
||||
use crate::runtime::{focus, measure, pass_state, pointer};
|
||||
use craft_behavior::PartRef;
|
||||
use egui::{Context, Id, Rect, Ui};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use egui::{Context, Id, IdMap, IdSet, Rect, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A rule a component broke that the pipeline reports instead of panicking.
|
||||
@@ -27,13 +26,13 @@ pub struct Finding {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Log {
|
||||
steps: HashMap<Id, Vec<&'static str>>,
|
||||
steps: IdMap<Vec<&'static str>>,
|
||||
findings: Vec<Finding>,
|
||||
canvas_controls: Vec<&'static str>,
|
||||
/// The inspected regions open in the running pass, innermost last.
|
||||
open: Vec<Open>,
|
||||
/// The latest record of each region, and the element its list points at, by the region's key.
|
||||
kept: HashMap<Id, Kept>,
|
||||
kept: IdMap<Kept>,
|
||||
}
|
||||
|
||||
/// Whether records are kept: in frames a test fixture drives, and inside an inspected region in any build.
|
||||
@@ -289,7 +288,7 @@ fn edited(ctx: &Context, read: BindKey, editor: Id) {
|
||||
fn finish(ctx: &Context, open: Open) -> Recorded {
|
||||
let from_screen = areas::layer_to_screen(ctx, open.layer).inverse();
|
||||
let to_region = |layer: Layer, rect: Rect| from_screen * (areas::layer_to_screen(ctx, layer) * rect);
|
||||
let ids: HashSet<Id> = open.elements.iter().map(|(element, _)| element.id).collect();
|
||||
let ids: IdSet = open.elements.iter().map(|(element, _)| element.id).collect();
|
||||
let mut elements: Vec<Element> = Vec::with_capacity(open.elements.len() + open.parts.len());
|
||||
let mut parts = open.parts;
|
||||
let labels = open.labels;
|
||||
@@ -316,7 +315,7 @@ fn finish(ctx: &Context, open: Open) -> Recorded {
|
||||
}
|
||||
name_from_labels(&mut elements);
|
||||
// The sensing core keeps its shapes by root, in no order; a record compares equal to the same region's next one.
|
||||
let place: HashMap<Id, usize> = elements.iter().enumerate().rev().map(|(index, element)| (element.id, index)).collect();
|
||||
let place: IdMap<usize> = elements.iter().enumerate().rev().map(|(index, element)| (element.id, index)).collect();
|
||||
hits.sort_by(|a, b| {
|
||||
let key = |hit: &HitArea| (place.get(&hit.owner).copied(), hit.rect.min.y, hit.rect.min.x);
|
||||
key(a).partial_cmp(&key(b)).unwrap_or(std::cmp::Ordering::Equal)
|
||||
@@ -341,7 +340,7 @@ fn finish(ctx: &Context, open: Open) -> Recorded {
|
||||
|
||||
/// Names each node without a name of its own by the nodes of the region that label it, as a screen reader reads it.
|
||||
fn name_from_labels(elements: &mut [Element]) {
|
||||
let names: HashMap<Id, String> = elements
|
||||
let names: IdMap<String> = elements
|
||||
.iter()
|
||||
.filter(|element| element.part.is_none())
|
||||
.filter_map(|element| Some((element.id, element.facts.as_ref()?.name.clone()?)))
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::runtime::egui::input::Action;
|
||||
use crate::runtime::frame::PerViewport;
|
||||
use craft_behavior::EditCommand;
|
||||
use craft_keymap::{Chord, Key, KeyInput, Layout, Mods};
|
||||
use egui::{Context, Id, Vec2, ViewportId};
|
||||
use egui::{Context, Id, IdMap, Vec2, ViewportId};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -218,7 +218,7 @@ pub(crate) struct Stage {
|
||||
layout: Layout,
|
||||
nodes: HashMap<u64, Node>,
|
||||
last_nodes: HashMap<u64, Node>,
|
||||
activated: HashMap<Id, Id>,
|
||||
activated: IdMap<Id>,
|
||||
alt: AltTrack,
|
||||
/// The keys down now, as the input hook read them before it withheld any press.
|
||||
down: Vec<Key>,
|
||||
|
||||
@@ -12,7 +12,7 @@ use craft_behavior::keys;
|
||||
use craft_behavior::{EditCommand, Intent, KeyOwner, MoveMods, NavMove, OwnerClass};
|
||||
use craft_host::target::Os;
|
||||
use craft_keymap::{Chord, Key, Layout, Mods};
|
||||
use egui::{Context, Id, Vec2};
|
||||
use egui::{Context, Id, IdMap, Vec2};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -47,7 +47,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
|
||||
stage.enter_stale
|
||||
});
|
||||
let mut routed: HashMap<Option<Id>, Routed> = HashMap::new();
|
||||
let mut activated = HashMap::new();
|
||||
let mut activated = IdMap::default();
|
||||
let mut consumed = vec![Taken::No; batch.presses.len()];
|
||||
let driven = target.as_ref().and_then(|rec| Driven::of(ctx, rec));
|
||||
let field_list = target.as_ref().filter(|_| driven.is_none()).and_then(|rec| list_of_field(ctx, rec));
|
||||
@@ -542,7 +542,7 @@ fn apply_press(
|
||||
press: &Press,
|
||||
route: PressRoute,
|
||||
routed: &mut HashMap<Option<Id>, Routed>,
|
||||
activated: &mut HashMap<Id, Id>,
|
||||
activated: &mut IdMap<Id>,
|
||||
) -> Taken {
|
||||
let stop = &rec.stop;
|
||||
let id = Some(stop.id);
|
||||
@@ -572,7 +572,7 @@ fn apply_press(
|
||||
|
||||
/// `Activate` of a group member goes to the group's root, which reads `activated_member`. A child or part of a
|
||||
/// collection row activates itself.
|
||||
fn route_activate(ctx: &Context, rec: &StopRec, routed: &mut HashMap<Option<Id>, Routed>, activated: &mut HashMap<Id, Id>) {
|
||||
fn route_activate(ctx: &Context, rec: &StopRec, routed: &mut HashMap<Option<Id>, Routed>, activated: &mut IdMap<Id>) {
|
||||
let target = if rec.stop.group.is_some() && !focus::is_row_child(ctx, &rec.stop) {
|
||||
activated.insert(rec.stop.root, rec.stop.id);
|
||||
rec.stop.root
|
||||
@@ -595,13 +595,7 @@ fn nudge_of(key: Key, mods: Mods) -> Option<(Vec2, Mods)> {
|
||||
}
|
||||
|
||||
/// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2).
|
||||
fn route_access(
|
||||
ctx: &Context,
|
||||
request: &Action,
|
||||
nodes: &HashMap<u64, Node>,
|
||||
routed: &mut HashMap<Option<Id>, Routed>,
|
||||
activated: &mut HashMap<Id, Id>,
|
||||
) {
|
||||
fn route_access(ctx: &Context, request: &Action, nodes: &HashMap<u64, Node>, routed: &mut HashMap<Option<Id>, Routed>, activated: &mut IdMap<Id>) {
|
||||
let Some(node) = nodes.get(&request.node()).copied() else { return };
|
||||
let owner = Some(node.owner);
|
||||
if node.focusable {
|
||||
|
||||
@@ -17,9 +17,9 @@ use crate::runtime::egui::sizing;
|
||||
use crate::runtime::frame::{self, PerViewport};
|
||||
use craft_behavior::layout_memory::{SizeTween, measure_tolerance, measured_change_asks_for_discard};
|
||||
use craft_behavior::{Axis, Proposal};
|
||||
use egui::{Context, Id, Vec2};
|
||||
use egui::{Context, Id, IdMap, IdSet, Vec2};
|
||||
use std::any::Any;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// What an entry holds.
|
||||
@@ -111,7 +111,7 @@ enum Item {
|
||||
}
|
||||
|
||||
/// The inputs outside a measure that it read (`read_input`), by key: the widest value of each.
|
||||
pub(crate) type Inputs = HashMap<Id, f32>;
|
||||
pub(crate) type Inputs = IdMap<f32>;
|
||||
|
||||
/// One measure call a component got, the inputs besides its room it read, and its answer.
|
||||
#[derive(Clone)]
|
||||
@@ -135,10 +135,10 @@ struct Transcript {
|
||||
/// The inputs the run measured under.
|
||||
key: Box<dyn Any + Send + Sync>,
|
||||
items: Vec<Item>,
|
||||
leaves: HashMap<Id, Leaf>,
|
||||
leaves: IdMap<Leaf>,
|
||||
/// What the real run of the pass that measured found for the body's regions and its rows that run lazily: the
|
||||
/// backstop for content that allocates without a component.
|
||||
real: Mutex<Option<HashMap<Id, Vec2>>>,
|
||||
real: Mutex<Option<IdMap<Vec2>>>,
|
||||
}
|
||||
|
||||
/// A record of this pass's runs.
|
||||
@@ -191,7 +191,7 @@ enum Undo {
|
||||
|
||||
impl Scope {
|
||||
fn boundary() -> Scope {
|
||||
Scope { body: None, boundary: true, served: None, fresh: None, visited: HashSet::new(), fills: HashSet::new(), reported: Vec::new() }
|
||||
Scope { body: None, boundary: true, served: None, fresh: None, visited: IdSet::default(), fills: IdSet::default(), reported: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ enum Open {
|
||||
Body {
|
||||
id: Id,
|
||||
items: Vec<Item>,
|
||||
leaves: HashMap<Id, Leaf>,
|
||||
leaves: IdMap<Leaf>,
|
||||
inputs: Inputs,
|
||||
},
|
||||
Boundary,
|
||||
@@ -223,19 +223,19 @@ struct Scope {
|
||||
/// this pass left (whose `real` this run fills).
|
||||
served: Option<Arc<Transcript>>,
|
||||
fresh: Option<Arc<Transcript>>,
|
||||
visited: HashSet<Id>,
|
||||
fills: HashSet<Id>,
|
||||
visited: IdSet,
|
||||
fills: IdSet,
|
||||
/// What the real run contributed in this scope.
|
||||
reported: Vec<(Id, f32)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Entries {
|
||||
entries: HashMap<Id, Entry>,
|
||||
measured: HashMap<Id, Found>,
|
||||
kept: HashMap<Id, Kept>,
|
||||
entries: IdMap<Entry>,
|
||||
measured: IdMap<Found>,
|
||||
kept: IdMap<Kept>,
|
||||
/// The bodies whose records a kept transcript gave in this pass, with that transcript.
|
||||
served: HashMap<Id, Arc<Transcript>>,
|
||||
served: IdMap<Arc<Transcript>>,
|
||||
measuring: Vec<Open>,
|
||||
scopes: Vec<Scope>,
|
||||
/// The kept calls a real run asks again, as the transcript, the component and the call's index, innermost last:
|
||||
@@ -252,7 +252,7 @@ impl Entries {
|
||||
/// inside, up to the first boundary, and asks for the discard pass.
|
||||
fn changed(&mut self, frame: u64, body: Option<Id>) {
|
||||
log::debug!(target: sizing::RERUN_LOG, "the content of {body:?} changed from its kept transcript");
|
||||
let invalidate = |kept: &mut HashMap<Id, Kept>, body: Id| {
|
||||
let invalidate = |kept: &mut IdMap<Kept>, body: Id| {
|
||||
if let Some(kept) = kept.get_mut(&body) {
|
||||
kept.valid = false;
|
||||
kept.moved = Some(frame);
|
||||
@@ -598,10 +598,10 @@ pub(crate) fn read_input(ctx: &Context, from: usize, key: Id, value: f32) -> f32
|
||||
/// outside its room, which the call's transcript entry keeps.
|
||||
pub(crate) fn measure_call<R>(ctx: &Context, f: impl FnOnce() -> R) -> (R, Inputs) {
|
||||
if !crate::runtime::measure::active(ctx) {
|
||||
return (f(), Inputs::new());
|
||||
return (f(), Inputs::default());
|
||||
}
|
||||
let moment = Moment::of(ctx);
|
||||
with(ctx, &moment, |memory| memory.measuring.push(Open::Call { inputs: Inputs::new() }));
|
||||
with(ctx, &moment, |memory| memory.measuring.push(Open::Call { inputs: Inputs::default() }));
|
||||
let out = f();
|
||||
let inputs = with(ctx, &moment, |memory| {
|
||||
let at = memory.measuring.iter().rposition(|open| matches!(open, Open::Call { .. }))?;
|
||||
@@ -898,7 +898,9 @@ pub(crate) fn run_found(ctx: &Context, id: Id) -> bool {
|
||||
/// Opens the measuring run of `body`: what it hands forward until `end_measure` becomes its transcript.
|
||||
pub(crate) fn begin_measure(ctx: &Context, body: Id) {
|
||||
let moment = Moment::of(ctx);
|
||||
with(ctx, &moment, |memory| memory.measuring.push(Open::Body { id: body, items: Vec::new(), leaves: HashMap::new(), inputs: Inputs::new() }));
|
||||
with(ctx, &moment, |memory| {
|
||||
memory.measuring.push(Open::Body { id: body, items: Vec::new(), leaves: IdMap::default(), inputs: Inputs::default() })
|
||||
});
|
||||
}
|
||||
|
||||
/// Closes the measuring run of `body` and keeps its transcript under the inputs `key` it ran under.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//!
|
||||
//! A settling child (`Lazy::settles`) also keeps its last real run (`runtime::replay`): while it is settled, it adds
|
||||
//! that run to the pass again in place of running, in view or not, inside a scroll area or not. It is settled when
|
||||
//! nothing the framework tracks has changed for it since that run (`settled`).
|
||||
//! nothing the framework tracks has changed for it since that run, its content version included (`settled`).
|
||||
|
||||
use crate::runtime::egui::areas::Layer;
|
||||
use crate::runtime::egui::{focus as focus_state, input as input_state, pass};
|
||||
@@ -19,8 +19,8 @@ use crate::runtime::focus::{self, Transcript};
|
||||
use crate::runtime::frame::{self, PerViewport};
|
||||
use crate::runtime::reads::BindKey;
|
||||
use crate::runtime::replay::{self, Record};
|
||||
use egui::{Context, Id, Layout, Rect, Vec2};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use egui::{Context, Id, IdMap, IdSet, Layout, Rect, Vec2};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The view of the innermost scroll area, as the run that lays its content out sees it: the rect the pass shows,
|
||||
@@ -140,14 +140,19 @@ struct Settled {
|
||||
rect: Rect,
|
||||
/// The pointer was over it, or one of its stops held focus: it runs again to show that they left.
|
||||
engaged: bool,
|
||||
/// The version of the app data it showed (`Lazy::content`).
|
||||
content: Option<u64>,
|
||||
}
|
||||
|
||||
/// What changed in the frame for every settling child.
|
||||
#[derive(Default)]
|
||||
struct Changes {
|
||||
/// Every settling child runs through this frame: a frame with input other than pointer motion, an app's repaint
|
||||
/// request or an edit of a given value unsettles every child for that frame and the next.
|
||||
/// Every settling child runs through this frame: an app's repaint request outside every settling child or an edit
|
||||
/// of a given value unsettles every child for that frame and the next.
|
||||
unsettled_through: u64,
|
||||
/// Every settling child with no content version runs through this frame: a frame with input other than pointer
|
||||
/// motion unsettles them for that frame and the next.
|
||||
input_through: u64,
|
||||
/// The pass whose input was looked at.
|
||||
scanned: u64,
|
||||
/// The values changed in a frame, and the frame.
|
||||
@@ -156,12 +161,12 @@ struct Changes {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Store {
|
||||
entries: HashMap<Id, Entry>,
|
||||
entries: IdMap<Entry>,
|
||||
changes: Changes,
|
||||
/// The last frame each scroll area reached one of its children in.
|
||||
reached: HashMap<Id, u64>,
|
||||
reached: IdMap<u64>,
|
||||
/// What the real run that lays a scroll area's content out found, by area, from `begin` to `placed`.
|
||||
placed: HashMap<Id, Placed>,
|
||||
placed: IdMap<Placed>,
|
||||
/// The frame the entries were last pruned in.
|
||||
pruned: u64,
|
||||
}
|
||||
@@ -191,7 +196,7 @@ fn with<R>(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
|
||||
store.entries.retain(|_, entry| {
|
||||
entry.touched + 1 >= frame || entry.owner.is_some_and(|owner| reached.get(&owner).is_none_or(|ran| ran + 1 < frame))
|
||||
});
|
||||
let owners: HashSet<Id> = store.entries.values().filter_map(|entry| entry.owner).collect();
|
||||
let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect();
|
||||
store.reached.retain(|owner, _| owners.contains(owner));
|
||||
}
|
||||
f(store, pass_nr, frame)
|
||||
@@ -254,10 +259,12 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
|
||||
/// none of that held in its last run;
|
||||
/// - none of its stops holds focus or is the target of a focus request, now or in its last run;
|
||||
/// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`);
|
||||
/// - no frame unsettled every child (`unsettle`): input other than pointer motion this frame or the one before, an app's
|
||||
/// repaint request or an edit of a given value;
|
||||
/// - its content version is the one of its last run;
|
||||
/// - no frame unsettled every child (`unsettle`): an app's repaint request outside every settling child or an edit of a
|
||||
/// given value, this frame or the one before;
|
||||
/// - for a child with no content version: no input other than pointer motion this frame or the one before;
|
||||
/// - the run did nothing a replay cannot repeat (`runtime::replay`).
|
||||
pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, place: Option<Place>) -> Option<Vec2> {
|
||||
pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, place: Option<Place>, content: Option<u64>) -> Option<Vec2> {
|
||||
let input = ctx.input(|input| {
|
||||
input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone))
|
||||
});
|
||||
@@ -268,13 +275,13 @@ pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, pl
|
||||
if store.changes.scanned != pass_nr {
|
||||
store.changes.scanned = pass_nr;
|
||||
if input {
|
||||
store.changes.unsettled_through = store.changes.unsettled_through.max(frame + 1);
|
||||
store.changes.input_through = store.changes.input_through.max(frame + 1);
|
||||
}
|
||||
}
|
||||
let changes = &store.changes;
|
||||
// Usually empty: only the values written this frame.
|
||||
let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone());
|
||||
let unsettled = changes.unsettled_through >= frame;
|
||||
let unsettled = changes.unsettled_through >= frame || (content.is_none() && changes.input_through >= frame);
|
||||
let entry = store.touch(owner, id, frame);
|
||||
let replays = match entry.replays {
|
||||
Some((decided_in, replays)) if decided_in == pass_nr => replays,
|
||||
@@ -283,6 +290,7 @@ pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, pl
|
||||
&& entry.settled.as_ref().is_some_and(|settled| {
|
||||
let facts = &settled.record.facts;
|
||||
settled.frame < frame
|
||||
&& settled.content == content
|
||||
&& !settled.engaged
|
||||
&& !facts.unsettled
|
||||
&& !facts.blocked
|
||||
@@ -338,11 +346,12 @@ pub(crate) fn keep(ctx: &Context, owner: Option<Id>, id: Id) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Keeps the real run `record` of the settling child `id`, which ran at `place` and took `rect`.
|
||||
pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect) {
|
||||
/// Keeps the real run `record` of the settling child `id`, which ran at `place`, took `rect` and showed the app data
|
||||
/// of version `content`.
|
||||
pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, content: Option<u64>) {
|
||||
let targets = focus::targets(ctx);
|
||||
let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)));
|
||||
let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now };
|
||||
let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, content };
|
||||
settled.engaged |= engaged(ctx, &settled);
|
||||
with(ctx, |store, _, frame| {
|
||||
settled.frame = frame;
|
||||
@@ -363,7 +372,8 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Unsettles every settling child for this frame and the next: a change the framework cannot attribute to a child.
|
||||
/// Unsettles every settling child for this frame and the next: a change of app data the framework cannot attribute to
|
||||
/// a child.
|
||||
pub(crate) fn unsettle(ctx: &Context) {
|
||||
with(ctx, |store, _, frame| store.changes.unsettled_through = store.changes.unsettled_through.max(frame + 1));
|
||||
}
|
||||
|
||||
@@ -9,13 +9,12 @@ use crate::runtime::pending::{self, Job, Pending};
|
||||
use craft_behavior::eviction::owner_due;
|
||||
use craft_host::Host;
|
||||
use craft_settings::Remembered;
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use egui::{Context, Id, IdSet, ViewportId};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::any::{Any, TypeId};
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::marker::PhantomData;
|
||||
@@ -246,7 +245,7 @@ pub(crate) fn evict(ctx: &Context) {
|
||||
let live = pass::live_viewports(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 dead: HashSet<Id> = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect();
|
||||
let dead: IdSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect();
|
||||
if dead.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -457,13 +456,8 @@ impl MemoryStage {
|
||||
self.claimed.borrow_mut().push(base);
|
||||
let viewport = pass::current_viewport(&self.ctx);
|
||||
let pass_nr = pass::pass_nr(&self.ctx, viewport);
|
||||
let duplicate = PerViewport::<Stamped<HashSet<Id>>>::with_pass(
|
||||
&self.ctx,
|
||||
viewport,
|
||||
pass_nr,
|
||||
|claimed, _| claimed.clear(),
|
||||
|claimed| !claimed.insert(base),
|
||||
);
|
||||
let duplicate =
|
||||
PerViewport::<Stamped<IdSet>>::with_pass(&self.ctx, viewport, pass_nr, |claimed, _| claimed.clear(), |claimed| !claimed.insert(base));
|
||||
debug_assert!(!duplicate, "an id is the base of two open stages in one pass");
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,8 @@ use crate::runtime::pointer;
|
||||
use craft_behavior::OwnerClass;
|
||||
use craft_behavior::overlay::Side;
|
||||
use egui::emath::TSTransform;
|
||||
use egui::{Context, Id, Pos2, Rect, ViewportId};
|
||||
use egui::{Context, Id, IdMap, IdSet, Pos2, Rect, ViewportId};
|
||||
use smallvec::SmallVec;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A modal's backdrop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -235,7 +234,7 @@ pub(crate) struct TopModal {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Persist {
|
||||
raised: HashMap<Id, u64>,
|
||||
raised: IdMap<u64>,
|
||||
counter: u64,
|
||||
modal: bool,
|
||||
/// The layers of the last pass, bottom to top, as `end_pass` handed them to egui.
|
||||
@@ -252,9 +251,9 @@ pub(crate) struct Persist {
|
||||
/// A popup stands over a modal layer here, as of the last finished pass.
|
||||
popup_over_modal: bool,
|
||||
/// The layers that first showed while the primary button was held, until that press ends.
|
||||
held_open: std::collections::HashSet<Id>,
|
||||
held_open: IdSet,
|
||||
/// The root frame and pass each shown layer first ran its body in; gone with the layer's last entry.
|
||||
appeared: HashMap<Id, (u64, u64)>,
|
||||
appeared: IdMap<(u64, u64)>,
|
||||
}
|
||||
|
||||
/// The closes queued and not yet taken, each with the root frame that queued it and whether it is carried: a carried
|
||||
@@ -674,7 +673,7 @@ pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) {
|
||||
}
|
||||
|
||||
/// Groups `entries` into families, each parent first, ordered bottom to top.
|
||||
fn families(entries: &[OpenEntry], raised: &HashMap<Id, u64>) -> Vec<Vec<OpenEntry>> {
|
||||
fn families(entries: &[OpenEntry], raised: &IdMap<u64>) -> Vec<Vec<OpenEntry>> {
|
||||
let root_of = |entry: &OpenEntry| {
|
||||
let mut at = entry;
|
||||
while let Some(parent) = at.parent.and_then(|parent| entries.iter().find(|other| other.id == parent)) {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
use crate::runtime::egui::memory::Service;
|
||||
use crate::runtime::frame::{self, PerViewport, Stamped, Stored};
|
||||
use egui::Context;
|
||||
use egui::{Context, IdSet};
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -137,7 +137,7 @@ pass_state! {
|
||||
ids: crate::contract::steps::id::IdPass,
|
||||
pass_pointer: Arc<crate::runtime::pointer::PassPointer>,
|
||||
overlay_pass: crate::runtime::overlay::Pass,
|
||||
shown_ids: std::collections::HashSet<egui::Id>,
|
||||
shown_ids: IdSet,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,8 @@ use crate::runtime::frame;
|
||||
use crate::runtime::memory::{self, MemoryStage};
|
||||
use craft_host::queue::{Cancel, JobQueue, Priority, QueueOptions};
|
||||
use craft_host::{Jobs, Wake};
|
||||
use egui::{Context, Id, ViewportId};
|
||||
use egui::{Context, Id, IdMap, ViewportId};
|
||||
use std::any::TypeId;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
@@ -199,7 +198,7 @@ type Queue = (Arc<dyn Jobs>, Arc<JobQueue<Id, ()>>);
|
||||
#[derive(Default)]
|
||||
struct PendingState {
|
||||
queue: Option<Queue>,
|
||||
tracked: HashMap<Id, Tracked>,
|
||||
tracked: IdMap<Tracked>,
|
||||
}
|
||||
|
||||
fn queue_of(ctx: &Context, jobs: &Arc<dyn Jobs>) -> Arc<JobQueue<Id, ()>> {
|
||||
|
||||
@@ -13,7 +13,7 @@ use craft_behavior::{
|
||||
};
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::HitSizes;
|
||||
use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId};
|
||||
use egui::{Context, Id, IdMap, Pos2, Rect, Vec2, ViewportId};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -97,7 +97,7 @@ pub(crate) struct Memory {
|
||||
/// Whether any arena of the viewport holds an open press; sensing registers it, as the layer above.
|
||||
press_probe: Option<fn(&Context) -> bool>,
|
||||
/// The arena roots whose members the next pass resolves without (`withhold_members`), with the pass that asked.
|
||||
withheld: HashMap<Id, u64>,
|
||||
withheld: IdMap<u64>,
|
||||
}
|
||||
|
||||
/// What one root registered on one layer: its shapes and its egui widgets.
|
||||
@@ -110,7 +110,7 @@ struct RootRecord {
|
||||
click: bool,
|
||||
}
|
||||
|
||||
type LayerRecord = HashMap<Layer, HashMap<Id, RootRecord>>;
|
||||
type LayerRecord = HashMap<Layer, IdMap<RootRecord>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Shapes {
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::runtime::focus::{self, Transcript};
|
||||
use crate::runtime::frame;
|
||||
use crate::runtime::pass_state;
|
||||
use crate::runtime::reads::BindKey;
|
||||
use egui::{Context, Id};
|
||||
use egui::{Context, Id, IdSet};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -70,11 +70,12 @@ pub(crate) struct Record {
|
||||
journal: Vec<Entry>,
|
||||
egui: egui::PassRecords,
|
||||
/// The egui widgets of the run.
|
||||
pub(crate) widgets: HashSet<Id>,
|
||||
pub(crate) widgets: IdSet,
|
||||
pub(crate) facts: Facts,
|
||||
}
|
||||
|
||||
fn recording(ctx: &Context) -> bool {
|
||||
/// Whether a record is open around the running code.
|
||||
pub(crate) fn recording(ctx: &Context) -> bool {
|
||||
OPEN.load(Ordering::Acquire) > 0 && pass_state::with::<Recorder, _>(ctx, |recorder| !recorder.open.is_empty())
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,14 @@ pub trait DockPanels<P> {
|
||||
/// (`PanelSpec::window_kind` `Document`) gets the group's body edge to edge.
|
||||
fn body(&mut self, panel: &P, ui: &mut Ui, cx: &mut BodyCx<'_>);
|
||||
|
||||
/// The version of the app data `panel`'s body shows that the framework does not track (a document's revision, a
|
||||
/// job's progress). With one, the body settles (`Lazy::settles` with `Lazy::content`): it runs only when its
|
||||
/// version, its room or something the framework tracks in it changed, the pointer is over it or focus is in it, and
|
||||
/// otherwise repaints its last run. `None` (the default) runs the body every pass.
|
||||
fn content(&self, _panel: &P) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Takes the group holding `panels`, whose tab `active` is selected, in place of its tab strip and body: at
|
||||
/// `GroupAt::Show(rect)` it shows its view in `ui`, which the dock holds to `rect` and clips to it; at
|
||||
/// `GroupAt::Measure(width)` it measures that view at `width` the way it shows it. It returns the height the view
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::hide::{self, Shown};
|
||||
use crate::contract::overlay::PlacementChange;
|
||||
use crate::contract::{
|
||||
Bind, BindMut, BodyCx, Cx, Entry, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _,
|
||||
Bind, BindMut, BodyCx, Cx, Entry, Lazy, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _,
|
||||
};
|
||||
use crate::docking::SplitFramesCx as _;
|
||||
use crate::docking::stack::{StackSection, StackSections, section_heights};
|
||||
@@ -818,20 +818,19 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
};
|
||||
let rect = match at {
|
||||
GroupAt::Measure(width) => {
|
||||
let measured =
|
||||
make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panels.borrow_mut().body(shown, ui, body));
|
||||
let measured = make(active, look.minimized).measure_in(ui, Proposal::Width(width), |ui, body| panel_body(&panels, shown, ui, body));
|
||||
return Some(measured.y);
|
||||
}
|
||||
GroupAt::Show(rect) => rect,
|
||||
};
|
||||
let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panels.borrow_mut().body(shown, ui, body)).output;
|
||||
let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output;
|
||||
// The size `panel` floats at out of this group: the group's width, and the height the group measures at with
|
||||
// `panel` shown in a floating window's room, so content that fills the body takes that room.
|
||||
let fitted = |ui: &Ui, panel: &P| {
|
||||
let at = members.iter().position(|member| member == panel).unwrap_or(active);
|
||||
let room = Vec2::new(rect.width(), scene.space.content_room());
|
||||
let measured = make(at, false).id(output.response.id).measure_in(ui, Proposal::Size(room), |ui, body| {
|
||||
panels.borrow_mut().body(&members[at], ui, body);
|
||||
panel_body(&panels, &members[at], ui, body);
|
||||
});
|
||||
Vec2::new(rect.width(), measured.y)
|
||||
};
|
||||
@@ -1149,3 +1148,14 @@ fn window_edit<P: Clone + Eq + Hash>(
|
||||
_ => moving.take().map(|held| EditEvent::cancel(held.id, CancelReason::Dismissed, Some(Mixed::Same(held.before)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `panel`'s body in a group's body; a panel with a content version settles (`DockPanels::content`).
|
||||
fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels<P> + 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) {
|
||||
let content = panels.borrow().content(panel);
|
||||
match content {
|
||||
Some(version) => {
|
||||
Lazy::new(("panel", PanelKey::of(panel).0), 0.0).settles(true).content(version).show(ui, |ui| panels.borrow_mut().body(panel, ui, body));
|
||||
}
|
||||
None => panels.borrow_mut().body(panel, ui, body),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The runs of a settled docked layout: each group adds the same runs whatever its tab count, and a closed menu, the
|
||||
//! group's header controls and its tabs add none.
|
||||
//! The runs of a settled docked layout: each group adds the same runs whatever its tab count, a closed menu, the
|
||||
//! group's header controls and its tabs add none, and a panel body with a content version runs only when it changes.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
|
||||
@@ -9,6 +9,8 @@ use craft_ui::menu::PanelRow;
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::{Fixture, last_pass_runs, trial};
|
||||
use egui::{Ui, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
struct Panels;
|
||||
|
||||
@@ -70,3 +72,47 @@ fn a_settled_dock_group_runs_the_same_whatever_its_tab_count() {
|
||||
let parts: Vec<_> = shown.iter().filter(|(ty, _)| matches!(short(ty), "Row" | "Tab" | "IconButton" | "GroupGrip")).collect();
|
||||
assert!(parts.is_empty(), "a settled dock ran header parts as runs: {parts:?}");
|
||||
}
|
||||
|
||||
/// Two panels in two groups: panel 0 gives the content version `version`, panel 1 none. Each body counts its runs.
|
||||
struct Versioned {
|
||||
runs: Rc<[Cell<usize>; 2]>,
|
||||
version: Rc<Cell<u64>>,
|
||||
}
|
||||
|
||||
impl DockPanels<usize> for Versioned {
|
||||
fn spec(&self, panel: &usize) -> PanelSpec {
|
||||
PanelSpec::new(format!("Panel {panel}"))
|
||||
}
|
||||
|
||||
fn body(&mut self, panel: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
self.runs[*panel].set(self.runs[*panel].get() + 1);
|
||||
}
|
||||
|
||||
fn content(&self, panel: &usize) -> Option<u64> {
|
||||
(*panel == 0).then(|| self.version.get())
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel body with a content version runs in the frame its version changes and settles otherwise; a body without one
|
||||
/// runs every frame.
|
||||
#[trial]
|
||||
fn a_panel_body_with_a_content_version_runs_only_when_its_version_changes() {
|
||||
let (runs, version): (Rc<[Cell<usize>; 2]>, _) = (Rc::default(), Rc::new(Cell::new(1)));
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0));
|
||||
let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new()));
|
||||
let mut panels = Versioned { runs: Rc::clone(&runs), version: Rc::clone(&version) };
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 600.0)).settle();
|
||||
let mut frame = || {
|
||||
runs.iter().for_each(|runs| runs.set(0));
|
||||
fixture.frame(Vec::new());
|
||||
[runs[0].get(), runs[1].get()]
|
||||
};
|
||||
let [versioned, plain] = frame();
|
||||
assert!(versioned == 0 && plain > 0, "the versioned body settles, the other runs: {versioned}, {plain}");
|
||||
version.set(2);
|
||||
assert!(frame()[0] > 0, "a new version runs the versioned body");
|
||||
assert_eq!(frame()[0], 0, "and it settles at it");
|
||||
}
|
||||
|
||||
@@ -14,13 +14,13 @@ use super::screen_mode::{ScreenMode, ScreenModeCommands, ScreenModeFollow};
|
||||
use super::words::ShellWords;
|
||||
use crate::contract::overlay::Resize;
|
||||
use crate::contract::{
|
||||
Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, PaneEdge, Props as _, Remember as _, Role,
|
||||
ShellPane, ShowContainer as _, Sizing,
|
||||
Bind, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, Lazy, Mount, NoValue, Outcome, PaneEdge, Props as _, Remember as _,
|
||||
Role, ShellPane, ShowContainer as _, Sizing,
|
||||
};
|
||||
use crate::notices::ToastStack;
|
||||
use crate::runtime::commands::{CommandAccess as _, CommandSet as _};
|
||||
use crate::runtime::egui::pass;
|
||||
use crate::runtime::env::{AppValues, BodyMode, Env, Label, RevealEdge, ShellCx, ShellEntry, ShellRegions, WindowKey};
|
||||
use crate::runtime::env::{AppValues, BodyMode, Env, Label, RevealEdge, ShellCx, ShellEntry, ShellRegions, SlotKey, WindowKey};
|
||||
use crate::runtime::focus::FocusPolicy;
|
||||
use crate::runtime::frame::{note_shell, take_chrome_toggles};
|
||||
use crate::runtime::overlay::{OpenFilter, any_open};
|
||||
@@ -411,6 +411,15 @@ impl<'a, S> AppShell<'a, S> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Gives the slot keyed `key`, added before, the version of the app data it shows ([`Slot::content`]), for the
|
||||
/// slots the `options_bar`, `tools` and `status` builders make.
|
||||
pub fn content(mut self, key: SlotKey, version: u64) -> Self {
|
||||
for placed in self.title.iter_mut().chain(self.slots.iter_mut()).filter(|placed| placed.slot.key() == key) {
|
||||
placed.slot = placed.slot.clone().content(version);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Lays out the slots, then the body in what is left, runs the window's dialogs over them and shows the toasts of
|
||||
/// the window. Each slot and the body get `app`, one after the other: the slots that do not cover the body, then the
|
||||
/// body, then the slots a reveal lays over it.
|
||||
@@ -542,7 +551,13 @@ impl<'a, S> AppShell<'a, S> {
|
||||
if let Some(label) = slot.name().cloned().or_else(|| named.map(|name| name(&words))) {
|
||||
region = region.label(label);
|
||||
}
|
||||
region.show(ui, |ui, bcx| add(ui, bcx, app));
|
||||
let content = slot.content_version();
|
||||
region.show(ui, |ui, bcx| match content {
|
||||
Some(version) => {
|
||||
Lazy::new(("slot", slot.key()), 0.0).settles(true).content(version).show(ui, |ui| add(ui, bcx, app));
|
||||
}
|
||||
None => add(ui, bcx, app),
|
||||
});
|
||||
}
|
||||
};
|
||||
show_slots(ui, false, app);
|
||||
|
||||
@@ -44,9 +44,9 @@ impl SlotSize {
|
||||
}
|
||||
}
|
||||
|
||||
/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size and its AccessKit
|
||||
/// name. The shell paints the chrome surface over the whole slot and a divider along its edge toward the body; the
|
||||
/// title slot's bar paints its own.
|
||||
/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size, its AccessKit
|
||||
/// name and the version of the app data it shows. The shell paints the chrome surface over the whole slot and a divider
|
||||
/// along its edge toward the body; the title slot's bar paints its own.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Slot {
|
||||
@@ -56,13 +56,14 @@ pub struct Slot {
|
||||
visible: bool,
|
||||
reveal: bool,
|
||||
label: Option<Label>,
|
||||
content: Option<u64>,
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
/// A slot with a key that is stable and unique in the window. It is visible and does not show in a reveal. Without a
|
||||
/// [`size`](Self::size) it takes the default of its edge: the title bar, options bar, status bar or rail width.
|
||||
pub fn new(key: SlotKey) -> Self {
|
||||
Self { key, size: None, columns: 1, visible: true, reveal: false, label: None }
|
||||
Self { key, size: None, columns: 1, visible: true, reveal: false, label: None, content: None }
|
||||
}
|
||||
|
||||
/// The size along the slot's edge, in place of the default of the edge.
|
||||
@@ -103,6 +104,20 @@ impl Slot {
|
||||
self
|
||||
}
|
||||
|
||||
/// The version of the app data the slot shows that the framework does not track (a document's revision, a job's
|
||||
/// progress). A slot with one settles (`Lazy::settles` with `Lazy::content`): it runs only when its version, its
|
||||
/// room or something the framework tracks in it changed, the pointer is over it or focus is in it, and otherwise
|
||||
/// repaints its last run. A slot without one runs every pass.
|
||||
pub fn content(mut self, version: u64) -> Self {
|
||||
self.content = Some(version);
|
||||
self
|
||||
}
|
||||
|
||||
/// The version set by [`content`](Self::content), if any.
|
||||
pub fn content_version(&self) -> Option<u64> {
|
||||
self.content
|
||||
}
|
||||
|
||||
/// The slot's key, as visibility flags and [`ShellCx::slot_visible`](crate::runtime::env::ShellCx::slot_visible) name it.
|
||||
pub fn key(&self) -> SlotKey {
|
||||
self.key
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The app shell's named slots: a slot keeps its region name on either edge, and a bar in a top or bottom slot fills
|
||||
//! it with its members on the slot's middle.
|
||||
//! The app shell's named slots: a slot keeps its region name on either edge, a bar in a top or bottom slot fills it
|
||||
//! with its members on the slot's middle, and a slot with a content version settles.
|
||||
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::buttons::Button;
|
||||
@@ -7,7 +7,8 @@ use craft_ui::contract::{PaneEdge, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::runtime::env::WindowKey;
|
||||
use craft_ui::shell::{AppShell, Title, TitleBar};
|
||||
use craft_ui::shell::{AppShell, Title, TitleBar, slots};
|
||||
use craft_ui::testing::pointer::{press, release};
|
||||
use craft_ui::testing::{Fixture, Frames, trial};
|
||||
use egui::{Rect, Vec2};
|
||||
use std::cell::Cell;
|
||||
@@ -148,3 +149,39 @@ fn a_title_bar_in_the_title_slot_shows_its_content_there() {
|
||||
assert!(member.width() > 0.0 && slot.contains_rect(member), "the bar's member {member:?} shows in the slot {slot:?} (bar {bar:?})");
|
||||
assert!((member.center().y - slot.center().y).abs() <= 1.0, "the member {member:?} sits on the slot's middle {slot:?}");
|
||||
}
|
||||
|
||||
/// A status slot that gives a content version runs only in the frame its version changes: frames with no input and a
|
||||
/// click in the body leave it settled.
|
||||
#[trial]
|
||||
fn a_slot_with_a_content_version_runs_only_when_its_version_changes() {
|
||||
let (runs, version, body) = (Cell::new(0), Cell::new(1), Cell::new(Rect::NOTHING));
|
||||
let frame = |frames: &mut Frames, events| {
|
||||
runs.set(0);
|
||||
frames.frame(events, |ui| {
|
||||
let out = AppShell::new(WindowKey::main())
|
||||
.status(true, |ui, _, _: &mut ()| {
|
||||
runs.set(runs.get() + 1);
|
||||
Text::new("Ready").show(ui);
|
||||
})
|
||||
.content(slots::STATUS, version.get())
|
||||
.body(|ui, _, _| {
|
||||
Button::new("Body").show(ui);
|
||||
})
|
||||
.show(ui, &mut ());
|
||||
body.set(out.regions.body);
|
||||
});
|
||||
runs.get()
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
for _ in 0..30 {
|
||||
frame(&mut frames, vec![]);
|
||||
}
|
||||
assert_eq!(frame(&mut frames, vec![]), 0, "the status slot settles");
|
||||
let at = body.get().center();
|
||||
for events in [vec![press(at)], vec![release(at)], vec![]] {
|
||||
assert_eq!(frame(&mut frames, events.clone()), 0, "a click in the body ({events:?}) leaves the slot settled");
|
||||
}
|
||||
version.set(2);
|
||||
assert!(frame(&mut frames, vec![]) > 0, "a new version runs the slot");
|
||||
assert_eq!(frame(&mut frames, vec![]), 0, "and it settles at it");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Settling children (`Lazy::settles`): a settled child adds its last run to the pass in place of running, and runs
|
||||
//! when something it shows may have changed: the pointer over it, a bound value, inspection record or command state it
|
||||
//! read, its room, an animation.
|
||||
//! read, its room, its content version, an animation or a repaint asked inside it.
|
||||
|
||||
use crate::values::kit::{AT, INITIAL, Scrub, Seen};
|
||||
use craft_ui::buttons::Button;
|
||||
@@ -8,7 +8,7 @@ use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowCont
|
||||
use craft_ui::display::Spinner;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _};
|
||||
use craft_ui::runtime::inspect;
|
||||
use craft_ui::runtime::{frame, inspect};
|
||||
use craft_ui::testing::layout::in_region;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Frames, last_pass_measuring_runs, trial};
|
||||
@@ -23,12 +23,17 @@ const READER: Rect = Rect { min: Pos2::new(150.0, 70.0), max: Pos2::new(250.0, 9
|
||||
const SETTLED: usize = 4;
|
||||
|
||||
/// Two settling children, `reader` and `other`, under a scrub bound to the value the reader's own scrub shows. The
|
||||
/// scrub that edits comes before the children in the pass when `editor_first`, else after them.
|
||||
/// scrub that edits comes before the children in the pass when `editor_first`, else after them. Each child shows the
|
||||
/// content version in `versions`, if any; `other` asks for a repaint in each run while `repaints` holds, and the app
|
||||
/// asks for one outside both children while `app_repaints` holds.
|
||||
struct Scene {
|
||||
value: RefCell<f32>,
|
||||
room: Cell<Vec2>,
|
||||
editor_first: bool,
|
||||
spinner: bool,
|
||||
versions: [Cell<Option<u64>>; 2],
|
||||
repaints: Cell<bool>,
|
||||
app_repaints: Cell<bool>,
|
||||
runs: [Cell<usize>; 2],
|
||||
buttons: [Cell<(Id, Rect)>; 2],
|
||||
seen: Seen,
|
||||
@@ -41,25 +46,43 @@ impl Scene {
|
||||
room: Cell::new(ROOM),
|
||||
editor_first,
|
||||
spinner,
|
||||
versions: Default::default(),
|
||||
repaints: Cell::new(false),
|
||||
app_repaints: Cell::new(false),
|
||||
runs: Default::default(),
|
||||
buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))],
|
||||
seen: Seen::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The settling child `key`, with the content version of child `at`.
|
||||
fn child(&self, key: &str, at: usize) -> Lazy {
|
||||
let child = Lazy::new(key, 0.0).settles(true);
|
||||
match self.versions[at].get() {
|
||||
Some(version) => child.content(version),
|
||||
None => child,
|
||||
}
|
||||
}
|
||||
|
||||
fn show(&self, ui: &mut Ui) {
|
||||
if self.app_repaints.get() {
|
||||
frame::request_repaint(ui.ctx());
|
||||
}
|
||||
if self.editor_first {
|
||||
self.editor(ui);
|
||||
}
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| {
|
||||
Lazy::new("reader", 0.0).settles(true).show(ui, |ui| {
|
||||
self.child("reader", 0).show(ui, |ui| {
|
||||
self.runs[0].set(self.runs[0].get() + 1);
|
||||
let response = Button::new("Alpha").show(ui).response;
|
||||
self.buttons[0].set((response.id, response.rect));
|
||||
Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER);
|
||||
});
|
||||
Lazy::new("other", 0.0).settles(true).show(ui, |ui| {
|
||||
self.child("other", 1).show(ui, |ui| {
|
||||
self.runs[1].set(self.runs[1].get() + 1);
|
||||
if self.repaints.get() {
|
||||
frame::request_repaint(ui.ctx());
|
||||
}
|
||||
// In a body, whose measure a run that is not settled takes from what its last run kept.
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
let response = Button::new("Beta").show(ui).response;
|
||||
@@ -199,6 +222,37 @@ fn a_child_with_a_running_animation_runs_every_frame() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A repaint asked inside a settling child runs that child again, and only it.
|
||||
#[trial]
|
||||
fn a_repaint_asked_inside_a_settled_child_runs_only_that_child() {
|
||||
let scene = Scene::new(false, false);
|
||||
scene.repaints.set(true);
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
for frame in 0..SETTLED {
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 1], "frame {frame}: the child that asks runs, the other does not");
|
||||
}
|
||||
}
|
||||
|
||||
/// A child with a content version runs in the frame its version changes, and only then; input elsewhere in the window
|
||||
/// leaves it settled, and a repaint the app asks for outside every child runs it.
|
||||
#[trial]
|
||||
fn a_child_with_a_content_version_runs_when_it_changes() {
|
||||
let scene = Scene::new(false, false);
|
||||
scene.versions.iter().for_each(|version| version.set(Some(1)));
|
||||
let mut frames = Frames::new();
|
||||
scene.settle(&mut frames);
|
||||
let away = Pos2::new(ORIGIN.x + ROOM.x + 90.0, ORIGIN.y + ROOM.y + 40.0);
|
||||
for events in [vec![moved(away)], vec![press(away)], vec![release(away)], vec![]] {
|
||||
assert_eq!(scene.frame(&mut frames, events.clone()), [0, 0], "input elsewhere ({events:?}) runs no versioned child");
|
||||
}
|
||||
scene.versions[0].set(Some(2));
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [1, 0], "the child whose version changed runs, the other does not");
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "both settle at the new version");
|
||||
scene.app_repaints.set(true);
|
||||
assert_eq!(scene.frame(&mut frames, vec![]), [1, 1], "an app repaint outside both children runs both");
|
||||
}
|
||||
|
||||
/// The app commands the command scene's children show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "settleTrial")]
|
||||
|
||||
Reference in New Issue
Block a user