From 0bc621b93f7979e2a44e8376855fa19a56604ccb Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 22:47:02 +0000 Subject: [PATCH] fu-canvas: app batch 1 rulings (S-L233, S-L236, S-L238, S-L243, S-L244, S-L247) --- crates/pages/src/ui/mod.rs | 2 +- crates/pages/src/ui/page_rulers.rs | 28 +++- crates/pages/src/ui/view.rs | 106 +++++++++++++-- crates/pages/src/ui/view/stories.rs | 64 ++++++++- crates/pages/tests/it/rulers.rs | 59 ++++++++- crates/pages/tests/it/views.rs | 146 ++++++++++++++++++++- crates/review/src/ui/balloons.rs | 21 ++- crates/review/src/ui/balloons/stories.rs | 23 +++- crates/review/tests/it/balloons.rs | 27 +++- crates/text/src/ui/ruler.rs | 7 +- crates/text/src/ui/ruler/run.rs | 4 + crates/text/src/ui/ruler/stories.rs | 8 ++ crates/ui-canvas/src/canvas/stories.rs | 59 ++++++++- crates/ui-canvas/src/canvas/tool.rs | 12 +- crates/ui-canvas/src/canvas/tool_host.rs | 30 ++++- crates/ui-canvas/tests/it/canvas/editor.rs | 62 ++++++++- crates/ui-canvas/tests/it/canvas/tool.rs | 61 +++++++++ crates/ui-contract/src/contract/editor.rs | 5 +- crates/ui-contract/src/contract/tooltip.rs | 42 +++++- crates/ui-contract/src/runtime/focus.rs | 6 + 20 files changed, 717 insertions(+), 55 deletions(-) diff --git a/crates/pages/src/ui/mod.rs b/crates/pages/src/ui/mod.rs index 481fa343e..4d0ba29d6 100644 --- a/crates/pages/src/ui/mod.rs +++ b/crates/pages/src/ui/mod.rs @@ -61,4 +61,4 @@ pub use text_selection::{ pub use thumbnails::{ PageThumbnails, PageThumbnailsOutput, THUMBNAIL_ZOOM, ThumbnailEvent, ThumbnailMarks, ThumbnailSection, ThumbnailWords, moved_page, }; -pub use view::{PageBody, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage}; +pub use view::{PageBody, PageRegion, PageSnap, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage}; diff --git a/crates/pages/src/ui/page_rulers.rs b/crates/pages/src/ui/page_rulers.rs index 3c4aa0bbf..3f290121c 100644 --- a/crates/pages/src/ui/page_rulers.rs +++ b/crates/pages/src/ui/page_rulers.rs @@ -14,14 +14,14 @@ use craft_text::ui::DocUnit; use craft_text::ui::ruler::{RulerValues, TabAlign, TextRuler, TextRulerOutput, nudge_size, ruler_text, snap_step, snap_stop}; use craft_ui::canvas::{RulerTick, Rulers, TickRule}; use craft_ui::contract::{ - Access, Bind, Common, Component, Cx, Focus as _, Input, MeasureCx, Name, Numeric, Outcome, NoValue, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, + Access, Bind, Common, Component, Cx, Focus as _, IdSource, Input, MeasureCx, Name, Numeric, Outcome, NoValue, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Show as _, Styled as _, WordSetCx as _, }; use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick, TickEdge, TickRank}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse}; use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole}; -use egui::{CornerRadius, Pos2, Rangef, Rect, Response, Ui, Vec2, pos2, vec2}; +use egui::{AsIdSalt, CornerRadius, IdSalt, Pos2, Rangef, Rect, Response, Ui, Vec2, pos2, vec2}; use super::margins::{MarginHandles, MarginHandlesOutput, MarginRules, PageEdges}; use super::view::PlacedPage; @@ -391,6 +391,8 @@ pub struct PageRulers<'a> { rows: &'a [f32], gutter: f64, mirrored_even: bool, + id: IdSource, + gaps_draggable: bool, } impl<'a> PageRulers<'a> { @@ -410,9 +412,24 @@ impl<'a> PageRulers<'a> { rows: &[], gutter: 0.0, mirrored_even: false, + id: IdSource::Auto, + gaps_draggable: true, } } + /// Salts the text ruler's id with `salt` (the caret paragraph's key): a new salt is a new ruler, so a drag open on + /// the ruler of another paragraph ends with no commit. + pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self { + self.id = IdSource::Salt(IdSalt::new(salt)); + self + } + + /// Whether the column gaps' edges take a drag (the default): [`TextRuler::gaps_draggable`]. + pub fn gaps_draggable(mut self, on: bool) -> Self { + self.gaps_draggable = on; + self + } + /// The text column's start and end, points from the page's left. Without it the column is the text area between the /// margins. pub fn column(mut self, column: (f32, f32)) -> Self { @@ -470,7 +487,8 @@ impl<'a> PageRulers<'a> { /// Shows the rulers over the canvas at `canvas_rect`. pub fn show_at(self, ui: &mut Ui, canvas_rect: Rect) -> PageRulersOutput { - let PageRulers { label, page, mut edges, ruler, column, unit, kind, right_to_left, columns, gaps, rows, gutter, mirrored_even } = self; + let PageRulers { label, page, mut edges, ruler, column, unit, kind, right_to_left, columns, gaps, rows, gutter, mirrored_even, id, gaps_draggable } = + self; let (words, interface_rtl) = { let env = Env::of(ui); (env.words::(), env.view().direction().is_rtl()) @@ -494,10 +512,12 @@ impl<'a> PageRulers<'a> { .unit(unit) .columns(columns) .gaps(gaps) + .gaps_draggable(gaps_draggable) .origin(origin) .extent(extent) .scale(scale) - .right_to_left(rtl); + .right_to_left(rtl) + .id_source(id); if let Some(kind) = kind { horizontal = horizontal.kind(kind); } diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index e4c4f2e2b..26d87f498 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -27,8 +27,9 @@ use super::access::AccessDescriber; use crate::layout::{ Fit, LayoutOptions, PageDisplay, PageSpacing, PagedLayout, SCREEN_POINTS_PER_POINT, ViewDefaults, ZOOM_RANGE, fit_scale, place_pages, shown_row, }; +use craft_behavior::geometry::{SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; -use craft_behavior::{CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder}; +use craft_behavior::{Axis, CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder}; use craft_ui::canvas::{ BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, PageKey, Pasteboard, PasteboardOutput, Snap, ToolPass, ToolRegion, canvas_space, tool_pass, @@ -218,6 +219,45 @@ impl PageBody<'_> { } } +/// The snapping of the coordinates the pointer sets on the view ([`PageView::snap`]), over targets on the pages in +/// each page's own points: the view places them where their page shows in each pass. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct PageSnap { + options: SnapOptions, + pages: Vec<(usize, Vec)>, +} + +impl PageSnap { + /// Snapping with `options` and no targets yet. + pub fn new(options: SnapOptions) -> Self { + PageSnap { options, pages: Vec::new() } + } + + /// Adds `targets` on page `page`, in the page's own points from its top left corner, their spans included. + #[must_use] + pub fn page(mut self, page: usize, targets: Vec) -> Self { + self.pages.push((page, targets)); + self + } +} + +/// An area of a page where the active tool takes a press over the canvas controls ([`PageView::tool_regions`]), in the +/// page's own points: the view places it where its page shows in each pass. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct PageRegion { + page: usize, + points: Vec, +} + +impl PageRegion { + /// The polygon with the corners `points` on page `page`, in the page's own points from its top left corner. + pub fn polygon(page: usize, points: Vec) -> Self { + PageRegion { page, points } + } +} + /// What the view did this pass. #[derive(Debug)] #[non_exhaustive] @@ -285,8 +325,8 @@ pub struct PageView<'a> { describer: Option<&'a dyn AccessDescriber>, paper: DataColor, editor: Option, - snap: Option, - tool_regions: Vec, + snap: Option, + tool_regions: Vec, rulers: bool, } @@ -345,16 +385,19 @@ impl<'a> PageView<'a> { self } - /// The snapping of the coordinates the pointer sets on the view, passed to the inner canvas. + /// The snapping of the coordinates the pointer sets on the view, with its targets in page points. The view places + /// them on the pages that show this pass, drops those of pages outside the shown row and passes the result to the + /// inner canvas. #[must_use] - pub fn snap(mut self, snap: Option) -> Self { + pub fn snap(mut self, snap: Option) -> Self { self.snap = snap; self } - /// The areas where the active tool takes a press over the canvas controls, passed to the inner canvas. + /// The areas where the active tool takes a press over the canvas controls, in page points. The view places them + /// as [`snap`](Self::snap)'s targets and passes them to the inner canvas. #[must_use] - pub fn tool_regions(mut self, regions: Vec) -> Self { + pub fn tool_regions(mut self, regions: Vec) -> Self { self.tool_regions = regions; self } @@ -393,12 +436,14 @@ impl<'a> PageView<'a> { let given = frame.view(rect, start.offset, geo.scale / SCREEN_POINTS_PER_POINT); let mut navigation = navigation; navigation.overscroll = !start.continuous; - let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(tool_regions).show_rulers(rulers); + // The app's page geometry, in page points, placed where its page shows in this pass's layout. + let regions: Vec = tool_regions.iter().filter_map(|region| placed_region(region, &geo, &frame)).collect(); + let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(regions).show_rulers(rulers); if let Some(purpose) = editor { canvas = canvas.editor(purpose); } - if let Some(snap) = snap { - canvas = canvas.snap(snap); + if let Some(snap) = &snap { + canvas = canvas.snap(placed_snap(snap, &geo, &frame)); } if start.continuous { canvas = canvas.document(frame.document(&geo)); @@ -547,6 +592,47 @@ impl Frame { fn layout_point(&self, p: Point) -> Point { Point::new(p.x * self.zoom + self.origin.x, p.y * self.zoom + self.origin.y) } + + /// A layout point as a document point. + fn document_point(&self, l: Point) -> Point { + Point::new((l.x - self.origin.x) / self.zoom, (l.y - self.origin.y) / self.zoom) + } +} + +/// The document point of `p`, a point of page `page` in the page's own points; `None` for a page outside the row +/// `geo` shows. +fn page_to_document(geo: &Placed, frame: &Frame, page: usize, p: Point) -> Option { + if !geo.row.contains(&page) { + return None; + } + let origin = geo.layout.rects.get(page)?.origin(); + Some(frame.document_point(Point::new(origin.x + p.x * geo.scale, origin.y + p.y * geo.scale))) +} + +/// The snapping over `snap`'s targets on the pages `geo` shows, in `frame`'s document units. +fn placed_snap(snap: &PageSnap, geo: &Placed, frame: &Frame) -> Snap { + let mut targets = SnapTargets::new(); + for (page, list) in &snap.pages { + let to_doc = |p: Point| page_to_document(geo, frame, *page, p); + for target in list { + // A line along Y snaps x and spans y; one along X snaps y and spans x. The mapping is separate per axis. + let vertical = target.along == Axis::Y; + let across = |v: f64| to_doc(if vertical { Point::new(v, 0.0) } else { Point::new(0.0, v) }).map(|d| if vertical { d.x } else { d.y }); + let along = |v: f64| to_doc(if vertical { Point::new(0.0, v) } else { Point::new(v, 0.0) }).map(|d| if vertical { d.y } else { d.x }); + let Some(position) = across(target.position) else { break }; + let mut placed = *target; + placed.position = position; + placed.span = target.span.and_then(|(a, b)| Some((along(a)?, along(b)?))); + targets.add(placed); + } + } + Snap::new(Arc::new(targets), snap.options) +} + +/// `region` on the page it names, in `frame`'s document units; `None` for a page outside the row `geo` shows. +fn placed_region(region: &PageRegion, geo: &Placed, frame: &Frame) -> Option { + let points = region.points.iter().map(|p| page_to_document(geo, frame, region.page, *p)).collect::>>()?; + Some(ToolRegion::polygon(points)) } /// One pass of the canvas body: layout, scrolling, zoom and paging folded into the state; the pasteboard, the diff --git a/crates/pages/src/ui/view/stories.rs b/crates/pages/src/ui/view/stories.rs index e02f8b9e1..e0bd69e6d 100644 --- a/crates/pages/src/ui/view/stories.rs +++ b/crates/pages/src/ui/view/stories.rs @@ -1,13 +1,15 @@ //! Stories of the page view and its leaves. use super::pictures::{PageMetrics, PagePictures}; -use super::{PageView, PageViewState}; +use super::{PageSnap, PageSource as _, PageView, PageViewState}; use crate::layout::{LayoutOptions, PageDisplay}; use crate::ui::fixtures::{DemoPages, PAPER, demo_placed}; -use craft_behavior::CanvasView; -use craft_behavior::kurbo::Point; -use craft_ui::canvas::Canvas; +use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget}; +use craft_behavior::kurbo::{Point, Rect as DocRect}; +use craft_behavior::{Axis, CancelReason, CanvasView}; +use craft_ui::canvas::{Canvas, CanvasTool, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer}; use craft_ui::contract::{Show as _, ShowContainer as _}; +use craft_ui::primitives::Draw; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::{Pos2, Ui, Vec2}; @@ -45,6 +47,60 @@ fn one_page_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { view(ui, data, false, |state| state.continuous = false) } +/// A page margin's inset from each edge, in page points. +const MARGIN: f64 = 72.0; + +/// A tool whose drag snaps the point under the pointer as a point-sized box, so the host draws the smart guide it +/// snapped to. +struct MarginSnapper; + +impl CanvasTool for MarginSnapper { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + if let Some(space) = cx.space() { + let at = space.view.to_doc(pointer.pos); + let _ = cx.snap_rect(DocRect::from_points(at, at)); + } + } + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Snap to Margins command") + } +} + +/// Two-up spreads whose page margins are snap targets handed over in page points ([`PageSnap`]): a drag snaps to the +/// margins of the page it is over, where that page shows, and the smart guide shows where it snapped. +#[story(PageView<'static>, covers = [], drive = Drive::Never)] +fn snapped_margins(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let state = data.value("view", PageViewState { display: PageDisplay::TwoUp, ..PageViewState::default() }); + let pages = DemoPages::new(PAGES); + let snap = (0..PAGES).fold(PageSnap::new(SnapOptions::default()), |snap, page| { + let size = pages.page_size(page); + let margins = vec![ + SnapTarget::new(Axis::Y, MARGIN, SnapKind::LayerEdge), + SnapTarget::new(Axis::Y, size.width - MARGIN, SnapKind::LayerEdge), + SnapTarget::new(Axis::X, MARGIN, SnapKind::LayerEdge), + SnapTarget::new(Axis::X, size.height - MARGIN, SnapKind::LayerEdge), + ]; + snap.page(page, margins) + }); + let out = PageView::new("Pages", &pages, state, PAPER).options(LayoutOptions::ACROBAT).snap(Some(snap)).show(ui, |ui, body| { + if let Some(pass) = body.pass { + let _ = ToolHost::new().run(ui, pass, &mut MarginSnapper); + } + }); + out.canvas.response.into() +} + #[story(PageMetrics, covers = [Default], drive = Drive::Never)] fn page_metrics(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let room = craft_ui::testing::stage(ui); diff --git a/crates/pages/tests/it/rulers.rs b/crates/pages/tests/it/rulers.rs index f781a65cf..a551e39e5 100644 --- a/crates/pages/tests/it/rulers.rs +++ b/crates/pages/tests/it/rulers.rs @@ -1,19 +1,19 @@ //! The page rulers: ruler numbers keep clear of table column markers, the margin handles stop short of the opposite //! edge and swap sides on a mirrored even page, and a table row grip drags as one gesture. -use craft_behavior::GesturePhase; +use craft_behavior::{EditEvent, GesturePhase}; use craft_pages::setup::Margins; use craft_pages::ui::fixtures::demo_placed; use craft_pages::ui::margins::{MIN_TEXT, MarginHandlesWords}; use craft_pages::ui::page_rulers::PageRulersWords; use craft_pages::ui::{PageEdges, PageRulers, RowDrag, VerticalRuler}; use craft_text::ui::DocUnit; -use craft_text::ui::ruler::{RulerValues, TextRulerWords}; +use craft_text::ui::ruler::{RulerValues, TabAlign, TabLeader, TabStop, TextRulerWords}; use craft_ui::contract::{Bind, Role, Show as _}; use craft_ui::runtime::env::UnitKind; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, Rangef, Rect, pos2, vec2}; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; /// Where the page's top-left corner sits in the fixture, points. @@ -144,3 +144,56 @@ fn a_row_grip_drag_reports_one_gesture_with_alt_free_and_the_arrow_nudges() { assert_eq!(nudge.phase, GesturePhase::Commit, "a nudge is a lone Commit"); assert!(nudge.position > 100.0, "Down moves the border down: {}", nudge.position); } + +/// Where the trial's left tab stop sits, points from the column's start edge. +const STOP_AT: f32 = 144.0; + +/// Guards `PageRulers::id_salt`: the caret paragraph's key salts the text ruler, so a new paragraph is a new ruler and +/// a stop drag open on the old one commits nothing when its button comes up. The first drag, with the salt kept, is the +/// control: it commits once. +#[trial] +fn a_new_salt_during_a_tab_drag_commits_nothing() { + let salt = Rc::new(Cell::new(1u32)); + let commits = Rc::new(Cell::new(0usize)); + let mut start = RulerValues::default(); + start.stops.push(TabStop::new(STOP_AT, TabAlign::Left, TabLeader::None)); + let values = Rc::new(RefCell::new(start)); + let (shown_salt, seen, shown_values) = (Rc::clone(&salt), Rc::clone(&commits), Rc::clone(&values)); + let mut fixture = Fixture::new(move |ui| { + let full = craft_ui::testing::stage(ui); + let page = demo_placed(1, pos2(full.min.x + PAGE_AT.0, full.min.y + PAGE_AT.1)).remove(0); + let mut edges = PageEdges::new(Margins::uniform(72.0)); + let out = PageRulers::new("Rulers", &page, Bind::bound(&mut edges), Bind::bound(&mut *shown_values.borrow_mut())) + .id_salt(shown_salt.get()) + .show_at(ui, full); + let committed = out.ruler.edit.events.iter().filter(|event| matches!(event, EditEvent::Commit { .. })).count(); + seen.set(seen.get() + committed); + }); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + let left_tab = TextRulerWords::default().left_tab; + let stop = |fixture: &Fixture| { + fixture + .by_role(Role::SLIDER) + .into_iter() + .find(|target| craft_ui::testing::access::name(fixture.tree(), target.node).is_some_and(|name| name.starts_with(left_tab.as_str()))) + .expect("the ruler shows the stop") + .rect + .center() + }; + let by = vec2(40.0, 0.0); + + let at = stop(&fixture); + fixture.drag_hold_at(at, by); + fixture.release_at(at + by); + fixture.settle(); + assert_eq!(commits.get(), 1, "a stop drag on one paragraph's ruler commits once"); + + let at = stop(&fixture); + fixture.drag_hold_at(at, by); + salt.set(2); + fixture.idle(1); + fixture.release_at(at + by); + fixture.settle(); + assert_eq!(commits.get(), 1, "the drag open when the paragraph changed commits nothing"); +} diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index d5fd620fa..d6b292fda 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -1,15 +1,20 @@ //! The page view and the page preview: the scroll anchor under a zoom change, wheel input at the end of the document, //! the view's page and arrow keys and its zoom commands, and the preview's keys. +use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget}; use craft_behavior::kurbo; -use craft_pages::layout::{Fit, LayoutOptions}; +use craft_behavior::{Axis, CancelReason, CanvasView}; +use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; -use craft_pages::ui::{PagePreview, PageSource, PageView, PageViewState, PageViewWords, ReadingNav, ReadingState, ReadingView}; -use craft_ui::contract::{Role, Show as _}; +use craft_pages::ui::{ + PagePreview, PageRegion, PageSnap, PageSource, PageView, PageViewState, PageViewWords, PlacedPage, ReadingNav, ReadingState, ReadingView, +}; +use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer}; +use craft_ui::contract::{Bind, Role, Show as _}; -use craft_ui::primitives::EditorPurpose; +use craft_ui::primitives::{Draw, EditorPurpose}; use craft_ui::runtime::env::Env; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::{Fixture, pointer, trial}; use egui::{Key, Modifiers, pos2, vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -511,3 +516,134 @@ fn a_view_with_an_editor_purpose_takes_no_plain_keys_for_moving() { let (before, after) = keyed(true); assert_eq!((after.current, after.offset), (before.current, before.offset), "the editor view leaves moving to the app"); } + +/// Where a snap line lies on page 2, in that page's own points. +const LINE_X: f64 = 120.0; + +/// A tool that snaps the document point under each drag sample and keeps the last one, and counts its presses. +#[derive(Default)] +struct Snapper { + snapped: Option, + presses: usize, +} + +impl CanvasTool for Snapper { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + self.presses += 1; + ToolAction::Claimed + } + + fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + if let Some(space) = cx.space() { + self.snapped = Some(cx.snap(space.view.to_doc(pointer.pos))); + } + } + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Snap command") + } +} + +/// A drag a few points beside the snap line at `LINE_X` on page 2, in a view of `state` with the line handed over in +/// page points: where the drag snapped to on screen, and where the line shows on page 2. +fn drag_beside_the_line_on_page_two(state: PageViewState) -> (f32, f32) { + let tool = Rc::new(RefCell::new(Snapper::default())); + let two: Rc>> = Rc::default(); + let (shown_tool, seen) = (Rc::clone(&tool), Rc::clone(&two)); + let pages = DemoPages::new(4); + let mut state = state; + let mut fixture = Fixture::new(move |ui| { + let snap = PageSnap::new(SnapOptions::default()).page(1, vec![SnapTarget::new(Axis::Y, LINE_X, SnapKind::Guide)]); + PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).snap(Some(snap)).show(ui, |ui, body| { + if let Some(page) = body.pages.iter().find(|placed| placed.page == 1) { + seen.set(Some((*page, body.view))); + } + if let Some(pass) = body.pass { + let _ = ToolHost::new().run(ui, pass, &mut *shown_tool.borrow_mut()); + } + }); + }); + fixture.room(vec2(900.0, 700.0)); + fixture.settle(); + let (page, _) = two.get().expect("page 2 shows"); + let line = page.to_screen(kurbo::Point::new(LINE_X, 200.0)); + let from = line + vec2(30.0, 0.0); + fixture.frame(vec![pointer::moved(from)]); + fixture.frame(vec![pointer::press(from)]); + for step in 1..=3 { + fixture.frame(vec![pointer::moved(from - vec2(9.0 * step as f32, 0.0))]); + } + let (_, view) = two.get().expect("page 2 shows"); + let snapped = tool.borrow().snapped.expect("the tool dragged"); + (view.to_screen(snapped).x, line.x) +} + +/// Guards the view's placement of page geometry: a target in page points snaps where its page shows, not at the +/// same numbers in document units, in a continuous view and in a two-up spread. +#[trial] +fn a_snap_target_on_page_two_snaps_a_drag_where_page_two_shows() { + let continuous = state_with(|s| { + s.fit = Fit::None; + s.zoom = 0.4; + s.continuous = true; + }); + let spread = state_with(|s| { + s.fit = Fit::None; + s.zoom = 0.4; + s.continuous = false; + s.display = PageDisplay::TwoUp; + }); + for (name, state) in [("continuous", continuous), ("two-up", spread)] { + let (snapped, line) = drag_beside_the_line_on_page_two(state); + assert!((snapped - line).abs() < 0.5, "{name}: the drag snaps onto page 2's line: {snapped} against {line}"); + } +} + +/// Guards the view's placement of tool regions: a region in page points on page 1 takes a press over a canvas +/// control there. +#[trial] +fn a_tool_region_on_page_one_takes_a_press_over_a_canvas_control_there() { + let tool = Rc::new(RefCell::new(Snapper::default())); + let crop: Rc>> = Rc::default(); + let (shown_tool, shown_crop) = (Rc::clone(&tool), Rc::clone(&crop)); + let pages = DemoPages::new(2); + let mut state = state_with(|s| { + s.fit = Fit::None; + s.zoom = 0.4; + }); + // The region covers the crop frame's top left corner, at page 1's (100, 80) points. + let corner = vec![kurbo::Point::new(80.0, 60.0), kurbo::Point::new(120.0, 60.0), kurbo::Point::new(120.0, 100.0), kurbo::Point::new(80.0, 100.0)]; + let mut fixture = Fixture::new(move |ui| { + let regions = vec![PageRegion::polygon(0, corner.clone())]; + PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).tool_regions(regions).show(ui, |ui, body| { + let Some(first) = body.pages.iter().find(|placed| placed.page == 0) else { return }; + let mut crop = shown_crop.borrow_mut(); + let frame = crop.get_or_insert_with(|| { + let (a, b) = (first.to_doc(&body.view, kurbo::Point::new(100.0, 80.0)), first.to_doc(&body.view, kurbo::Point::new(300.0, 220.0))); + CropBox::upright(kurbo::Rect::from_points(a, b)) + }); + let _ = CropOverlay::new("Crop", Bind::bound(frame)).show_at(ui, body.rect); + if let Some(pass) = body.pass { + let _ = ToolHost::new().run(ui, pass, &mut *shown_tool.borrow_mut()); + } + }); + }); + fixture.room(vec2(900.0, 700.0)); + fixture.settle(); + let start = crop.borrow().as_ref().map(|frame| frame.rect).expect("the crop shows on page 1"); + let at = fixture.by_label("Crop corner, top left").expect("the crop shows its corners").rect.center(); + let by = vec2(20.0, 15.0); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![pointer::press(at)]); + fixture.frame(vec![pointer::moved(at + by * 0.5)]); + fixture.frame(vec![pointer::moved(at + by)]); + fixture.frame(vec![pointer::release(at + by)]); + assert_eq!(tool.borrow().presses, 1, "a press in the region is the tool's"); + assert_eq!(crop.borrow().as_ref().map(|frame| frame.rect), Some(start), "the corner under the region does not move"); +} diff --git a/crates/review/src/ui/balloons.rs b/crates/review/src/ui/balloons.rs index 6bdf9ae25..aebca5636 100644 --- a/crates/review/src/ui/balloons.rs +++ b/crates/review/src/ui/balloons.rs @@ -100,12 +100,20 @@ pub struct CommentBalloons<'a> { place: BalloonPlace, width: Option, now: Option, + read_only: bool, } impl<'a> CommentBalloons<'a> { /// Balloons named `label` for `items` on `pages`, with the card state in `state`. pub fn new(label: impl Into