Merge pull request #2470 from aiongg/canvas-view-clip

Clip a canvas's body to its view; the canvas shows its rulers
This commit is contained in:
aiongg
2026-11-19 23:24:05 -05:00
committed by GitHub
20 changed files with 368 additions and 152 deletions
+1 -1
View File
@@ -160,7 +160,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
canvas = canvas.snap(snap);
}
if let Some(ruler) = config.rulers {
canvas = canvas.rulers(ruler, ruler, Point::ZERO);
canvas = canvas.rulers(ruler, ruler);
}
let canvas = canvas.show(ui, |ui, body| {
let mut guide_edits = 0;
+2 -2
View File
@@ -475,9 +475,9 @@ 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 strips = Rulers::new("Rulers", Bind::bound(&mut *zero));
let shown = Canvas::new("Document").id(canvas).view(*view).rulers(text, text).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));
}
+53 -21
View File
@@ -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<Rulers<'a>>,
/// 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<RulersOutput>,
/// 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).
@@ -198,6 +205,8 @@ pub struct Canvas<'a> {
keys_to_body: bool,
/// The rulers' units and zero point, published to the body in its [`CanvasSpace`].
rulers: Option<CanvasRulers>,
/// The zero point of the rulers given to `with_rulers`, which the space publishes in `rulers`.
ruler_zero: Point,
/// The snapping of the coordinates the pointer sets on this canvas (View > Snap To), as data over the document's
/// targets: the rulers snap their zero point with it, the guides snap a guide with it and the tool host hands it to
/// the tool ([`ToolContext::snap`]). The canvas sets its tolerance each pass from the view it shows. Without it
@@ -272,11 +281,14 @@ 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,
rulers: None,
ruler_zero: Point::ZERO,
snap: None,
settled: None,
context_key: false,
@@ -294,7 +306,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 +391,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 +400,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,13 +491,25 @@ impl<'a> Canvas<'a> {
Settled { target, shown, easing, keys }
}
/// 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).
/// 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 rulers(mut self, x: RulerText, y: RulerText, zero: Point) -> Self {
self.rulers = Some(CanvasRulers::new(x, y, zero));
pub fn with_rulers(mut self, rulers: Option<Rulers<'a>>) -> Self {
self.ruler_zero = rulers.as_ref().map_or(Point::ZERO, Rulers::zero);
self.strips_shown = rulers.is_some();
self.strips = rulers;
self
}
/// Measures the document's axes in `x` and `y`, counted from the zero point of the [`Rulers`] given to
/// [`with_rulers`](Self::with_rulers) (the document's origin without them). 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 the zero
/// 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 [`with_rulers`](Self::with_rulers).
#[must_use]
pub fn rulers(mut self, x: RulerText, y: RulerText) -> Self {
self.rulers = Some(CanvasRulers::new(x, y, Point::ZERO));
self
}
@@ -508,7 +527,7 @@ impl<'a> Canvas<'a> {
let space = space
.with_keys(keys)
.with_document(self.document_size())
.with_rulers(self.rulers)
.with_rulers(self.rulers.map(|rulers| CanvasRulers::new(rulers.x, rulers.y, self.ruler_zero)))
.with_pasteboard(self.pasteboard)
.with_background(background)
.with_precise(self.precise_cursors != caps_lock)
@@ -583,6 +602,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<CanvasView>,
/// What the rulers given to [`Canvas::with_rulers`] reported in this pass.
pub rulers: Option<RulersOutput>,
}
impl CanvasOutput {
@@ -655,9 +676,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 +720,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 +755,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 }
}
}
+36 -16
View File
@@ -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,14 @@ 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
/// Rulers show only through [`Canvas::with_rulers`](super::Canvas::with_rulers): the canvas hands them its space and
/// snap, and shown anywhere else they take no input.
///
/// - 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,14 +212,17 @@ 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<CanvasSpace>,
snap: Option<Snap>,
guide: Option<GuideDrag>,
picked: Option<UnitKind>,
context: Option<RulerPart>,
}
impl<'a> Rulers<'a> {
/// Rulers named `label` that edit the zero point `zero` (document units). The units and the zero they count from
/// are the canvas's ([`Canvas::rulers`](super::Canvas::rulers)); the app passes the same zero to both.
/// Rulers named `label` that edit the zero point `zero` (document units). The canvas reads its zero from here;
/// the units are the canvas's ([`Canvas::rulers`](super::Canvas::rulers)).
pub fn new(label: impl Into<Label>, zero: Bind<'a, Point>) -> Self {
Rulers {
common: Common::new(),
@@ -225,6 +231,8 @@ impl<'a> Rulers<'a> {
interactive: true,
margins: RulerMargins::default(),
units: None,
space: None,
snap: None,
guide: None,
picked: None,
context: None,
@@ -245,13 +253,25 @@ impl<'a> Rulers<'a> {
ticks::ticks(units, rule, zoom, values)
}
/// The zero point the binding holds, which the canvas publishes in its space.
pub(super) fn zero(&self) -> Point {
Self::zero_of(self.zero.value())
}
fn zero_of(value: Option<&Point>) -> Point {
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<CanvasSpace>, snap: Option<Snap>) -> 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 +374,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 +400,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 +422,7 @@ impl Component for Rulers<'_> {
}
PressPhase::Drag { pos, .. } => {
let start = cx.press_slot::<Point>().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 +460,7 @@ impl Component for Rulers<'_> {
let popup = cx.popup("menu");
let numbers = cx.env.units();
let words = cx.words::<CanvasWords>();
let shown = Self::published(&cx.env).x.kind;
let shown = self.published().x.kind;
let mut entries: Vec<Entry<MenuRow>> =
units.iter().map(|&kind| Entry::new(MenuRow::Unit(kind), Label::from(numbers.symbol(kind))).checked(kind == shown)).collect();
entries.push(Entry::separator());
@@ -461,7 +481,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));
+15 -23
View File
@@ -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 their zero in pixels.
fn rulers_canvas<'a>(room: Rect, pixels_per_point: f32, 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)
}
#[story(Rulers<'static>, covers = [Default], drive = Drive::Custom(drag_corner))]
@@ -83,10 +83,8 @@ 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 canvas = rulers_canvas(room, ui.pixels_per_point(), 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 +92,8 @@ 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 canvas = rulers_canvas(room, ui.pixels_per_point(), 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 +101,8 @@ fn zero_points_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let settings = settings(data);
let zero = data.value("zero", Mixed::<Point>::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(), 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 +110,8 @@ 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 inside =
|zero: &Point| if zero.x < LEAST_X { Validity::Refuse(Message::new("The zero point is left of the document")) } else { Validity::Ok };
let canvas = rulers_canvas(room, ui.pixels_per_point(), settings, Rulers::new("Rulers", Bind::bound(&mut *zero).check(inside)));
on_ruled_canvas(ui, room, canvas, Some(&StoryDocument::STANDARD))
}
+22
View File
@@ -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<super::GuideDrag>);
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<super::GuideDrag>) {
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<super::GuideDrag> {
env.get::<InRulerGuide>().0
}
/// Publishes `space` (or none) to a canvas's body.
pub(super) fn publish(values: &mut AppValues, space: Option<CanvasSpace>) {
values.set(InCanvas(space));
@@ -167,6 +167,17 @@ pub fn on_canvas_with<R: Into<StoryOutput>>(
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) {
@@ -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<T: CanvasTool + 'static> ToolFixture<T> {
/// 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<T: CanvasTool + 'static> ToolFixture<T> {
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<T: CanvasTool + 'static> ToolFixture<T> {
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<RefCell<Point>>,
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<T: CanvasTool + 'static> ToolFixture<T> {
tool: T,
view: Option<Box<dyn Fn(Rect) -> CanvasView>>,
snap: Option<Snap>,
zero: Option<Rc<RefCell<Point>>>,
mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'static,
) -> Self {
let tool = Rc::new(RefCell::new(tool));
@@ -85,6 +100,7 @@ impl<T: CanvasTool + 'static> ToolFixture<T> {
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<T: CanvasTool + 'static> ToolFixture<T> {
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) {
+5 -5
View File
@@ -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();
@@ -791,9 +791,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);
@@ -820,13 +820,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<CanvasSpace>, lines: &[SnapLine], color: Option<DataColor>) {
fn paint_smart_lines(ui: &Ui, env: &Env, space: Option<CanvasSpace>, lines: &[SnapLine], color: Option<DataColor>) {
let Some(space) = space else { return };
let smart: Vec<SmartLine> = 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(), <SmartGuides<'static> as Component>::style);
paint_lines(&content, &space.view, &smart, &style, color);
}
@@ -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<GuideDrag>,
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.
@@ -1,14 +1,13 @@
//! Stories of `Guides`.
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::contract::{Bind, Props as _, Show as _, Validity};
use crate::runtime::env::Message;
use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_with, show_document, story_view};
use crate::canvas::{Canvas, Guide, GuideKey, GuideLine, RasterSource, RulerText, Rulers};
use crate::contract::{Bind, Props as _, Role, Show as _, ShowContainer as _, Validity};
use crate::runtime::env::{Message, UnitKind};
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, RulerUnits};
use egui::{Id, Rect, Ui, Vec2};
/// The most guides the invalid story accepts.
@@ -43,6 +42,35 @@ fn drag_first(fixture: &mut Fixture) {
fixture.drag(&line, Vec2::new(travel, 0.0));
}
/// Drags a guide out of the top ruler's strip onto the document.
fn drag_out_of_the_top_ruler(fixture: &mut Fixture) {
let Some(canvas) = fixture.by_role(Role::CANVAS).first().map(|target| target.rect) else { return };
// Inside the top strip, clear of the corner.
let from = egui::pos2(canvas.center().x, canvas.min.y + 4.0);
fixture.drag_at(from, Vec2::new(0.0, canvas.height() / 4.0));
}
#[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_out_of_the_top_ruler))]
fn guide_dragged_out_of_a_ruler(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let guides = data.value("guides", guides());
let mut zero = Point::ZERO;
let canvas = ui.scope_id().with("guides story canvas");
let room = stage(ui);
let size = StoryDocument::STANDARD.size();
let centre = Point::new(f64::from(size.width) / 2.0, f64::from(size.height) / 2.0);
let view = story_view(room, ui.pixels_per_point(), centre, 100.0);
let text = RulerText::new(RulerUnits::pixels(), UnitKind::Pixels);
let strips = Rulers::new("Rulers", Bind::bound(&mut zero)).interactive(true);
let shown = Canvas::new("Document").id(canvas).view(view).with_rulers(Some(strips)).rulers(text, text).show_at(ui, room, |ui, body| {
show_document(ui, body.rect, &StoryDocument::STANDARD);
Guides::new("Guides", canvas, Bind::bound(&mut *guides)).interactive(true).show_at(ui, body.rect)
});
let mut output: StoryOutput = shown.inner.map(Into::into).unwrap_or_default();
// A click on a strip is the rulers' to report.
output.clicked |= shown.output.rulers.is_some_and(|rulers| StoryOutput::from(rulers).clicked);
output
}
#[story(Guides<'static>, covers = [Default], drive = Drive::Custom(drag_first))]
fn guides_over_a_canvas(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let guides = data.value("guides", guides());
@@ -72,13 +100,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());
+79 -3
View File
@@ -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,68 @@ 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:?}");
// The view starts where the strips end: the top strip is as thick as the view's clip lies below the canvas's top.
let thickness = overflowing.iter().map(|(clip, _)| clip.min.y - canvas.min.y).fold(f32::INFINITY, f32::min);
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:?}"
);
}
// The canvas's own surface spans the whole rect, so only a shape inside the top strip, under the canvas's rect as
// its clip, comes from the rulers.
let strip = Rect::from_min_max(canvas.min, egui::pos2(canvas.max.x, canvas.min.y + thickness));
let strips_keep_the_canvas = shapes.iter().any(|(clip, shape)| {
let bounds = shape.visual_bounding_rect();
bounds.is_finite() && bounds.width() > 0.0 && strip.expand(1.0).contains_rect(bounds) && clip.contains_rect(strip)
});
assert!(strips_keep_the_canvas, "the rulers paint inside the top strip under the canvas's rect: {strip:?} in {shapes:?}");
}
@@ -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<Vec<Guide>>) -> (ToolFixture<Recorder>, Rc<Cell<Rect>>) {
/// 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<Vec<Guide>>) -> ToolFixture<Recorder> {
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<Recorder>, 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<Vec<Guide>> = 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<Vec<Guide>> = 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<f64> = deep.borrow().iter().map(|guide| guide.position).collect();
@@ -927,6 +927,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<Rect>,
/// 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.
@@ -960,6 +962,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
}
@@ -1257,6 +1262,7 @@ impl BodyHooks<'_> {
columns: LabelColumns::of(props, !self.wide() && !self.held(props, env)),
env: body_env,
reveal_clip,
view_clip: props.scroll_owner && props.transform.is_none(),
};
let body_rect = plan.body_rect;
let share = plan.share(false);
+2 -1
View File
@@ -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)]
+10
View File
@@ -212,6 +212,16 @@ impl<'a, T: Value> Bind<'a, T> {
self.reset.as_ref()
}
/// The one value the binding holds before this pass's edits; `None` for a mixed or kept binding.
pub fn value(&self) -> Option<&T> {
match &self.source {
Source::Given(Mixed::Same(value)) | Source::MutMixed(Mixed::Same(value)) => Some(value),
Source::Mut(value) => Some(&**value),
Source::Tracked { value, .. } => Some(&**value),
_ => None,
}
}
/// The binding holds one value equal to `shown` this pass: what a component reads in `Component::keys`, which has
/// no context to read the value from.
#[doc(hidden)]
+14
View File
@@ -439,6 +439,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<Event>) -> Vec<egui::Shape> {
+11 -20
View File
@@ -214,32 +214,20 @@ 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(
ui,
|ui, body| {
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).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.
@@ -257,8 +245,11 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) {
if let Some(rect) = document.marquee {
let _ = Marquee::rect("Selection", rect).show_at(ui, body.rect);
}
},
);
});
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;
+16 -13
View File
@@ -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");
}
@@ -193,7 +193,7 @@ name = "Document"
old = ""
new = "craft_ui_gallery::mock::Document"
status = "replaced"
note = "The open document of the mock: title, dirty flag, size, layers (top first), the layer selection whose lead is the current layer, the canvas view (a never-shown view opens fitted; the canvas sets its rect), ruler zero and unit, guides, the Marquee selection and drag, and the rulers flag, which the canvas's `show_rulers` follows. `resize(PixelSize)` applies the Image Size answer."
note = "The open document of the mock: title, dirty flag, size, layers (top first), the layer selection whose lead is the current layer, the canvas view (a never-shown view opens fitted; the canvas sets its rect), ruler zero and unit, guides, the Marquee selection and drag, and the rulers flag. `resize(PixelSize)` applies the Image Size answer."
[[type]]
name = "Layer"