diff --git a/crates/ui-bench/src/bin/foundation/main.rs b/crates/ui-bench/src/bin/foundation/main.rs index 1295c3093..b43ce0d33 100644 --- a/crates/ui-bench/src/bin/foundation/main.rs +++ b/crates/ui-bench/src/bin/foundation/main.rs @@ -475,9 +475,10 @@ impl Scene for CanvasViewScene { let text = RulerText::new(RulerUnits::pixels(), UnitKind::Pixels); let canvas = ui.scope_id().with("canvas scene"); let mut hosted = None; - let shown = Canvas::new("Document").id(canvas).view(*view).rulers(text, text, *zero).show_rulers(true).show(ui, |ui, body| { + let at = *zero; + let strips = Rulers::new("Rulers", Bind::bound(&mut *zero)); + let shown = Canvas::new("Document").id(canvas).view(*view).rulers(text, text, at).with_rulers(Some(strips)).show(ui, |ui, body| { let _ = Guides::new("Guides", canvas, Bind::bound(&mut *guides)).show_at(ui, body.rect); - let _ = Rulers::new("Rulers", Bind::bound(&mut *zero)).show_at(ui, body.rect); if let Some(pass) = tool_pass(&body.env) { hosted = Some(ToolHost::new().run(ui, &pass, &mut *hand)); } diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 2439b191d..5e8654b06 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -30,7 +30,7 @@ pub use crop::{CropOverlay, CropOverlayOutput, CropShield, CropStyle, ShieldColo pub use frame_step::{FRAME_STEP_MAX, frame_step}; pub(crate) use march::{MARCH_SECONDS, MARCH_TICK, march_shift}; pub use readout::{ShowReadouts, hud, readout}; -pub use space::{CanvasSpace, RulerText, canvas_space, pixel_aligned}; +pub use space::{CanvasSpace, RulerText, canvas_space, pixel_aligned, ruler_guide}; pub use words::CanvasWords; #[doc(hidden)] @@ -120,6 +120,9 @@ use zoom_motion::{Steer, ViewMotion}; pub(crate) const BACKGROUND: PartKey = PartKey::new("background"); +/// The key the canvas shows its rulers under. +const RULERS: &str = "rulers"; + /// The areas the active tool claims over the canvas controls ([`Canvas::tool_regions`]): `TOOL_REGION.at(i)` is the /// region at `i`. const TOOL_REGION: PartKey = PartKey::new("toolRegion"); @@ -188,9 +191,13 @@ pub struct Canvas<'a> { /// eases (Animated Zoom) and whether the view may leave the document (Overscroll). #[prop] navigation: NavigationOptions, - /// Whether the rulers show along the top and left edges (View > Rulers): the view lies inside them. - #[prop] - show_rulers: bool, + /// The rulers along the top and left edges (View > Rulers), which the canvas shows itself: the view lies inside + /// them ([`with_rulers`](Self::with_rulers)). + strips: Option>, + /// Whether the strips show; the rulers' own output of this pass is [`CanvasOutput::rulers`]. + strips_shown: bool, + /// What the rulers reported in this pass, from the paint step. + ruler_output: Option, /// Whether the canvas leaves Page Up, Page Down, Home, End and the arrows to its body: it applies no page keys /// and gives no tool or session control the arrows, and its body reads them in [`CanvasSpace::keys`]. For a /// body that pages its document itself (a page view). @@ -272,7 +279,9 @@ impl<'a> Canvas<'a> { layer_bounds: None, queued: &[], navigation: NavigationOptions::default(), - show_rulers: false, + strips: None, + strips_shown: false, + ruler_output: None, keys_to_body: false, pasteboard: PasteboardColor::Default, precise_cursors: false, @@ -294,7 +303,7 @@ impl<'a> Canvas<'a> { /// (`Bind::given`, or a plain [`CanvasView`]) is only read: the app copies what a tool changed from /// [`ToolHostResponse::view`] (or [`CanvasOutput::view`] without a tool host) every pass. /// - /// The canvas sets the view's rect to its own rect, inside the rulers while they show ([`show_rulers`](Self::show_rulers)), + /// The canvas sets the view's rect to its own rect, inside the rulers while they show ([`with_rulers`](Self::with_rulers)), /// so the body and the reported view carry this pass's rect. A view whose rect has no area (`CanvasView::new(Rect::NOTHING, ..)`, /// a document never shown) opens fitted: Fit on Screen in the first pass the canvas has area and a document. A /// canvas with no area (a minimized window) leaves the view as it is, so a restore does not refit. @@ -379,11 +388,6 @@ impl<'a> Canvas<'a> { self.document.map(|target| target.document) } - /// The rect the view lies in: the canvas's own, inside the rulers while they show. - fn view_rect(&self, rect: Rect, style: &CanvasStyle) -> Rect { - if self.show_rulers { Rect::from_min_max(rect.min + style.rulers, rect.max) } else { rect } - } - /// The view of this pass from the app's `given` view: this pass's rect, the first fit, the wheel, a middle-button /// pan, the view commands, the Overscroll clamp, and the zoom ease. fn settle(&self, cx: &mut Cx<'_, Self>, given: CanvasView) -> Settled { @@ -393,7 +397,7 @@ impl<'a> Canvas<'a> { let pixels_per_point = cx.env.scale().0; let size = self.document_size().unwrap_or(Size::ZERO); let mut view = given; - let area = self.view_rect(cx.content_rect, cx.style); + let area = cx.content_rect; if area.width() > 0.0 && area.height() > 0.0 { let never_shown = !(view.rect.width() > 0.0 && view.rect.height() > 0.0); view.rect = area; @@ -484,10 +488,20 @@ impl<'a> Canvas<'a> { Settled { target, shown, easing, keys } } + /// Shows `rulers` along the top and left edges of the canvas, which the view lies inside (View > Rulers); none shows + /// no strips. The canvas hands them its space and snap, and the body (guides) reads the guide a drag out of them + /// places with [`ruler_guide`]. What they report comes back in [`CanvasOutput::rulers`]. + #[must_use] + pub fn with_rulers(mut self, rulers: Option>) -> Self { + self.strips_shown = rulers.is_some(); + self.strips = rulers; + self + } + /// Measures the document's axes in `x` and `y`, counted from `zero` (document units). The rulers, the guides and /// the measures of the body read the units and the zero from the canvas's [`CanvasSpace`], so the app states them /// once. A canvas that publishes none measures in pixels from the document's origin. Whether the strips show, and - /// so where the view lies, is [`show_rulers`](Self::show_rulers). + /// so where the view lies, is [`with_rulers`](Self::with_rulers). #[must_use] pub fn rulers(mut self, x: RulerText, y: RulerText, zero: Point) -> Self { self.rulers = Some(CanvasRulers::new(x, y, zero)); @@ -583,6 +597,8 @@ pub struct CanvasOutput { /// target; the canvas shows the way there itself. [`ToolHost::run`] carries it in [`ToolHostResponse::view`] /// when no tool set a view, so an app with a tool host copies that one view. pub view: Option, + /// What the rulers given to [`Canvas::with_rulers`] reported in this pass. + pub rulers: Option, } impl CanvasOutput { @@ -655,9 +671,19 @@ impl Component for Canvas<'_> { WheelNotch::Points(WheelNavigation::LINE) } - /// Reserves the slot the picture paints into, under every canvas control of the body (`CanvasSpace::paint_picture`). + /// The rulers' strips lie outside the view the body is clipped to. + fn padding(&self, _rect: Rect, style: &CanvasStyle) -> craft_behavior::Insets { + if self.strips_shown { craft_behavior::Insets::new(style.rulers.x, 0.0, style.rulers.y, 0.0) } else { style.metrics().padding } + } + + /// Reserves the slot the picture paints into, under every canvas control of the body (`CanvasSpace::paint_picture`), + /// and shows the rulers over the canvas's rect. fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { self.picture = Some(ui.reserve_slot(cx.content_rect)); + if let Some(rulers) = self.strips.take() { + let pass = self.tool_pass(cx); + self.ruler_output = Some(ui.child(RULERS, cx.rect, rulers.on_canvas(pass.space, pass.snap))); + } } /// The view of this pass, kept for the body and `finish`. @@ -689,6 +715,7 @@ impl Component for Canvas<'_> { let pass = self.tool_pass(cx); space::publish(values, pass.space); snap::publish(values, pass.snap.clone()); + space::publish_ruler_guide(values, self.ruler_output.as_ref().and_then(|output| output.guide)); tool_host::publish(values, (!measure::active(&cx.response.ctx)).then_some(pass)); } @@ -723,7 +750,7 @@ impl Component for Canvas<'_> { fn finish(self, cx: Cx<'_, Self>) -> CanvasOutput { let pass = self.tool_pass(&cx); - CanvasOutput { response: cx.response.clone(), press: pass.press, space: pass.space, view: pass.view } + CanvasOutput { response: cx.response.clone(), press: pass.press, space: pass.space, view: pass.view, rulers: self.ruler_output } } } diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index f30d57f3a..d3e31d939 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -9,7 +9,7 @@ mod ticks; pub use ticks::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule}; use super::words::CanvasWords; -use super::{CanvasRulers, CanvasSpace, GuideDrag, RulerText, Snap, canvas_snap, canvas_space, context_menu, readout}; +use super::{CanvasRulers, CanvasSpace, GuideDrag, RulerText, Snap, context_menu, readout}; use crate::contract::overlay::Anchor; use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, Focus as _, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, @@ -17,7 +17,7 @@ use crate::contract::{ }; use crate::menu::Menu; use crate::primitives::{PaintShape, RectSide, StrokeWidth, TextRun, Tick, TickEdge, TickRank}; -use crate::runtime::env::{EnvView, Label, UnitKind}; +use crate::runtime::env::{Label, UnitKind}; use crate::runtime::focus::KeyUse; use crate::runtime::memory::Remember as _; use crate::style::{ComponentStyle, RuleKind, StyleColor, StyleCx, TextLook, TypeRole, UiTokens}; @@ -178,11 +178,11 @@ enum MenuRow { /// The rulers of a canvas: ticks and labels counted from a zero point, level whatever the view's rotation, a pointer /// marker, the guide drag-out and the zero point's corner. /// -/// - Show it with `show_at` over the canvas's rect inside the `Canvas` body, and lay the view out in -/// [`Rulers::content_rect`] of that rect. The units come from the canvas ([`Canvas::rulers`](super::Canvas::rulers)); -/// the rulers hold the zero point's edit. -/// - A drag on the top ruler reports a horizontal guide in [`RulersOutput::guide`], one on the left ruler a vertical -/// guide; Alt turns it, Shift snaps it to the ticks, and a release over a ruler or off the document reports no +/// - Give it to the canvas ([`Canvas::with_rulers`](super::Canvas::with_rulers)), which shows it along the top and +/// left of its rect and lays its view out inside the strips. The units come from the canvas +/// ([`Canvas::rulers`](super::Canvas::rulers)); the rulers hold the zero point's edit. +/// - A drag on the top ruler reports a horizontal guide in [`RulersOutput::guide`] and to the canvas's body +/// ([`ruler_guide`](super::ruler_guide)), one on the left ruler a vertical guide; Alt turns it, Shift snaps it to the ticks, and a release over a ruler or off the document reports no /// position, which removes the guide. /// - A drag out of the corner moves the zero point: cross hairs show where it lands, Shift snaps to the ticks /// (otherwise the canvas's [`Snap`]), dropped back on the corner it stays, Esc cancels. A double click @@ -209,6 +209,9 @@ pub struct Rulers<'a> { /// no menu. #[prop] units: Option<&'a [UnitKind]>, + /// The canvas's space and snap in this pass, which the canvas hands to the rulers it shows. + space: Option, + snap: Option, guide: Option, picked: Option, context: Option, @@ -225,6 +228,8 @@ impl<'a> Rulers<'a> { interactive: true, margins: RulerMargins::default(), units: None, + space: None, + snap: None, guide: None, picked: None, context: None, @@ -249,9 +254,16 @@ impl<'a> Rulers<'a> { value.copied().unwrap_or(Point::ZERO) } + /// The canvas's space and snap of this pass: the canvas shows the rulers and hands them over. + pub(super) fn on_canvas(mut self, space: Option, snap: Option) -> Self { + self.space = space; + self.snap = snap; + self + } + /// The units the canvas published, whatever the pass. - fn published(env: &EnvView<'_>) -> CanvasRulers { - canvas_space(env).map(|space| space.rulers()).unwrap_or_default() + fn published(&self) -> CanvasRulers { + self.space.map(|space| space.rulers()).unwrap_or_default() } /// Where the zero point lands for the pointer at `pos`: on the nearest tick of the rulers with Shift, else where @@ -354,7 +366,7 @@ impl Component for Rulers<'_> { /// strip's keyboard path is the guide dialog. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let (top, left, corner) = strips(rect, cx.style.thickness); - let space = canvas_space(&cx.env); + let space = self.space; let handle = HitPriority::new(HitLevel::Handle, 0); for (part, strip) in [(RulerPart::Horizontal, top), (RulerPart::Vertical, left)] { let declared = cx.part(part.part(), strip).priority(handle).pointer_only("the New Guide... command places a guide by number"); @@ -380,7 +392,7 @@ impl Component for Rulers<'_> { } fn update(&mut self, cx: &mut Cx<'_, Self>) { - let Some(space) = canvas_space(&cx.env) else { return }; + let Some(space) = self.space else { return }; let (_, _, corner) = strips(cx.rect, cx.style.thickness); let content = Rulers::content_rect_of(cx.rect, cx.style.thickness); let zero = Self::zero_of(cx.value()); @@ -402,7 +414,7 @@ impl Component for Rulers<'_> { } PressPhase::Drag { pos, .. } => { let start = cx.press_slot::().unwrap_or(zero); - let at = if corner.contains(pos) { start } else { Self::landing(&space, canvas_snap(&cx.env).as_ref(), pos, press.mods, zero) }; + let at = if corner.contains(pos) { start } else { Self::landing(&space, self.snap.as_ref(), pos, press.mods, zero) }; cx.propose(at); } PressPhase::Release { click: false, .. } => cx.commit(), @@ -440,7 +452,7 @@ impl Component for Rulers<'_> { let popup = cx.popup("menu"); let numbers = cx.env.units(); let words = cx.words::(); - let shown = Self::published(&cx.env).x.kind; + let shown = self.published().x.kind; let mut entries: Vec> = units.iter().map(|&kind| Entry::new(MenuRow::Unit(kind), Label::from(numbers.symbol(kind))).checked(kind == shown)).collect(); entries.push(Entry::separator()); @@ -461,7 +473,7 @@ impl Component for Rulers<'_> { let style = cx.style; let (top, left, corner) = strips(cx.rect, style.thickness); let zero = Self::zero_of(cx.value()); - let space = canvas_space(&cx.env); + let space = self.space; let draw = ui.draw(); let rect = |rect: Rect| PaintShape::Rect(rect, CornerRadius::ZERO); let dragging = matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)); diff --git a/crates/ui-canvas/src/canvas/rulers/stories.rs b/crates/ui-canvas/src/canvas/rulers/stories.rs index 49861242a..4ab12b2ba 100644 --- a/crates/ui-canvas/src/canvas/rulers/stories.rs +++ b/crates/ui-canvas/src/canvas/rulers/stories.rs @@ -1,9 +1,9 @@ //! Stories of the rulers. use super::{CORNER, Rulers}; -use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with}; +use crate::canvas::testing::canvas_story::{StoryDocument, on_ruled_canvas}; use crate::canvas::{Canvas, RulerText}; -use crate::contract::{Bind, Show as _, Validity}; +use crate::contract::{Bind, Validity}; use crate::runtime::env::{Message, UnitKind}; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use crate::testing::{pointer, stage}; @@ -70,12 +70,12 @@ fn configured<'a>(rulers: Rulers<'a>, settings: Settings) -> Rulers<'a> { rulers.interactive(settings.interactive).origin_locked(settings.locked) } -/// A canvas whose view lies inside the strips and whose rulers count from `zero` in pixels. -fn rulers_canvas(room: Rect, pixels_per_point: f32, zero: Point, settings: Settings) -> Canvas<'static> { +/// A canvas that shows `rulers` and whose view lies inside the strips, counting from `zero` in pixels. +fn rulers_canvas<'a>(room: Rect, pixels_per_point: f32, zero: Point, settings: Settings, rulers: Rulers<'a>) -> Canvas<'a> { let text = pixels(); let view = StoryDocument::STANDARD.view(room, pixels_per_point, settings.zoom).rotation(settings.rotation).flip_x(settings.flip).aspect(settings.aspect); - Canvas::new("Document").view(view).show_rulers(true).rulers(text, text, zero) + Canvas::new("Document").view(view).with_rulers(Some(configured(rulers, settings))).rulers(text, text, zero) } #[story(Rulers<'static>, covers = [Default], drive = Drive::Custom(drag_corner))] @@ -83,10 +83,9 @@ fn zero_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); let zero = data.value("zero", Point::ZERO); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), *zero, settings); - on_canvas_with(ui, room, canvas, Some(&StoryDocument::STANDARD), |ui, at| { - configured(Rulers::new("Rulers", Bind::bound(&mut *zero)), settings).show_at(ui, at) - }) + let at = *zero; + let canvas = rulers_canvas(room, ui.pixels_per_point(), at, settings, Rulers::new("Rulers", Bind::bound(&mut *zero))); + on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } #[story(Rulers<'static>, covers = [Open], drive = Drive::Custom(open_units_menu))] @@ -94,10 +93,9 @@ fn units_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); let zero = data.value("zero", Point::ZERO); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), *zero, settings); - on_canvas_with(ui, room, canvas, Some(&StoryDocument::STANDARD), |ui, at| { - configured(Rulers::new("Rulers", Bind::bound(&mut *zero)), settings).units(&UNITS).show_at(ui, at) - }) + let at = *zero; + let canvas = rulers_canvas(room, ui.pixels_per_point(), at, settings, Rulers::new("Rulers", Bind::bound(&mut *zero)).units(&UNITS)); + on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } #[story(Rulers<'static>, covers = [Mixed], drive = Drive::Custom(drag_corner))] @@ -105,10 +103,8 @@ fn zero_points_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let settings = settings(data); let zero = data.value("zero", Mixed::::Mixed); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), Point::ZERO, settings); - on_canvas_with(ui, room, canvas, Some(&StoryDocument::STANDARD), |ui, at| { - configured(Rulers::new("Rulers", Bind::bound_mixed(&mut *zero)), settings).show_at(ui, at) - }) + let canvas = rulers_canvas(room, ui.pixels_per_point(), Point::ZERO, settings, Rulers::new("Rulers", Bind::bound_mixed(&mut *zero))); + on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } #[story(Rulers<'static>, covers = [Invalid], drive = Drive::Custom(drag_corner))] @@ -116,10 +112,9 @@ fn zero_point_left_of_the_document(ui: &mut Ui, data: &mut StoryData) -> StoryOu let settings = settings(data); let zero = data.value("zero", Point::new(LEAST_X - 1.0, 0.0)); let room = stage(ui); - let canvas = rulers_canvas(room, ui.pixels_per_point(), *zero, settings); - on_canvas_with(ui, room, canvas, Some(&StoryDocument::STANDARD), |ui, at| { - let inside = - |zero: &Point| if zero.x < LEAST_X { Validity::Refuse(Message::new("The zero point is left of the document")) } else { Validity::Ok }; - configured(Rulers::new("Rulers", Bind::bound(&mut *zero).check(inside)), settings).show_at(ui, at) - }) + let at = *zero; + let inside = + |zero: &Point| if zero.x < LEAST_X { Validity::Refuse(Message::new("The zero point is left of the document")) } else { Validity::Ok }; + let canvas = rulers_canvas(room, ui.pixels_per_point(), at, settings, Rulers::new("Rulers", Bind::bound(&mut *zero).check(inside))); + on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD)) } diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index fbf32a377..be491c572 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -356,6 +356,28 @@ impl EnvValue for InCanvas { } } +/// The env value that carries the guide a drag out of the canvas's rulers is placing in this pass. +#[derive(Clone, Copy, Debug, PartialEq)] +struct InRulerGuide(Option); + +impl EnvValue for InRulerGuide { + fn root() -> Self { + InRulerGuide(None) + } +} + +/// Publishes the ruler guide of this pass (or none) to a canvas's body. +pub(super) fn publish_ruler_guide(values: &mut AppValues, guide: Option) { + values.set(InRulerGuide(guide)); +} + +/// The guide a drag out of the rulers of the innermost `Canvas` around the component is placing in this pass, as the +/// rulers report it ([`RulersOutput::guide`](super::RulersOutput::guide)); `Guides` shows and commits it. `None` +/// outside a canvas, when the canvas shows no rulers, and while no drag runs. +pub fn ruler_guide(env: &EnvView<'_>) -> Option { + env.get::().0 +} + /// Publishes `space` (or none) to a canvas's body. pub(super) fn publish(values: &mut AppValues, space: Option) { values.set(InCanvas(space)); diff --git a/crates/ui-canvas/src/canvas/testing/canvas_story.rs b/crates/ui-canvas/src/canvas/testing/canvas_story.rs index d8eb337ac..5ed679788 100644 --- a/crates/ui-canvas/src/canvas/testing/canvas_story.rs +++ b/crates/ui-canvas/src/canvas/testing/canvas_story.rs @@ -167,6 +167,17 @@ pub fn on_canvas_with>( shown.inner.map(Into::into).unwrap_or_default() } +/// Shows `canvas`, which shows its own rulers ([`Canvas::with_rulers`]), over `room` and `document` as +/// [`on_canvas_with`] does, with no control in its body, and returns what the rulers reported. +pub fn on_ruled_canvas(ui: &mut Ui, room: Rect, canvas: Canvas<'_>, document: Option<&dyn RasterSource>) -> StoryOutput { + let shown = canvas.show_at(ui, room, |ui, body| { + if let Some(document) = document { + show_document(ui, body.rect, document); + } + }); + shown.output.rulers.map(Into::into).unwrap_or_default() +} + /// Shows `document` on the story document's ground ([`on_ground`]) at the canvas rect `at`, in the body of a canvas /// with a view, under the canvas controls shown after it. pub fn show_document(ui: &mut Ui, at: Rect, document: &dyn RasterSource) { diff --git a/crates/ui-canvas/src/canvas/testing/tool_fixture.rs b/crates/ui-canvas/src/canvas/testing/tool_fixture.rs index 70193ef42..d3a23a5d7 100644 --- a/crates/ui-canvas/src/canvas/testing/tool_fixture.rs +++ b/crates/ui-canvas/src/canvas/testing/tool_fixture.rs @@ -1,11 +1,11 @@ //! `ToolFixture` (22.4, the tool row): drives a [`CanvasTool`] on a [`Canvas`] through press, drag, release and //! Escape, and checks what every tool owes the canvas. -use crate::canvas::{Canvas, CanvasTool, Snap, ToolHost, ToolPath, tool_pass}; -use crate::contract::{BodyCx, Props as _, ShowContainer as _}; +use crate::canvas::{Canvas, CanvasTool, Rulers, Snap, ToolHost, ToolPath, tool_pass}; +use crate::contract::{Bind, BodyCx, Props as _, ShowContainer as _}; use crate::runtime::access::Role; use crate::testing::{Fixture, Target, pointer}; -use craft_behavior::kurbo::Size; +use craft_behavior::kurbo::{Point, Size}; use craft_behavior::{CanvasView, GesturePhase}; use egui::{Event, Id, Key, Modifiers, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, Ref, RefCell, RefMut}; @@ -45,7 +45,7 @@ impl ToolFixture { /// A canvas named `label` whose body `body` fills: canvas controls shown at the body's rect join the canvas's /// arena, and a press on one of their parts never reaches the tool. pub fn with_body(label: &'static str, tool: T, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static) -> Self { - Self::shown(label, tool, None, None, body) + Self::shown(label, tool, None, None, None, body) } /// [`ToolFixture::with_body`] over a canvas given the view `view` makes of the canvas's room, so the body's @@ -56,7 +56,7 @@ impl ToolFixture { view: impl Fn(Rect) -> CanvasView + 'static, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, ) -> Self { - Self::shown(label, tool, Some(Box::new(view)), None, body) + Self::shown(label, tool, Some(Box::new(view)), None, None, body) } /// [`ToolFixture::with_view`] over a canvas that snaps with `snap` ([`Canvas::snap`]): the tool's @@ -68,7 +68,21 @@ impl ToolFixture { snap: Snap, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, ) -> Self { - Self::shown(label, tool, Some(Box::new(view)), Some(snap), body) + Self::shown(label, tool, Some(Box::new(view)), Some(snap), None, body) + } + + /// [`ToolFixture::with_snap`] over a canvas that shows rulers whose zero point is `zero` + /// ([`Canvas::with_rulers`]): the body is the view inside the strips, and the guide a drag out of a strip places + /// reaches the body's controls through [`ruler_guide`](crate::canvas::ruler_guide). + pub fn with_rulers( + label: &'static str, + tool: T, + view: impl Fn(Rect) -> CanvasView + 'static, + snap: Snap, + zero: Rc>, + body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, + ) -> Self { + Self::shown(label, tool, Some(Box::new(view)), Some(snap), Some(zero), body) } fn shown( @@ -76,6 +90,7 @@ impl ToolFixture { tool: T, view: Option CanvasView>>, snap: Option, + zero: Option>>, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static, ) -> Self { let tool = Rc::new(RefCell::new(tool)); @@ -85,6 +100,7 @@ impl ToolFixture { let (shown, seen, id, on) = (Rc::clone(&tool), Rc::clone(&gestures), Rc::clone(&canvas), Rc::clone(&enabled)); let mut fixture = Fixture::new(move |ui| { // The tool's claims for the pass, asked before the canvas shows, as an app does. + let mut held = zero.as_ref().map(|zero| zero.borrow_mut()); let regions = shown.borrow().regions(); let mut shown_canvas = Canvas::new(label).id(canvas_id(label)).document(DOCUMENT).tool_regions(regions); if let Some(view) = &view { @@ -93,6 +109,9 @@ impl ToolFixture { if let Some(snap) = &snap { shown_canvas = shown_canvas.snap(snap.clone()); } + if let Some(zero) = held.as_mut() { + shown_canvas = shown_canvas.with_rulers(Some(Rulers::new("Rulers", Bind::bound(&mut **zero)))); + } let canvas = shown_canvas.show(ui, |ui, body_cx| { body(ui, body_cx); if let Some(pass) = tool_pass(&body_cx.env) { diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index 573c1f353..960c3f9ec 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -613,7 +613,7 @@ impl<'m> ToolHost<'m> { }; paint_tool(ui, &env, effective, context()); if pass.snap.as_ref().is_some_and(|snap| snap.options().smart_guides) { - paint_smart_lines(ui, &env, rect, space, &requests.snapped, smart_guide_color); + paint_smart_lines(ui, &env, space, &requests.snapped, smart_guide_color); } response.snapped = requests.snapped; let cx = context(); @@ -789,9 +789,9 @@ fn sub_decl(owner: Id, node: &SubNode, rect: Rect, parent: Id) -> SubDecl<'_> { SubDecl { owner, component: "", node, rect, enabled: true, focusable: false, clickable: false, active: false, face: None, label: "", parent } } -/// Paints the tool over the canvas, clipped to it. +/// Paints the tool over the canvas, under the clip of the body it runs in: the canvas's view. fn paint_tool(ui: &Ui, env: &Env, tool: &dyn CanvasTool, cx: ToolContext<'_>) { - let painter = ui.painter().with_clip_rect(cx.rect); + let painter = ui.painter().clone(); let record = RefCell::new(PaintRecord::default()); let draw = Draw::new(&painter, &record, DrawEnv { tokens: &env.tokens, direction: env.direction, ink: env.ink }); let content = ContentPainterCx::new(painter.clone(), env, env.ink); @@ -818,13 +818,13 @@ fn host_style<'a>(ui: &'a Ui, env: &'a Env) -> StyleCx<'a> { /// Paints the smart kinds of the snap `lines` over the canvas through the smart guides' one line loop, in `color` or /// the theme's smart guide colour. `SmartGuides` itself paints only inside a canvas body, which the host is not in. -fn paint_smart_lines(ui: &Ui, env: &Env, rect: Rect, space: Option, lines: &[SnapLine], color: Option) { +fn paint_smart_lines(ui: &Ui, env: &Env, space: Option, lines: &[SnapLine], color: Option) { let Some(space) = space else { return }; let smart: Vec = lines.iter().filter(|line| line.kind.is_smart()).map(|line| SmartLine::of(line, space.view.visible())).collect(); if smart.is_empty() { return; } - let content = ContentPainterCx::new(ui.painter().with_clip_rect(rect), env, env.ink); + let content = ContentPainterCx::new(ui.painter().clone(), env, env.ink); let style = resolve_style(&host_style(ui, env), SmartGuides::new(&[], &[]).style_key(), ui.ctx(), as Component>::style); paint_lines(&content, &space.view, &smart, &style, color); } diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index 36be120da..7918af4a4 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -11,6 +11,7 @@ pub use reading::GuideReading; use super::words::CanvasControlWords; use crate::canvas::{ CanvasSpace, Guide, GuideDrag, GuideKey, GuideLine, LABEL_STEP_MIN, NUDGE, NUDGE_FAR, Snap, canvas_snap, canvas_space, context_menu, readout, + ruler_guide, }; use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Numeric, Outcome, PaintUi, PartsCx, @@ -136,8 +137,8 @@ struct HeldGuide; /// (one that reaches the canvas's tool) clears the selection, reported as `Some(None)`. /// - The units, the zero point and the ruler a guide is placed in come from the canvas /// ([`Canvas::rulers`](crate::canvas::Canvas::rulers)). -/// - [`pending`](Guides::pending) shows the guide a ruler drag is creating. Show the `Rulers` before the guides in -/// the canvas body: the guides read the drag the rulers reported in the same pass. +/// - The guide a ruler drag is creating shows and commits through [`ruler_guide`](crate::canvas::ruler_guide): the canvas +/// shows its rulers before its body and publishes the drag they reported in the same pass. /// - While a drag moves or creates a guide, [`running`](reading::running) reads that guide's axis and position by the canvas id, from /// the note the drag sets on its gesture. #[derive(crate::contract::Component, crate::contract::Props)] @@ -165,9 +166,6 @@ pub struct Guides<'a> { /// The distance an arrow key moves a guide with Shift held, in document units. #[prop(quantity = "document units")] big_step: f64, - /// The guide a ruler is creating, as the rulers report it in this pass (`RulersOutput::guide`); not set, none shows. - #[prop] - pending: Option, report: Report, } @@ -191,7 +189,6 @@ impl<'a> Guides<'a> { bounds: None, step: NUDGE, big_step: NUDGE_FAR, - pending: None, report: Report::default(), } .label(label) @@ -507,7 +504,7 @@ impl Component for Guides<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; let guides = cx.value().cloned().unwrap_or_default(); - if let Some(drag) = self.pending { + if let Some(drag) = ruler_guide(&cx.env) { self.run_pending(cx, &space, &guides, drag); } // `parts` declares the guides only when the pointer may take them, and `run_pointer` reads declared parts only. diff --git a/crates/ui-canvas/src/canvas_controls/guides/stories.rs b/crates/ui-canvas/src/canvas_controls/guides/stories.rs index a87e3c15c..652837f89 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/stories.rs @@ -2,13 +2,12 @@ use super::{GUIDE, Guides, GuidesOutput}; use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with, story_view}; -use crate::canvas::{Canvas, Guide, GuideDrag, GuideKey, GuideLine, RasterSource}; +use crate::canvas::{Canvas, Guide, GuideKey, GuideLine, RasterSource}; use crate::contract::{Bind, Props as _, Show as _, Validity}; use crate::runtime::env::Message; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, stage, story}; use craft_behavior::kurbo::{Point, Rect as DocRect}; -use craft_behavior::{Axis, GesturePhase, Mixed}; -use craft_keymap::Mods; +use craft_behavior::{Axis, Mixed}; use egui::{Id, Rect, Ui, Vec2}; /// The most guides the invalid story accepts. @@ -72,13 +71,6 @@ fn guides_that_only_draw(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, Bind::bound(&mut *guides)).show_at(ui, at)) } -#[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_first))] -fn guide_dragged_out_of_a_ruler(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let guides = data.value("guides", guides()); - let drag = GuideDrag::new_guide(Axis::Y, GesturePhase::Update, Some(200.0), Mods::NONE); - on_guides_canvas(ui, |ui, at, canvas| Guides::new("Guides", canvas, Bind::bound(&mut *guides)).interactive(true).pending(drag).show_at(ui, at)) -} - #[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_first))] fn bounded_guides(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let guides = data.value("guides", guides()); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 95ca61634..f378f315a 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -1,9 +1,20 @@ //! The ruler tick rule (`Rulers::ticks`): labelled ticks stay at least `LABEL_STEP_MIN` apart at every zoom. -use craft_behavior::{RulerUnits, Ticks}; -use craft_ui::canvas::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, Rulers, StepLadder, TickRule}; +use craft_behavior::geometry::{SnapOptions, SnapTargets}; +use craft_behavior::kurbo::{Point, Rect as DocRect}; +use craft_behavior::{CancelReason, CanvasView, RulerUnits, Ticks}; +use craft_ui::canvas::{ + CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, Rulers, Snap, StepLadder, TickRule, ToolAction, ToolContext, + ToolPath, ToolPointer, +}; +use craft_ui::contract::Show as _; use craft_ui::primitives::TickRank; -use craft_ui::testing::trial; +use craft_ui::primitives::{Draw, PaintShape}; +use craft_ui::style::StyleColor; +use craft_ui::testing::{ToolFixture, trial}; +use egui::{Color32, CornerRadius, Rect, Shape, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; /// Screen points per document unit, from far out to deep in. const ZOOMS: [f64; 10] = [0.01, 0.0625, 0.25, 1.0 / 3.0, 1.0, 3.7, 16.0, 64.0, 320.0, 3200.0]; @@ -57,3 +68,63 @@ fn a_five_character_vertical_label_fits_the_least_label_step() { assert!(5.0 * pitch + tokens.space.gap.tight < LABEL_STEP_MIN, "{mode:?}: five characters at pitch {pitch}"); } } + +/// How far past the canvas the tool's fill and the marquee reach. +const PAST: f32 = 60.0; + +/// A tool that paints past the canvas's rect. +struct Overpaint; + +impl CanvasTool for Overpaint { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { + draw.fill(&PaintShape::Rect(cx.rect.expand(PAST), CornerRadius::ZERO), StyleColor(Color32::RED)); + } + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Select Area... command") + } +} + +// With rulers on, what the body shows (the tool's paint and a canvas control) is clipped to the view inside the +// strips; the rulers keep the canvas rect. +#[trial] +fn with_rulers_on_the_tool_and_a_canvas_control_paint_inside_the_view_and_the_rulers_keep_the_canvas() { + let zero = Rc::new(RefCell::new(Point::ZERO)); + let view = |room: Rect| CanvasView::new(room, Point::new(f64::from(room.center().x), f64::from(room.center().y)), 1.0); + let snap = Snap::new(std::sync::Arc::new(SnapTargets::new()), SnapOptions::default()); + let mut fixture = ToolFixture::with_rulers("Document", Overpaint, view, snap, zero, |ui, body| { + let pages = [PageFrame::new(DocRect::new(-f64::from(PAST), -f64::from(PAST), 500.0 + f64::from(PAST), 400.0 + f64::from(PAST)))]; + let _ = Pasteboard::new("Pasteboard", &pages).show_at(ui, body.rect); + }); + fixture.fixture().room(Vec2::new(500.0, 400.0)).settle(); + let canvas = fixture.canvas().rect; + let shapes = fixture.fixture().frame_clipped_shapes(); + let past = |shape: &Shape| { + let bounds = shape.visual_bounding_rect(); + bounds.is_finite() && !canvas.expand(PAST / 2.0).contains_rect(bounds) + }; + let overflowing: Vec<&(Rect, Shape)> = shapes.iter().filter(|(_, shape)| past(shape)).collect(); + // The tool's fill and the marquee's outline reach past the canvas; the strips and the surface do not. + assert!(overflowing.len() >= 2, "the tool and the pasteboard paint past the canvas: {overflowing:?}"); + let strip = fixture.fixture().shape_bounds().first().copied(); + let _ = strip; + for (clip, shape) in overflowing { + assert!( + clip.min.x > canvas.min.x && clip.min.y > canvas.min.y && canvas.contains_rect(*clip), + "past the canvas, a shape paints inside the view, past the strips: clip {clip:?} in {canvas:?} for {shape:?}" + ); + } + let strips_keep_the_canvas = + shapes.iter().any(|(clip, shape)| matches!(shape, Shape::Rect(rect) if rect.rect.min == canvas.min) && *clip == canvas); + assert!(strips_keep_the_canvas, "the rulers' corner paints under the canvas's rect: {shapes:?}"); +} diff --git a/crates/ui-canvas/tests/it/canvas_controls/guides.rs b/crates/ui-canvas/tests/it/canvas_controls/guides.rs index 1b5441081..b23c3ae79 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/guides.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/guides.rs @@ -3,7 +3,7 @@ use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_behavior::{Axis, CancelReason, CanvasView}; -use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Rulers, Snap, ToolAction, ToolContext, ToolPath, ToolPointer}; +use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Snap, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft_ui::canvas_controls::Guides; use craft_ui::canvas_controls::reading::{GuideReading, running}; use craft_ui::contract::{Bind, BodyCx, Show as _}; @@ -136,29 +136,30 @@ fn the_running_guide_reading_follows_the_drag_and_goes_when_it_ends() { /// Where guides may live, in document units. const BOUNDS: DocRect = DocRect::new(100.0, 100.0, 600.0, 400.0); -/// A canvas at `zoom` that snaps to horizontal guide targets at y = 224.3 and y = 250.3, its body showing rulers and -/// interactive guides kept inside [`BOUNDS`], in a room that holds the bounds with a margin, so a release outside them -/// still lands on the canvas; the body's rect, read each pass. -fn ruled(zoom: f64, guides: &Shared>) -> (ToolFixture, Rc>) { +/// A canvas at `zoom` that snaps to horizontal guide targets at y = 224.3 and y = 250.3, its rulers shown by the canvas and its body +/// showing interactive guides kept inside [`BOUNDS`], in a room that holds the bounds with a margin, so a release outside them +/// still lands on the canvas. +fn ruled(zoom: f64, guides: &Shared>) -> ToolFixture { let mut targets = SnapTargets::new(); targets.add(SnapTarget::new(Axis::X, 224.3, SnapKind::Guide)); targets.add(SnapTarget::new(Axis::X, 250.3, SnapKind::Guide)); let snap = Snap::new(Arc::new(targets), SnapOptions::default()); let (shown, zero) = (Rc::clone(guides), Rc::new(RefCell::new(Point::ZERO))); - let body = Rc::new(Cell::new(Rect::NOTHING)); - let seen = Rc::clone(&body); - let mut fixture = ToolFixture::with_snap("Document", Recorder::default(), view_at(zoom), snap, move |ui, cx| { - seen.set(cx.rect); - let rulers = Rulers::new("Rulers", Bind::bound(&mut *zero.borrow_mut())).show_at(ui, cx.rect); + // The view lies inside the strips: it keeps the document point under the screen point it was given, so at zoom 1 + // document and screen points coincide, from the second pass on (the strips' inset is the first pass's body). + let inset = Rc::new(Cell::new(Vec2::ZERO)); + let moved = Rc::clone(&inset); + let view = move |room: Rect| { + let centre = room.center() + inset.get() / 2.0; + CanvasView::new(room, Point::new(f64::from(centre.x), f64::from(centre.y)), zoom) + }; + let mut fixture = ToolFixture::with_rulers("Document", Recorder::default(), view, snap, zero, move |ui, cx| { + moved.set(cx.rect.min.to_vec2()); let mut guides = shown.borrow_mut(); - let mut control = Guides::new("Guides", canvas_of(cx), Bind::bound(&mut *guides)).interactive(true).bounds(BOUNDS); - if let Some(drag) = rulers.guide { - control = control.pending(drag); - } - let _ = control.show_at(ui, cx.rect); + let _ = Guides::new("Guides", canvas_of(cx), Bind::bound(&mut *guides)).interactive(true).bounds(BOUNDS).show_at(ui, cx.rect); }); fixture.fixture().room(Vec2::new(700.0, 500.0)).settle(); - (fixture, body) + fixture } /// A drag with `mods` held from `from` to `to`. @@ -176,8 +177,8 @@ fn drag_with(fixture: &mut ToolFixture, mods: Modifiers, from: Pos2, t #[trial] fn a_dragged_guide_is_removed_off_the_bounds_or_on_a_ruler_and_alt_and_shift_change_where_it_lands() { let guides: Shared> = Rc::new(RefCell::new(Vec::new())); - let (mut fixture, body) = ruled(1.0, &guides); - let rect = body.get(); + let mut fixture = ruled(1.0, &guides); + let rect = fixture.canvas().rect; // Inside the top strip, clear of the corner, and inside the left strip. let top = |x: f32| pos2(x, rect.min.y + 4.0); let left = |y: f32| pos2(rect.min.x + 4.0, y); @@ -219,8 +220,8 @@ fn a_dragged_guide_is_removed_off_the_bounds_or_on_a_ruler_and_alt_and_shift_cha assert_eq!(guides.borrow().len(), count - 1); let deep: Shared> = Rc::new(RefCell::new(Vec::new())); - let (mut fixture, body) = ruled(8.0, &deep); - let rect = body.get(); + let mut fixture = ruled(8.0, &deep); + let rect = fixture.canvas().rect; let centre = rect.center(); drag_with(&mut fixture, Modifiers::SHIFT, pos2(centre.x, rect.min.y + 4.0), centre + Vec2::new(0.0, 13.0)); let landed: Vec = deep.borrow().iter().map(|guide| guide.position).collect(); diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 99ad64759..4ba7bce7b 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -920,6 +920,8 @@ struct BodyRun<'r> { env: &'r Env, /// While the body opens or closes, it shows only the part of its last height that the presence reaches. reveal_clip: Option, + /// The body shows through a view of its own (`ContainerProps::scroll_owner`): its region is its clip. + view_clip: bool, } /// The region a scrolling body's content runs in, and what its run reads after the content. @@ -953,6 +955,9 @@ fn body_ui(run: &BodyRun<'_>, parent: &mut Ui, at: Rect) -> Ui { if let Some(clip) = run.reveal_clip { body_ui.set_clip_rect(clip.intersect(body_ui.clip_rect())); } + if run.view_clip { + body_ui.set_clip_rect(at.intersect(body_ui.clip_rect())); + } body_ui } @@ -1250,6 +1255,7 @@ impl BodyHooks<'_> { columns: LabelColumns::of(props, !self.wide() && !self.held(props, env)), env: body_env, reveal_clip, + view_clip: props.scroll_owner, }; let body_rect = plan.body_rect; let share = plan.share(false); diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index c996143d6..0dbe72d3c 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -759,7 +759,8 @@ pub struct ContainerProps { pub arena: bool, /// The container is its body's scroll owner without a scroll region, as a canvas with a view of its own is: the /// page and end moves and the reveals its children leave go to it (`Focus::take_scroll_moves`, - /// `Focus::take_reveal`). A container with a `scroll` region is one already. + /// `Focus::take_reveal`). A container with a `scroll` region is one already. The body is clipped to its body + /// region, the view, so what it shows never paints over the container's padding (a canvas's rulers). pub scroll_owner: bool, /// The container's value is a gate that disables its content while off. #[doc(hidden)] diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 5065b8d83..1469cd499 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -433,6 +433,20 @@ impl Fixture { self.frame_shapes_with(Vec::new()) } + /// One frame with no events; returns the shapes it painted, nested shapes flattened, each with the clip it paints under. + pub fn frame_clipped_shapes(&mut self) -> Vec<(Rect, egui::Shape)> { + self.frames.record_paint(); + self.frame(Vec::new()); + let mut out = Vec::new(); + let Some(paint) = self.frames.take_paint() else { return out }; + for clipped in paint.shapes { + let mut shapes = Vec::new(); + fixture::flatten(clipped.shape, &mut shapes); + out.extend(shapes.into_iter().map(|shape| (clipped.clip_rect, shape))); + } + out + } + /// One frame with `events`; returns the shapes it painted, nested shapes flattened. What the frame that took the /// input paints, not the one after it. pub fn frame_shapes_with(&mut self, events: Vec) -> Vec { diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index 7fad69c94..fe2eef059 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -214,32 +214,21 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) { // What the host reported; none in a measuring run, where it does not run. let mut reported = None; let mut scrolled = None; - let _ = Canvas::new("Document").id(canvas_id).view(view).document(page.size()).show_rulers(show_rulers).rulers(units, units, document.zero).show( + let mut zero = document.zero; + let strips = show_rulers.then(|| Rulers::new("Rulers", Bind::bound(&mut zero)).units(&UNITS)); + let shown = Canvas::new("Document").id(canvas_id).view(view).document(page.size()).with_rulers(strips).rulers(units, units, document.zero).show( ui, |ui, body| { let _ = Pasteboard::new("Pasteboard", &pages).show_at(ui, body.rect); - let mut content = body.rect; - let mut pending = None; - let Document { guides, guide, zero, units: unit, .. } = &mut *document; - if show_rulers { - let rulers = Rulers::new("Rulers", Bind::bound(zero)).units(&UNITS).show_at(ui, body.rect); - content = rulers.content_rect(); - pending = rulers.guide; - if let Some(picked) = rulers.unit_picked { - *unit = picked; - } - } + let Document { guides, guide, .. } = &mut *document; let mut controls = Guides::new("Guides", canvas_id, Bind::bound(guides)).interactive(editing); if let Some(selected) = *guide { controls = controls.selected_guide(selected); } - if let Some(drag) = pending { - controls = controls.pending(drag); - } if let Some(select) = controls.show_at(ui, body.rect).select { *guide = select; } - let bars = CanvasScrollbars::new("Scroll bars", Bind::given(view), page).show_at(ui, content); + let bars = CanvasScrollbars::new("Scroll bars", Bind::given(view), page).show_at(ui, body.rect); scrolled = bars.view.value().copied(); // The tool runs after the controls, which take a press first, and before the picture and the selection, // which show what it did with this pass's input. The tool leaves the press alone over a scroll bar. @@ -259,6 +248,10 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) { } }, ); + if let Some(picked) = shown.output.rulers.and_then(|rulers| rulers.unit_picked) { + document.units = picked; + } + document.zero = zero; let reported: craft_ui::canvas::ToolHostResponse = reported.unwrap_or_default(); if let Some(next) = scrolled.or(reported.view) { document.view = next; diff --git a/crates/ui/tests/it/canvas/document_canvas.rs b/crates/ui/tests/it/canvas/document_canvas.rs index d0733315d..c25119937 100644 --- a/crates/ui/tests/it/canvas/document_canvas.rs +++ b/crates/ui/tests/it/canvas/document_canvas.rs @@ -3,7 +3,7 @@ use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Size}; -use craft_ui::canvas::{Canvas, HandTool, NavigationOptions, ToolHost, canvas_space, tool_pass}; +use craft_ui::canvas::{Canvas, HandTool, NavigationOptions, Rulers, ToolHost, canvas_space, tool_pass}; use craft_ui::contract::{Bind, ShowContainer as _}; use craft_ui::patterns::canvas::NavigatorPanel; use craft_ui::testing::{Fixture, trial}; @@ -49,10 +49,13 @@ impl Document { } let given = *held.borrow(); let mut hosted = None; - let shown = Canvas::new("Document").view(given).document(DOC).navigation(navigation).show_rulers(ruled.get()).show_at( - ui, - at.get(), - |ui, body| { + let mut zero = Point::ZERO; + let shown = Canvas::new("Document") + .view(given) + .document(DOC) + .navigation(navigation) + .with_rulers(ruled.get().then(|| Rulers::new("Rulers", Bind::bound(&mut zero)))) + .show_at(ui, at.get(), |ui, body| { if let Some(space) = canvas_space(&body.env) { saw.borrow_mut().push((body.rect, space.view)); } @@ -61,8 +64,7 @@ impl Document { { hosted = Some(ToolHost::new().run(ui, &pass, &mut hand)); } - }, - ); + }); let next = hosted.and_then(|hosted| hosted.view).or(shown.output.view); if let Some(next) = next { *held.borrow_mut() = next; @@ -77,9 +79,10 @@ impl Document { } } -/// `view.rect` lies in `body` past the rulers along the top and left edges, out to the body's far corner. -fn inside_the_rulers(body: Rect, view: CanvasView) -> bool { - body.contains_rect(view.rect) && view.rect.min.x > body.min.x && view.rect.min.y > body.min.y && view.rect.max == body.max +/// The body is the view, which lies in `canvas` past the rulers along the top and left edges, out to the canvas's far +/// corner. +fn inside_the_rulers(canvas: Rect, body: Rect, view: CanvasView) -> bool { + body == view.rect && canvas.contains_rect(body) && body.min.x > canvas.min.x && body.min.y > canvas.min.y && body.max == canvas.max } #[trial] @@ -89,17 +92,17 @@ fn the_body_reads_this_passes_rect_inside_the_rulers_while_they_show() { document.rulers.set(true); document.fixture.frame(Vec::new()); let (body, first) = *document.seen.borrow().first().expect("the body ran in the first pass"); - assert!(inside_the_rulers(body, first), "the first pass's view lies inside the rulers: {:?} in {body:?}", first.rect); + assert!(inside_the_rulers(CANVAS, body, first), "the first pass's view lies inside the rulers: {:?} in {body:?}", first.rect); let wider = Rect::from_min_max(CANVAS.min, CANVAS.max + Vec2::new(200.0, 100.0)); document.rect.set(wider); document.fixture.frame(Vec::new()); let (body, after) = document.last_seen(); assert_eq!(body.max, wider.max, "the canvas took its new rect"); - assert!(inside_the_rulers(body, after), "the pass after a resize carries the new rect: {:?} in {body:?}", after.rect); + assert!(inside_the_rulers(wider, body, after), "the pass after a resize carries the new rect: {:?} in {body:?}", after.rect); document.rulers.set(false); document.fixture.frame(Vec::new()); let (body, plain) = document.last_seen(); - assert_eq!(plain.rect, body, "with the rulers off the view takes the canvas's whole rect"); + assert_eq!((plain.rect, body), (wider, wider), "with the rulers off the view takes the canvas's whole rect"); }