PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(ui): comments, links and text selection decide a press by one hit test
alehel35d28a60cc7f
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex c2c74ac8a..d67b18b80 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -29,6 +29,7 @@ mod navigation;mod organize;pub(super) mod page_cursor;pub(super) mod page_pointer;+pub(super) mod page_router;pub mod scroll_speed;mod selection;pub(super) mod signature_drag;@@ -473,6 +474,8 @@ pub struct DocView {pub(crate) signature_drag: crate::signature_drag::SignatureDrag,/// What the page modules claim for the cursor this frame; `document_area` sets it once.pub(crate) cursor: crate::page_cursor::PageCursor,+ /// Who the press the pages hold belongs to.+ pub(crate) router: crate::page_router::PageRouter,/// Escape cancelled the press the pages hold: the page ignores it until the button is up, so/// its release neither clicks nor ends a drag.pub(crate) press_cancelled: bool,@@ -590,6 +593,7 @@ impl DocView {self.org_drag = None;self.panel_drag = None;self.selection_drag = false;+ self.router.cancel();self.auto_scroll.cancel();self.prepare.cancel_pointer_gesture();self.content.cancel_pointer_gesture();@@ -729,6 +733,7 @@ impl DocView {fill_signature_page: None,signature_drag: Default::default(),cursor: Default::default(),+ router: Default::default(),press_cancelled: false,}}@@ -1124,6 +1129,11 @@ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<let PageFrame { resp, ptr, pointer, .. } = *frame;let cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info };let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ let hits = |view: &DocView, p: Pos2| [link_hit(info, &xf, i, p), comments::hit(&pcx, view, p)].into_iter().flatten();+ if let Some(o) = ptr.pressed().filter(|o| xf.rect.contains(*o)) {+ let at = hits(view, o).collect::<Vec<_>>();+ view.router.press(i, at, tool);+ }if let QuickTool::Measure(measure_tool) = tool {crate::measure_ui::page_input(ui, resp, doc, view, &pcx, measure_tool, units);}@@ -1326,6 +1336,15 @@ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<view.links.context = Some((i, l.index));}let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, resp, &pcx, view);+ // The cursor and the tip from what lies under the pointer, after the tools claimed theirs (the+ // last claim on a layer stands).+ if frame.env.unobstructed+ && let Some(p) = pointer+ {+ for h in hits(view, p).collect::<Vec<_>>() {+ view.cursor.claim_with_tip(h.layer, h.icon, h.tip);+ }+ }PageInput { consumed, area_tool }}@@ -1430,8 +1449,10 @@ fn update_text_cursor(view: &mut DocView, gesture: &TextGesture<'_>) {}fn update_selection_on_press(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) {+ // A press held by what keeps its drag (a link, a comment that moves) selects no text; one on+ // text markup lets its drag select the text underneath.let press_here = gesture.ptr.origin.is_some_and(|origin| gesture.rect.contains(origin));- if gesture.ptr.pressed().is_some() && press_here && !gesture.over_link {+ if gesture.ptr.pressed().is_some() && press_here && !view.router.keeps_drag() {let now = ui.input(|input| input.time);let (max_delay, max_dist) = ui.ctx().options(|options| (options.input_options.max_double_click_delay, options.input_options.max_click_dist));let consecutive = now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(gesture.pointer) <= max_dist);@@ -1446,7 +1467,7 @@ fn update_selection_on_press(ui: &egui::Ui, view: &mut DocView, text: &PageText,view.selection = Some(Selection::run(gesture.page, first, last));}}- if gesture.resp.drag_started() && press_here && !gesture.over_link {+ if gesture.resp.drag_started() && press_here && !view.router.keeps_drag() {view.actions_dismissed = None;view.selection_drag = true;let origin = gesture.ptr.origin.unwrap_or(gesture.pointer);@@ -1518,7 +1539,7 @@ fn finish_text_pointer_gesture(ui: &egui::Ui, view: &mut DocView, text: &PageTex&& let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor)){view.selection = Some(Selection::run(gesture.page, first, last));- } else if gesture.resp.clicked() && view.clicks < 2 && !gesture.over_link {+ } else if gesture.resp.clicked() && view.clicks < 2 && !view.router.keeps_drag() {let shift = ui.input(|input| input.modifiers.shift);match (view.selection.as_mut().filter(|selection| shift && selection.page == gesture.page).map(|selection| &mut selection.span),@@ -1606,25 +1627,14 @@ fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_// Links: the hand and the link's target, which count only for the tools that follow or// edit links (`Layer::reached_by`). Tips draw above the palette, so none shows while it is// open, even beside it.- if unobstructed && let Some(p) = pointer {- for l in info.links.iter().filter(|l| l.page == i) {- let sr = xf.user_rect(info, i, l.rect);- if sr.contains(p) {- let label = match &l.target {- LinkTarget::Page(n, _) => {- crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))])- }- LinkTarget::Uri(u) => u.clone(),- LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),- LinkTarget::RemoteGoTo { file, .. } => file.clone(),- LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),- };- view.cursor.claim_with_tip(Layer::Link, egui::CursorIcon::PointingHand, Some(label));- if resp.clicked() && tool == QuickTool::Select && !input.consumed {- frame.out.clicked_link = Some(l.target.clone());- }- }- }+ if unobstructed+ && resp.clicked()+ && tool == QuickTool::Select+ && !input.consumed+ && let Some(crate::page_router::Owner::Link { index }) = view.router.owner(i)+ && let Some(l) = info.links.get(index)+ {+ frame.out.clicked_link = Some(l.target.clone());}// Comments say what they are with any tool, beside its cursor, as Acrobat's do.comments::describe(&pcx, view);@@ -1759,6 +1769,21 @@ fn draw_page(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, ipage_overlays(ui, view, frame, &slot, &input);}+/// The link under `p` on `page`: the hand, and where a click goes. Only the Select tool follows+/// links and the Link tool edits them (`Layer::reached_by`).+fn link_hit(info: &DocInfo, xf: &PageXform, page: usize, p: Pos2) -> Option<crate::page_router::Hit> {+ let (index, l) = info.links.iter().enumerate().rfind(|(_, l)| l.page == page && xf.user_rect(info, page, l.rect).contains(p))?;+ let label = match &l.target {+ LinkTarget::Page(n, _) => crate::i18n::fmt(tl!("Go to page {p}"), &[("p", info.pages.get(*n).map(|p| p.label.as_str()).unwrap_or("?"))]),+ LinkTarget::Uri(u) => u.clone(),+ LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(),+ LinkTarget::RemoteGoTo { file, .. } => file.clone(),+ LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]),+ };+ let owner = crate::page_router::Owner::Link { index };+ Some(crate::page_router::Hit { tip: Some(label), ..crate::page_router::Hit::new(owner, Layer::Link, egui::CursorIcon::PointingHand) })+}+/// Escape while the pages hold a press abandons the gesture it drives, whichever tool's: nothing is/// placed, drawn, moved, resized or opened, and the press is ignored until the button is up. The/// frame of the release still belongs to the cancelled press.@@ -1853,6 +1878,7 @@ fn draw_pages(// or a press they hold. The page modules read it rather than egui's raw pointer state.let ptr = PagePointer::read(ui, &resp, modal);cancel_on_escape(ui.ctx(), view, &ptr);+ view.router.settle(ptr.any_down, !ptr.edges.is_empty());let pointer = ptr.pos;// A press on a page makes it the current one (as in Acrobat), so a page command with// no selection (Rotate, Delete) acts on the page the reader pointed at, not on a pagediff --git a/crates/ui-egui/src/canvas/page_router.rs b/crates/ui-egui/src/canvas/page_router.rsnew file mode 100644index 000000000..82769bd8f--- /dev/null+++ b/crates/ui-egui/src/canvas/page_router.rs@@ -0,0 +1,151 @@+//! Who a press on the pages belongs to.+//!+//! Each page module answers "what of mine is under this point?" in one place, its hit test, and+//! the answer is a [`Hit`]: what is there ([`Owner`]), on which [`Layer`], with which cursor and+//! tip. The pointer's hits set the cursor and the tip; on the frame of a press, the hits at the+//! press point decide who captures it ([`PageRouter::press`]), by the same table: the highest layer+//! the active tool reaches. Until the button is up only the owner acts on the press, its drag and+//! its release, so what the cursor promised is what the press does, and nothing takes a gesture+//! back halfway.++use egui::CursorIcon;++use crate::QuickTool;+use crate::page_cursor::Layer;++/// What a hit is on.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Owner {+ /// A comment (or a Fill & Sign mark), by its `/Annots` index, and the part of it.+ Comment { index: usize, part: CommentPart },+ /// A link, by its index in the document's links.+ Link { index: usize },+}++/// The part of a comment a hit is on.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum CommentPart {+ /// The comment itself: a drag moves it, a click selects it.+ Body,+ /// A resize handle of the selected comment: (-1, 0 or 1) across, then down.+ Handle(i8, i8),+ /// A point of the selected line, polygon or cloud.+ Point(usize),+}++/// What lies under a point, for one page module.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct Hit {+ pub owner: Owner,+ pub layer: Layer,+ pub icon: CursorIcon,+ /// Beside the pointer where this hit wins (a link's target).+ pub tip: Option<String>,+ /// A drag from here is not this owner's: a click on a highlight selects it, a drag across it+ /// selects the text underneath.+ pub declines_drag: bool,+}++impl Hit {+ pub(crate) fn new(owner: Owner, layer: Layer, icon: CursorIcon) -> Self {+ Hit { owner, layer, icon, tip: None, declines_drag: false }+ }+}++/// The hit that wins among `hits` with `tool`: the highest layer the tool reaches, the last of+/// equals (modules are asked bottom up, in paint order).+pub(crate) fn top(hits: impl IntoIterator<Item = Hit>, tool: QuickTool) -> Option<Hit> {+ hits.into_iter().filter(|h| h.layer.reached_by(tool)).fold(None, |best: Option<Hit>, h| match best {+ Some(b) if b.layer > h.layer => Some(b),+ _ => Some(h),+ })+}++/// A press the pages hold, and who it belongs to.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct Capture {+ pub page: usize,+ pub owner: Owner,+ pub declines_drag: bool,+}++/// The press the pages hold, from its frame until the button is up.+#[derive(Debug, Default)]+pub(crate) struct PageRouter {+ capture: Option<Capture>,+}++impl PageRouter {+ /// A press on `page`: `hits` at the press point decide who it belongs to. A press nobody's+ /// hit claims is held by nobody (the page's text, or a tool that acts anywhere on the page).+ pub(crate) fn press(&mut self, page: usize, hits: impl IntoIterator<Item = Hit>, tool: QuickTool) {+ self.capture = top(hits, tool).map(|h| Capture { page, owner: h.owner, declines_drag: h.declines_drag });+ }++ /// Who holds the press on `page`.+ pub(crate) fn owner(&self, page: usize) -> Option<Owner> {+ self.capture.as_ref().filter(|c| c.page == page).map(|c| c.owner)+ }++ /// Whether the press is held by someone who keeps its drag: then the page's text is not+ /// selected by it.+ pub(crate) fn keeps_drag(&self) -> bool {+ self.capture.as_ref().is_some_and(|c| !c.declines_drag)+ }++ /// The press is over once the button is up and its release has been seen.+ pub(crate) fn settle(&mut self, any_down: bool, edges: bool) {+ if !any_down && !edges {+ self.capture = None;+ }+ }++ /// Drops the press (Escape, a dialog, automation's cancel).+ pub(crate) fn cancel(&mut self) {+ self.capture = None;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn hit(layer: Layer, index: usize) -> Hit {+ Hit::new(Owner::Comment { index, part: CommentPart::Body }, layer, CursorIcon::Move)+ }++ #[test]+ fn the_highest_reached_layer_wins_and_the_last_of_equals() {+ let hits = [hit(Layer::Comment, 0), hit(Layer::Link, 1), hit(Layer::Comment, 2)];+ assert_eq!(top(hits.clone(), QuickTool::Select).map(|h| h.owner), Some(hits[2].owner));+ // A stamp reaches neither links nor comments.+ let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved);+ assert_eq!(top(hits, stamp), None);+ assert_eq!(top([hit(Layer::Placed, 3), hit(Layer::Comment, 4)], stamp).map(|h| h.owner), Some(hit(Layer::Placed, 3).owner));+ }++ #[test]+ fn a_press_is_held_until_the_button_is_up_and_its_release_seen() {+ let mut r = PageRouter::default();+ r.press(2, [hit(Layer::Comment, 7)], QuickTool::Select);+ assert_eq!(r.owner(2), Some(hit(Layer::Comment, 7).owner));+ assert_eq!(r.owner(1), None, "only on its page");+ assert!(r.keeps_drag());+ r.settle(false, true);+ assert!(r.owner(2).is_some(), "the release frame still belongs to the press");+ r.settle(false, false);+ assert_eq!(r.owner(2), None);+ r.press(0, [], QuickTool::Select);+ assert_eq!(r.owner(0), None, "a press nobody claims is held by nobody");+ assert!(!r.keeps_drag());+ }++ #[test]+ fn a_highlight_lets_its_drag_go_to_the_text() {+ let mut r = PageRouter::default();+ r.press(0, [Hit { declines_drag: true, ..hit(Layer::Comment, 0) }], QuickTool::Select);+ assert!(r.owner(0).is_some() && !r.keeps_drag());+ r.cancel();+ assert_eq!(r.owner(0), None);+ }+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 8a8c51775..317c2b45c 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -77,6 +77,7 @@ use canvas::fling;use canvas::image_pick;use canvas::page_cursor;use canvas::page_pointer;+use canvas::page_router;pub use canvas::scroll_speed;use canvas::signature_drag;use canvas::wheel_boost;diff --git a/crates/ui-egui/src/tools/comments.rs b/crates/ui-egui/src/tools/comments.rsindex 5909fdd42..ac1d82ea9 100644--- a/crates/ui-egui/src/tools/comments.rs+++ b/crates/ui-egui/src/tools/comments.rs@@ -37,7 +37,7 @@ pub(crate) use geometry::{corner_ratio, page_rotation, resized};pub use geometry::{drawn_text_box_rect, text_box_rect};#[cfg(test)]use input::hover_tip;-pub(crate) use input::{describe, fill_grabs, keys, nudge_keys, page_after_text, page_input, select_grabs};+pub(crate) use input::{describe, fill_grabs, hit, keys, nudge_keys, page_after_text, page_input, select_grabs};pub use menu::{CanvasAction, fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid};#[cfg(test)]use menu::{RECENT_CUSTOM, same_colour};diff --git a/crates/ui-egui/src/tools/comments/input.rs b/crates/ui-egui/src/tools/comments/input.rsindex af78a1e46..102767b6c 100644--- a/crates/ui-egui/src/tools/comments/input.rs+++ b/crates/ui-egui/src/tools/comments/input.rs@@ -6,6 +6,7 @@ use super::paint::{drawn_shape, edit_anchor, erase, new_comment};use super::state::{Composer, ComposerKind, Gesture, PageCx};use super::{Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, Pos2, QuickTool, Rect, Shape, vec2};use crate::page_cursor::{Layer, Subject};+use crate::page_router::{CommentPart, Hit, Owner};/// Comment input on one page, before text selection runs. Returns `true` when the pointer/// gesture belongs to commenting (text selection must ignore it).@@ -34,79 +35,104 @@ pub(crate) fn page_input(ui: &egui::Ui, resp: &egui::Response, cx: &PageCx<'_>,}let gestures = Gestures { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page };match cx.tool {- QuickTool::Comment(_) if draw_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),+ QuickTool::Comment(_) if draw_grab => select_input(ui, resp, cx, view, pointer, origin),QuickTool::Comment(tool) if tool.draws() => gestures.draw_shape(view, tool),QuickTool::Comment(tool) if tool.clicks_points() => gestures.click_points(view, tool),QuickTool::Comment(CommentTool::Callout) => gestures.callout(view),QuickTool::Comment(CommentTool::Attach) => gestures.attach(view),QuickTool::Comment(CommentTool::Caret) => gestures.caret(view, caret_text.as_deref()),QuickTool::Comment(tool @ (CommentTool::Note | CommentTool::TextBox)) => gestures.note_or_box(view, tool),- QuickTool::Select => select_input(ui, resp, cx, view, pointer, origin, pressed_here),- QuickTool::Fill(_) if fill_grab => select_input(ui, resp, cx, view, pointer, origin, pressed_here),+ QuickTool::Select => select_input(ui, resp, cx, view, pointer, origin),+ QuickTool::Fill(_) if fill_grab => select_input(ui, resp, cx, view, pointer, origin),_ => false,}}-/// With a Fill & Sign tool, the Fill & Sign marks already on the page are picked up as with the-/// Select tool, as in Acrobat: hovering one shows the move cursor, a click selects it, a drag-/// moves it and the selected one's handles resize it. Elsewhere the tool places its mark. While-/// the button is down the press decides; otherwise the pointer (egui clears the press origin on-/// release, so a click is located by the pointer).-pub(crate) fn fill_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {- matches!(cx.tool, QuickTool::Fill(_)) && grabs(cx, view, |a| a.fill_sign)-}--/// With the Select tool, a comment that would move (not text markup) is picked up before a form-/// field under it, so a signature placed over a field can still be dragged off it.-pub(crate) fn select_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {- cx.tool == QuickTool::Select && grabs(cx, view, |a| !is_markup(&a.subtype))-}--/// With a shape tool (rectangle, oval, line, polygon…), the selected comment's resize handles-/// are picked up as with the Select tool, so the shape just drawn can be resized straight away-/// (#2338). Only the handles: a press anywhere else, the shape itself included, still draws.-pub(crate) fn draw_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {- let QuickTool::Comment(tool) = cx.tool else { return false };- if !(tool.draws() || tool.clicks_points()) || tool == CommentTool::Eraser || cx.hidden {- return false;- }- let cv = &view.comments;- if matches!(cv.gesture, Some(Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {- return true;+/// What of the comments lies under `p`, for the cursor, the tip and the press: the one hit test+/// of this module. With the Select tool, the selected comment's point handles, then its resize+/// handles, then the topmost comment. With a Fill & Sign tool, the same over Fill & Sign's marks+/// only, as Acrobat picks them up: a press anywhere else places the tool's mark. With a shape+/// tool (rectangle, oval, line, polygon…), only the selected comment's handles, so the shape just+/// drawn can be resized straight away (#2338); a press anywhere else, the shape itself included,+/// draws. `None` with other tools, off the page, or with comments hidden.+pub(crate) fn hit(cx: &PageCx<'_>, view: &DocView, p: Pos2) -> Option<Hit> {+ if cx.hidden || !cx.xf.rect.contains(p) {+ return None;}- // A polygon being clicked out keeps its clicks, even near an old shape's handle.- if cv.gesture.is_some() {- return false;+ let pick: fn(&Annotation) -> bool = match cx.tool {+ QuickTool::Select => |_| true,+ QuickTool::Fill(_) => |a| a.fill_sign,+ QuickTool::Comment(tool) if (tool.draws() || tool.clicks_points()) && tool != CommentTool::Eraser => {+ // A polygon being clicked out keeps its clicks, even near an old shape's handle.+ if view.comments.gesture.is_some() {+ return None;+ }+ |_| true+ }+ _ => return None,+ };+ let bodies = matches!(cx.tool, QuickTool::Select | QuickTool::Fill(_));+ if let Some(a) = view.comments.selected.filter(|(page, _)| *page == cx.page).and_then(|(_, i)| cx.get(i)).filter(|a| pick(a) && cx.allowed) {+ if grabs_points(cx.tool)+ && reshapable(a)+ && let Some(point) = point_handle(cx, a, p)+ {+ return Some(Hit::new(Owner::Comment { index: a.index, part: CommentPart::Point(point) }, Layer::Handle, egui::CursorIcon::Crosshair));+ }+ if resizable(a)+ && let Some((x, y)) = HANDLES.into_iter().find(|h| handle_pos(cx.screen_rect(a), *h).distance(p) <= 7.0)+ {+ let icon = match (x, y) {+ (0, _) => egui::CursorIcon::ResizeVertical,+ (_, 0) => egui::CursorIcon::ResizeHorizontal,+ (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,+ _ => egui::CursorIcon::ResizeNeSw,+ };+ return Some(Hit::new(Owner::Comment { index: a.index, part: CommentPart::Handle(x, y) }, Layer::Handle, icon));+ }+ }+ let a = cx.hit(p).filter(|a| bodies && pick(a))?;+ // A click on a highlight over a link follows the link, so the link's hand and tip show there.+ if cx.tool == QuickTool::Select && a.subtype == "Highlight" && on_link(cx, p) {+ return None;}- press_point(cx).is_some_and(|p| on_handle(cx, view, p, |_| true))+ let markup = is_markup(&a.subtype);+ let icon = if cx.allowed && !markup { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand };+ // Signatures and Fill & Sign's marks are placed on the page rather than comments on it.+ let layer = if a.fill_sign { Layer::Placed } else { Layer::Comment };+ // Text markup does not move: a click selects it, a drag across it selects the text.+ Some(Hit { declines_drag: markup, ..Hit::new(Owner::Comment { index: a.index, part: CommentPart::Body }, layer, icon) })}-/// Whether the press (or, with no button down, the pointer) is on a `pick` comment or on the-/// selected one's resize handles.-fn grabs(cx: &PageCx<'_>, view: &DocView, pick: impl Fn(&Annotation) -> bool) -> bool {- if cx.hidden {- return false;- }+/// Whether the comments take the press on this page (or, with no button down, would take one+/// under the pointer), so the tools beneath leave it: a live move, resize or reshape, or a press+/// held by a comment that keeps its drag.+fn grabs(cx: &PageCx<'_>, view: &DocView) -> bool {if matches!(view.comments.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page){return true;}- let Some(p) = press_point(cx) else { return false };- on_handle(cx, view, p, &pick) || cx.hit(p).is_some_and(pick)+ if cx.ptr.any_down {+ return matches!(view.router.owner(cx.page), Some(Owner::Comment { .. })) && view.router.keeps_drag();+ }+ cx.ptr.pos.and_then(|p| hit(cx, view, p)).is_some_and(|h| !h.declines_drag)+}++/// With a Fill & Sign tool, a Fill & Sign mark already on the page is picked up as with the Select+/// tool ([`hit`]), so the tool does not place a mark there.+pub(crate) fn fill_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ matches!(cx.tool, QuickTool::Fill(_)) && grabs(cx, view)}-/// Where a gesture on this page is decided: the press while the button is down, otherwise the-/// pointer (egui clears the press origin on release). `None` off the page.-fn press_point(cx: &PageCx<'_>) -> Option<Pos2> {- (if cx.ptr.any_down { cx.ptr.origin } else { cx.ptr.pos }).filter(|p| cx.xf.rect.contains(*p))+/// With the Select tool, a comment that would move (not text markup) is picked up before a form+/// field under it, so a signature placed over a field can still be dragged off it.+pub(crate) fn select_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ cx.tool == QuickTool::Select && grabs(cx, view)}-/// Whether `p` is on a resize handle of the selected comment, when it is a resizable `pick`.-fn on_handle(cx: &PageCx<'_>, view: &DocView, p: Pos2, pick: impl Fn(&Annotation) -> bool) -> bool {- view.comments.selected.filter(|(page, _)| *page == cx.page).and_then(|(_, i)| cx.get(i)).filter(|a| pick(a) && cx.allowed).is_some_and(|a| {- (resizable(a) && HANDLES.into_iter().any(|h| handle_pos(cx.screen_rect(a), h).distance(p) <= 7.0))- || (grabs_points(cx.tool) && reshapable(a) && point_handle(cx, a, p).is_some())- })+/// With a shape tool, the selected comment's handles are picked up ([`hit`]).+fn draw_grabs(cx: &PageCx<'_>, view: &DocView) -> bool {+ matches!(cx.tool, QuickTool::Comment(_)) && grabs(cx, view)}/// Whether `p` is on one of this page's links.@@ -149,80 +175,45 @@ pub(super) fn hover_tip(a: &Annotation, prefs: &CommentPrefs) -> Option<String>Some(if body.is_empty() { who } else { format!("{who}\n{body}") })}-/// The Select tool: hover, select, move, resize, edit, delete.-fn select_input(- ui: &egui::Ui,- resp: &egui::Response,- cx: &PageCx<'_>,- view: &mut DocView,- pointer: Option<Pos2>,- origin: Option<Pos2>,- pressed_here: bool,-) -> bool {- let cv = &mut view.comments;- let selected = cv.selected.filter(|(p, _)| *p == cx.page).and_then(|(_, i)| cx.get(i));- // Handles of a selected, resizable comment.- let handle_at = |p: Pos2| -> Option<(i8, i8)> {- let a = selected.filter(|a| cx.allowed && resizable(a))?;- let r = cx.screen_rect(a);- HANDLES.into_iter().find(|h| handle_pos(r, *h).distance(p) <= 7.0)+/// The Select tool: select, move, resize, edit, delete, on the comment the press was on (its+/// owner, from [`hit`]). The cursor comes from [`hit`] too.+fn select_input(ui: &egui::Ui, resp: &egui::Response, cx: &PageCx<'_>, view: &mut DocView, pointer: Option<Pos2>, origin: Option<Pos2>) -> bool {+ let owner = match view.router.owner(cx.page) {+ Some(Owner::Comment { index, part }) => cx.get(index).map(|a| (a, part)),+ _ => None,};- // Ends and corners of a selected line, connected lines, polygon or cloud.- let point_at =- |p: Pos2| -> Option<usize> { selected.filter(|a| cx.allowed && grabs_points(cx.tool) && reshapable(a)).and_then(|a| point_handle(cx, a, p)) };+ let cv = &mut view.comments;let mut consumed = false;- if let Some(p) = pointer {- if point_at(p).is_some() {- view.cursor.claim(Layer::Handle, egui::CursorIcon::Crosshair);- } else if let Some(h) = handle_at(p) {- view.cursor.claim(- Layer::Handle,- match h {- (0, _) => egui::CursorIcon::ResizeVertical,- (_, 0) => egui::CursorIcon::ResizeHorizontal,- (-1, -1) | (1, 1) => egui::CursorIcon::ResizeNwSe,- _ => egui::CursorIcon::ResizeNeSw,- },- );- } else if let Some(a) = cx.hit(p)- // A click on a highlight over a link follows the link, so the link's hand and tip- // show there.- && !(a.subtype == "Highlight" && on_link(cx, p))- {- let movable = cx.allowed && !is_markup(&a.subtype);- let icon = if movable { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand };- // Signatures and Fill & Sign's marks are placed on the page rather than comments on it.- view.cursor.claim(if a.fill_sign { Layer::Placed } else { Layer::Comment }, icon);- }- }if resp.drag_started()- && pressed_here- && let Some(o) = origin+ && let (Some((a, part)), Some(o)) = (owner, origin){- if let (Some(point), Some(a)) = (point_at(o), selected) {- let points = a.points.iter().map(|q| [f64::from(q[0]), f64::from(q[1])]).collect();- cv.gesture = Some(Gesture::Reshape { page: cx.page, index: a.index, point, points });- consumed = true;- } else if let (Some(h), Some(a)) = (handle_at(o), selected) {- // On screen, the image is also turned by the view's rotation.- let turned = !cx.xf.rot.is_multiple_of(180);- let aspect_ratio = view.signature_drag.aspect_ratio(cx.page, a.index).map(|ratio| if turned { ratio.recip() } else { ratio });- // A drawn signature keeps its shape from the corners, as image signatures do.- let aspect_ratio = aspect_ratio.or_else(|| {- let r = cx.screen_rect(a);- (a.fill_sign && a.subtype == "Ink" && r.height() > 0.0).then(|| r.width() / r.height())- });- cv.gesture = Some(Gesture::Resize { page: cx.page, index: a.index, handle: h, from: o, aspect_ratio });- consumed = true;- } else if let Some(a) = cx.hit(o)- && !is_markup(&a.subtype)- {- cv.selected = Some((cx.page, a.index));- cv.reveal = true;- if cx.allowed {- cv.gesture = Some(Gesture::Move { page: cx.page, index: a.index, from: o });+ match part {+ CommentPart::Point(point) => {+ let points = a.points.iter().map(|q| [f64::from(q[0]), f64::from(q[1])]).collect();+ cv.gesture = Some(Gesture::Reshape { page: cx.page, index: a.index, point, points });+ consumed = true;+ }+ CommentPart::Handle(x, y) => {+ // On screen, the image is also turned by the view's rotation.+ let turned = !cx.xf.rot.is_multiple_of(180);+ let aspect_ratio = view.signature_drag.aspect_ratio(cx.page, a.index).map(|ratio| if turned { ratio.recip() } else { ratio });+ // A drawn signature keeps its shape from the corners, as image signatures do.+ let aspect_ratio = aspect_ratio.or_else(|| {+ let r = cx.screen_rect(a);+ (a.fill_sign && a.subtype == "Ink" && r.height() > 0.0).then(|| r.width() / r.height())+ });+ cv.gesture = Some(Gesture::Resize { page: cx.page, index: a.index, handle: (x, y), from: o, aspect_ratio });+ consumed = true;}- consumed = true;+ CommentPart::Body if !is_markup(&a.subtype) => {+ cv.selected = Some((cx.page, a.index));+ cv.reveal = true;+ if cx.allowed {+ cv.gesture = Some(Gesture::Move { page: cx.page, index: a.index, from: o });+ }+ consumed = true;+ }+ CommentPart::Body => {}}}if matches!(cv.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page) {@@ -266,15 +257,10 @@ fn select_input(// (egui clears the press origin on release, so clicks are located by the pointer.)let on_page = pointer.is_some_and(|p| cx.xf.rect.contains(p));if resp.clicked() && on_page {- let follow_link =- cx.tool == QuickTool::Select && !consumed && cv.gesture.is_none() && !resp.double_clicked() && pointer.is_some_and(|p| on_link(cx, p));- match pointer.and_then(|p| cx.hit(p)) {- Some(a) if a.subtype == "Highlight" && follow_link => {- // A plain click follows the link beneath text highlighting. Keep other- // annotations and active gestures in control of their own input.- cv.selected = None;- }- Some(a) => {+ // A click elsewhere (a link beneath text highlighting included: it follows the link)+ // leaves comments unselected.+ match owner {+ Some((a, _)) => {cv.selected = Some((cx.page, a.index));cv.reveal = true;consumed = true;@@ -285,7 +271,7 @@ fn select_input(if resp.double_clicked()&& on_page&& cx.allowed- && let Some(a) = pointer.and_then(|p| cx.hit(p))+ && let Some((a, _)) = owner{cv.selected = Some((cx.page, a.index));cv.composer = Some(Composer {diff --git a/crates/ui-egui/src/tools/comments/state.rs b/crates/ui-egui/src/tools/comments/state.rsindex 36149bb2a..3bcb12f90 100644--- a/crates/ui-egui/src/tools/comments/state.rs+++ b/crates/ui-egui/src/tools/comments/state.rs@@ -307,9 +307,10 @@ impl PageCx<'_> {.collect()}- /// The topmost comment under `p`.+ /// The topmost comment under `p`: the one drawn last, in `/Annots` order (inspection lists+ /// comments by position, not in paint order).pub(super) fn hit(&self, p: Pos2) -> Option<&Annotation> {- self.comments().filter(|a| self.screen_rects(a).any(|r| r.expand(3.0).contains(p))).last()+ self.comments().filter(|a| self.screen_rects(a).any(|r| r.expand(3.0).contains(p))).max_by_key(|a| a.index)}pub(crate) fn get(&self, index: usize) -> Option<&Annotation> {diff --git a/crates/ui-egui/tests/it/pointer.rs b/crates/ui-egui/tests/it/pointer.rsindex 442eade9e..fbd3d720e 100644--- a/crates/ui-egui/tests/it/pointer.rs+++ b/crates/ui-egui/tests/it/pointer.rs@@ -296,11 +296,23 @@ fn a_links_tip_shows_only_with_its_hand() {assert_eq!(hover(&mut h, rectangle, 3.0), (Crosshair, false), "a drag draws a rectangle");}+/// A drag from plain text onto a link still selects the text: the press decides, not where the+/// pointer has got to once egui calls it a drag.+#[test]+fn a_drag_from_text_onto_a_link_selects_the_text() {+ let mut h = open(linked_text_pdf(), "150", false);+ // "before you start." lies right of the link, which covers x 40..160.+ let (plain, linked) = (at(&h, 200.0, 303.0), at(&h, 100.0, 303.0));+ assert_eq!(wait_for_cursor(&mut h, plain, |c| c == egui::CursorIcon::Text), egui::CursorIcon::Text, "the page's text has arrived");+ mouse_drag(&mut h, plain, linked - plain);+ let selected = h.state().views[0].selected_text().unwrap_or_default();+ assert!(selected.contains("example.org"), "the drag selected across the link: {selected:?}");+}+/// Over two comments the tip names the one drawn on top (#3620), and a click should select that/// one too. The renderer paints in `/Annots` order, but the hit test takes the last comment in/// inspection's order, which is by top edge, and selects the one underneath.#[test]-#[ignore = "step 3 of the page pointer router: one hit test"]fn a_click_on_stacked_comments_selects_the_one_drawn_on_top() {let mut h = open(stacked_comments_pdf(), "150", false);let overlap = at(&h, 125.0, 225.0);