pdf-comments-w8: net change of 3 commits

- pdf-comments-w8: written from its sheet
- pdf-comments-w8: repair 1
- pdf-comments-w8: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:27 -05:00
parent b3217c7b37
commit ce521c18e4
5 changed files with 687 additions and 1435 deletions
+34 -117
View File
@@ -1,40 +1,21 @@
use super::bridge::new_comment;
use super::geometry::{drawn_text_box_rect, page_rotation, text_box_rect};
use super::paint::{edited_in_view, new_comment};
use super::state::{ComposerKind, PageCx};
use super::{
Color32, CommentPrefs, CommentTool, CornerRadius, DocInfo, DocView, Edit, LineEnding, Markup, NoteIcon, PagePointer, QuickTool, Shape, Tokens,
pos2, theme,
};
use crate::page_keys::PageKeys;
use super::{CommentPrefs, CommentTool, DocInfo, DocView, Edit, LineEnding, Markup, NoteIcon, Rect, Shape};
use craft::review::ui::thread::{CommentComposer, ComposerClose, ComposerDraft};
/// The floating composer card (new note, new text box, edit). Returns the edit to apply.
pub(crate) fn composer(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, info: &DocInfo, prefs: &CommentPrefs) -> Option<Edit> {
pub(crate) fn composer(ui: &mut egui::Ui, view: &mut DocView, info: &DocInfo, prefs: &CommentPrefs) -> Option<Edit> {
let c = view.comments.composer.as_ref()?;
let page = c.page;
let Some(xf) = view.page_xform(page) else {
// Scrolled away: keep the draft until the page is back, and give it the keyboard then.
if let Some(c) = view.comments.composer.as_mut() {
c.focus = true;
}
return None;
};
let cx = PageCx {
page,
xf: &xf,
ptr: &PagePointer::default(),
info,
tool: QuickTool::Select,
prefs,
allowed: true,
hidden: false,
redact_mark: ([0.89, 0.13, 0.13], 1.0),
keys,
};
let anchor = cx.to_screen(c.at);
// Scrolled away: keep the draft until the page is back.
let xf = view.page_xform(page)?;
let cx = PageCx { page, xf: &xf, info, prefs, allowed: true, hidden: false };
let mut anchor = Some(cx.to_screen(c.at));
let viewport = view.viewport_rect();
let t = Tokens::get(ctx);
let mut post = false;
let mut cancel = false;
let typewriter_edit = matches!(c.kind, ComposerKind::Edit(index) if info.annotations.iter().any(|a|
a.page == page && a.index == index && a.subtype == "FreeText" && a.intent.as_deref() == Some("FreeTextTypeWriter")
));
let c = view.comments.composer.as_mut()?;
let title = match c.kind {
ComposerKind::Note => "Sticky note",
@@ -48,87 +29,39 @@ pub(crate) fn composer(ctx: &egui::Context, keys: PageKeys, view: &mut DocView,
// Its comment scrolled out of the document: keep the draft until it is back, rather than
// pushing the card into the window over the mode bar and toolbar (#4021). An edited comment
// that is only partly scrolled away keeps its card, at the nearest point inside the document.
let mut anchor = anchor;
if !viewport.contains(anchor) {
if let Some(at) = anchor
&& !viewport.contains(at)
{
let part_visible = matches!(c.kind, ComposerKind::Edit(index) if edited_in_view(&cx, index, viewport));
if !part_visible {
c.focus = true;
return None;
if part_visible {
anchor = Some(at.clamp(viewport.min, viewport.max));
} else {
anchor = None;
}
anchor = anchor.clamp(viewport.min, viewport.max);
}
let pos = pos2(anchor.x + 12.0, anchor.y);
let area = egui::Area::new(egui::Id::unique(("comment-composer", view.pane.key))).order(egui::Order::Foreground).constrain_to(viewport);
area.fixed_pos(pos).show(ctx, |ui| {
egui::Frame::popup(ui.style()).inner_margin(egui::Margin::same(12)).corner_radius(CornerRadius::same(8)).show(ui, |ui| {
ui.set_width(260.0);
ui.horizontal(|ui| {
ui.label(egui::RichText::new(prefs.author.clone()).font(theme::semibold(13.0)));
ui.label(egui::RichText::new(tl!(title)).font(theme::regular(11.5)).color(t.text_faint));
});
ui.add_space(6.0);
let hint = match c.kind {
ComposerKind::TextBox { .. } | ComposerKind::Callout { .. } => tl!("Type text"),
ComposerKind::Caret { .. } => tl!("Text to insert"),
ComposerKind::Replace => tl!("Replacement text"),
_ => tl!("Add a comment"),
};
let edit = ui
.add(egui::TextEdit::multiline(&mut c.text).hint_text(hint).desired_rows(3).desired_width(f32::INFINITY).id_salt("composer-text"))
// 0.37 kittest rejects an unnamed text input; the hint is its logical name.
.accessible_name(hint);
if c.focus {
edit.request_focus();
c.focus = false;
}
let enter = submit_key(ui, &edit, false);
if keys.pressed(ui.ctx(), egui::Key::Escape) {
cancel = true;
}
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let can_post = !c.text.trim().is_empty() || matches!(c.kind, ComposerKind::Edit(_));
if ui
.add_enabled(
can_post,
egui::Button::new(egui::RichText::new(tl!("Post")).color(Color32::WHITE)).fill(t.accent).corner_radius(14),
)
.clicked()
|| (enter && can_post)
{
post = true;
}
if ui.add(egui::Button::new(tl!("Cancel")).corner_radius(14)).clicked() {
cancel = true;
}
});
});
});
});
if cancel {
let draft = match c.kind {
ComposerKind::Edit(_) if typewriter_edit => ComposerDraft::EditVerbatim,
ComposerKind::Edit(_) => ComposerDraft::Edit,
_ => ComposerDraft::New,
};
let output = CommentComposer::new(anchor, &mut c.text).header(tl!(title), &prefs.author).draft_kind(draft).close(ComposerClose::OnPostOrCancel).show(ui);
if output.cancelled {
view.comments.composer = None;
return None;
}
if !post {
return None;
}
let text = output.posted?;
let c = view.comments.composer.take()?;
let typewriter_edit = matches!(c.kind, ComposerKind::Edit(index) if info.annotations.iter().any(|a|
a.page == page && a.index == index && a.subtype == "FreeText" && a.intent.as_deref() == Some("FreeTextTypeWriter")
));
let text = if typewriter_edit { c.text } else { c.text.trim_end().to_string() };
match c.kind {
ComposerKind::Edit(index) => {
info.annotations.iter().any(|a| a.page == page && a.index == index).then_some(Edit::SetAnnotationContents { page, index, text })
}
ComposerKind::Note => {
view.comments.tool_done = true;
Some(new_comment(&cx, CommentTool::Note, Shape::Note { at: c.at, icon: NoteIcon::Comment }, text))
Some(new_comment(page, prefs, CommentTool::Note, Shape::Note { at: c.at, icon: NoteIcon::Comment }, text))
}
ComposerKind::TextNote { quads } => {
view.comments.tool_done = true;
Some(new_comment(&cx, CommentTool::Highlight, Shape::TextMarkup { kind: Markup::Highlight, quads }, text))
Some(new_comment(page, prefs, CommentTool::Highlight, Shape::TextMarkup { kind: Markup::Highlight, quads }, text))
}
ComposerKind::TextBox { size } => {
view.comments.tool_done = true;
@@ -139,7 +72,7 @@ pub(crate) fn composer(ctx: &egui::Context, keys: PageKeys, view: &mut DocView,
(Some(size), Some(p)) => drawn_text_box_rect(p, c.at, size, &text, font_size, border),
_ => text_box_rect(c.at, &text, font_size, rotation),
};
Some(new_comment(&cx, CommentTool::TextBox, Shape::TextBox { rect, font_size }, text))
Some(new_comment(page, prefs, CommentTool::TextBox, Shape::TextBox { rect, font_size }, text))
}
ComposerKind::Callout { point } => {
view.comments.tool_done = true;
@@ -147,7 +80,7 @@ pub(crate) fn composer(ctx: &egui::Context, keys: PageKeys, view: &mut DocView,
let font_size = prefs.font_size(CommentTool::Callout).unwrap_or(10.0);
let rect = text_box_rect(c.at, &text, font_size, 0);
let knee = pdfcraft_engine::callout_knee(rect, point);
Some(new_comment(&cx, CommentTool::Callout, Shape::Callout { rect, knee, point, font_size, ending: LineEnding::OpenArrow }, text))
Some(new_comment(page, prefs, CommentTool::Callout, Shape::Callout { rect, knee, point, font_size, ending: LineEnding::OpenArrow }, text))
}
ComposerKind::Replace => {
view.comments.tool_done = true;
@@ -168,28 +101,12 @@ pub(crate) fn composer(ctx: &egui::Context, keys: PageKeys, view: &mut DocView,
view.comments.tool_done = true;
let [x, y] = c.at;
let half = size / 2.0;
Some(new_comment(&cx, CommentTool::Caret, Shape::Caret { rect: [x - half, y - size, x + half, y] }, text))
Some(new_comment(page, prefs, CommentTool::Caret, Shape::Caret { rect: [x - half, y - size, x + half, y] }, text))
}
}
}
/// Submit only from the focused comment editor. Match each key event's modifiers exactly,
/// so Shift+Enter stays a newline and another editor cannot submit this draft. Replies also
/// keep their existing unmodified Enter-to-post behavior.
pub(crate) fn submit_key(ui: &mut egui::Ui, field: &egui::Response, plain_enter: bool) -> bool {
field.has_focus()
&& ui.input_mut(|input| {
let mut submit = false;
input.events.retain(|event| {
let matched = matches!(event,
egui::Event::Key { key: egui::Key::Enter, pressed: true, modifiers, .. }
if modifiers.matches_exact(egui::Modifiers::CTRL)
|| modifiers.matches_exact(egui::Modifiers::COMMAND)
|| plain_enter && modifiers.matches_exact(egui::Modifiers::NONE)
);
submit |= matched;
!matched
});
submit
})
/// Whether comment `index` on the composer's page is at least partly inside `viewport`, as drawn.
pub(crate) fn edited_in_view(cx: &PageCx<'_>, index: usize, viewport: Rect) -> bool {
cx.info.annotations.iter().any(|a| a.page == cx.page && a.index == index && viewport.intersects(cx.screen_rect(a)))
}
-886
View File
@@ -1,886 +0,0 @@
use super::geometry::{
CARET_SIZE, HANDLES, clamp_to, corner_ratio, drawn_box, frame, handle_pos, held, is_callout, is_markup, on_text, point_handle, reaches_points,
reshapable, reshape_for, resizable, resized, snapped_caret,
};
use super::paint::{closes_at, drawn_shape, edit_anchor, erase, moves_box_only, new_comment};
use super::popups::has_popup;
use super::state::{Composer, ComposerKind, Gesture, PageCx};
use super::{Annotation, CommentPrefs, CommentTool, CommentView, DocInfo, DocView, Edit, Pos2, QuickTool, Rect, Shape, vec2};
use crate::page_cursor::{Layer, Subject};
use crate::page_keys::PageKeys;
use crate::page_router::{CommentPart, Hit, Owner, PagePress};
/// Comment input on one page, before text selection runs. `press` is what this page has to do with
/// the press the pages hold: a press on a comment where the tool reaches it ([`hit`]: the Select
/// tool, Fill & Sign over its marks, a shape tool over the selected shape's handles) is that
/// comment's, and one nobody holds is a commenting tool's. When another tool took this frame
/// (`taken`: Prepare, added content), the commenting tools leave it to that tool, as before; the
/// Select tool's click there still unselects. Returns `true` when
/// the pointer gesture belongs to commenting (text selection must ignore it).
pub(crate) fn page_input(ui: &egui::Ui, resp: &egui::Response, cx: &PageCx<'_>, press: PagePress, taken: bool, view: &mut DocView) -> bool {
let (pointer, origin) = (cx.ptr.pos, cx.ptr.origin);
let page_rect = cx.xf.rect;
let free = press == PagePress::Free;
let pressed_here = free && origin.is_some_and(|o| page_rect.contains(o));
let over_page = pointer.is_some_and(|p| page_rect.contains(p));
let owned = match press {
PagePress::Mine(Owner::Comment { index, part }) => Some((index, part)),
_ => None,
};
let caret_text = if cx.tool == QuickTool::Comment(CommentTool::Caret) { view.page_text(cx.page) } else { None };
let cv = &mut view.comments;
if cv.gesture.is_some() && cx.keys.take(ui.ctx(), egui::Key::Escape) {
cv.gesture = None;
return true;
}
// Copied comments on the pointer: a click places the bundle, centred where it is clicked,
// on this page; a right-click lets it go. Nothing else on the page takes the click.
if let Some(Gesture::Place { xfdf, bounds, .. }) = cv.gesture.clone() {
if over_page {
view.cursor.claim(Layer::Drag, egui::CursorIcon::Grabbing);
}
let cv = &mut view.comments;
if resp.secondary_clicked() {
cv.gesture = None;
return true;
}
if resp.clicked()
&& over_page
&& cx.allowed
&& let Some(p) = pointer
{
let [x, y] = cx.to_user(p);
let offset = [x - (bounds[0] + bounds[2]) / 2.0, y - (bounds[1] + bounds[3]) / 2.0];
// Larger than the page it lands on (an A0 bundle on an A4 page): placed as it is,
// and said so.
if let Some(page) = cx.info.pages.get(cx.page) {
let a = page.user_to_view((bounds[0] + offset[0]) as f32, (bounds[1] + offset[1]) as f32);
let b = page.user_to_view((bounds[2] + offset[0]) as f32, (bounds[3] + offset[1]) as f32);
let (w, h) = ((a[0] - b[0]).abs(), (a[1] - b[1]).abs());
if w > page.width + 1.0 || h > page.height + 1.0 {
cv.notice = Some("The copied comments are larger than this page; they were placed as they are");
}
}
cv.gesture = None;
view.pending_edit = Some(Edit::PasteComments { xfdf, page: cx.page, offset: Some(offset) });
}
return true;
}
let moving = moving_on(view, cx.page);
let gestures = Gestures { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page, free };
match cx.tool {
// The selected shape's handles, and Fill & Sign's marks, take their own presses.
QuickTool::Comment(_) | QuickTool::Fill(_) if owned.is_some() || moving => select_input(ui, resp, cx, view, press, pointer, origin),
// Neither a press nor a double-click or a key another tool took this frame.
QuickTool::Comment(_) if taken => false,
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, press, pointer, origin),
_ => false,
}
}
/// A comment (a Fill & Sign mark included) is being moved, resized or reshaped on `page`: it keeps
/// the page's frames until its gesture ends.
pub(crate) fn moving_on(view: &DocView, page: usize) -> bool {
matches!(view.comments.gesture, Some(Gesture::Move { page: p, .. } | Gesture::Resize { page: p, .. } | Gesture::Reshape { page: p, .. }) if p == page)
}
/// 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. `on_link`: a link lies
/// under `p` ([`crate::link_ui::hit`]).
pub(crate) fn hit(cx: &PageCx<'_>, view: &DocView, p: Pos2, on_link: bool) -> Option<Hit> {
if cx.hidden || !cx.xf.rect.contains(p) {
return None;
}
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 reaches_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, point_cursor(Some(a), point)));
}
if resizable(a)
&& let Some((x, y)) = HANDLES.into_iter().find(|h| handle_pos(cx.frame_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));
}
}
// A group subordinate (`/RT /Group`) stands for its primary (ISO 32000-2 §12.5.6.2): a click
// there selects the group. Only a click: a drag still moves what is under the pointer.
let (a, member) = match cx.comment_at(p) {
Some(a) => (a, false),
None => (cx.click_target(p)?, true),
};
let a = Some(a).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 {
return None;
}
let markup = on_text(a);
let icon = if cx.allowed && !markup { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand };
// Text markup does not move: a click selects it, a drag across it selects the text.
Some(Hit { declines_drag: markup || member, ..Hit::new(Owner::Comment { index: a.index, part: CommentPart::Body }, layer(a), icon) })
}
/// The layer a comment's body lies on: what a drag moves whole (a note, a shape, a signature, a
/// Fill & Sign mark) is placed on the page, over a form field; text markup lies on the text, under
/// one.
fn layer(a: &Annotation) -> Layer {
if a.fill_sign || !is_markup(&a.subtype) { Layer::Placed } else { Layer::Comment }
}
/// The comment a right-click at `p` is on: the topmost, with every tool, as a comment's menu shows
/// whatever tool is active; on a group subordinate (`/RT /Group`), its group's primary, so the menu
/// offers the comment's actions (ISO 32000-2 §12.5.6.2). A highlight over a link is the highlight's
/// here (a left click on it follows the link, [`hit`]). `None` off the page or with comments hidden.
pub(crate) fn context_hit(cx: &PageCx<'_>, p: Pos2) -> Option<Hit> {
if cx.hidden || !cx.xf.rect.contains(p) {
return None;
}
let a = cx.click_target(p)?;
Some(Hit::new(Owner::Comment { index: a.index, part: CommentPart::Body }, layer(a), egui::CursorIcon::Default))
}
/// A right-click at `p` on this page: the page's menu is anchored there (Delete page, Paste, Copy
/// Image, a note added here).
pub(crate) fn anchor(cx: &PageCx<'_>, p: Pos2, view: &mut DocView) {
view.comments.context_at = Some((cx.page, cx.to_user(p)));
}
/// A right-click at `p` on comment `index` of this page ([`context_hit`], when it wins there)
/// selects it, remembering the group subordinate under `p` when it is that group's primary; one on
/// anything else selects none.
pub(crate) fn context(cx: &PageCx<'_>, p: Pos2, index: Option<usize>, view: &mut DocView) {
match index {
// `index` is what the right-click is on ([`context_hit`]): no second look at the point.
Some(i) => match cx.get(i) {
Some(a) => view.comments.pick(cx, p, a),
None => view.comments.select(Some((cx.page, i))),
},
None => view.comments.select(None),
}
}
/// Whether the page shows a tip for what lies under the pointer (a comment, a signature's badge)
/// with `tool`: not with Fill & Sign, whose placement stays clear; not while drawing freehand,
/// where it would cover the next stroke (#429); and not while a comment is moved, resized or drawn.
pub(crate) fn tips_shown(tool: QuickTool, view: &DocView) -> bool {
let freehand = matches!(tool, QuickTool::Comment(CommentTool::Ink | CommentTool::FreehandHighlight | CommentTool::Eraser));
!(matches!(tool, QuickTool::Fill(_)) || freehand || view.comments.gesture.is_some())
}
/// The tip for the comment under the pointer, with any tool, beside that tool's own cursor: Acrobat
/// shows a comment's tooltip whatever tool is active. Not where [`tips_shown`] says no.
pub(crate) fn describe(cx: &PageCx<'_>, view: &mut DocView) {
if !tips_shown(cx.tool, view) {
return;
}
let Some(p) = cx.ptr.pos else { return };
// Inspection sorts comments by position, but the renderer paints them in `/Annots` order: the
// tip is that of the one drawn on top, among those with something to say (#3620).
let top = cx
.comments()
// An open pop-up already shows the comment: no tooltip over it.
.filter(|a| !a.popup.is_some_and(|w| w.open))
.filter_map(|a| {
let marker = cx.comment_marker_rect(a).is_some_and(|r| r.contains(p));
if !marker && !cx.screen_rects(a).any(|r| r.contains(p)) {
return None;
}
hover_tip(a, cx.prefs).map(|text| (marker, a.index, text))
})
.max_by_key(|(marker, index, _)| (*marker, *index));
if let Some((_, _, text)) = top {
view.cursor.describe(Subject::Comment, text);
}
}
/// What hovering `a` says, as Acrobat's popups do. Replies and Fill & Sign's marks (typed text,
/// checks, signatures) say nothing: they are page content being edited, not comments. Neither
/// does a highlight with no text of its own, when the preferences say so.
pub(super) fn hover_tip(a: &Annotation, prefs: &CommentPrefs) -> Option<String> {
let empty_highlight = a.subtype == "Highlight" && a.contents.as_deref().is_none_or(str::is_empty);
if a.is_reply() || a.fill_sign || prefs.hide_empty_highlight_hover && empty_highlight {
return None;
}
let who = a.author.clone().unwrap_or_else(|| a.subtype.clone());
let body = a.contents.clone().unwrap_or_default();
Some(if body.is_empty() { who } else { format!("{who}\n{body}") })
}
/// The Select tool: select, move, resize, edit, delete, on the comment the press is on and the
/// part of it (`press`, from [`hit`]). The cursor comes from [`hit`] too. A click on this page on
/// anything else (a link, a field, added text, the page) leaves comments unselected; one that
/// began off the pages is no page's.
fn select_input(
ui: &egui::Ui,
resp: &egui::Response,
cx: &PageCx<'_>,
view: &mut DocView,
press: PagePress,
pointer: Option<Pos2>,
origin: Option<Pos2>,
) -> bool {
let owner = match press {
PagePress::Mine(Owner::Comment { index, part }) => cx.get(index).map(|a| (a, part)),
_ => None,
};
let cv = &mut view.comments;
let mut consumed = false;
if cx.ptr.drag_started
&& let (Some((a, part)), Some(o)) = (owner, origin)
{
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.frame_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;
}
CommentPart::Body if !on_text(a) => {
// Dragging one of several selected comments moves them all; any other drag starts
// a selection of its own.
let grabbed = (cx.page, a.index);
if !cv.is_selected(grabbed) {
// A press on a group picks its member under the pointer (`CommentView::pick`).
cv.pick(cx, o, a);
} else {
// The grabbed one takes the handles; the one that had them stays selected.
if let Some(previous) = cv.selected.replace(grabbed)
&& previous != grabbed
{
cv.also.push(previous);
}
cv.also.retain(|k| *k != grabbed);
}
cv.reveal = true;
if cx.allowed {
cv.gesture = Some(Gesture::Move { page: cx.page, index: a.index, from: o });
}
consumed = true;
}
CommentPart::Body => {}
}
}
let live =
matches!(cv.gesture, Some(Gesture::Move { page, .. } | Gesture::Resize { page, .. } | Gesture::Reshape { page, .. }) if page == cx.page);
if live {
consumed = true;
}
// A move, resize or reshape ends where its drag stops. One whose release the pages missed (the
// button is up, and no drag stopped here) ends with nothing applied: where it came up is not
// known, and the pointer may be anywhere by now.
if live && !resp.drag_stopped() && !cx.ptr.primary_down {
cv.gesture = None;
}
if resp.drag_stopped()
&& let Some(p) = pointer
{
finish_select_gesture(ui, cx, view, p);
}
let cv = &mut view.comments;
// (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 {
// A click elsewhere (a link beneath text highlighting included: it follows the link; a
// form field; added text) leaves comments unselected.
match owner {
Some((a, _)) => {
// ⌘/Ctrl-click (or ⇧-click) adds the comment to the selection, as in Acrobat.
if ui.input(|i| i.modifiers.command || i.modifiers.shift) {
cv.toggle((cx.page, a.index));
} else {
match pointer {
Some(p) => cv.pick(cx, p, a),
None => cv.select_only((cx.page, a.index)),
}
}
cv.reveal = true;
consumed = true;
}
None if press != PagePress::Elsewhere => cv.clear_selection(),
None => {}
}
}
if (resp.double_clicked() || resp.triple_clicked())
&& on_page
&& cx.allowed
&& let Some((a, _)) = owner
{
cv.select_only((cx.page, a.index));
// A double-click opens the comment's pop-up window, as in Acrobat; a text box, whose
// text is the comment itself, is edited in place.
if has_popup(a) {
if !a.popup.is_some_and(|p| p.open) {
view.pending_edit = Some(Edit::SetAnnotationPopup { page: cx.page, index: a.index, rect: None, open: Some(true) });
}
return true;
}
cv.composer = Some(Composer {
page: cx.page,
at: edit_anchor(cx.info, a),
kind: ComposerKind::Edit(a.index),
text: a.contents.clone().unwrap_or_default(),
focus: true,
});
consumed = true;
}
consumed
}
/// The end of a move, resize or reshape the Select tool began on this page: the edit it makes,
/// for the pointer released at `p`.
fn finish_select_gesture(ui: &egui::Ui, cx: &PageCx<'_>, view: &mut DocView, p: Pos2) {
match view.comments.gesture.clone() {
Some(Gesture::Move { page, index, from }) if page == cx.page => {
view.comments.gesture = None;
let (a, b) = (cx.to_user(from), cx.to_user(p));
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
if from.distance(p) >= 2.0 {
// A callout dragged by its text box moves the box alone: its arrow point stays.
if let Some(a) = cx.get(index).filter(|a| moves_box_only(cx, a, from)) {
let f = frame(a, cx.rotation()).map(f64::from);
view.pending_edit = Some(Edit::ResizeAnnotation { page, index, rect: [f[0] + dx, f[1] + dy, f[2] + dx, f[3] + dy] });
return;
}
// The other selected comments on this page (not text markup or a Replace Text
// caret, which are where their text is, nor a locked one, which would refuse the
// whole step) move with the dragged one, as one undo step.
let others: Vec<usize> = view
.comments
.also
.iter()
.filter(|(p, i)| *p == page && *i != index && cx.get(*i).is_some_and(|a| !on_text(a) && !a.locked))
.map(|(_, i)| *i)
.collect();
view.pending_edit = Some(if others.is_empty() {
Edit::MoveAnnotation { page, index, dx, dy }
} else {
let edits = std::iter::once(index).chain(others).map(|index| Edit::MoveAnnotation { page, index, dx, dy }).collect();
Edit::Batch { label: tl!("Move comments").to_owned(), edits }
});
}
}
Some(Gesture::Resize { page, index, handle, from, aspect_ratio }) if page == cx.page => {
view.comments.gesture = None;
if let Some(a) = cx.get(index) {
let from_rect = cx.frame_rect(a);
let shift = ui.input(|i| i.modifiers.shift);
let r = resized(from_rect, handle, p - from, corner_ratio(from_rect, aspect_ratio, shift));
let rect = a.rect_for_shown(cx.rect_to_user(r), cx.rotation());
if r.width() >= 4.0 && r.height() >= 4.0 {
view.pending_edit = Some(Edit::ResizeAnnotation { page, index, rect });
}
}
}
Some(Gesture::Reshape { page, index, point, points }) if page == cx.page => {
view.comments.gesture = None;
let shift = ui.input(|i| i.modifiers.shift);
let moved = points.get(point).is_some_and(|q| cx.to_screen(*q).distance(p) >= 2.0);
if moved && let Some(a) = cx.get(index) {
view.pending_edit = Some(Edit::ReshapeAnnotation { page, index, points: reshape_for(a, &points, point, cx.to_user(p), shift) });
}
}
_ => {}
}
}
/// After text selection ran: a markup tool turns a finished selection into a comment; Replace
/// Text asks for the replacement.
pub(crate) fn page_after_text(resp: &egui::Response, cx: &PageCx<'_>, view: &mut DocView) {
let QuickTool::Comment(tool) = cx.tool else { return };
let finished = resp.drag_stopped_by(egui::PointerButton::Primary) || resp.double_clicked();
if tool == CommentTool::ReplaceText && cx.allowed && finished {
// A replacement sits on one page: a selection across pages stays selected for the bar's
// markup or Copy.
if let Ok([(page, quads)]) = <[_; 1]>::try_from(view.selection_quads(cx.info))
&& page == cx.page
{
view.clear_selection();
let last = quads.last().copied().unwrap_or_default();
let at = [last[2].max(last[6]), last[1].max(last[3])];
view.comments.replace = Some(quads);
view.comments.composer = Some(Composer { page, at, kind: ComposerKind::Replace, text: String::new(), focus: true });
}
return;
}
let Some(kind) = tool.markup().filter(|_| cx.allowed) else { return };
// Once, from whichever of the selection's pages is drawn: after an edge scroll its first page
// may be out of view. Every page it covers gets its own markup, in one undo step, once all
// of them are read.
if let crate::canvas::ToolMarks::Marks(marks, head) = view.tool_marks(cx.tool, finished, Some(cx.page), false, cx.info) {
view.clear_selection();
let edits = marks.into_iter().map(|(page, quads)| {
Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
page,
shape: Shape::TextMarkup { kind, quads },
style: cx.prefs.style(tool),
contents: String::new(),
author: cx.prefs.author.clone(),
})
});
view.pending_edit = view.selection_marks_edit(edits.collect(), head);
}
}
/// What the pointer is doing on one page, for the comment tools that draw or place things.
#[derive(Clone, Copy)]
struct Gestures<'a> {
ui: &'a egui::Ui,
resp: &'a egui::Response,
cx: &'a PageCx<'a>,
pointer: Option<Pos2>,
origin: Option<Pos2>,
page_rect: Rect,
/// The press began on this page, and nobody holds it: the tool's.
pressed_here: bool,
over_page: bool,
/// Nobody holds the press, and it began on this page, or no button is down.
free: bool,
}
impl Gestures<'_> {
/// The tool's own click: one nobody holds.
fn clicked(&self) -> bool {
self.free && self.resp.clicked()
}
fn draw_shape(&self, view: &mut DocView, tool: CommentTool) -> bool {
// Shift holds a line level or plumb (ortho).
let shift = self.resp.ctx.input(|i| i.modifiers.shift);
let Self { ui, resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;
let cv = &mut view.comments;
if !cx.allowed {
return false;
}
if over_page {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);
}
if cx.ptr.drag_started
&& pressed_here
&& let Some(o) = origin
{
cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });
cv.select(None);
}
if let Some(Gesture::Draw { page, tool, points }) = cv.gesture.as_mut()
&& *page == cx.page
&& let Some(p) = pointer
{
let p = clamp_to(page_rect, p);
let u = cx.to_user(p);
if matches!(*tool, CommentTool::Ink | CommentTool::FreehandHighlight | CommentTool::Eraser) {
let last = points.last().map(|l| cx.to_screen(*l)).unwrap_or(p);
if last.distance(p) >= 1.5 {
points.push(u);
}
} else {
points.truncate(1);
let line = matches!(*tool, CommentTool::Line | CommentTool::Arrow);
points.push(held(points.first(), u, line && shift));
}
}
if resp.drag_stopped()
&& let Some(Gesture::Draw { page, tool, points }) = cv.gesture.clone()
&& page == cx.page
{
cv.gesture = None;
if tool == CommentTool::Eraser {
view.pending_edit = erase(cx, &points);
} else if let Some(shape) = drawn_shape(tool, &points) {
let now = ui.input(|i| i.time);
cv.settle(now, page, tool, &points);
view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));
}
}
// A quick press/release does not start an egui drag, but Acrobat's Draw tool treats
// it as a one-point ink stroke (a dot). The appearance uses round line caps, so a
// single PDF point is visible and remains editable like any other drawing.
if matches!(tool, CommentTool::Ink | CommentTool::FreehandHighlight)
&& self.clicked()
&& over_page
&& let Some(p) = pointer
&& let Some(shape) = drawn_shape(tool, &[cx.to_user(p)])
{
cv.select(None);
let now = ui.input(|i| i.time);
cv.settle(now, cx.page, tool, &[cx.to_user(p)]);
view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));
}
true
}
fn click_points(&self, view: &mut DocView, tool: CommentTool) -> bool {
// Shift holds the next side of connected lines, a polygon or a cloud level or plumb.
let shift = self.resp.ctx.input(|i| i.modifiers.shift);
let Self { ui, resp, cx, pointer, over_page, .. } = *self;
let cv = &mut view.comments;
if !cx.allowed {
return false;
}
if over_page {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);
}
// The menu's Complete is taken by the page the drawing is on: every page on screen
// passes here in a frame, and an earlier one must not swallow it. With no drawing
// left, a request is stale.
let drawing_here = match &cv.gesture {
Some(Gesture::Draw { page, .. }) => *page == cx.page,
_ => {
cv.finish_request = false;
false
}
};
let finish = resp.double_clicked() || cx.keys.pressed(ui.ctx(), egui::Key::Enter) || (drawing_here && std::mem::take(&mut cv.finish_request));
// Backspace (or Delete) takes back the last point, e.g. after a wrong click; Undo does too.
// Only while a drawing is in progress: otherwise Delete belongs to the selected comment.
if matches!(cv.gesture, Some(Gesture::Draw { page, .. }) if page == cx.page)
&& !ui.ctx().egui_wants_keyboard_input()
&& (cx.keys.take(ui.ctx(), egui::Key::Backspace) || cx.keys.take(ui.ctx(), egui::Key::Delete))
{
cv.undo_point();
return true;
}
if self.clicked()
&& over_page
&& let Some(p) = pointer
{
let u = cx.to_user(p);
match cv.gesture.as_mut() {
Some(Gesture::Draw { page, tool: t, points }) if *page == cx.page && *t == tool => {
// Clicking the first point again closes a polygon.
let closes = closes_at(cx, tool, points, p);
let u = held(points.last(), u, shift);
let repeat = points.last().is_some_and(|l| cx.to_screen(*l).distance(cx.to_screen(u)) < 2.0);
if closes {
let pts = std::mem::take(points);
cv.gesture = None;
if let Some(shape) = drawn_shape(tool, &pts) {
view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));
}
return true;
}
if !repeat {
points.push(u);
}
}
_ => {
cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![u] });
cv.select(None);
}
}
}
if finish
&& let Some(Gesture::Draw { page, tool: t, points }) = cv.gesture.clone()
&& page == cx.page
&& t == tool
{
cv.gesture = None;
if let Some(shape) = drawn_shape(tool, &points) {
view.pending_edit = Some(new_comment(cx, tool, shape, String::new()));
}
}
true
}
fn callout(&self, view: &mut DocView) -> bool {
let Self { resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;
let cv = &mut view.comments;
// Drag from what the callout points at to where its text box goes.
if !cx.allowed {
return false;
}
if over_page {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);
}
if cx.ptr.drag_started
&& pressed_here
&& let Some(o) = origin
{
cv.gesture = Some(Gesture::Draw { page: cx.page, tool: CommentTool::Callout, points: vec![cx.to_user(o)] });
cv.select(None);
}
if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()
&& *page == cx.page
&& let Some(p) = pointer
{
points.truncate(1);
points.push(cx.to_user(clamp_to(page_rect, p)));
}
if resp.drag_stopped()
&& let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()
&& page == cx.page
{
cv.gesture = None;
if let [point, at] = points[..]
&& (point[0] - at[0]).hypot(point[1] - at[1]) >= 8.0
{
cv.composer = Some(Composer { page, at, kind: ComposerKind::Callout { point }, text: String::new(), focus: true });
}
}
true
}
fn attach(&self, view: &mut DocView) -> bool {
let Self { cx, pointer, over_page, .. } = *self;
let cv = &mut view.comments;
if !cx.allowed {
return false;
}
if over_page {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);
}
if self.clicked()
&& over_page
&& let Some(p) = pointer
{
cv.attach_at = Some((cx.page, cx.to_user(p)));
cv.select(None);
}
true
}
fn caret(&self, view: &mut DocView, caret_text: Option<&pdfcraft_render::PageText>) -> bool {
let Self { cx, pointer, over_page, .. } = *self;
let cv = &mut view.comments;
if !cx.allowed {
return false;
}
if over_page {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Text);
}
if self.clicked()
&& over_page
&& let Some(p) = pointer
{
let (vx, vy) = cx.xf.screen_to_view(p);
let snapped = cx.info.pages.get(cx.page).zip(caret_text).and_then(|(page, t)| snapped_caret(page, t, vx, vy));
let (at, size) = snapped.unwrap_or_else(|| (cx.to_user(p), CARET_SIZE));
cv.composer = Some(Composer { page: cx.page, at, kind: ComposerKind::Caret { size }, text: String::new(), focus: true });
cv.select(None);
}
true
}
fn note_or_box(&self, view: &mut DocView, tool: CommentTool) -> bool {
let Self { resp, cx, pointer, origin, page_rect, pressed_here, over_page, .. } = *self;
let cv = &mut view.comments;
if !cx.allowed {
return false;
}
if over_page {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);
}
// A text box also takes a drag, as in Acrobat: the box is drawn at that size and its
// text wraps inside it (#2669).
if tool == CommentTool::TextBox {
if cx.ptr.drag_started
&& pressed_here
&& let Some(o) = origin
{
cv.gesture = Some(Gesture::Draw { page: cx.page, tool, points: vec![cx.to_user(o)] });
cv.select(None);
}
if let Some(Gesture::Draw { page, points, .. }) = cv.gesture.as_mut()
&& *page == cx.page
&& let Some(p) = pointer
{
points.truncate(1);
points.push(cx.to_user(clamp_to(page_rect, p)));
}
if resp.drag_stopped()
&& let Some(Gesture::Draw { page, points, .. }) = cv.gesture.clone()
&& page == cx.page
{
cv.gesture = None;
if let (Some(first), Some(last)) = (points.first(), points.last()) {
let r = Rect::from_two_pos(cx.to_screen(*first), cx.to_screen(*last));
// A drag of a few pixels is a click: the box fits its text.
let drawn =
(r.width() >= 6.0 && r.height() >= 6.0).then(|| cx.info.pages.get(page)).flatten().map(|p| drawn_box(p, *first, *last));
let (at, size) = drawn.map_or((*first, None), |(at, size)| (at, Some(size)));
cv.composer = Some(Composer { page, at, kind: ComposerKind::TextBox { size }, text: String::new(), focus: true });
}
}
}
if self.clicked()
&& over_page
&& let Some(p) = pointer
{
let kind = if tool == CommentTool::Note { ComposerKind::Note } else { ComposerKind::TextBox { size: None } };
cv.composer = Some(Composer { page: cx.page, at: cx.to_user(p), kind, text: String::new(), focus: true });
cv.select(None);
}
true
}
}
/// Delete / Escape handling for comments (only while no text field has focus, and nothing is over
/// the pages).
pub(crate) fn keys(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, info: &DocInfo, tool: &mut QuickTool, allowed: bool) {
if ctx.egui_wants_keyboard_input() {
return;
}
let cv = &mut view.comments;
if keys.pressed(ctx, egui::Key::Escape) {
// One step back per press: cancel the gesture, then deselect, then drop the tool (a
// comment tool, or a Fill & Sign one: its Text tool would otherwise open a box at every
// click with no way out by the keyboard).
let had_selection = cv.selected.is_some();
cv.clear_selection();
let cancelled = cv.gesture.take().is_some() || had_selection;
if !cancelled && matches!(tool, QuickTool::Comment(_) | QuickTool::Fill(_)) {
*tool = QuickTool::Select;
}
}
if allowed && cv.selected.is_some() && (keys.pressed(ctx, egui::Key::Delete) || keys.pressed(ctx, egui::Key::Backspace)) {
view.pending_edit = delete_selected(cv, info);
}
}
/// The edit that deletes every selected comment (one undo step for several), and clears the
/// selection. Later positions go first, so each deletion leaves the earlier ones where they are.
pub(crate) fn delete_selected(cv: &mut CommentView, info: &DocInfo) -> Option<Edit> {
// A group's member picked on the page, with its group the selection alone, goes by itself, as
// Acrobat deletes the member clicked ([`CommentView::target`]).
let raw = if cv.also.is_empty() { cv.target().into_iter().collect() } else { cv.selection() };
let mut keys: Vec<(usize, usize)> =
raw.into_iter().filter(|(page, index)| info.annotations.iter().any(|a| a.page == *page && a.index == *index && !a.locked)).collect();
cv.clear_selection();
keys.sort_unstable_by(|a, b| b.cmp(a));
keys.dedup();
match keys.as_slice() {
[] => None,
[(page, index)] => Some(Edit::DeleteAnnotation { page: *page, index: *index }),
_ => Some(Edit::Batch {
label: tl!("Delete comments").to_owned(),
edits: keys.into_iter().map(|(page, index)| Edit::DeleteAnnotation { page, index }).collect(),
}),
}
}
/// The arrow keys move selected comments a screen pixel; with ⌘/Ctrl or Shift, ten. Up is up
/// on screen whatever the zoom, the page's rotation and the view's; the keys are taken before
/// the view scrolls or turns the page with them. Each press is one undo step. Text markup stays
/// with its text, and a locked comment where it is.
pub(crate) fn nudge_keys(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, info: &DocInfo) {
if ctx.egui_wants_keyboard_input() || view.pending_edit.is_some() {
return;
}
let cv = &view.comments;
if cv.gesture.is_some() || cv.composer.is_some() {
return;
}
let Some((page, index)) = cv.selected else { return };
let movable = info.annotations.iter().any(|a| a.page == page && a.index == index && !a.is_reply() && !on_text(a) && !a.locked);
let (Some(xf), Some(p)) = (view.page_xform(page), info.pages.get(page)) else { return };
if !movable {
return;
}
use egui::Key;
let mut step = egui::Vec2::ZERO;
// Only an arrow pressed alone or with ⌘/Ctrl or Shift, judged by each press's own
// modifiers. Alt+← / Alt+→ go back and forward through the view history in
// `canvas::shortcuts` (#3632), and egui's key patterns would let an extra Alt through.
// A Ctrl that isn't the command key (macOS) is left alone, as the patterns left it.
keys.take_presses(ctx, |key, modifiers| {
if modifiers.alt || (modifiers.ctrl && !modifiers.command) {
return false;
}
let direction = match key {
Key::ArrowLeft => vec2(-1.0, 0.0),
Key::ArrowRight => vec2(1.0, 0.0),
Key::ArrowUp => vec2(0.0, -1.0),
Key::ArrowDown => vec2(0.0, 1.0),
_ => return false,
};
step += direction * if modifiers.command || modifiers.shift { 10.0 } else { 1.0 };
true
});
if step == egui::Vec2::ZERO {
return;
}
// The step on screen, in user space: from the page's centre to `step` pixels away.
let user = |s: Pos2| {
let (vx, vy) = xf.screen_to_view(s);
let u = p.view_to_user(vx, vy);
[f64::from(u[0]), f64::from(u[1])]
};
let (a, b) = (user(xf.rect.center()), user(xf.rect.center() + step));
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
if dx.is_finite() && dy.is_finite() && (dx != 0.0 || dy != 0.0) {
// Match a pointer drag: move the eligible selection on this page as one undo step.
// Text markup and locked comments cannot be moved and would reject a batch.
let mut indices = vec![index];
for &(other_page, other_index) in &view.comments.also {
if other_page == page
&& !indices.contains(&other_index)
&& info.annotations.iter().any(|a| a.page == page && a.index == other_index && !a.is_reply() && !on_text(a) && !a.locked)
{
indices.push(other_index);
}
}
view.pending_edit = Some(if indices.len() == 1 {
Edit::MoveAnnotation { page, index, dx, dy }
} else {
Edit::Batch {
label: tl!("Move comments").to_owned(),
edits: indices.into_iter().map(|index| Edit::MoveAnnotation { page, index, dx, dy }).collect(),
}
});
}
}
/// The pointer over point handle `i` of `selected`: a callout's knee moves along its knee line only
/// (see `callout_reshaped`), so it shows that direction; other points move freely.
fn point_cursor(selected: Option<&Annotation>, i: usize) -> egui::CursorIcon {
let knee_side = selected.filter(|a| i == 1 && is_callout(a)).and_then(|a| {
let (tb, knee) = (a.text_box?, a.points.get(1)?);
Some(pdfcraft_engine::callout_side(tb.map(f64::from), [f64::from(knee[0]), f64::from(knee[1])]))
});
match knee_side {
Some(side) if side.horizontal() => egui::CursorIcon::ResizeHorizontal,
Some(_) => egui::CursorIcon::ResizeVertical,
None => egui::CursorIcon::Crosshair,
}
}
@@ -0,0 +1,232 @@
use craft::behavior::kurbo::{BezPath, Point, Rect as DocRect, Shape as _};
use craft::pages::ui::PageBody;
use craft::review::annotate::pick_at;
use craft::review::ui::annotate::{AnnotationOverlay, BodyPaint};
use craft::review::{Annotation as Marked, AnnotationId, AnnotationKind, HandleRule};
use craft::ui::canvas::ToolContext;
use craft::ui::canvas_controls::{HoverOutline, HoverShape};
use craft::ui::primitives::{Draw, PaintShape, StrokeWidth, TextRun};
use craft::ui::style::{DataColor, StyleColor};
use egui::{Color32, Pos2, Rect, vec2};
use pdfcraft_engine::CommentOutline as O;
use super::bridge::{self, PageMap};
use super::state::Settling;
use super::tool::PastePlacement;
use super::{Annotation, CommentPrefs, DocInfo, DocView, QuickTool, color32};
/// What the overlay needs besides the document: where it paints and what the pointer is over.
// PLAN: assumed the "comments after text" slot of canvas-w5's `PageOverlays` hands a `Draw` (the redaction fill is
// data painted through it); `pointer` is the tool host's last pointer sample, `None` while a button is down (the page
// body's `ToolPass` carries no position); pdf-canvas-w8/w9 build this.
pub(crate) struct Hover<'a, 'b> {
/// The slot's painter.
pub draw: &'a Draw<'b>,
/// The pointer on screen, when it is over the pages with no button down.
pub pointer: Option<Pos2>,
/// The user's Redaction Tool Properties fill and opacity.
pub redact: ([f64; 3], f64),
/// The page-unit `(tolerance, icon side)` of the hit test.
pub pick: (f64, f64),
/// The document allows commenting.
pub allowed: bool,
}
/// Paints the page's comments: the annotation overlay over the pages `body` places, the outline of the comment a
/// press under the pointer would take, and a redaction mark's fill while the pointer is over it, as Acrobat's does,
/// so the marked area reads before anything is applied.
pub(crate) fn show(ui: &mut egui::Ui, body: &PageBody<'_>, view: &DocView, info: &DocInfo, prefs: &CommentPrefs, tool: QuickTool, hover: Hover<'_, '_>) {
let map = PageMap::new(body.pages, info);
let all = bridge::annotations(info, &map, QuickTool::Select, hover.allowed);
let reached = bridge::annotations(info, &map, tool, hover.allowed);
let markers = bridge::markers(info, &map, hover.pick.1);
let selected: Vec<AnnotationId> = view.comments.tool.selected.clone();
let in_flight = view.comments.tool.in_flight();
let idle = in_flight.is_none() && view.comments.tool.drawing().is_empty() && !body.pass.is_some_and(|p| p.press.phase.is_press());
for page in body.pages {
let mut on_page: Vec<Marked> = all.iter().filter(|a| a.page == page.page).cloned().collect();
// The settling strokes are drawn by the overlay until their page is drawn again; their ids sit at the top of
// the id space, which `id_of(page, index)` never reaches.
let mut settling_ids = Vec::new();
for (n, s) in view.comments.settling.iter().filter(|s| s.page == page.page).enumerate() {
let id = bridge::id_of(page.page, u32::MAX as usize - n);
if let Some(a) = settling_annotation(s, prefs, id, &map) {
settling_ids.push(id);
on_page.push(a);
}
}
AnnotationOverlay::new(tl!("Comments"), &on_page, &selected).bodies(BodyPaint::Only(&settling_ids)).live(in_flight.as_ref()).show(ui);
let Some(at) = hover.pointer.filter(|p| idle && page.rect.contains(*p)) else { continue };
let at = page.to_page(at);
let (tolerance, icon_side) = hover.pick;
let under = pick_at(&on_page, at, tolerance, icon_side, &markers).and_then(|id| on_page.iter().find(|a| a.id == id));
if let Some(a) = under
&& let (page_of, index) = bridge::key_of(a.id)
&& info.annotations.iter().any(|e| e.page == page_of && e.index == index && e.subtype == "Redact")
{
paint_redaction(&hover, &map, info, page_of, index);
}
let shape = under
.filter(|a| !selected.contains(&a.id) && matches!(tool, QuickTool::Select | QuickTool::Fill(_)) && reached.iter().any(|r| r.id == a.id))
.map(|a| hover_shape(a, &markers, icon_side));
HoverOutline::new(tl!("Comment under the pointer"), shape).show(ui);
}
}
/// The outline of `a`: the lines of a text markup, else its extent, with the marker of a commented markup.
// PLAN: the same shape `bridge::parts` gives its page part, which it does not expose; pdf-comments-w7 to share one.
fn hover_shape(a: &Marked, markers: &[(AnnotationId, DocRect)], icon_side: f64) -> HoverShape {
if !a.kind.is_markup() {
return HoverShape::Rect(a.extent(icon_side));
}
let mut path = BezPath::new();
for quad in a.points.chunks(4) {
let (min, max) = quad.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| {
(Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))
});
path.extend(DocRect::new(min.x, min.y, max.x, max.y).path_elements(0.1));
}
for (_, r) in markers.iter().filter(|(m, _)| *m == a.id) {
path.extend(r.path_elements(0.1));
}
HoverShape::Path(path)
}
/// A released drawing still waiting for its page raster, as an annotation under `id`.
fn settling_annotation(s: &Settling, prefs: &CommentPrefs, id: AnnotationId, map: &PageMap<'_>) -> Option<Marked> {
let kind = s.tool.kind()?;
let style = prefs.style(s.tool);
let points: Vec<Point> = s.points.iter().map(|p| map.to_doc(s.page, *p)).collect();
let first = points.first()?;
let rect = points.iter().fold(DocRect::new(first.x, first.y, first.x, first.y), |r, p| r.union_pt(*p));
let c = color32(style.color);
let (strokes, points) = match kind {
AnnotationKind::Ink | AnnotationKind::FreehandHighlight => (vec![points], Vec::new()),
AnnotationKind::Rectangle | AnnotationKind::Oval => (Vec::new(), Vec::new()),
_ => (Vec::new(), points),
};
Some(Marked {
id,
page: s.page,
kind,
rect,
points,
strokes,
color: [c.r(), c.g(), c.b()],
opacity: style.opacity as f32,
stroke_width: style.width,
text: String::new(),
locked: true,
aspect: None,
handle_rule: HandleRule::Free,
})
}
/// A redaction mark's fill in the user's colour and opacity, a data colour and not a theme value.
fn paint_redaction(hover: &Hover<'_, '_>, map: &PageMap<'_>, info: &DocInfo, page: usize, index: usize) {
let (rgb, opacity) = hover.redact;
let [r, g, b] = rgb.map(|c| (c.clamp(0.0, 1.0) * 255.0) as u8);
let fill = DataColor::new(Color32::from_rgba_unmultiplied(r, g, b, (opacity.clamp(0.0, 1.0) * 255.0) as u8));
for area in redact_areas(map, info, page, index) {
hover.draw.data_fill(&PaintShape::Polygon(vec![area.left_top(), area.right_top(), area.right_bottom(), area.left_bottom()]), fill);
}
}
/// A redaction mark's areas on screen: one per marked quad, or its rectangle.
fn redact_areas(map: &PageMap<'_>, info: &DocInfo, page: usize, index: usize) -> Vec<Rect> {
let Some(a) = info.annotations.iter().find(|a| a.page == page && a.index == index) else { return Vec::new() };
let Some(p) = info.pages.get(page) else { return Vec::new() };
let boxes: Vec<[f32; 4]> = if a.quads.is_empty() {
vec![a.shown_rect(p.rotation)]
} else {
a.quads
.iter()
.map(|q| {
let xs = [q[0], q[2], q[4], q[6]];
let ys = [q[1], q[3], q[5], q[7]];
let fold = |v: [f32; 4], f: fn(f32, f32) -> f32, seed: f32| v.into_iter().fold(seed, f);
[fold(xs, f32::min, f32::MAX), fold(ys, f32::min, f32::MAX), fold(xs, f32::max, f32::MIN), fold(ys, f32::max, f32::MIN)]
})
.collect()
};
boxes
.into_iter()
.filter_map(|b| {
let corners = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]];
let screen: Option<Vec<Pos2>> =
corners.iter().map(|c| map.to_screen(page, map.to_doc(page, [f64::from(c[0]), f64::from(c[1])]))).collect();
screen.map(|points| Rect::from_points(&points))
})
.collect()
}
/// The copied bundle's box and each comment's outline at the pointer, centred on it, in `overlay.line`, labelled with
/// how many comments it holds. `page` is the page under `at`.
pub(crate) fn paste_outline(draw: &Draw<'_>, cx: &ToolContext<'_>, paste: &PastePlacement, map: &PageMap<'_>, page: usize, at: Pos2) {
let Some(style) = cx.style() else { return };
let line = style.color(style.tokens.color.overlay.line);
let Some(under) = map.to_page(page, Point::new(f64::from(at.x), f64::from(at.y))) else { return };
let [x, y] = map.to_user(page, under);
let [bx0, by0, bx1, by1] = paste.bounds;
let (dx, dy) = (x - (bx0 + bx1) / 2.0, y - (by0 + by1) / 2.0);
let on_screen = |q: [f64; 2]| map.to_screen(page, map.to_doc(page, [q[0] + dx, q[1] + dy])).unwrap_or(at);
let gap = style.tokens.space.gap.tight;
let frame = Rect::from_two_pos(on_screen([bx0, by0]), on_screen([bx1, by1])).expand(gap);
draw.stroke(&PaintShape::Polygon(rect_corners(frame)), StrokeWidth::Thin, line);
for outline in &paste.outlines {
paint_outline(draw, outline, &on_screen, line);
}
let label = crate::i18n::fmt(tl!("Comments: {n}"), &[("n", &paste.count.to_string())]);
let mut run = TextRun::new(label);
run.color = Some(line);
let height = style.tokens.size.icon.md;
draw.text(Rect::from_min_size(frame.left_top() - vec2(0.0, height + gap), vec2(cx.rect.width(), height)), &run);
}
fn rect_corners(r: Rect) -> Vec<Pos2> {
vec![r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()]
}
/// One copied comment's outline on screen (`at` maps a user-space point, moved to where the bundle hangs), in the
/// comment's colour, or `fallback` when it has none.
fn paint_outline(draw: &Draw<'_>, outline: &O, at: &dyn Fn([f64; 2]) -> Pos2, fallback: StyleColor) {
let width = StrokeWidth::Medium;
let own = |c: &Option<[f64; 3]>| c.map(|[r, g, b]| DataColor::new(Color32::from_rgb((r.clamp(0.0, 1.0) * 255.0) as u8, (g.clamp(0.0, 1.0) * 255.0) as u8, (b.clamp(0.0, 1.0) * 255.0) as u8)));
let stroke = |shape: PaintShape, c: &Option<[f64; 3]>| match own(c) {
Some(color) => draw.stroke(&shape, width, color),
None => draw.stroke(&shape, width, fallback),
};
match outline {
O::Rect { rect, round, color } => {
let r = Rect::from_two_pos(at([rect[0], rect[1]]), at([rect[2], rect[3]]));
if *round {
let (c, rx, ry) = (r.center(), r.width() / 2.0, r.height() / 2.0);
let points = (0..48).map(|i| i as f32 / 48.0 * std::f32::consts::TAU).map(|t| Pos2::new(c.x + rx * t.cos(), c.y + ry * t.sin())).collect();
stroke(PaintShape::Polygon(points), color);
} else {
stroke(PaintShape::Polygon(rect_corners(r)), color);
}
}
O::Line { points, color } => stroke(PaintShape::Path(points.iter().map(|p| at(*p)).collect()), color),
O::Poly { points, closed, color } => {
let points = points.iter().map(|p| at(*p)).collect();
stroke(if *closed { PaintShape::Polygon(points) } else { PaintShape::Path(points) }, color);
}
O::Ink { strokes, color } => {
for s in strokes {
stroke(PaintShape::Path(s.iter().map(|p| at(*p)).collect()), color);
}
}
O::Quads { quads, color } => {
for q in quads {
// Upper left, upper right, lower right, lower left: a closed shape in that order.
stroke(PaintShape::Polygon(vec![at([q[0], q[1]]), at([q[2], q[3]]), at([q[6], q[7]]), at([q[4], q[5]])]), color);
}
}
O::Text { rect, color, .. } => {
// The text itself is not drawn on the pointer's outline; its box says where it lands.
let r = Rect::from_two_pos(at([rect[0], rect[1]]), at([rect[2], rect[3]]));
stroke(PaintShape::Polygon(rect_corners(r)), color);
}
}
}
-432
View File
@@ -1,432 +0,0 @@
use super::geometry::{HANDLES, handle_pos, held, is_callout, is_markup, reaches_points, reshapable, reshape_for, resizable};
use super::popups::paint_connectors;
use super::state::{CommentView, Gesture, PageCx, SETTLE_SECS};
use super::{
Annotation, Color32, CommentTool, CornerRadius, DocInfo, DocView, Edit, LineEnding, NewAnnotation, Pos2, QuickTool, Rect, SELECT_BLUE, Shape,
Stroke, color32, icons, pos2, vec2,
};
use crate::page_router::{CommentPart, Hit, Owner};
/// The comment outlined under the pointer: the one a press there would take (`hover`, the top hit),
/// with the Select tool or, over its own marks, Fill & Sign. Not the selected comment, nor while a
/// comment is moved, resized or drawn, nor one under a form field or added text that would take
/// the press.
pub(super) fn hover_outline<'c>(cx: &'c PageCx<'_>, cv: &CommentView, hover: Option<&Hit>) -> Option<&'c Annotation> {
let Some(Owner::Comment { index, part: CommentPart::Body }) = hover.map(|h| h.owner) else { return None };
let tool_outlines = matches!(cx.tool, QuickTool::Select | QuickTool::Fill(_));
(cv.gesture.is_none() && tool_outlines && cv.selected != Some((cx.page, index))).then(|| cx.get(index)).flatten()
}
/// Paint comment selection, hover and gesture previews on a page. `hover` is the top hit under the
/// pointer.
pub(crate) fn paint_page(ui: &egui::Ui, painter: &egui::Painter, cx: &PageCx<'_>, view: &DocView, hover: Option<&Hit>) {
let cv = &view.comments;
// All commented text markup, including imported markup, gets a viewer-only
// marker. Plain markup has none; comment_marker_rect owns that distinction.
for a in cx.comments() {
if let Some(marker) = cx.comment_marker_rect(a)
&& let Some(target) = cx.screen_rects(a).last()
{
painter.line_segment(
[marker.left_bottom(), pos2(target.right(), target.top())],
Stroke::new(1.0, Color32::from_rgba_unmultiplied(0xD4, 0x8A, 0x00, 150)),
);
icons::paint(ui, marker, "message-square", 12.0, Color32::from_rgb(0xD4, 0x8A, 0x00));
}
}
let pointer = cx.ptr.pos;
// A redaction mark shows its fill while the pointer is over it, as Acrobat's does, so the
// marked area reads before anything is applied.
if cv.gesture.is_none()
&& let Some(a) = pointer.and_then(|p| cx.comment_at(p))
&& a.subtype == "Redact"
{
let ([r, g, b], opacity) = cx.redact_mark;
let fill = Color32::from_rgba_unmultiplied((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, (opacity.clamp(0.0, 1.0) * 255.0) as u8);
for rect in cx.redact_rects(a) {
painter.rect_filled(rect, CornerRadius::ZERO, fill);
}
}
if let Some(a) = hover_outline(cx, cv, hover) {
for r in cx.screen_rects(a) {
painter.rect_stroke(r.expand(2.0), CornerRadius::same(2), Stroke::new(1.0, SELECT_BLUE.gamma_multiply(0.7)), egui::StrokeKind::Outside);
}
}
// The comments selected besides the one with the handles: outlined, not resizable.
for a in cv.also.iter().filter(|(p, _)| *p == cx.page).filter_map(|(_, i)| cx.get(*i)) {
for r in cx.screen_rects(a) {
painter.rect_stroke(r.expand(2.0), CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Middle);
}
}
if let Some((page, index)) = cv.selected
&& page == cx.page
&& let Some(a) = cx.get(index)
{
// The rest of the group is selected with its primary.
for (m, _) in cx.group_members().into_iter().filter(|(_, p)| p.index == index) {
for r in cx.screen_rects(m) {
painter.rect_stroke(r.expand(2.0), CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Middle);
}
}
if is_markup(&a.subtype) && !a.quads.is_empty() {
for r in cx.screen_rects(a) {
painter.rect_stroke(r.expand(2.0), CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Middle);
}
// Selected text markup is linked to its open pop-up too.
paint_connectors(painter, cx, view, pointer);
return paint_gesture(painter, cx, view);
}
if view.signature_drag.contains(page, index) && matches!(cv.gesture, Some(Gesture::Move { page: p, index: i, .. }) if (p, i) == (page, index))
{
return paint_gesture(painter, cx, view);
}
let shift = ui.input(|i| i.modifiers.shift);
let points = cx.allowed && reaches_points(cx.tool) && reshapable(a);
if points && !is_callout(a) {
return paint_points(painter, cx, view, a, pointer, shift);
}
let r = cx.adjusted_rect(a, cv.gesture.as_ref(), pointer, shift, view.pending_edit.as_ref()).expand(2.0);
painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Middle);
if cx.allowed && resizable(a) {
for h in HANDLES {
let c = handle_pos(r, h);
painter.circle(c, 4.5, Color32::WHITE, Stroke::new(1.0, SELECT_BLUE));
}
}
// A callout's arrow point and knee, over its text box's frame.
if points {
return paint_points(painter, cx, view, a, pointer, shift);
}
}
paint_connectors(painter, cx, view, pointer);
paint_gesture(painter, cx, view);
}
/// Whether dragging `a` from `from` moves a callout's text box alone: a press inside the box. Its
/// arrow point stays and its knee comes along, as seen in Acrobat Pro DC (a 2021 Continuous
/// release) and Acrobat Pro 2026.002.22031 (#1152), and "The text box moves around a stationary
/// anchor point" (Acrobat DC Help, 11/28/2019, p. 357). A press on the leader line moves the whole
/// callout (seen in the 2021 release).
pub(super) fn moves_box_only(cx: &PageCx<'_>, a: &Annotation, from: Pos2) -> bool {
is_callout(a) && resizable(a) && cx.frame_rect(a).contains(from)
}
/// A selected line, connected lines, polygon or cloud: a handle on each end or corner and, while
/// one is dragged (or its edit is on its way), the new shape over the old.
/// The points a selected line, polygon, cloud or callout is drawn with while it changes: an end,
/// corner, arrow point or knee being dragged (moved by `reshape`: [`reshaped`], or a callout's
/// [`callout_reshaped`]), the whole comment being moved by its body, or the edit just released
/// (until the page is drawn again). `None` while it isn't changing.
pub(super) fn changing_points(
gesture: Option<&Gesture>,
pending: Option<&Edit>,
(page, index): (usize, usize),
points: &[[f64; 2]],
to_user: impl Fn(Pos2) -> [f64; 2],
pointer: Option<Pos2>,
reshape: impl Fn(&[[f64; 2]], usize, [f64; 2]) -> Vec<[f64; 2]>,
) -> Option<Vec<[f64; 2]>> {
let shifted = |dx: f64, dy: f64| points.iter().map(|q| [q[0] + dx, q[1] + dy]).collect();
match (gesture, pending) {
(Some(Gesture::Reshape { page: p, index: i, point, points: from }), _) if (*p, *i) == (page, index) => {
pointer.map(|at| reshape(from, *point, to_user(at)))
}
(Some(Gesture::Move { page: p, index: i, from }), _) if (*p, *i) == (page, index) => pointer.map(|at| {
let (a, b) = (to_user(*from), to_user(at));
shifted(b[0] - a[0], b[1] - a[1])
}),
(_, Some(Edit::ReshapeAnnotation { page: p, index: i, points: to })) if (*p, *i) == (page, index) => Some(to.clone()),
(_, Some(Edit::MoveAnnotation { page: p, index: i, dx, dy })) if (*p, *i) == (page, index) => Some(shifted(*dx, *dy)),
// Moved with the rest of the selection: its own move in the batch.
(_, Some(Edit::Batch { edits, .. })) => edits.iter().find_map(|e| match e {
Edit::MoveAnnotation { page: p, index: i, dx, dy } if (*p, *i) == (page, index) => Some(shifted(*dx, *dy)),
_ => None,
}),
// A callout's text box resized (or moved alone): its points stay, and its line is drawn to
// the box where it is going (see `paint_points`).
(Some(Gesture::Resize { page: p, index: i, .. }), _) if (*p, *i) == (page, index) => pointer.map(|_| points.to_vec()),
(_, Some(Edit::ResizeAnnotation { page: p, index: i, .. })) if (*p, *i) == (page, index) => Some(points.to_vec()),
_ => None,
}
}
fn paint_points(painter: &egui::Painter, cx: &PageCx<'_>, view: &DocView, a: &Annotation, pointer: Option<Pos2>, shift: bool) {
let cv = &view.comments;
let points: Vec<[f64; 2]> = a.points.iter().map(|q| [f64::from(q[0]), f64::from(q[1])]).collect();
let reshape = |from: &[[f64; 2]], i: usize, to: [f64; 2]| reshape_for(a, from, i, to, shift);
let changing = changing_points(cv.gesture.as_ref(), view.pending_edit.as_ref(), (cx.page, a.index), &points, |p| cx.to_user(p), pointer, reshape);
let changed = changing.is_some();
let mut points = changing.unwrap_or(points);
// A callout's box moved alone leaves its arrow point where it is.
if let (Some(Gesture::Move { page, index, from }), Some(first)) = (cv.gesture.as_ref(), a.points.first())
&& (*page, *index) == (cx.page, a.index)
&& moves_box_only(cx, a, *from)
&& let Some(p) = points.first_mut()
{
*p = [f64::from(first[0]), f64::from(first[1])];
}
// A callout's box moved alone and released: its knee came along, as while it was dragged.
if let (Some(Edit::ResizeAnnotation { page, index, rect }), Some(tb)) = (view.pending_edit.as_ref(), a.text_box.filter(|_| is_callout(a)))
&& (*page, *index) == (cx.page, a.index)
{
let tb = tb.map(f64::from);
let same = |a: f64, b: f64| (a - b).abs() < 0.01;
if same(rect[2] - rect[0], tb[2] - tb[0]) && same(rect[3] - rect[1], tb[3] - tb[1]) {
let (dx, dy) = (rect[0] - tb[0], rect[1] - tb[1]);
for q in points.iter_mut().skip(1) {
*q = [q[0] + dx, q[1] + dy];
}
}
}
let screen: Vec<Pos2> = points.iter().map(|q| cx.to_screen(*q)).collect();
if changed {
let stroke = Stroke::new(1.5, SELECT_BLUE);
// A callout's line ends where it meets the (possibly moving) text box.
let mut line = screen.clone();
if is_callout(a)
&& let Some(toward) = points.last()
{
let tb = cx.rect_to_user(cx.adjusted_rect(a, cv.gesture.as_ref(), pointer, shift, view.pending_edit.as_ref()));
line.push(cx.to_screen(pdfcraft_engine::callout_attach(tb, *toward)));
}
painter.add(if a.subtype == "Polygon" { egui::Shape::closed_line(line, stroke) } else { egui::Shape::line(line, stroke) });
}
for c in screen {
painter.circle(c, 4.5, Color32::WHITE, Stroke::new(1.0, SELECT_BLUE));
}
paint_gesture(painter, cx, view);
}
fn paint_gesture(painter: &egui::Painter, cx: &PageCx<'_>, view: &DocView) {
let now = painter.ctx().input(|i| i.time);
for s in view.comments.settling.iter().filter(|s| s.page == cx.page && now - s.since < SETTLE_SECS) {
paint_draw(painter, cx, &s.tool, &s.points);
}
if let Some(Gesture::Draw { page, tool, points }) = &view.comments.gesture
&& *page == cx.page
{
paint_draw(painter, cx, tool, points);
}
// The bundle of copied comments, hanging on the pointer over this page: its box, and each
// comment's outline in its colour, so the drop can be aimed to the line.
if let Some(Gesture::Place { bounds, count, outlines, .. }) = &view.comments.gesture
&& let Some(p) = cx.ptr.pos
&& cx.xf.rect.contains(p)
{
let [x, y] = cx.to_user(p);
let (dx, dy) = (x - (bounds[0] + bounds[2]) / 2.0, y - (bounds[1] + bounds[3]) / 2.0);
let r = Rect::from_two_pos(cx.to_screen([bounds[0] + dx, bounds[1] + dy]), cx.to_screen([bounds[2] + dx, bounds[3] + dy]));
painter.rect_stroke(r.expand(2.0), CornerRadius::same(2), Stroke::new(1.0, SELECT_BLUE.gamma_multiply(0.6)), egui::StrokeKind::Middle);
let at = |q: [f64; 2]| cx.to_screen([q[0] + dx, q[1] + dy]);
for outline in outlines {
paint_outline(painter, outline, &at);
}
let label = crate::i18n::fmt(tl!("Comments: {n}"), &[("n", &count.to_string())]);
painter.text(r.left_top() + vec2(0.0, -4.0), egui::Align2::LEFT_BOTTOM, label, crate::theme::regular(11.0), SELECT_BLUE);
}
}
/// One copied comment's outline on screen (`at` maps a user-space point, moved to where the
/// bundle hangs), in the comment's colour.
fn paint_outline(painter: &egui::Painter, outline: &pdfcraft_engine::CommentOutline, at: &dyn Fn([f64; 2]) -> Pos2) {
use pdfcraft_engine::CommentOutline as O;
let color = |c: &Option<[f64; 3]>| {
c.map(|[r, g, b]| Color32::from_rgb((r.clamp(0.0, 1.0) * 255.0) as u8, (g.clamp(0.0, 1.0) * 255.0) as u8, (b.clamp(0.0, 1.0) * 255.0) as u8))
.unwrap_or(SELECT_BLUE)
};
match outline {
O::Rect { rect, round, color: c } => {
let stroke = Stroke::new(1.5, color(c));
let r = Rect::from_two_pos(at([rect[0], rect[1]]), at([rect[2], rect[3]]));
if *round {
let (cx, cy, rx, ry) = (r.center().x, r.center().y, r.width() / 2.0, r.height() / 2.0);
let points: Vec<Pos2> =
(0..48).map(|i| i as f32 / 48.0 * std::f32::consts::TAU).map(|t| pos2(cx + rx * t.cos(), cy + ry * t.sin())).collect();
painter.add(egui::Shape::closed_line(points, stroke));
} else {
painter.rect_stroke(r, CornerRadius::ZERO, stroke, egui::StrokeKind::Middle);
}
}
O::Line { points, color: c } => {
let stroke = Stroke::new(1.5, color(c));
painter.add(egui::Shape::line(points.iter().map(|p| at(*p)).collect(), stroke));
}
O::Poly { points, closed, color: c } => {
let stroke = Stroke::new(1.5, color(c));
let points: Vec<Pos2> = points.iter().map(|p| at(*p)).collect();
painter.add(if *closed { egui::Shape::closed_line(points, stroke) } else { egui::Shape::line(points, stroke) });
}
O::Ink { strokes, color: c } => {
let stroke = Stroke::new(1.5, color(c));
for s in strokes {
painter.add(egui::Shape::line(s.iter().map(|p| at(*p)).collect(), stroke));
}
}
O::Quads { quads, color: c } => {
let fill = color(c).gamma_multiply(0.35);
for q in quads {
// Upper left, upper right, lower right, lower left: a closed shape in that order.
let points = vec![at([q[0], q[1]]), at([q[2], q[3]]), at([q[6], q[7]]), at([q[4], q[5]])];
painter.add(egui::Shape::convex_polygon(points, fill, Stroke::NONE));
}
}
O::Text { rect, text, size, color: c } => {
// At the page's zoom, wrapped in the box; too small to read at this zoom, left out.
let r = Rect::from_two_pos(at([rect[0], rect[1]]), at([rect[2], rect[3]]));
let zoom = at([1.0, 0.0]).distance(at([0.0, 0.0]));
let px = *size as f32 * zoom;
if !(px.is_finite() && px >= 3.0) {
return;
}
let pad = 2.0 * zoom;
let galley = painter.layout(text.clone(), egui::FontId::proportional(px.min(400.0)), color(c), (r.width() - 2.0 * pad).max(1.0));
painter.with_clip_rect(r.intersect(painter.clip_rect())).galley(r.min + vec2(pad, pad), galley, color(c));
}
}
}
/// A drawing tool's shape from its points (a live drag, or a released one still settling).
fn paint_draw(painter: &egui::Painter, cx: &PageCx<'_>, tool: &CommentTool, points: &[[f64; 2]]) {
{
let style = cx.prefs.style(*tool);
let zoom = cx.xf.zoom();
let stroke = Stroke::new((style.width as f32 * zoom).max(1.0), color32(style.color).gamma_multiply(style.opacity as f32));
let pts: Vec<Pos2> = points.iter().map(|p| cx.to_screen(*p)).collect();
match tool {
CommentTool::Ink | CommentTool::FreehandHighlight => {
painter.add(egui::Shape::line(pts, stroke));
}
CommentTool::Eraser => {
// As wide as what it rubs out (see `erase`).
let width = (2.0 * eraser_radius_px(style.width)) as f32;
painter.add(egui::Shape::line(pts, Stroke::new(width, Color32::from_gray(128).gamma_multiply(0.35))));
}
CommentTool::Line | CommentTool::Arrow if pts.len() == 2 => {
painter.line_segment([pts[0], pts[1]], stroke);
if *tool == CommentTool::Arrow {
let d = (pts[0] - pts[1]).normalized();
let s = (6.0 + 3.0 * style.width as f32) * zoom;
let rot = |v: egui::Vec2, a: f32| vec2(v.x * a.cos() - v.y * a.sin(), v.x * a.sin() + v.y * a.cos());
for a in [0.52f32, -0.52] {
painter.line_segment([pts[1], pts[1] + rot(d, a) * s], stroke);
}
}
}
CommentTool::Rectangle if pts.len() == 2 => {
painter.rect_stroke(Rect::from_two_pos(pts[0], pts[1]), CornerRadius::ZERO, stroke, egui::StrokeKind::Inside);
}
CommentTool::Oval if pts.len() == 2 => {
let r = Rect::from_two_pos(pts[0], pts[1]);
painter.add(egui::Shape::ellipse_stroke(r.center(), r.size() / 2.0, stroke));
}
CommentTool::Polygon | CommentTool::PolyLine | CommentTool::Cloud => {
// The vertices so far, and a rubber band to where a click would put the next one: the
// first, where the click closes the shape, Shift or not.
let mut line = pts.clone();
if let Some(p) = cx.ptr.pos {
let shift = painter.ctx().input(|i| i.modifiers.shift);
line.push(if closes_at(cx, *tool, points, p) { pts[0] } else { cx.to_screen(held(points.last(), cx.to_user(p), shift)) });
}
painter.add(egui::Shape::line(line, stroke));
if let Some(first) = pts.first().filter(|_| *tool != CommentTool::PolyLine && pts.len() >= 3) {
painter.circle_stroke(*first, 5.0, Stroke::new(1.0, SELECT_BLUE));
}
}
CommentTool::TextBox if pts.len() == 2 => {
painter.rect_stroke(Rect::from_two_pos(pts[0], pts[1]), CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Inside);
}
CommentTool::Callout if pts.len() == 2 => {
painter.line_segment([pts[0], pts[1]], stroke);
painter.rect_stroke(Rect::from_min_size(pts[1], vec2(160.0, 40.0) * zoom), CornerRadius::ZERO, stroke, egui::StrokeKind::Inside);
}
_ => {}
}
}
}
/// Whether a click at `p` (on screen) closes the polygon or cloud drawn so far (`points`, user
/// space): on its first point again, once it has three.
pub(super) fn closes_at(cx: &PageCx<'_>, tool: CommentTool, points: &[[f64; 2]], p: Pos2) -> bool {
points.len() >= 3 && tool != CommentTool::PolyLine && cx.to_screen(points[0]).distance(p) <= 6.0
}
/// The shape a finished drawing gesture makes (`None` if it is too small to mean anything).
pub(super) fn drawn_shape(tool: CommentTool, points: &[[f64; 2]]) -> Option<Shape> {
let (first, last) = (*points.first()?, *points.last()?);
let far = (first[0] - last[0]).hypot(first[1] - last[1]) >= 2.0;
let rect = [first[0].min(last[0]), first[1].min(last[1]), first[0].max(last[0]), first[1].max(last[1])];
let big = rect[2] - rect[0] >= 2.0 && rect[3] - rect[1] >= 2.0;
match tool {
CommentTool::FreehandHighlight if !points.is_empty() => Some(Shape::FreehandHighlight { strokes: vec![points.to_vec()] }),
CommentTool::Ink if !points.is_empty() => Some(Shape::Ink { strokes: vec![points.to_vec()] }),
CommentTool::Line | CommentTool::Arrow if far => Some(Shape::Line {
from: first,
to: last,
start: LineEnding::None,
end: if tool == CommentTool::Arrow { LineEnding::OpenArrow } else { LineEnding::None },
}),
CommentTool::Rectangle if big => Some(Shape::Rectangle { rect }),
CommentTool::Oval if big => Some(Shape::Oval { rect }),
CommentTool::Polygon | CommentTool::Cloud if points.len() >= 3 => {
Some(Shape::Polygon { vertices: points.to_vec(), cloud: tool == CommentTool::Cloud })
}
CommentTool::PolyLine if points.len() >= 2 => {
Some(Shape::PolyLine { vertices: points.to_vec(), start: LineEnding::None, end: LineEnding::None })
}
_ => None,
}
}
/// The eraser's radius on screen, in pixels, from its thickness setting (#3747): three pixels
/// per point, so the default 2 pt keeps the 12-pixel eraser it always had, and the thickness
/// slider's 0.5–12 pt gives 3 to 72 pixels across. A setting that isn't a number is the default.
fn eraser_radius_px(width: f64) -> f64 {
3.0 * if width.is_finite() { width.clamp(0.5, super::MAX_LINE_WIDTH) } else { 2.0 }
}
/// Eraser: rub out drawings along `path` (user space); one undo step for all of them. It rubs
/// as wide on screen as its preview, whatever the zoom.
pub(super) fn erase(cx: &PageCx<'_>, path: &[[f64; 2]]) -> Option<Edit> {
let zoom = f64::from(cx.xf.zoom());
// A page with no size on screen has nothing to rub out (and no finite radius).
if !(zoom.is_finite() && zoom > 0.0) {
return None;
}
// Exactly the preview's width: no floor, which at a high zoom rubbed past it.
let radius = eraser_radius_px(cx.prefs.style(CommentTool::Eraser).width) / zoom;
let b = path.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |r, p| [r[0].min(p[0]), r[1].min(p[1]), r[2].max(p[0]), r[3].max(p[1])]);
let mut hits: Vec<usize> = cx
.comments()
.filter(|a| a.subtype == "Ink" && !a.locked)
.filter(|a| {
let r = a.rect;
(r[0] as f64) <= b[2] + radius && (r[2] as f64) >= b[0] - radius && (r[1] as f64) <= b[3] + radius && (r[3] as f64) >= b[1] - radius
})
.map(|a| a.index)
.collect();
if hits.is_empty() {
return None;
}
// Later indices first: deleting an emptied drawing shifts the ones after it.
hits.sort_unstable_by(|a, b| b.cmp(a));
let edits = hits.into_iter().map(|index| Edit::EraseInk { page: cx.page, index, path: path.to_vec(), radius }).collect();
Some(Edit::Batch { label: "Erase".into(), edits })
}
/// Where the composer for editing `a` opens: the top-right corner of the comment as drawn on the
/// displayed page.
pub(super) fn edit_anchor(info: &DocInfo, a: &Annotation) -> [f64; 2] {
let Some(p) = info.pages.get(a.page) else { return [f64::from(a.rect[2]), f64::from(a.rect[3])] };
let r = a.shown_rect(p.rotation);
let (u, v) = (p.user_to_view(r[0], r[1]), p.user_to_view(r[2], r[3]));
p.view_to_user(u[0].max(v[0]), u[1].min(v[1])).map(f64::from)
}
/// Whether comment `index` on the composer's page is at least partly inside `viewport`, as drawn.
pub(super) fn edited_in_view(cx: &PageCx<'_>, index: usize, viewport: Rect) -> bool {
cx.info.annotations.iter().any(|a| a.page == cx.page && a.index == index && viewport.intersects(cx.screen_rect(a)))
}
pub(super) fn new_comment(cx: &PageCx<'_>, tool: CommentTool, shape: Shape, contents: String) -> Edit {
Edit::AddAnnotation(NewAnnotation { page: cx.page, shape, style: cx.prefs.style(tool), contents, author: cx.prefs.author.clone() })
}
+421
View File
@@ -0,0 +1,421 @@
use craft::behavior::kurbo::Point;
use craft::behavior::{CancelReason, Cursor, CursorIcon, EditEvent, PointerButton, PressPhase};
use craft::keymap::Mods;
use craft::review::ui::annotate::{
AnnotateTool, AnnotateWords, DrawOptions, EmptyPress, EraseMode, FarNudge, HandlesWhileDrawing, InkStrokes, MarkupPress, OpenOn, SelectOptions,
ToggleMods,
};
use craft::review::{Annotation as Marked, AnnotationEdit, AnnotationKind, AnnotationTool, ShiftLock};
use craft::ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft::ui::primitives::Draw;
use egui::Pos2;
use super::bridge::{self, PageMap};
use super::state::{Composer, ComposerKind, PageCx};
use super::{CommentPrefs, CommentTool, CommentView, DocInfo, DocView, Edit, MAX_LINE_WIDTH, QuickTool};
use crate::canvas::PageSelectTool;
use crate::canvas::page_parts::{Owner, PagePress};
/// Copied comments hanging on the pointer, waiting for a click to place them.
pub(crate) struct PastePlacement {
/// The copied comments as XFDF.
pub xfdf: String,
/// The bundle's box in user space.
pub bounds: [f64; 4],
/// How many comments the bundle holds.
pub count: usize,
/// Each copied comment's shape, for the outline that follows the pointer.
pub outlines: Vec<pdfcraft_engine::CommentOutline>,
}
/// The caret's snap for the page under the pointer: the snapped tip and the caret's side, in page units.
type CaretSnap = Box<dyn Fn(Point) -> Option<(Point, f64)> + Send>;
/// The comment tools on the pages as a canvas tool: the annotation tool for the comment gestures, the paste
/// placement, and the text selection beneath a markup tool.
// PLAN: the sheet's constructor lists four arguments; the tool also needs the pass's tool, preferences and what the
// document allows (`settings`), where a paste click's edit and notice go (`outcome`), and `paste` as the whole slot so a
// click or Escape can drop it (pdf-canvas-w9's `view.paste.as_mut()` becomes `&mut view.paste`).
pub(crate) struct CommentsTool<'a> {
annotate: &'a mut AnnotateTool,
text: Option<PageSelectTool<'a>>,
paste: &'a mut Option<PastePlacement>,
placed: Option<&'a mut Option<Edit>>,
notice: Option<&'a mut Option<&'static str>>,
map: PageMap<'a>,
done: &'a mut bool,
quick: QuickTool,
prefs: Option<&'a CommentPrefs>,
allowed: bool,
hidden: bool,
caret: Option<CaretSnap>,
}
impl<'a> CommentsTool<'a> {
/// The tool over `annotate` (kept in `CommentView::tool`, so a gesture lasts across passes), the paste slot, the
/// pages on screen and the flag Escape sets when it leaves the tool (`CommentView::tool_done`).
pub(crate) fn new(annotate: &'a mut AnnotateTool, paste: &'a mut Option<PastePlacement>, map: PageMap<'a>, done: &'a mut bool) -> Self {
CommentsTool {
annotate,
text: None,
paste,
placed: None,
notice: None,
map,
done,
quick: QuickTool::Select,
prefs: None,
allowed: false,
hidden: false,
caret: None,
}
}
/// The text selection a press no comment takes goes on to.
pub(crate) fn text(mut self, text: PageSelectTool<'a>) -> Self {
self.text = Some(text);
self
}
/// The tool in use, the comment preferences, whether the document allows commenting and whether comments are
/// hidden.
pub(crate) fn settings(mut self, quick: QuickTool, prefs: &'a CommentPrefs, allowed: bool, hidden: bool) -> Self {
(self.quick, self.prefs, self.allowed, self.hidden) = (quick, Some(prefs), allowed, hidden);
self
}
/// Where a paste click's edit and notice go.
pub(crate) fn outcome(mut self, placed: &'a mut Option<Edit>, notice: &'a mut Option<&'static str>) -> Self {
self.placed = Some(placed);
self.notice = Some(notice);
self
}
/// The caret tool's snap to the text under the pointer.
// PLAN: assumed pdf-comments-w7 supplies the snap over `geometry::snapped_caret` and the page's text.
pub(crate) fn caret_snap(mut self, snap: impl Fn(Point) -> Option<(Point, f64)> + Send + 'static) -> Self {
self.caret = Some(Box::new(snap));
self
}
fn page_under(&self, at: Pos2) -> Option<usize> {
self.map.page_at(Point::new(f64::from(at.x), f64::from(at.y)))
}
/// Whether the annotation tool holds a gesture: the drag, release and cancel are its, else the text's.
fn annotating(&self) -> bool {
self.annotate.in_flight().is_some() || !self.annotate.drawing().is_empty()
}
fn place(&mut self, page: usize, at: Pos2) {
let Some(paste) = self.paste.take() else { return };
let Some(at) = self.map.to_page(page, Point::new(f64::from(at.x), f64::from(at.y))) else { return };
let [x, y] = self.map.to_user(page, at);
let offset = [x - (paste.bounds[0] + paste.bounds[2]) / 2.0, y - (paste.bounds[1] + paste.bounds[3]) / 2.0];
// Larger than the page it lands on (an A0 bundle on an A4 page): placed as it is, and said so.
if let Some(info) = self.map.info.pages.get(page) {
let a = info.user_to_view((paste.bounds[0] + offset[0]) as f32, (paste.bounds[1] + offset[1]) as f32);
let b = info.user_to_view((paste.bounds[2] + offset[0]) as f32, (paste.bounds[3] + offset[1]) as f32);
let (w, h) = ((a[0] - b[0]).abs(), (a[1] - b[1]).abs());
if w > info.width + 1.0 || h > info.height + 1.0
&& let Some(notice) = self.notice.as_deref_mut()
{
*notice = Some("The copied comments are larger than this page; they were placed as they are");
}
}
if let Some(placed) = self.placed.as_deref_mut() {
*placed = Some(Edit::PasteComments { xfdf: paste.xfdf, page, offset: Some(offset) });
}
}
}
/// The framework's tool for `quick`: the comment tool's own, or Select for every other tool.
fn annotation_tool(quick: QuickTool) -> AnnotationTool {
match quick {
QuickTool::Comment(tool) => tool.tool(),
_ => AnnotationTool::Select,
}
}
/// The eraser's radius, in screen points, from its thickness setting (#3747): three points per point of
/// thickness, so the default 2 pt keeps the 12-point eraser. A setting that is not a number is the default.
fn eraser_radius(width: f64) -> f32 {
(3.0 * if width.is_finite() { width.clamp(0.5, MAX_LINE_WIDTH) } else { 2.0 }) as f32
}
/// A preference colour as straight RGB bytes.
fn rgb8(color: pdfcraft_engine::Rgb) -> [u8; 3] {
let c = super::color32(color);
[c.r(), c.g(), c.b()]
}
impl CanvasTool for CommentsTool<'_> {
fn each_pass(&mut self, cx: &mut ToolContext<'_>) {
// The page the tool works on follows the pointer between gestures.
if cx.gesture_id().is_none()
&& self.annotate.drawing().is_empty()
&& let Some(page) = cx.pointer.and_then(|p| self.page_under(p.pos))
{
self.annotate.page = page;
}
let page = self.annotate.page;
self.annotate.tool = annotation_tool(self.quick);
self.annotate.annotations = if self.hidden {
Vec::new()
} else {
bridge::annotations(self.map.info, &self.map, self.quick, self.allowed).into_iter().filter(|a| a.page == page).collect()
};
let mut eraser_width = 2.0;
if let (Some(prefs), QuickTool::Comment(comment)) = (self.prefs, self.quick) {
let style = prefs.style(comment);
self.annotate.color = rgb8(style.color);
self.annotate.highlight_color = rgb8(prefs.style(CommentTool::Highlight).color);
self.annotate.width = style.width;
if comment == CommentTool::Eraser {
eraser_width = style.width;
}
}
let select = SelectOptions {
empty_press: EmptyPress::PassThrough,
toggle: ToggleMods::ShiftOrCommand,
open: OpenOn::Every,
shift_lock: ShiftLock::LevelOrPlumb,
far_nudge: FarNudge::ShiftOrCommand,
handles_while_drawing: HandlesWhileDrawing::Edit,
markup_press: MarkupPress::ClickOnly,
};
let draw = DrawOptions { ink: InkStrokes::PerStroke, erase: EraseMode::Path, eraser_radius: eraser_radius(eraser_width) };
// The options are builders over the owned tool: rebuilt from the tool taken out, its gesture kept.
let mut built = std::mem::take(self.annotate).select_options(select).draw_options(draw);
if self.quick == QuickTool::Comment(CommentTool::Caret)
&& let Some(snap) = self.caret.take()
{
built = built.caret_snap(snap);
}
*self.annotate = built;
self.annotate.each_pass(cx);
if let Some(text) = self.text.as_mut() {
text.each_pass(cx);
}
}
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
if self.paste.is_some() {
// A click places the bundle, centred where it is clicked, on the page under it; a right-click lets it
// go. Nothing else on the page takes the press.
if pointer.button == PointerButton::Secondary {
*self.paste = None;
} else if self.allowed
&& let Some(page) = self.page_under(pointer.pos)
{
self.place(page, pointer.pos);
}
return ToolAction::Done;
}
match self.annotate.press(pointer, cx) {
ToolAction::Ignored => match self.text.as_mut() {
Some(text) => text.press(pointer, cx),
None => ToolAction::Ignored,
},
action => action,
}
}
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
if self.annotating() {
self.annotate.drag(pointer, cx);
} else if let Some(text) = self.text.as_mut() {
text.drag(pointer, cx);
}
}
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
if self.annotating() {
self.annotate.release(pointer, cx);
} else if let Some(text) = self.text.as_mut() {
text.release(pointer, cx);
}
}
fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
self.annotate.hover(pointer, cx);
if let Some(text) = self.text.as_mut() {
text.hover(pointer, cx);
}
}
fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) {
if self.annotating() {
self.annotate.cancel(reason, cx);
} else if let Some(text) = self.text.as_mut() {
text.cancel(reason, cx);
}
}
fn claims(&self) -> ToolClaims {
self.annotate.claims()
}
fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool {
if matches!(key, ToolKey::Cancel) {
// One step back per press: drop a paste, cancel the drawing, deselect, then drop the tool (a comment
// tool, or a Fill & Sign one: its Text tool would otherwise open a box at every click with no way out
// by the keyboard).
if self.paste.take().is_some() {
return true;
}
if !self.annotate.drawing().is_empty() {
self.annotate.cancel_drawing();
return true;
}
if !self.annotate.selected.is_empty() {
self.annotate.selected.clear();
return true;
}
if matches!(self.quick, QuickTool::Comment(_) | QuickTool::Fill(_)) {
*self.done = true;
return true;
}
return false;
}
self.annotate.key(key, cx)
}
fn takes(&self, button: PointerButton, mods: Mods) -> bool {
button == PointerButton::Primary || self.paste.is_some() && button == PointerButton::Secondary || self.annotate.takes(button, mods)
}
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
if self.paste.is_some() && cx.pointer.is_some_and(|p| self.page_under(p.pos).is_some()) {
return Cursor::System(CursorIcon::Grabbing);
}
self.annotate.cursor(cx)
}
fn access(&self, cx: &ToolContext<'_>) -> Option<ToolAccess> {
self.annotate.access(cx)
}
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
self.annotate.paint(draw, cx);
if let (Some(paste), Some(pointer)) = (self.paste.as_ref(), cx.pointer)
&& let Some(page) = self.page_under(pointer.pos)
{
super::overlay::paste_outline(draw, cx, paste, &self.map, page, pointer.pos);
}
if let Some(text) = self.text.as_ref() {
text.paint(draw, cx);
}
}
fn command_form(&self) -> ToolPath {
self.annotate.command_form()
}
}
/// The comment a right-click at `at` is on: the topmost, with every tool, as a comment's menu shows whatever tool
/// is active; on a group subordinate (`/RT /Group`), its group's primary, so the menu offers the comment's actions
/// (ISO 32000-2 §12.5.6.2). A highlight over a link is the highlight's here (a left click on it follows the link).
/// `None` off the page or with comments hidden. The page's menu is anchored at `at` (Delete page, Paste, Copy
/// Image, a note added here), and the comment is selected, or the selection cleared.
pub(crate) fn context_target(cx: &PageCx<'_>, view: &mut CommentView, at: Pos2) -> Option<usize> {
if !cx.xf.rect.contains(at) {
return None;
}
view.context_at = Some((cx.page, cx.to_user(at)));
let target = if cx.hidden { None } else { cx.click_target(at) };
match target {
Some(a) => {
view.pick(cx, at, a);
Some(a.index)
}
None => {
view.select(None);
None
}
}
}
/// A click on a comment's body, from the page part that owns it (M-1): the annotation tool selects it with the
/// modifiers and click count of the press, a double click opening it. A click on a group subordinate selects its
/// group's primary and remembers the member under the pointer (`cx` is the comment's page).
pub(crate) fn part_pressed(view: &mut CommentView, press: &PagePress, cx: &PageCx<'_>, words: &AnnotateWords) {
let Owner::Comment { index } = press.owner else { return };
let PressPhase::Release { start, click: true, .. } = press.phase else { return };
if start.button != PointerButton::Primary {
return;
}
view.tool.click(bridge::id_of(press.page, index), press.mods, start.clicks, words);
view.member = cx.picked(start.origin, view.primary());
}
/// The engine edit the gestures of this pass made, taken from the annotation tool after the tool host ran: each
/// committed `EditEvent` is one engine edit, so a drag is one undo step. A drawn shape that is kept on screen until
/// its page is drawn again is remembered (`CommentView::settle`). The new comment is selected by the app once the
/// edit is applied (a pen stroke stays unselected, `editing.rs`).
pub(crate) fn take_edits(view: &mut CommentView, map: &PageMap<'_>, info: &DocInfo, prefs: &CommentPrefs, now: f64) -> Option<Edit> {
let mut edits = Vec::new();
for event in view.tool.take_edits() {
let (EditEvent::Commit { after, .. } | EditEvent::Set { after, .. }) = event else { continue };
if let AnnotationEdit::Create(a) = &after
&& let Some(tool) = CommentTool::from_kind(a.kind)
{
view.settle(now, a.page, tool, &settled_points(a, map));
}
edits.extend(bridge::edit(after, map, view, info, prefs));
}
match edits.len() {
0 => None,
1 => edits.pop(),
_ => Some(Edit::Batch { label: tl!("Comments").to_owned(), edits }),
}
}
/// The user-space points a released drawing is painted from while it settles: a stroke's points, a box's corners, a
/// line's ends.
fn settled_points(a: &Marked, map: &PageMap<'_>) -> Vec<[f64; 2]> {
let user = |p: &Point| map.to_user(a.page, *p);
match a.kind {
AnnotationKind::Ink | AnnotationKind::FreehandHighlight => a.strokes.last().map(|s| s.iter().map(user).collect()).unwrap_or_default(),
AnnotationKind::Rectangle | AnnotationKind::Oval => vec![user(&Point::new(a.rect.x0, a.rect.y0)), user(&Point::new(a.rect.x1, a.rect.y1))],
_ => a.points.iter().map(user).collect(),
}
}
/// After text selection ran: a markup tool turns a finished selection into a comment; Replace Text asks for the
/// replacement. `finished` is true in the pass the selection's release came (a drag release or a double click); the
/// call runs on every pass a markup tool is active, since a selection on pages still being read is marked later.
pub(crate) fn page_after_text(cx: &PageCx<'_>, tool: QuickTool, finished: bool, view: &mut DocView) {
let QuickTool::Comment(tool) = tool else { return };
if tool == CommentTool::ReplaceText && cx.allowed && finished {
// A replacement sits on one page: a selection across pages stays selected for the bar's
// markup or Copy.
if let Ok([(page, quads)]) = <[_; 1]>::try_from(view.selection_quads(cx.info))
&& page == cx.page
{
view.clear_selection();
let last = quads.last().copied().unwrap_or_default();
let at = [last[2].max(last[6]), last[1].max(last[3])];
view.comments.replace = Some(quads);
view.comments.composer = Some(Composer { page, at, kind: ComposerKind::Replace, text: String::new(), focus: true });
}
return;
}
let Some(kind) = tool.markup().filter(|_| cx.allowed) else { return };
// Once, from whichever of the selection's pages is drawn: after an edge scroll its first page
// may be out of view. Every page it covers gets its own markup, in one undo step, once all
// of them are read.
if let crate::canvas::ToolMarks::Marks(marks, head) = view.tool_marks(QuickTool::Comment(tool), finished, Some(cx.page), false, cx.info) {
view.clear_selection();
let edits = marks.into_iter().map(|(page, quads)| {
Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
page,
shape: super::Shape::TextMarkup { kind, quads },
style: cx.prefs.style(tool),
contents: String::new(),
author: cx.prefs.author.clone(),
})
});
view.pending_edit = view.selection_marks_edit(edits.collect(), head);
}
}