From b9c4d4787f2793dbd90a1a7f53cb7916acbb9554 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 06:54:15 -0500 Subject: [PATCH] pdf-comments-w1: net change of 4 commits - pdf-comments-w1: written from its sheet - pdf-comments-w1: repair 1 - pdf-comments-w1: finished by an agent - pdf-comments-w1: review fixes (review-1) --- crates/review/src/annotate.rs | 177 +++++++++++++++++----- crates/review/src/annotate_tests.rs | 179 ++++++++++++++++++++++- crates/review/src/lib.rs | 8 +- crates/review/src/ui/annotate/overlay.rs | 95 ++++++++++-- crates/review/src/ui/annotate/stories.rs | 143 +++++++++++++++++- crates/review/src/ui/annotate/words.rs | 32 ++-- crates/review/src/ui/mod.rs | 4 +- 7 files changed, 561 insertions(+), 77 deletions(-) diff --git a/crates/review/src/annotate.rs b/crates/review/src/annotate.rs index 0e965ef05..945f2a820 100644 --- a/crates/review/src/annotate.rs +++ b/crates/review/src/annotate.rs @@ -88,7 +88,9 @@ impl AnnotationGroup { use AnnotationTool::Draw as D; match self { AnnotationGroup::Comment => &[D(K::Note), D(K::TextBox), D(K::Callout), D(K::Attach)], - AnnotationGroup::Highlight => &[D(K::Highlight), D(K::Underline), D(K::StrikeOut), D(K::Squiggly), D(K::Caret), D(K::ReplaceText)], + AnnotationGroup::Highlight => { + &[D(K::Highlight), D(K::Underline), D(K::StrikeOut), D(K::Squiggly), D(K::FreehandHighlight), D(K::Caret), D(K::ReplaceText)] + } AnnotationGroup::Draw => { &[D(K::Ink), D(K::Line), D(K::Arrow), D(K::Rectangle), D(K::Oval), D(K::PolyLine), D(K::Polygon), D(K::Cloud), AnnotationTool::Eraser] } @@ -109,8 +111,8 @@ impl AnnotationKind { ) } - /// Kinds drawn by points (Line, Arrow, PolyLine, Polygon, Cloud, Ink): reshaped by moving a - /// point; the others resize by their box. + /// Kinds drawn by points or strokes (Line, Arrow, PolyLine, Polygon, Cloud, Ink, Freehand + /// highlight): reshaped by moving a point; the others resize by their box. pub fn is_pointwise(self) -> bool { matches!( self, @@ -120,13 +122,13 @@ impl AnnotationKind { | AnnotationKind::Polygon | AnnotationKind::Cloud | AnnotationKind::Ink + | AnnotationKind::FreehandHighlight ) } - /// Kinds that keep their size: icons placed at a point, and the callout, whose box also - /// holds its leader line (PdfCraft `geometry.rs:12` `resizable`). + /// Kinds that keep their size: icons placed at a point. pub fn is_fixed_size(self) -> bool { - matches!(self, AnnotationKind::Note | AnnotationKind::Attach | AnnotationKind::Caret | AnnotationKind::Callout) + matches!(self, AnnotationKind::Note | AnnotationKind::Attach | AnnotationKind::Caret) } } @@ -201,42 +203,112 @@ pub enum ShiftLock { LevelOrPlumb, } -/// `points` with the callout's point `i` moved to `to`: the knee (`i == 1`) moves along its knee line only and never -/// nearer the box than [`CALLOUT_KNEE_GAP`]; every other point moves freely through [`reshaped`]. -#[allow(dead_code)] // P3(pdf-comments-w1): CM-C2 +/// `points` with the callout's point `i` moved to `to`: the knee (`i == 1`) moves along its knee line only (level +/// beside the box, upright above or below it) and never nearer the box than [`CALLOUT_KNEE_GAP`]; every other point +/// moves through [`reshaped`], held to `lock` from its neighbour. pub fn callout_reshaped(rect: Rect, points: &[Point], i: usize, to: Point, lock: Option) -> Vec { - let _ = (rect, points, i, to, lock); - todo!("CM-C2") + let Some(&knee) = points.get(1).filter(|_| i == 1) else { return reshaped(points, i, to, lock) }; + let (r, gap) = (rect.abs(), CALLOUT_KNEE_GAP); + let to = match KneeSide::of(r, knee) { + KneeSide::Left => Point::new(to.x.min(r.x0 - gap), knee.y), + KneeSide::Right => Point::new(to.x.max(r.x1 + gap), knee.y), + KneeSide::Above => Point::new(knee.x, to.y.min(r.y0 - gap)), + KneeSide::Below => Point::new(knee.x, to.y.max(r.y1 + gap)), + }; + let mut out = points.to_vec(); + if let Some(k) = out.get_mut(1) { + *k = to; + } + out +} + +/// The side of a callout's box its knee lies on, which decides the knee line. +#[derive(Clone, Copy)] +enum KneeSide { + Left, + Right, + Above, + Below, +} + +impl KneeSide { + /// The side `knee` lies farthest outside of the normalised `rect`; inside it, the nearest edge's side. + fn of(rect: Rect, knee: Point) -> KneeSide { + [(KneeSide::Left, rect.x0 - knee.x), (KneeSide::Right, knee.x - rect.x1), (KneeSide::Above, rect.y0 - knee.y), (KneeSide::Below, knee.y - rect.y1)] + .into_iter() + .fold((KneeSide::Left, f64::NEG_INFINITY), |best, side| if side.1 > best.1 { side } else { best }) + .0 + } } /// The width over height a corner resize of `annotation` keeps from `from` (with Shift); `None` for a flat box. -#[allow(dead_code)] // P3(pdf-comments-w1): CM-C3 pub fn corner_aspect(annotation: &Annotation, from: Rect, shift: bool) -> Option { - let _ = (annotation, from, shift); - todo!("CM-C3") + annotation.aspect.or_else(|| (shift && from.height() > 0.0).then(|| from.width() / from.height())) } -/// The box of `annotation`'s marker on `page`, clamped to the page; `None` when it has none. -#[allow(dead_code)] // P3(pdf-comments-w1): CM-C6 +/// The gap between a marker and its markup's last quad, in icon sides. +const MARKER_GAP: f64 = 0.25; + +/// The box of `annotation`'s marker on `page`, clamped to the page; `None` when it has none. A commented markup has a +/// marker an `icon_side` square above and right of its last quad; a page smaller than the marker, or a markup off the +/// page, gets none rather than one covering the page or floating beside it. pub fn marker_rect(annotation: &Annotation, page: Rect, icon_side: f64) -> Option { - let _ = (annotation, page, icon_side); - todo!("CM-C6") + if !annotation.kind.is_markup() || annotation.text.trim().is_empty() { + return None; + } + let target = annotation.points.chunks(4).last().and_then(bounds)?; + let page = page.abs(); + let gap = icon_side * MARKER_GAP; + let wanted = Point::new(target.x1 + gap, target.y0 - gap - icon_side); + let fits = page.is_finite() + && target.is_finite() + && wanted.is_finite() + && icon_side > 0.0 + && page.width() >= icon_side + && page.height() >= icon_side; + let on_page = target.x0 <= page.x1 && target.x1 >= page.x0 && target.y0 <= page.y1 && target.y1 >= page.y0; + if !fits || !on_page { + return None; + } + // `min` then `max`, not `clamp`: rounding can put `x1 - icon_side` an ulp below `x0`. + let at = Point::new(wanted.x.min(page.x1 - icon_side).max(page.x0), wanted.y.min(page.y1 - icon_side).max(page.y0)); + Some(Rect::from_origin_size(at, (icon_side, icon_side))) } -/// The annotation the comment part, the hover outline and the marker hit at `at`, within `tolerance` page units. -#[allow(dead_code)] // P3(pdf-comments-w1): CM-C6 +/// The annotation the comment part, the hover outline and the marker hit at `at`, within `tolerance` page units: a +/// marker of `markers` first, the last listed winning, then the topmost body (see [`hit`]). pub fn pick_at(annotations: &[Annotation], at: Point, tolerance: f64, icon_side: f64, markers: &[(AnnotationId, Rect)]) -> Option { - let _ = (annotations, at, tolerance, icon_side, markers); - todo!("CM-C6") + if let Some((id, _)) = markers.iter().rev().find(|(_, r)| r.inflate(tolerance, tolerance).contains(at)) { + return Some(*id); + } + annotations.iter().rev().find(|a| body_hit(a, at, tolerance, icon_side)).map(|a| a.id) } impl Annotation { - /// The annotation as the in-flight `edit` leaves it, for the overlay's live paint. + /// The annotation as the in-flight `edit` leaves it, for the overlay's live paint; `None` when the edit does not + /// move, resize or reshape it. A resized callout keeps its tip and knee: only its box goes. #[cfg(feature = "ui")] - #[allow(dead_code)] // P3(pdf-comments-w1): CM-C4 pub fn edited(&self, edit: &AnnotationEdit) -> Option { - let _ = edit; - todo!("CM-C4") + let mut out = self.clone(); + match edit { + AnnotationEdit::Move { ids, delta } if ids.contains(&self.id) => { + out.rect = self.rect + *delta; + for p in out.points.iter_mut().chain(out.strokes.iter_mut().flatten()) { + *p += *delta; + } + } + AnnotationEdit::Resize { id, rect } if *id == self.id => out.rect = *rect, + AnnotationEdit::Reshape { id, points } if *id == self.id => { + out.points = points.clone(); + if self.kind.is_pointwise() + && let Some(r) = bounds(points) + { + out.rect = r; + } + } + _ => return None, + } + Some(out) } } @@ -273,8 +345,13 @@ pub enum AnnotationHit { } /// The handles `annotation` shows when selected: its points for pointwise kinds, else the eight -/// box handles (none for markups and locked annotations). +/// box handles, with a callout's tip and knee besides. None under a [`HandleRule`] that fixes the +/// shape, nor for markups, icon kinds and locked annotations: a handle that would do nothing is +/// never offered. pub fn handles(annotation: &Annotation) -> Vec<(AnnotationHandle, Point)> { + if matches!(annotation.handle_rule, HandleRule::FixedPoints | HandleRule::NoResize) { + return Vec::new(); + } if annotation.locked || annotation.kind.is_markup() { return Vec::new(); } @@ -284,7 +361,9 @@ pub fn handles(annotation: &Annotation) -> Vec<(AnnotationHandle, Point)> { if annotation.kind.is_fixed_size() { return Vec::new(); } - BOX_HANDLES.iter().map(|&(hx, hy)| (AnnotationHandle::Box(hx, hy), box_handle_point(annotation.rect, (hx, hy)))).collect() + let boxes = BOX_HANDLES.iter().map(|&(hx, hy)| (AnnotationHandle::Box(hx, hy), box_handle_point(annotation.rect, (hx, hy)))); + let leader = annotation.points.iter().take(2).enumerate().filter(|_| annotation.kind == AnnotationKind::Callout); + boxes.chain(leader.map(|(i, &p)| (AnnotationHandle::Point(i), p))).collect() } /// The eight box handles, clockwise from the top-left. @@ -324,22 +403,41 @@ fn distance_to_path(p: Point, path: &[Point], closed: bool) -> f64 { open.chain(closing).fold(f64::INFINITY, f64::min).min(path.first().map_or(f64::INFINITY, |&a| (p - a).hypot())) } +/// The box that holds `points`; `None` for none. +fn bounds(points: &[Point]) -> Option { + let (&first, rest) = points.split_first()?; + Some(rest.iter().fold(Rect::from_points(first, first), |r, &p| r.union_pt(p))) +} + +/// A callout's leader in page units: from its tip through its knee to the nearest point of its box. The overlay paints +/// it and [`body_hit`] tests it, so what is drawn is what is picked. +pub(crate) fn callout_leader(a: &Annotation) -> Vec { + let r = a.rect.abs(); + let mut path: Vec = a.points.iter().take(2).copied().collect(); + if let Some(&knee) = path.last() { + path.push(Point::new(knee.x.max(r.x0).min(r.x1), knee.y.max(r.y0).min(r.y1))); + } + path +} + fn body_hit(a: &Annotation, at: Point, tolerance: f64, icon_side: f64) -> bool { let reach = tolerance + a.stroke_width / 2.0; match a.kind { AnnotationKind::Line | AnnotationKind::Arrow | AnnotationKind::PolyLine => distance_to_path(at, &a.points, false) <= reach, AnnotationKind::Polygon | AnnotationKind::Cloud => distance_to_path(at, &a.points, true) <= reach, - AnnotationKind::Ink => a.strokes.iter().any(|s| distance_to_path(at, s, false) <= reach), + AnnotationKind::Ink | AnnotationKind::FreehandHighlight => a.strokes.iter().any(|s| distance_to_path(at, s, false) <= reach), + AnnotationKind::Callout => { + a.rect.inflate(tolerance, tolerance).contains(at) || (a.points.len() > 1 && distance_to_path(at, &callout_leader(a), false) <= reach) + } AnnotationKind::Oval => { let r = a.rect.inflate(tolerance, tolerance); let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); let c = r.center(); rx > 0.0 && ry > 0.0 && ((at.x - c.x) / rx).powi(2) + ((at.y - c.y) / ry).powi(2) <= 1.0 } - kind if kind.is_markup() && !a.points.is_empty() => a.points.chunks(4).any(|quad| { - let r = quad.iter().fold(Rect::from_points(quad[0], quad[0]), |r, &p| r.union_pt(p)); - r.inflate(tolerance, tolerance).contains(at) - }), + kind if kind.is_markup() && !a.points.is_empty() => { + a.points.chunks(4).filter_map(bounds).any(|r| r.inflate(tolerance, tolerance).contains(at)) + } _ => a.extent(icon_side).inflate(tolerance, tolerance).contains(at), } } @@ -393,12 +491,19 @@ pub fn resized(rect: Rect, handle: (i8, i8), delta: Vec2, aspect: Option) - } /// `points` with point `i` moved to `to`; with `lock` the segment from its neighbour is held to the rule. -// pdfcraft: crates/ui-egui/src/tools/comments/geometry.rs:37 `reshaped`. pub fn reshaped(points: &[Point], i: usize, to: Point, lock: Option) -> Vec { let mut out = points.to_vec(); let anchor = if i == 0 { points.get(1) } else { points.get(i - 1) }; - let to = match anchor { - Some(&a) if lock.is_some() => turn_to_45(a, to), // P3(pdf-comments-w1): CM-C5 (`LevelOrPlumb` is the writer's) + let to = match (anchor, lock) { + (Some(&a), Some(ShiftLock::Angle45)) => turn_to_45(a, to), + // The nearer axis from the neighbour: the segment goes level or plumb. + (Some(&a), Some(ShiftLock::LevelOrPlumb)) => { + if (to.x - a.x).abs() >= (to.y - a.y).abs() { + Point::new(to.x, a.y) + } else { + Point::new(a.x, to.y) + } + } _ => to, }; if let Some(p) = out.get_mut(i) { diff --git a/crates/review/src/annotate_tests.rs b/crates/review/src/annotate_tests.rs index 2c77d7b12..b0b1c27c8 100644 --- a/crates/review/src/annotate_tests.rs +++ b/crates/review/src/annotate_tests.rs @@ -3,7 +3,10 @@ use craft_ui::testing::trial; use kurbo::{Point, Rect}; -use crate::annotate::{Annotation, AnnotationHandle, AnnotationHit, AnnotationId, AnnotationKind, hit}; +use crate::annotate::{ + Annotation, AnnotationHandle, AnnotationHit, AnnotationId, AnnotationKind, CALLOUT_KNEE_GAP, HandleRule, ShiftLock, callout_reshaped, handles, hit, + marker_rect, pick_at, +}; /// The icon side, in page units, the hit tests are given. const ICON: f64 = 16.0; @@ -21,8 +24,8 @@ fn annotation(id: u64, kind: AnnotationKind, rect: Rect) -> Annotation { stroke_width: 2.0, text: String::new(), locked: false, - aspect: None, // P3(pdf-comments-w1): CM-C3 - handle_rule: crate::annotate::HandleRule::default(), // P3(pdf-comments-w1): CM-C30 + aspect: None, + handle_rule: HandleRule::Free, } } @@ -30,6 +33,25 @@ fn square(id: u64, kind: AnnotationKind) -> Annotation { annotation(id, kind, Rect::new(10.0, 10.0, 50.0, 30.0)) } +/// The four corners of `r`, as a markup's quad. +fn quad(r: Rect) -> Vec { + vec![Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} + +/// A highlight over `r` with a comment. +fn commented_highlight(r: Rect) -> Annotation { + let mut a = annotation(1, AnnotationKind::Highlight, r); + a.points = quad(r); + a.text = "Check this".to_owned(); + a +} + +/// Whether `r` lies inside `page`, give or take rounding. +fn within(r: Rect, page: Rect) -> bool { + const SLACK: f64 = 1e-9; + r.x0 >= page.x0 - SLACK && r.x1 <= page.x1 + SLACK && r.y0 >= page.y0 - SLACK && r.y1 <= page.y1 + SLACK +} + // handles by kind; none for markups and locked ones. // hit order: selected handles, then last-drawn bodies. @@ -49,6 +71,157 @@ fn hit_prefers_handles_then_the_topmost_body() { assert_eq!(hit(&[line], &[], Point::new(150.0, 110.0), 2.0, ICON), None); } +/// One pick serves the comment part, the hover outline and the marker: a marker before any body, the last listed +/// marker first; then the topmost body, a markup by its quads and a note by its icon. +#[trial] +fn pick_at_takes_the_marker_before_any_body_and_the_topmost_body_after() { + // The markup's quads lie away from its rect, so only the quads can pick it. + let mut markup = annotation(1, AnnotationKind::Highlight, Rect::new(10.0, 60.0, 50.0, 80.0)); + markup.points = quad(Rect::new(200.0, 10.0, 240.0, 30.0)); + let boxed = square(2, AnnotationKind::Rectangle); + // A note's rect smaller than its icon: the icon's extent picks it. + let note = annotation(3, AnnotationKind::Note, Rect::new(100.0, 100.0, 104.0, 104.0)); + let all = [markup, boxed, note]; + let over_box = Point::new(25.0, 20.0); + let markers = [(AnnotationId(1), Rect::new(20.0, 15.0, 32.0, 27.0)), (AnnotationId(3), Rect::new(22.0, 17.0, 30.0, 25.0))]; + + assert_eq!(pick_at(&all, over_box, 0.0, ICON, &markers[..1]), Some(AnnotationId(1)), "the marker over the rectangle"); + assert_eq!(pick_at(&all, over_box, 0.0, ICON, &markers), Some(AnnotationId(3)), "the last listed marker"); + assert_eq!(pick_at(&all, over_box, 0.0, ICON, &[]), Some(AnnotationId(2)), "the topmost body"); + assert_eq!(pick_at(&all, Point::new(220.0, 20.0), 0.0, ICON, &[]), Some(AnnotationId(1)), "the markup by its quad"); + assert_eq!(pick_at(&all, Point::new(30.0, 70.0), 0.0, ICON, &[]), None, "a markup's rect outside its quads"); + assert_eq!(pick_at(&all, Point::new(112.0, 112.0), 0.0, ICON, &[]), Some(AnnotationId(3)), "the note by its icon"); + assert_eq!(pick_at(&all, Point::new(120.0, 120.0), 0.0, ICON, &[]), None); +} + +/// The marker is clamped inside the page whatever its bounds: at the page's right edge, with inverted or fractional +/// bounds; a page smaller than the marker and a markup off the page get none, as do plain markups and other kinds. +#[trial] +fn marker_rect_stays_inside_the_page_on_rounded_or_inverted_bounds() { + let page = Rect::new(0.0, 0.0, 100.0, 200.0); + let at_edge = commented_highlight(Rect::new(90.0, 10.0, 100.0, 20.0)); + let marker = marker_rect(&at_edge, page, ICON); + assert!(marker.is_some_and(|m| within(m, page) && m.width() == ICON && m.height() == ICON), "{marker:?}"); + assert_eq!(marker_rect(&at_edge, Rect::new(100.0, 200.0, 0.0, 0.0), ICON), marker, "inverted bounds name the same page"); + let rounded = Rect::new(0.3, 0.7, 99.7, 199.3); + let marker = marker_rect(&at_edge, rounded, ICON); + assert!(marker.is_some_and(|m| within(m, rounded)), "{marker:?}"); + + let open = commented_highlight(Rect::new(20.0, 50.0, 60.0, 60.0)); + let marker = marker_rect(&open, page, ICON); + assert!(marker.is_some_and(|m| m.x0 > 60.0 && m.y1 < 50.0), "beside the quad's top right: {marker:?}"); + + let tiny = Rect::new(0.0, 0.0, 10.0, 10.0); + assert_eq!(marker_rect(&commented_highlight(Rect::new(2.0, 2.0, 8.0, 8.0)), tiny, ICON), None, "a page smaller than the marker"); + assert_eq!(marker_rect(&commented_highlight(Rect::new(300.0, 300.0, 320.0, 310.0)), page, ICON), None, "a markup off the page"); + let mut plain = at_edge.clone(); + plain.text = " ".to_owned(); + assert_eq!(marker_rect(&plain, page, ICON), None, "a markup with no comment"); + let mut boxed = square(2, AnnotationKind::Rectangle); + boxed.text = "Check this".to_owned(); + assert_eq!(marker_rect(&boxed, page, ICON), None, "a shape"); +} + +/// A callout's knee keeps to its knee line, level beside the box and upright above or below it, and never comes nearer +/// the box than the gap; its tip moves freely, or held to the lock from the knee. +#[trial] +fn a_callout_knee_stays_on_its_line_at_least_the_gap_from_the_box_and_only_the_tip_moves_freely() { + let r = Rect::new(100.0, 100.0, 200.0, 150.0); + let gap = CALLOUT_KNEE_GAP; + let tip = Point::new(10.0, 10.0); + // (knee, a drag across its line, where that lands, a drag into the box, where that stops) + let cases = [ + (Point::new(80.0, 125.0), Point::new(60.0, 140.0), Point::new(60.0, 125.0), Point::new(150.0, 125.0), Point::new(r.x0 - gap, 125.0)), + (Point::new(220.0, 125.0), Point::new(250.0, 90.0), Point::new(250.0, 125.0), Point::new(120.0, 125.0), Point::new(r.x1 + gap, 125.0)), + (Point::new(150.0, 80.0), Point::new(130.0, 60.0), Point::new(150.0, 60.0), Point::new(150.0, 120.0), Point::new(150.0, r.y0 - gap)), + (Point::new(150.0, 170.0), Point::new(170.0, 190.0), Point::new(150.0, 190.0), Point::new(150.0, 110.0), Point::new(150.0, r.y1 + gap)), + ]; + for (knee, across, lands, into, stops) in cases { + let points = [tip, knee]; + assert_eq!(callout_reshaped(r, &points, 1, across, None), vec![tip, lands], "knee {knee:?} dragged across its line"); + assert_eq!(callout_reshaped(r, &points, 1, into, None), vec![tip, stops], "knee {knee:?} dragged into the box"); + } + + let (tip, knee) = (Point::new(20.0, 60.0), Point::new(80.0, 125.0)); + let points = [tip, knee]; + let free = Point::new(30.0, 120.0); + assert_eq!(callout_reshaped(r, &points, 0, free, None), vec![free, knee], "the tip lands on the pointer"); + assert_eq!(callout_reshaped(r, &points, 0, free, Some(ShiftLock::LevelOrPlumb)), vec![Point::new(30.0, 125.0), knee], "held level from the knee"); + let held = callout_reshaped(r, &points, 0, Point::new(30.0, 80.0), Some(ShiftLock::Angle45)); + let diagonal = |p: Point| { + let d = p - knee; + d.x < 0.0 && d.y < 0.0 && (d.x.abs() - d.y.abs()).abs() < 1e-9 + }; + assert!(matches!(held.as_slice(), [t, k] if *k == knee && diagonal(*t)), "held to 45 degrees from the knee: {held:?}"); +} + +/// The overlay paints an annotation as the in-flight edit leaves it: moved with its points and strokes, resized, +/// reshaped with its box around the new points, and a resized callout's box going while its tip and knee stay. +#[cfg(feature = "ui")] +#[trial] +fn an_edited_annotation_takes_a_live_move_reshape_and_callout_resize() { + use crate::annotate::AnnotationEdit; + use kurbo::Vec2; + + let delta = Vec2::new(5.0, 10.0); + let boxed = square(1, AnnotationKind::Rectangle); + let moved = boxed.edited(&AnnotationEdit::Move { ids: vec![AnnotationId(1)], delta }); + assert_eq!(moved.map(|a| a.rect), Some(Rect::new(15.0, 20.0, 55.0, 40.0))); + assert_eq!(boxed.edited(&AnnotationEdit::Move { ids: vec![AnnotationId(9)], delta }), None, "another annotation's move"); + let to = Rect::new(0.0, 0.0, 80.0, 60.0); + assert_eq!(boxed.edited(&AnnotationEdit::Resize { id: AnnotationId(1), rect: to }).map(|a| a.rect), Some(to)); + assert_eq!(boxed.edited(&AnnotationEdit::Resize { id: AnnotationId(9), rect: to }), None, "another annotation's resize"); + assert_eq!(boxed.edited(&AnnotationEdit::Delete(vec![AnnotationId(1)])), None, "not a live edit"); + + let mut line = annotation(2, AnnotationKind::Line, Rect::new(10.0, 10.0, 50.0, 10.0)); + line.points = vec![Point::new(10.0, 10.0), Point::new(50.0, 10.0)]; + let moved = line.edited(&AnnotationEdit::Move { ids: vec![AnnotationId(1), AnnotationId(2)], delta }); + assert_eq!(moved.map(|a| a.points), Some(vec![Point::new(15.0, 20.0), Point::new(55.0, 20.0)])); + let points = vec![Point::new(10.0, 10.0), Point::new(60.0, 40.0)]; + let reshaped = line.edited(&AnnotationEdit::Reshape { id: AnnotationId(2), points: points.clone() }); + assert_eq!(reshaped.map(|a| (a.points, a.rect)), Some((points, Rect::new(10.0, 10.0, 60.0, 40.0)))); + + let mut ink = annotation(3, AnnotationKind::Ink, Rect::new(0.0, 0.0, 10.0, 10.0)); + ink.strokes = vec![vec![Point::new(0.0, 0.0), Point::new(10.0, 10.0)]]; + let moved = ink.edited(&AnnotationEdit::Move { ids: vec![AnnotationId(3)], delta }); + assert_eq!(moved.map(|a| a.strokes), Some(vec![vec![Point::new(5.0, 10.0), Point::new(15.0, 20.0)]])); + + let mut callout = annotation(4, AnnotationKind::Callout, Rect::new(100.0, 100.0, 200.0, 150.0)); + callout.points = vec![Point::new(20.0, 60.0), Point::new(80.0, 125.0)]; + let to = Rect::new(110.0, 90.0, 230.0, 160.0); + let resized = callout.edited(&AnnotationEdit::Resize { id: AnnotationId(4), rect: to }); + assert_eq!(resized.map(|a| (a.rect, a.points)), Some((to, callout.points.clone()))); +} + +/// Under `FixedPoints` and `NoResize` a selected annotation offers no handle, pointwise or boxed, and its body still +/// selects; `Free` keeps the kind's handles, a callout's tip and knee among them. +#[trial] +fn a_fixed_points_or_no_resize_annotation_shows_no_handle_and_still_selects() { + let mut line = square(1, AnnotationKind::Line); + line.points = vec![Point::new(100.0, 100.0), Point::new(200.0, 100.0)]; + let boxed = square(2, AnnotationKind::Rectangle); + assert_eq!(handles(&line).len(), 2); + assert_eq!(handles(&boxed).len(), 8); + let selected = [AnnotationId(1), AnnotationId(2)]; + for rule in [HandleRule::FixedPoints, HandleRule::NoResize] { + let (mut line, mut boxed) = (line.clone(), boxed.clone()); + line.handle_rule = rule; + boxed.handle_rule = rule; + assert!(handles(&line).is_empty(), "{rule:?} line: {:?}", handles(&line)); + assert!(handles(&boxed).is_empty(), "{rule:?} box: {:?}", handles(&boxed)); + let all = [line, boxed]; + assert_eq!(hit(&all, &selected, Point::new(100.0, 100.0), 2.0, ICON), Some(AnnotationHit::Body(AnnotationId(1))), "{rule:?} line end"); + assert_eq!(hit(&all, &selected, Point::new(11.0, 11.0), 2.0, ICON), Some(AnnotationHit::Body(AnnotationId(2))), "{rule:?} box corner"); + } + + let mut callout = annotation(3, AnnotationKind::Callout, Rect::new(100.0, 100.0, 200.0, 150.0)); + let (tip, knee) = (Point::new(20.0, 60.0), Point::new(80.0, 125.0)); + callout.points = vec![tip, knee]; + let shown = handles(&callout); + assert_eq!(shown.len(), 10, "{shown:?}"); + assert!(shown.contains(&(AnnotationHandle::Point(0), tip)) && shown.contains(&(AnnotationHandle::Point(1), knee)), "{shown:?}"); +} + // reshaped with shift snaps the segment. // AnnotationGroup::tools order and Eraser in Draw. diff --git a/crates/review/src/lib.rs b/crates/review/src/lib.rs index c27a790fd..24803f782 100644 --- a/crates/review/src/lib.rs +++ b/crates/review/src/lib.rs @@ -29,9 +29,11 @@ mod annotate_tests; mod versions_tests; #[cfg(feature = "ui")] -pub use annotate::AnnotationEdit; -pub use annotate::{Annotation, AnnotationGroup, AnnotationHandle, AnnotationHit, AnnotationId, AnnotationKind, AnnotationTool}; -pub use comments::{CommentAnchor, CommentFilter, CommentMessage, CommentSort, CommentThread, Reaction, ReviewStatus, ThreadId}; +pub use annotate::{AnnotationEdit, Placement}; +pub use annotate::{Annotation, AnnotationGroup, AnnotationHandle, AnnotationHit, AnnotationId, AnnotationKind, AnnotationTool, HandleRule, ShiftLock}; +pub use comments::{ + CommentAnchor, CommentFilter, CommentMessage, CommentSort, CommentThread, PageOrder, Reaction, ReviewStatus, ReviewerStatus, ThreadId, +}; pub use revisions::{Revision, RevisionAction, RevisionKind}; pub use signature::{SavedSignature, SignatureDraft, SignatureImage, SignatureTab}; pub use versions::{Branch, BranchId, BranchState, HistoryRow, Version, VersionId}; diff --git a/crates/review/src/ui/annotate/overlay.rs b/crates/review/src/ui/annotate/overlay.rs index 63f83d824..18cccd2a9 100644 --- a/crates/review/src/ui/annotate/overlay.rs +++ b/crates/review/src/ui/annotate/overlay.rs @@ -1,17 +1,19 @@ //! Painting annotations on the canvas: [`AnnotationOverlay`]. -use craft_behavior::{Input, Metrics}; +use std::borrow::Cow; + +use craft_behavior::{IconId, Input, Metrics}; use craft_ui::canvas::canvas_space; use craft_ui::contract::{Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; use craft_ui::fonts::FontRef; -use craft_ui::primitives::{DataWidth, DocRun, DocText, Draw, Handle, HandleShape, PaintShape, StrokeWidth}; +use craft_ui::primitives::{DataWidth, DocRun, DocText, Draw, Handle, HandleShape, IconSpec, PaintShape, StrokeWidth}; use craft_ui::runtime::env::Label; use craft_ui::style::{ComponentStyle, DataColor, HandleLook, StateSet, StyleColor, StyleCx}; use egui::{CornerRadius, Pos2, Response}; use kurbo::{Point, Rect}; use super::tool::{color32, corners}; -use crate::annotate::{Annotation, AnnotationEdit, AnnotationHandle, AnnotationId, AnnotationKind, handles}; +use crate::annotate::{Annotation, AnnotationEdit, AnnotationHandle, AnnotationId, AnnotationKind, callout_leader, handles, marker_rect}; /// The ellipse inscribed in `rect`, as a closed run of page points. pub(super) fn ellipse_points(rect: Rect) -> Vec { @@ -83,6 +85,28 @@ fn closed(mut points: Vec) -> PaintShape { PaintShape::Path(points) } +/// Strokes the pictogram of `kind` into the screen `slot` with `line`. +fn paint_pictogram(kind: AnnotationKind, slot: egui::Rect, line: &impl Fn(PaintShape)) { + for (run, is_closed) in pictogram(kind) { + let points: Vec = run.iter().map(|&(x, y)| slot.min + egui::vec2(x * slot.width(), y * slot.height())).collect(); + line(if is_closed { closed(points) } else { PaintShape::Path(points) }); + } +} + + +/// A commented markup's marker in the screen `slot`, with a leader to the top right of its last quad. It takes the +/// annotation's colour at full strength, so a faint highlight still shows its marker. +fn paint_marker(draw: &Draw<'_>, a: &Annotation, slot: egui::Rect, to_screen: &impl Fn(Point) -> Pos2) { + let [r, g, b] = a.color; + let color = DataColor::new(egui::Color32::from_rgb(r, g, b)); + let line = |shape: PaintShape| draw.stroke(&shape, StrokeWidth::Thin, color); + if let Some(target) = a.points.chunks(4).last().map(|quad| around(quad.iter().map(|&p| to_screen(p)))) { + line(PaintShape::Path(vec![slot.left_bottom(), target.right_top()])); + } + // PLAN: assumed Draw::data_icon(&self, Rect, &IconSpec, DataColor) (pdf-comments-w5) + draw.data_icon(slot, &IconSpec::svg(IconId::new("note")), color); +} + fn paint_annotation(draw: &Draw<'_>, a: &Annotation, to_screen: &impl Fn(Point) -> Pos2, (text_size, icon_side): (f32, f32), hairline: f32) { use AnnotationKind as K; let scale = (to_screen(Point::new(1.0, 0.0)) - to_screen(Point::ZERO)).length(); @@ -98,7 +122,6 @@ fn paint_annotation(draw: &Draw<'_>, a: &Annotation, to_screen: &impl Fn(Point) draw.data_fill(&PaintShape::Rect(r, CornerRadius::ZERO), color); } } - K::FreehandHighlight => todo!("CM-C1"), K::Underline | K::StrikeOut | K::Squiggly | K::ReplaceText => { for r in quads() { let y = if matches!(a.kind, K::StrikeOut | K::ReplaceText) { r.center().y } else { r.bottom() }; @@ -134,7 +157,8 @@ fn paint_annotation(draw: &Draw<'_>, a: &Annotation, to_screen: &impl Fn(Point) line(closed(scalloped(&corners, width * CLOUD_BUMP))); } } - K::Ink => { + // A freehand highlight is ink at its own width, translucent through its colour's opacity. + K::Ink | K::FreehandHighlight => { for s in &a.strokes { line(PaintShape::Path(map(s))); } @@ -142,6 +166,10 @@ fn paint_annotation(draw: &Draw<'_>, a: &Annotation, to_screen: &impl Fn(Point) K::Rectangle => line(closed(map(&corners(a.rect)))), K::Oval => line(closed(map(&ellipse_points(a.rect)))), K::TextBox | K::Callout => { + let leader = if a.kind == K::Callout { callout_leader(a) } else { Vec::new() }; + if leader.len() > 1 { + line(PaintShape::Path(map(&leader))); + } let r = screen_rect(a.rect, to_screen); line(PaintShape::Rect(r, CornerRadius::ZERO)); // The text is document-scaled: the body size at zoom 1, wrapped at the box's width. @@ -152,10 +180,7 @@ fn paint_annotation(draw: &Draw<'_>, a: &Annotation, to_screen: &impl Fn(Point) } K::Note | K::Attach | K::Caret => { let slot = egui::Rect::from_min_size(to_screen(Point::new(a.rect.x0, a.rect.y0)), egui::Vec2::splat(icon_side)); - for (run, is_closed) in pictogram(a.kind) { - let points: Vec = run.iter().map(|&(x, y)| slot.min + egui::vec2(x * slot.width(), y * slot.height())).collect(); - line(if is_closed { closed(points) } else { PaintShape::Path(points) }); - } + paint_pictogram(a.kind, slot, &line); } } } @@ -179,9 +204,11 @@ pub struct AnnotationOverlayStyle { } /// Draws a page's annotations over it: markups as translucent quads (highlight at the annotation's opacity, lines -/// for underline and strike-out, a wave for squiggly), shapes and ink with their stroke, notes as their icon, text -/// boxes with their text, and the handles of the selected ones. A canvas control shown with `show_at` at the -/// canvas's rect and mapped through its view. It takes no pointer: the tool does. +/// for underline and strike-out, a wave for squiggly), shapes, ink and freehand highlights with their stroke, notes as +/// their icon, text boxes with their text and callouts with their leader, a marker beside each commented markup, the +/// frames of the selected ones and the handles of the primary (the last selected). The in-flight edit (`live`) paints +/// where it is going. A canvas control shown with `show_at` at the canvas's rect and mapped through its view. It takes +/// no pointer: the tool does. #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] #[component(canvas_control, content_painter)] pub struct AnnotationOverlay<'a> { @@ -206,6 +233,16 @@ pub enum BodyPaint<'a> { Only(&'a [AnnotationId]), } +impl BodyPaint<'_> { + /// Whether the overlay paints the body of `id`. + fn paints(self, id: AnnotationId) -> bool { + match self { + BodyPaint::All => true, + BodyPaint::Only(ids) => ids.contains(&id), + } + } +} + impl<'a> AnnotationOverlay<'a> { /// An overlay named `label` for `annotations`, with `selected` drawing handles. pub fn new(label: impl Into