pdf-comments-w7: net change of 3 commits

- pdf-comments-w7: written from its sheet
- pdf-comments-w7: repair 1
- pdf-comments-w7: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-18 16:15:27 -05:00
1 parent 23d6572d6a
commit 4e1062265e
4 files changed
+800 -400

No files matched your search

+71 -25
View File
@@ -16,45 +16,49 @@ use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, pos2, vec2};
use pdfcraft_engine::{Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, Style};
use pdfcraft_render::{Annotation, DocInfo, PageInfo, PageText};
use craft::review::ui::annotate::{AnnotateCommand, AnnotateIcons};
use craft::review::{AnnotationKind, AnnotationTool};
use crate::canvas::{DocView, PageXform};
use crate::page_pointer::PagePointer;
use crate::theme::{self, Tokens};
use crate::{QuickTool, icons};
mod bridge;
mod colours;
mod composer;
mod geometry;
mod input;
mod menu;
mod paint;
mod overlay;
mod popups;
mod state;
mod tool;
pub(crate) use composer::{composer, submit_key};
pub(crate) use bridge::{
PageMap, annotations, delete_selected, edit, edit_anchor, id_of, key_of, kind_of, markers, parts, pdf_date_seconds, screen_to_user_rect,
thread_id, thread_key, tips, tips_shown,
};
#[cfg(test)]
use geometry::handle_pos;
use bridge::hover_tip;
// PLAN: assumed colours exports (pdf-comments-w10): the colour pickers and buttons that `menu` exported before.
pub use colours::{fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid};
pub(crate) use colours::{border_colour_button, quick_bar_colour};
pub(crate) use composer::composer;
#[cfg(test)]
use composer::edited_in_view;
#[cfg(test)]
pub(crate) use geometry::{caret_snap, snapped_caret};
pub(crate) use geometry::{corner_ratio, page_rotation, resized};
pub(crate) use geometry::page_rotation;
pub use geometry::{drawn_text_box_rect, snug_text_box_rect, text_box_rect};
#[cfg(test)]
use input::hover_tip;
pub(crate) use input::{anchor, context, context_hit, describe, hit, keys, moving_on, nudge_keys, page_after_text, page_input, tips_shown};
pub use menu::{CanvasAction, fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid};
pub(crate) use menu::{MenuRights, attachment_items, border_colour_button, context_menu, quick_bar_colour, quick_bar_controls};
#[cfg(test)]
use menu::{RECENT_CUSTOM, same_colour};
pub(crate) use paint::paint_page;
#[cfg(test)]
use paint::{changing_points, drawn_shape, edited_in_view};
pub(crate) use popups::popups;
pub use menu::CanvasAction;
pub(crate) use menu::{CommentMenuCx, MenuRights, QuickBarPick, attachment_items, context_rows, quick_bar_controls};
pub(crate) use overlay::show;
pub(crate) use popups::note_popups;
#[cfg(test)]
use state::after_delete;
use state::login_name;
pub use state::{CommentView, Composer, ComposerKind, Gesture, SortBy};
pub(crate) use state::{EditorFocus, PageCx};
/// Acrobat's selection blue for annotation frames and handles (11-visual-spec §5).
const SELECT_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);
pub use state::{CommentView, Composer, ComposerKind};
pub(crate) use state::PageCx;
pub(crate) use tool::{CommentsTool, PastePlacement, context_target, page_after_text, part_pressed};
/// Maximum stroke thickness offered by commenting controls, in PDF points.
pub const MAX_LINE_WIDTH: f64 = 100.0;
@@ -192,14 +196,50 @@ impl CommentTool {
}
}
/// Lucide icon name for this commenting tool.
/// The framework's annotation kind this tool draws; the Eraser draws none.
pub(crate) fn kind(self) -> Option<AnnotationKind> {
Some(match self {
Self::Note => AnnotationKind::Note,
Self::TextBox => AnnotationKind::TextBox,
Self::Highlight => AnnotationKind::Highlight,
Self::Underline => AnnotationKind::Underline,
Self::StrikeOut => AnnotationKind::StrikeOut,
Self::Squiggly => AnnotationKind::Squiggly,
Self::Ink => AnnotationKind::Ink,
Self::FreehandHighlight => AnnotationKind::FreehandHighlight,
Self::Line => AnnotationKind::Line,
Self::Arrow => AnnotationKind::Arrow,
Self::Rectangle => AnnotationKind::Rectangle,
Self::Oval => AnnotationKind::Oval,
Self::Polygon => AnnotationKind::Polygon,
Self::PolyLine => AnnotationKind::PolyLine,
Self::Cloud => AnnotationKind::Cloud,
Self::Callout => AnnotationKind::Callout,
Self::Caret => AnnotationKind::Caret,
Self::ReplaceText => AnnotationKind::ReplaceText,
Self::Attach => AnnotationKind::Attach,
Self::Eraser => return None,
})
}
/// The framework's tool for this one.
pub fn tool(self) -> AnnotationTool {
self.kind().map_or(AnnotationTool::Eraser, AnnotationTool::Draw)
}
/// The tool that draws `kind`.
pub fn from_kind(kind: AnnotationKind) -> Option<Self> {
ALL.into_iter().find(|t| t.kind() == Some(kind))
}
/// Icon name for this commenting tool: a catalogue name, or a Lucide name the app's icon set serves.
pub fn icon(self) -> &'static str {
match self {
Self::Note => "message-square-plus",
Self::TextBox => "type",
Self::Highlight => "highlighter",
Self::Underline => "underline",
Self::StrikeOut => "strikethrough",
Self::Underline => "text_underline",
Self::StrikeOut => "text_strikethrough",
Self::Squiggly => "spline",
Self::FreehandHighlight => "highlighter",
Self::Ink => "pencil",
@@ -297,6 +337,12 @@ impl CommentTool {
}
}
/// Each comment tool's icon as the framework's annotate commands show it, on every surface (toolbar, flyouts,
/// palette, menus): [`CommentTool::icon`] is the one map.
pub(crate) fn annotate_icons() -> AnnotateIcons {
ALL.iter().fold(AnnotateIcons::new(), |set, t| set.with(AnnotateCommand::of(t.tool()), t.icon()))
}
/// The comment swatches (our palette, close to Acrobat's quick colours).
pub const SWATCHES: [(&str, Rgb); 10] = [
("Yellow", [1.0, 0.94, 0.0]),
+624
View File
@@ -0,0 +1,624 @@
//! The one place that maps the engine's annotations and `Edit`s to the framework's `Annotation` and `AnnotationEdit`
//! and back. The framework's page units here are the page as shown: its `/Rotate` and the view's quarter turn both
//! applied, in points, top-left origin. [`PageMap`] carries the view's turn.
use std::collections::HashMap;
use chrono::NaiveDate;
use craft::behavior::kurbo::{Point, Rect, Vec2};
use craft::behavior::{Cursor, CursorIcon};
use craft::pages::ui::PlacedPage;
use craft::review::annotate::{marker_rect, pick_at};
use craft::review::ui::AnnotateTool;
use craft::review::{Annotation as Marked, AnnotationEdit, AnnotationId, AnnotationKind, HandleRule, Placement, ThreadId};
use super::geometry::{CARET_SIZE, clamp_to, frame, is_callout, on_text, reshapable, resizable};
use super::popups::has_popup;
use super::state::{CommentView, Composer, ComposerKind, PageCx};
use super::{Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, LineEnding, NewAnnotation, PageInfo, QuickTool, Shape, tool_for};
// PLAN: assumed `PagePart::new(owner, page, shape: Vec<egui::Rect>, layer)` with `.passes_drag()`, `.tip(String)` and
// `.cursor(CursorIcon)`, and `Owner::Comment { index }` (pdf-canvas-w9, `canvas/page_parts.rs`).
use crate::canvas::page_parts::{Owner, PageLayer, PagePart};
/// The id of the annotation at `index` on `page`: the page in the high 32 bits, the index in the low 32.
pub(crate) fn id_of(page: usize, index: usize) -> AnnotationId {
let half = |v: usize| u64::from(u32::try_from(v).unwrap_or(u32::MAX));
AnnotationId((half(page) << 32) | half(index))
}
/// The `(page, index)` an [`id_of`] id names.
pub(crate) fn key_of(id: AnnotationId) -> (usize, usize) {
let half = |v: u64| usize::try_from(v).unwrap_or(usize::MAX);
(half(id.0 >> 32), half(id.0 & u64::from(u32::MAX)))
}
/// The panel's thread id of the comment at `(page, index)`: the comment's own annotation id. The one mapping the
/// panel, the pop-ups and the tests use.
pub(crate) fn thread_id(page: usize, index: usize) -> ThreadId {
ThreadId(id_of(page, index).0)
}
/// The `(page, index)` of a thread's root comment.
pub(crate) fn thread_key(thread: ThreadId) -> (usize, usize) {
key_of(AnnotationId(thread.0))
}
/// The pages on screen this pass with the document's page geometry: the maps between a page's user space, its
/// displayed space (the framework's page units) and the screen.
pub(crate) struct PageMap<'a> {
/// The pages placed on screen.
pub pages: &'a [PlacedPage],
/// The document's page geometry.
pub info: &'a DocInfo,
/// The view's quarter turn in degrees, which the placed pages show but `PageInfo`'s own transform does not.
pub rotation: u16,
}
impl<'a> PageMap<'a> {
/// A map over `pages` of the document `info`, shown turned by `rotation` degrees.
pub(crate) fn new(info: &'a DocInfo, pages: &'a [PlacedPage], rotation: u16) -> Self {
Self { pages, info, rotation }
}
fn placed(&self, page: usize) -> Option<&PlacedPage> {
self.pages.iter().find(|p| p.page == page)
}
fn shows(&self, page: usize) -> bool {
self.info.pages.get(page).is_some() && self.placed(page).is_some()
}
/// A user-space point of `page` in the page's displayed units.
pub(crate) fn to_doc(&self, page: usize, user: [f64; 2]) -> Point {
match self.info.pages.get(page) {
Some(p) => view_point(p, self.rotation, [user[0] as f32, user[1] as f32]),
None => Point::new(user[0], user[1]),
}
}
/// A displayed point of `page` in the page's user space.
pub(crate) fn to_user(&self, page: usize, at: Point) -> [f64; 2] {
match self.info.pages.get(page) {
Some(p) => user_point(p, self.rotation, at),
None => [at.x, at.y],
}
}
/// The placed page under the screen point `screen`.
// PLAN: the sheet's `page_at(Point)` takes a screen point: a displayed point alone cannot say which page.
pub(crate) fn page_at(&self, screen: Point) -> Option<usize> {
let at = egui::pos2(screen.x as f32, screen.y as f32);
self.pages.iter().find(|p| p.rect.contains(at)).map(|p| p.page)
}
/// The displayed point of `page` under the screen point `screen`.
pub(crate) fn to_page(&self, page: usize, screen: Point) -> Option<Point> {
Some(self.placed(page)?.to_page(egui::pos2(screen.x as f32, screen.y as f32)))
}
/// The screen position of the displayed point `at` of `page`.
pub(crate) fn to_screen(&self, page: usize, at: Point) -> Option<egui::Pos2> {
Some(self.placed(page)?.to_screen(at))
}
/// A length of `screen` points as page units. Every page is shown at one zoom, so the first placed page's scale
/// serves.
// PLAN: the sheet's `doc_len(screen)` has no page: the pages share one scale.
pub(crate) fn doc_len(&self, screen: f32) -> f64 {
let scale = self.pages.first().map_or(1.0, |p| p.scale);
if scale.is_finite() && scale > 0.0 { f64::from(screen) / scale } else { f64::from(screen) }
}
}
/// `PageInfo` has one entry per page; this names the "is there such a page" question for [`PageMap::shows`].
trait HasPage {
fn contains_key_page(&self, page: usize) -> bool;
}
impl HasPage for Vec<PageInfo> {
fn contains_key_page(&self, page: usize) -> bool {
page < self.len()
}
}
fn view_point(page: &PageInfo, user: [f32; 2]) -> Point {
let v = page.user_to_view(user[0], user[1]);
Point::new(f64::from(v[0]), f64::from(v[1]))
}
fn user_point(page: &PageInfo, at: Point) -> [f64; 2] {
let u = page.view_to_user(at.x as f32, at.y as f32);
[f64::from(u[0]), f64::from(u[1])]
}
/// A user-space rectangle as the displayed rectangle that bounds it.
fn view_rect(page: &PageInfo, r: [f32; 4]) -> Rect {
let (a, b) = (view_point(page, [r[0], r[1]]), view_point(page, [r[2], r[3]]));
Rect::new(a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y))
}
/// A displayed rectangle as the user-space rectangle that bounds it.
fn user_rect(page: &PageInfo, r: Rect) -> [f32; 4] {
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| page.view_to_user(x as f32, y as f32));
let fold = |f: fn(f32, f32) -> f32, i: usize, seed: f32| corners.iter().fold(seed, |m, c| f(m, c[i]));
[fold(f32::min, 0, f32::MAX), fold(f32::min, 1, f32::MAX), fold(f32::max, 0, f32::MIN), fold(f32::max, 1, f32::MIN)]
}
/// A displayed offset as the user-space offset it makes.
fn user_delta(page: &PageInfo, d: Vec2) -> (f64, f64) {
let (o, p) = (page.view_to_user(0.0, 0.0), page.view_to_user(d.x as f32, d.y as f32));
(f64::from(p[0]) - f64::from(o[0]), f64::from(p[1]) - f64::from(o[1]))
}
/// A displayed length as the user-space length it makes.
fn user_len(page: &PageInfo, len: f64) -> f64 {
let (dx, dy) = user_delta(page, Vec2::new(len, 0.0));
dx.hypot(dy)
}
fn bounds(points: &[Point]) -> Option<Rect> {
let first = points.first()?;
let seed = Rect::new(first.x, first.y, first.x, first.y);
Some(points.iter().fold(seed, |r, p| r.union_pt(*p)))
}
/// The annotation as the framework's `AnnotationKind`: the kind of tool that makes it, and for what no tool makes (a
/// stamp, typed text, a sound) the nearest that behaves alike.
// PLAN: `DocInfo` carries no line endings, so an arrow reads as a Line here.
pub(crate) fn kind_of(all: &[Annotation], a: &Annotation) -> AnnotationKind {
tool_for_default(all, a, None).and_then(CommentTool::kind).unwrap_or(match a.subtype.as_str() {
"FreeText" => AnnotationKind::TextBox,
"Stamp" => AnnotationKind::Rectangle,
_ => AnnotationKind::Note,
})
}
fn rgb8(c: [f32; 3]) -> [u8; 3] {
c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
}
/// The framework's annotation for `a`, with `members` (its group's subordinates) joined to its shape.
// PLAN: `DocInfo` carries no ink strokes, opacity or line width, and the image signatures' aspect lives in the view's
// signature drag: `strokes` is empty, opacity 1 and width 1, and `aspect` is only a drawn signature's box.
pub(super) fn marked(info: &DocInfo, a: &Annotation, members: &[&Annotation], allowed: bool) -> Option<Marked> {
let page = info.pages.get(a.page)?;
let kind = kind_of(&info.annotations, a);
let rotation = page.rotation;
let mut rect = view_rect(page, frame(a, rotation));
for m in members {
rect = rect.union(view_rect(page, m.shown_rect(rotation)));
}
let points = if kind.is_pointwise() {
a.points.iter().map(|q| view_point(page, *q)).collect()
} else if kind.is_markup() {
std::iter::once(a)
.chain(members.iter().copied())
.flat_map(|m| m.quads.iter())
.flat_map(|q| [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]])
.map(|p| view_point(page, p))
.collect()
} else {
Vec::new()
};
let drawn_signature = a.fill_sign && a.subtype == "Ink" && rect.height() > 0.0;
let measured = matches!(a.subtype.as_str(), "Line" | "PolyLine" | "Polygon") && a.intent.as_deref().is_some_and(|i| i.ends_with("Dimension"));
let handle_rule = if measured {
HandleRule::FixedPoints
} else if kind == AnnotationKind::Callout && a.text_box.is_none() {
HandleRule::NoResize
} else {
HandleRule::Free
};
Some(Marked {
id: id_of(a.page, a.index),
page: a.page,
kind,
rect,
points,
strokes: Vec::new(),
color: a.color.map_or([255, 240, 0], rgb8),
opacity: 1.0,
stroke_width: 1.0,
text: a.contents.clone().unwrap_or_default(),
locked: a.locked || !allowed,
aspect: drawn_signature.then(|| rect.width() / rect.height()),
handle_rule,
})
}
/// The comments `tool` reaches: every one with Select, a Fill & Sign tool's own marks, and with a shape tool the lot
/// (a press on one draws unless it is a handle of the selected one). None with a tool that places or marks text.
fn reach(tool: QuickTool) -> Option<fn(&Annotation) -> bool> {
match tool {
QuickTool::Select => Some(|_| true),
QuickTool::Fill(_) => Some(|a| a.fill_sign),
QuickTool::Comment(t) if t.draws() || t.clicks_points() => Some(|_| true),
_ => None,
}
}
/// Every comment on the placed pages that `tool` reaches, except pop-ups. A group (`/RT /Group`, or a Replace Text
/// pair) is one annotation under its primary's id with its members' shapes joined to it.
pub(crate) fn annotations(info: &DocInfo, map: &PageMap<'_>, tool: QuickTool, allowed: bool) -> Vec<Marked> {
let Some(pick) = reach(tool) else { return Vec::new() };
let all = &info.annotations;
let primaries = pdfcraft_render::group_primaries(all);
let mut members: HashMap<usize, Vec<&Annotation>> = HashMap::new();
for (m, primary) in all.iter().zip(&primaries) {
if let (true, Some(p)) = (m.is_group_member(), primary) {
members.entry(*p).or_default().push(m);
}
}
all.iter()
.enumerate()
.filter(|(_, a)| a.is_comment() && a.subtype != "Popup" && map.shows(a.page) && pick(a))
.filter_map(|(i, a)| marked(info, a, members.get(&i).map_or(&[][..], Vec::as_slice), allowed))
.collect()
}
fn marker_boxes(info: &DocInfo, anns: &[Marked], icon_side: f64) -> Vec<(AnnotationId, Rect)> {
anns.iter()
.filter_map(|a| {
let p = info.pages.get(a.page)?;
let page = Rect::new(0.0, 0.0, f64::from(p.width), f64::from(p.height));
marker_rect(a, page, icon_side).map(|r| (a.id, r))
})
.collect()
}
/// The markers of commented text markup, in displayed units, an `icon_side` square.
pub(crate) fn markers(info: &DocInfo, map: &PageMap<'_>, icon_side: f64) -> Vec<(AnnotationId, Rect)> {
marker_boxes(info, &annotations(info, map, QuickTool::Select, true), icon_side)
}
/// Whether `tool` shows tips at all: not with Fill & Sign, whose placement stays clear, and not while drawing
/// freehand, where a tip would cover the next stroke (#429).
fn tool_tips(tool: QuickTool) -> bool {
let freehand = matches!(tool, QuickTool::Comment(CommentTool::Ink | CommentTool::FreehandHighlight | CommentTool::Eraser));
!(matches!(tool, QuickTool::Fill(_)) || freehand)
}
/// Whether the page shows a tip for what lies under the pointer (a comment, a signature's badge) with `tool`: not
/// with Fill & Sign, not while drawing freehand, and not while a comment is moved, resized or drawn.
pub(crate) fn tips_shown(tool: QuickTool, view: &DocView) -> bool {
tool_tips(tool) && view.comments.tool.in_flight().is_none() && view.comments.tool.drawing().is_empty()
}
/// 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 tips of the comments with something to say; an open pop-up already shows its comment, so it has none.
pub(crate) fn tips(info: &DocInfo, prefs: &CommentPrefs, tool: QuickTool) -> Vec<(AnnotationId, String)> {
if !tool_tips(tool) {
return Vec::new();
}
info.annotations
.iter()
.filter(|a| a.is_comment() && a.subtype != "Popup" && !a.popup.is_some_and(|w| w.open))
.filter_map(|a| hover_tip(a, prefs).map(|t| (id_of(a.page, a.index), t)))
.collect()
}
/// The one part for the comment under the screen point `pointer`, as `pick_at` finds it (so overlapping comments
/// never meet the arena's nearest-centre rule). `tolerance` and `icon_side` are page units ([`PageMap::doc_len`] of
/// the tool host's slop and icon side). Registers only under Select.
// PLAN: `pointer` is a screen point (the sheet says `Option<Point>`): `page_at` finds its page.
#[allow(clippy::too_many_arguments)]
pub(crate) fn parts(
info: &DocInfo,
map: &PageMap<'_>,
prefs: &CommentPrefs,
tool: QuickTool,
pointer: Option<Point>,
annotate: &AnnotateTool,
tolerance: f64,
icon_side: f64,
) -> Vec<PagePart> {
let Some(screen) = pointer else { return Vec::new() };
let (Some(page), at) = (map.page_at(screen), ()) else { return Vec::new() };
let _ = at;
let Some(at) = map.to_page(page, screen) else { return Vec::new() };
let anns: Vec<Marked> = annotations(info, map, tool, true).into_iter().filter(|a| a.page == page).collect();
let markers = marker_boxes(info, &anns, icon_side);
let Some(id) = pick_at(&anns, at, tolerance, icon_side, &markers) else { return Vec::new() };
let Some(found) = anns.iter().find(|a| a.id == id) else { return Vec::new() };
let mut shapes: Vec<Rect> = if found.kind.is_markup() { found.points.chunks(4).filter_map(bounds).collect() } else { vec![found.extent(icon_side)] };
shapes.extend(markers.iter().filter(|(m, _)| *m == id).map(|(_, r)| *r));
let screen_shapes: Vec<egui::Rect> = shapes
.iter()
.filter_map(|r| Some(egui::Rect::from_two_pos(map.to_screen(page, Point::new(r.x0, r.y0))?, map.to_screen(page, Point::new(r.x1, r.y1))?)))
.collect();
let icon = match annotate.cursor_at(at, tolerance, icon_side) {
Cursor::System(icon) => icon,
_ => CursorIcon::Default,
};
let part = PagePart::new(Owner::Comment { index: key_of(id).1 }, page, screen_shapes, PageLayer::Comment).passes_drag().cursor(icon);
match tips(info, prefs, tool).into_iter().find(|(t, _)| *t == id) {
Some((_, tip)) => vec![part.tip(tip)],
None => vec![part],
}
}
fn engine(info: &DocInfo, page: usize, index: usize) -> Option<&Annotation> {
info.annotations.iter().find(|a| a.page == page && a.index == index)
}
/// Whether the in-flight `edit` moves, resizes or reshapes the annotation `id`.
fn targets(edit: &AnnotationEdit, id: AnnotationId) -> bool {
match edit {
AnnotationEdit::Move { ids, .. } => ids.contains(&id),
AnnotationEdit::Resize { id: own, .. } | AnnotationEdit::Reshape { id: own, .. } => *own == id,
_ => false,
}
}
/// Where the in-flight `edit` leaves `a`, as a user-space rectangle, when it is `a`'s: what the live image, the
/// handles and the released edit all draw.
pub(super) fn edited_user_rect(info: &DocInfo, a: &Annotation, edit: &AnnotationEdit) -> Option<[f32; 4]> {
let own = marked(info, a, &[], true)?;
if !targets(edit, own.id) {
return None;
}
Some(user_rect(info.pages.get(a.page)?, own.edited(edit)?.rect))
}
/// The engine edit for one framework edit. A gesture that changes nothing (a click with no drag) gives none.
/// `Place` opens a composer draft (or asks for an attachment's file) on `view` and gives none itself.
pub(crate) fn edit(e: AnnotationEdit, map: &PageMap<'_>, view: &mut CommentView, info: &DocInfo, prefs: &CommentPrefs) -> Option<Edit> {
match e {
AnnotationEdit::Create(a) => create(&a, map, prefs),
AnnotationEdit::Move { ids, delta } => moved(&ids, delta, info),
AnnotationEdit::Resize { id, rect } => {
let (page, index) = key_of(id);
engine(info, page, index).filter(|a| resizable(a))?;
let r = user_rect(info.pages.get(page)?, rect).map(f64::from);
Some(Edit::ResizeAnnotation { page, index, rect: r })
}
AnnotationEdit::Reshape { id, points } => {
let (page, index) = key_of(id);
engine(info, page, index).filter(|a| reshapable(a))?;
Some(Edit::ReshapeAnnotation { page, index, points: points.iter().map(|p| map.to_user(page, *p)).collect() })
}
AnnotationEdit::Delete(ids) => {
let keys: Vec<(usize, usize)> = ids.into_iter().map(key_of).collect();
// A group member picked on the page, with its group the selection alone, goes by itself.
let raw = match view.target() {
Some(member) if view.selection().len() <= 1 => vec![member],
_ => keys,
};
view.clear_selection();
delete_edit(raw, info)
}
AnnotationEdit::EraseAlong { ids, path, radius } => erased(&ids, &path, radius, map, info),
AnnotationEdit::Open(id) => {
let (page, index) = key_of(id);
let a = engine(info, page, 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) {
return (!a.popup.is_some_and(|p| p.open)).then_some(Edit::SetAnnotationPopup { page, index, rect: None, open: Some(true) });
}
view.composer = Some(Composer {
page,
at: edit_anchor(info, a),
kind: ComposerKind::Edit(index),
text: a.contents.clone().unwrap_or_default(),
focus: true,
});
None
}
AnnotationEdit::Place(p) => {
place(&p, map, view);
None
}
// The tool holds the selection; whole-stroke erasing is off (the app's tool erases along the path).
_ => None,
}
}
fn moved(ids: &[AnnotationId], delta: Vec2, info: &DocInfo) -> Option<Edit> {
if delta == Vec2::ZERO {
return None;
}
let mut seen: Vec<(usize, usize)> = Vec::new();
let mut edits: Vec<Edit> = ids
.iter()
.map(|id| key_of(*id))
.filter(|k| {
let new = !seen.contains(k);
seen.push(*k);
new
})
.filter_map(|(page, index)| {
// Text markup and a Replace Text caret are where their text is, a locked comment stays, and a reply is
// moved with its comment.
let a = engine(info, page, index).filter(|a| !a.is_reply() && !on_text(a) && !a.locked)?;
let p = info.pages.get(page)?;
let (dx, dy) = user_delta(p, delta);
if !(dx.is_finite() && dy.is_finite()) {
return None;
}
// A callout is pressed in its text box: the box moves alone and its arrow point stays.
Some(if is_callout(a) && resizable(a) {
let f = frame(a, p.rotation).map(f64::from);
Edit::ResizeAnnotation { page, index, rect: [f[0] + dx, f[1] + dy, f[2] + dx, f[3] + dy] }
} else {
Edit::MoveAnnotation { page, index, dx, dy }
})
})
.collect();
match edits.len() {
0 => None,
1 => edits.pop(),
_ => Some(Edit::Batch { label: tl!("Move comments").to_owned(), edits }),
}
}
/// The edit deleting `raw` (one undo step for several): locked and stale slots are dropped, later positions go first
/// so each deletion leaves the earlier ones where they are.
fn delete_edit(raw: Vec<(usize, usize)>, info: &DocInfo) -> Option<Edit> {
let mut keys: Vec<(usize, usize)> = raw.into_iter().filter(|(page, index)| engine(info, *page, *index).is_some_and(|a| !a.locked)).collect();
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 edit that deletes every selected comment, and clears the selection. 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`]).
pub(crate) fn delete_selected(cv: &mut CommentView, info: &DocInfo) -> Option<Edit> {
let raw = if cv.selection().len() <= 1 { cv.target().into_iter().collect() } else { cv.selection() };
cv.clear_selection();
delete_edit(raw, info)
}
fn erased(ids: &[AnnotationId], path: &[Point], radius: f64, map: &PageMap<'_>, info: &DocInfo) -> Option<Edit> {
let mut hits: Vec<(usize, usize)> =
ids.iter().map(|id| key_of(*id)).filter(|(p, i)| engine(info, *p, *i).is_some_and(|a| a.subtype == "Ink" && !a.locked)).collect();
// Later indices first: deleting an emptied drawing shifts the ones after it.
hits.sort_unstable_by(|a, b| b.cmp(a));
hits.dedup();
let edits: Vec<Edit> = hits
.into_iter()
.filter_map(|(page, index)| {
let p = info.pages.get(page)?;
Some(Edit::EraseInk { page, index, path: path.iter().map(|q| map.to_user(page, *q)).collect(), radius: user_len(p, radius) })
})
.collect();
(!edits.is_empty()).then(|| Edit::Batch { label: "Erase".into(), edits })
}
fn create(a: &Marked, map: &PageMap<'_>, prefs: &CommentPrefs) -> Option<Edit> {
let tool = CommentTool::from_kind(a.kind)?;
let page = map.info.pages.get(a.page)?;
let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(page.width, page.height));
let user = |p: Point| {
let c = clamp_to(bounds, egui::pos2(p.x as f32, p.y as f32));
map.to_user(a.page, Point::new(f64::from(c.x), f64::from(c.y)))
};
let pts: Vec<[f64; 2]> = a.points.iter().map(|p| user(*p)).collect();
let strokes = || -> Vec<Vec<[f64; 2]>> { a.strokes.iter().map(|s| s.iter().map(|p| user(*p)).collect()).collect() };
let boxed = || {
let (p, q) = (user(Point::new(a.rect.x0, a.rect.y0)), user(Point::new(a.rect.x1, a.rect.y1)));
[p[0].min(q[0]), p[1].min(q[1]), p[0].max(q[0]), p[1].max(q[1])]
};
let shape = match a.kind {
AnnotationKind::Ink => Shape::Ink { strokes: strokes() },
AnnotationKind::FreehandHighlight => Shape::FreehandHighlight { strokes: strokes() },
AnnotationKind::Line | AnnotationKind::Arrow => Shape::Line {
from: *pts.first()?,
to: *pts.get(1)?,
start: LineEnding::None,
end: if a.kind == AnnotationKind::Arrow { LineEnding::OpenArrow } else { LineEnding::None },
},
AnnotationKind::Rectangle => Shape::Rectangle { rect: boxed() },
AnnotationKind::Oval => Shape::Oval { rect: boxed() },
AnnotationKind::Polygon | AnnotationKind::Cloud => Shape::Polygon { vertices: pts, cloud: a.kind == AnnotationKind::Cloud },
AnnotationKind::PolyLine => Shape::PolyLine { vertices: pts, start: LineEnding::None, end: LineEnding::None },
AnnotationKind::Highlight | AnnotationKind::Underline | AnnotationKind::StrikeOut | AnnotationKind::Squiggly => Shape::TextMarkup {
kind: tool.markup()?,
quads: a
.points
.chunks_exact(4)
.filter_map(|q| {
let [p0, p1, p2, p3] = q else { return None };
let [u0, u1, u2, u3] = [user(*p0), user(*p1), user(*p2), user(*p3)];
Some([u0[0], u0[1], u1[0], u1[1], u2[0], u2[1], u3[0], u3[1]])
})
.collect(),
},
_ => return None,
};
Some(new_comment(a.page, prefs, tool, shape, String::new()))
}
/// A placement opens its composer draft (a note, a text box, a callout, an insertion), or asks for an attachment's
/// file, and leaves nothing selected.
fn place(p: &Placement, map: &PageMap<'_>, view: &mut CommentView) {
let at = map.to_user(p.page, p.at);
let kind = match p.kind {
AnnotationKind::Note => ComposerKind::Note,
AnnotationKind::TextBox => ComposerKind::TextBox { size: p.size.map(|s| [s.x, s.y]) },
AnnotationKind::Callout => {
let Some(from) = p.from else { return };
ComposerKind::Callout { point: map.to_user(p.page, from) }
}
AnnotationKind::Caret => ComposerKind::Caret { size: p.size.map_or(CARET_SIZE, |s| s.y) },
AnnotationKind::Attach => {
view.attach_at = Some((p.page, at));
view.select(None);
return;
}
_ => return,
};
view.composer = Some(Composer { page: p.page, at, kind, text: String::new(), focus: true });
view.select(None);
}
/// The edit adding a comment made with `tool`, styled by the preferences.
pub(super) fn new_comment(page: usize, prefs: &CommentPrefs, tool: CommentTool, shape: Shape, contents: String) -> Edit {
Edit::AddAnnotation(NewAnnotation { page, shape, style: prefs.style(tool), contents, author: prefs.author.clone() })
}
/// Where the composer for editing `a` opens: the top-right corner of the comment as drawn on the displayed page.
pub(crate) 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)
}
/// The user-space box of the screen rectangle `r`: the bounds of its corners' user points, for a pop-up's `/Rect`.
pub(crate) fn screen_to_user_rect(cx: &PageCx<'_>, r: egui::Rect) -> [f64; 4] {
let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|c| cx.to_user(c));
corners.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, c| [b[0].min(c[0]), b[1].min(c[1]), b[2].max(c[0]), b[3].max(c[1])])
}
/// A PDF date (`D:YYYYMMDDHHmmSS` with an optional `Z` or `±HH'mm'` zone) as Unix seconds. Missing parts take the PDF
/// defaults (month and day 1, time 0, zone UTC); text that is not a date gives `None`.
pub(crate) fn pdf_date_seconds(text: &str) -> Option<i64> {
let text = text.trim();
let body = text.strip_prefix("D:").unwrap_or(text);
let digits_len = body.bytes().take_while(u8::is_ascii_digit).count();
let (digits, zone) = body.split_at_checked(digits_len)?;
if digits_len < 4 || digits_len % 2 != 0 {
return None;
}
let part = |from: usize, len: usize, default: u32| -> Option<u32> {
if digits_len <= from { Some(default) } else { digits.get(from..from + len)?.parse().ok() }
};
let year: i32 = digits.get(..4)?.parse().ok()?;
let local = NaiveDate::from_ymd_opt(year, part(4, 2, 1)?, part(6, 2, 1)?)?.and_hms_opt(part(8, 2, 0)?, part(10, 2, 0)?, part(12, 2, 0)?)?;
local.and_utc().timestamp().checked_sub(zone_seconds(zone)?)
}
/// The seconds a PDF date's zone (`Z`, `+HH'mm'`, `-HH'mm'`, or none) lies east of UTC.
fn zone_seconds(zone: &str) -> Option<i64> {
let mut chars = zone.chars();
let sign = match chars.next() {
None | Some('Z') => return Some(0),
Some('+') => 1,
Some('-') => -1,
Some(_) => return None,
};
let digits: String = chars.filter(char::is_ascii_digit).collect();
let part = |from: usize| -> Option<i64> { if digits.len() <= from { Some(0) } else { digits.get(from..from + 2)?.parse().ok() } };
let (hours, minutes) = (part(0)?, part(2)?);
(hours < 24 && minutes < 60).then_some(sign * (hours * 3600 + minutes * 60))
}
+1 -118
View File
@@ -1,5 +1,4 @@
use super::state::PageCx;
use super::{Annotation, DocInfo, PageInfo, PageText, Pos2, QuickTool, Rect, pos2, vec2};
use super::{Annotation, DocInfo, PageInfo, PageText, Pos2, Rect, pos2};
pub(super) fn is_markup(subtype: &str) -> bool {
matches!(subtype, "Highlight" | "Underline" | "StrikeOut" | "Squiggly")
@@ -42,122 +41,6 @@ pub(super) fn frame(a: &Annotation, rotation: u16) -> [f32; 4] {
a.text_box.unwrap_or_else(|| a.shown_rect(rotation))
}
/// A callout's points while one is dragged to `to`. Its knee moves along its knee line only
/// (Acrobat: "The knee line can be resized in one direction only; horizontal knee lines can be
/// resized horizontally only; vertical knee lines can be resized vertically only", Acrobat DC Help,
/// 11/28/2019, p. 357), and no nearer the box than [`pdfcraft_engine::CALLOUT_KNEE_LINE`]
/// (Acrobat Pro DC, a 2021 Continuous release, lays a knee dragged into the box out again at that
/// distance). Its arrow point moves freely, with Shift held to 45° from the knee.
pub(super) fn callout_reshaped(points: &[[f64; 2]], text_box: [f32; 4], i: usize, to: [f64; 2], shift: bool) -> Vec<[f64; 2]> {
let tb = text_box.map(f64::from);
let gap = pdfcraft_engine::CALLOUT_KNEE_LINE;
match (i, points.get(1)) {
(1, Some(knee)) => {
let to = match pdfcraft_engine::callout_side(tb, *knee) {
pdfcraft_engine::CalloutSide::Left => [to[0].min(tb[0] - gap), knee[1]],
pdfcraft_engine::CalloutSide::Right => [to[0].max(tb[2] + gap), knee[1]],
pdfcraft_engine::CalloutSide::Top => [knee[0], to[1].max(tb[3] + gap)],
pdfcraft_engine::CalloutSide::Bottom => [knee[0], to[1].min(tb[1] - gap)],
};
let mut out = points.to_vec();
if let Some(k) = out.get_mut(1) {
*k = to;
}
out
}
_ => reshaped(points, i, to, shift),
}
}
/// A selected comment's points moved as handle `i` is dragged to `to` ([`reshaped`], or
/// [`callout_reshaped`] for a callout).
pub(super) fn reshape_for(a: &Annotation, points: &[[f64; 2]], i: usize, to: [f64; 2], shift: bool) -> Vec<[f64; 2]> {
match a.text_box.filter(|_| is_callout(a)) {
Some(tb) => callout_reshaped(points, tb, i, to, shift),
None => reshaped(points, i, to, shift),
}
}
/// Whether `tool` reaches a line's end and corner handles: the Select and Fill & Sign tools.
/// The drawing tools draw from where they are pressed, so a new line starts at the end of the
/// one just drawn rather than dragging it.
pub(super) fn reaches_points(tool: QuickTool) -> bool {
!matches!(tool, QuickTool::Comment(t) if t.draws() || t.clicks_points())
}
/// The point of `a` (an end or a corner) whose handle is at `p` on screen.
pub(super) fn point_handle(cx: &PageCx<'_>, a: &Annotation, p: Pos2) -> Option<usize> {
a.points.iter().position(|q| cx.to_screen([f64::from(q[0]), f64::from(q[1])]).distance(p) <= 7.0)
}
/// `to` held level or plumb with `last` while Shift is down (ortho, as in a CAD drawing): the
/// next end or corner of a line, arrow, connected lines, polygon or cloud.
pub(crate) fn held(last: Option<&[f64; 2]>, to: [f64; 2], shift: bool) -> [f64; 2] {
match last {
Some(l) if shift => pdfcraft_engine::measure::snap::ortho(*l, to),
_ => to,
}
}
/// `points` with point `i` moved to `to`; with Shift, held level or plumb with the point before
/// it (a line's other end; the first corner is held to the second).
pub(crate) fn reshaped(points: &[[f64; 2]], i: usize, to: [f64; 2], shift: bool) -> Vec<[f64; 2]> {
let mut out = points.to_vec();
let anchor = if i == 0 { points.get(1) } else { points.get(i - 1) };
let to = held(anchor, to, shift);
if let Some(p) = out.get_mut(i) {
*p = to;
}
out
}
pub(super) const HANDLES: [(i8, i8); 8] = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)];
pub(super) fn handle_pos(r: Rect, (hx, hy): (i8, i8)) -> Pos2 {
let x = match hx {
-1 => r.left(),
0 => r.center().x,
_ => r.right(),
};
let y = match hy {
-1 => r.top(),
0 => r.center().y,
_ => r.bottom(),
};
pos2(x, y)
}
/// The proportions a corner drag of `r` keeps: the box's own fixed ratio (an image signature's),
/// else `r`'s current one while Shift is held, else none.
pub(crate) fn corner_ratio(r: Rect, fixed: Option<f32>, shift: bool) -> Option<f32> {
fixed.or_else(|| (shift && r.width() > 0.0 && r.height() > 0.0).then(|| r.width() / r.height()))
}
pub(crate) fn resized(r: Rect, (hx, hy): (i8, i8), d: egui::Vec2, aspect_ratio: Option<f32>) -> Rect {
if hx != 0
&& hy != 0
&& let Some(ratio) = aspect_ratio.filter(|v| v.is_finite() && *v > 0.0)
{
// As in content_ui, the larger requested dimension drives proportional corner resizing.
// Keep the opposite corner fixed and prevent crossing it from flipping the image.
let width = (r.width() + f32::from(hx) * d.x).max((r.height() + f32::from(hy) * d.y) * ratio).max(4.0).max(4.0 * ratio);
let anchor = handle_pos(r, (-hx, -hy));
return Rect::from_two_pos(anchor, anchor + vec2(f32::from(hx) * width, f32::from(hy) * width / ratio));
}
let mut r = r;
match hx {
-1 => r.min.x += d.x,
1 => r.max.x += d.x,
_ => {}
}
match hy {
-1 => r.min.y += d.y,
1 => r.max.y += d.y,
_ => {}
}
Rect::from_two_pos(r.min, r.max)
}
pub(super) fn clamp_to(r: Rect, p: Pos2) -> Pos2 {
pos2(p.x.clamp(r.left(), r.right()), p.y.clamp(r.top(), r.bottom()))
}
+104 -257
View File
@@ -1,8 +1,12 @@
use std::collections::HashMap;
use super::geometry::{corner_ratio, frame, is_markup, resized};
use super::{Annotation, CommentPrefs, CommentTool, DocInfo, Edit, PagePointer, PageXform, Pos2, QuickTool, Rect, pos2, vec2};
use crate::page_keys::PageKeys;
use craft::review::AnnotationEdit;
use craft::review::ui::{AnnotateTool, CommentsPanelState, NoteDrafts};
use super::bridge;
use super::geometry::{frame, is_markup};
use super::tool::PastePlacement;
use super::{Annotation, CommentPrefs, CommentTool, DocInfo, Edit, PageXform, Pos2, Rect};
/// The user's login name, which Acrobat uses as the default comment author.
pub(super) fn login_name() -> String {
@@ -17,25 +21,6 @@ pub(super) fn login_name() -> String {
"Guest".into()
}
/// A drag in progress on a page.
#[derive(Clone, Debug, PartialEq)]
pub enum Gesture {
/// Drawing with a tool: points in user space (ink: the stroke; polygons: the vertices
/// clicked so far; others: start and end).
Draw { page: usize, tool: CommentTool, points: Vec<[f64; 2]> },
/// Moving a comment, from the press position on screen.
Move { page: usize, index: usize, from: Pos2 },
/// Resizing a comment by one of its handles: (dx, dy) ∈ {-1, 0, 1}² says which sides move.
Resize { page: usize, index: usize, handle: (i8, i8), from: Pos2, aspect_ratio: Option<f32> },
/// Dragging point `point` of a line, connected lines, a polygon or a cloud (its `points`
/// before the drag, in user space) to where the pointer is.
Reshape { page: usize, index: usize, point: usize, points: Vec<[f64; 2]> },
/// Copied comments hanging on the pointer as one bundle (their box `bounds` in user space,
/// `count` of them, their `outlines` drawn along so the drop can be aimed): a click puts
/// their centre there, on the page clicked; Escape or a right-click lets them go.
Place { xfdf: String, bounds: [f64; 4], count: usize, outlines: Vec<pdfcraft_engine::CommentOutline> },
}
#[derive(Clone, Debug, PartialEq)]
pub enum ComposerKind {
Note,
@@ -133,15 +118,14 @@ impl CommentView {
}
}
/// Per-document commenting state.
#[derive(Clone, Debug, Default)]
/// Per-document commenting state. The selection lives on [`Self::tool`] (`tool.selected`), the one store.
#[derive(Default)]
pub struct CommentView {
/// The selected comment: (page, index in `/Annots`). With several selected (`also`), the one
/// the handles, the properties and the context menu act on.
pub selected: Option<(usize, usize)>,
/// The other selected comments (⌘/Ctrl-click or ⇧-click on the page adds one, ⇧-click in the
/// Comments panel a range): Delete, Copy, Properties and a drag act on them with `selected`.
pub also: Vec<(usize, usize)>,
/// The annotation tool on the page: its selection, drawing and in-flight edit.
pub tool: AnnotateTool,
/// Copied comments hanging on the pointer as one bundle: a click puts their centre there, on the
/// page clicked; Escape or a right-click lets them go.
pub paste: Option<PastePlacement>,
/// Copy the selected comments (set by the menus; the app has the clipboard).
pub copy_request: bool,
/// Paste the copied comments onto this page, centred at this user-space point (set by the
@@ -149,51 +133,20 @@ pub struct CommentView {
pub paste_request: Option<(usize, [f64; 2])>,
/// A notice for the app to show (the page input has no app).
pub notice: Option<&'static str>,
/// Finish the connected lines, polygon or cloud being drawn (the context menu's Complete).
pub finish_request: bool,
/// The group subordinate a click on the page picked, with the selection (its group's primary)
/// it was picked under: Delete acts on it while that group stays selected, as Acrobat deletes
/// the member clicked ([`Self::target`]).
pub(crate) member: Option<((usize, usize), (usize, usize))>,
pub gesture: Option<Gesture>,
/// Drawings just released: shown from their points until the page raster that includes the
/// committed annotation arrives, so the stroke never vanishes in between (#1858).
pub(crate) settling: Vec<Settling>,
pub composer: Option<Composer>,
/// Reply being typed under the selected card.
pub reply: String,
/// Inline edit of a card's text in the Comments panel: (page, index, text).
pub editing: Option<(usize, usize, String)>,
/// The Comments panel's own state: search, sort, filter, folded pages, inline edit and drafts.
pub panel: CommentsPanelState,
/// What is typed or being dragged in the open pop-up windows of one comment: (page, index, drafts).
pub popup_drafts: Option<(usize, usize, NoteDrafts)>,
/// The panel should scroll the selected card into view.
pub reveal: bool,
/// A pop-up window's title bar being dragged: the comment, and where the window's top-left
/// corner is now on screen.
pub popup_drag: Option<(usize, usize, Pos2)>,
/// A pop-up window's corner being dragged: the comment, and the window's size on screen now.
pub popup_resize: Option<(usize, usize, egui::Vec2)>,
/// Text being typed in a pop-up window: (page, index, text).
pub popup_text: Option<(usize, usize, String)>,
/// A reply being typed in a pop-up window: the comment or reply it answers (page, index), and its text.
pub popup_reply: Option<(usize, usize, String)>,
/// Where each open pop-up was drawn last frame, for the connector lines and hit-testing.
pub popup_rects: Vec<((usize, usize), Rect)>,
/// The pop-up the pointer was over last frame.
pub popup_hovered: Option<(usize, usize)>,
/// The "Add a comment" box at the top of the Comments panel.
pub add_box: String,
/// The Comments panel's search query (`None`: search closed).
pub search: Option<String>,
/// Comment types, authors and statuses hidden by the panel's filter.
pub hidden_types: Vec<String>,
pub hidden_authors: Vec<String>,
pub hidden_statuses: Vec<String>,
/// Colours (`RRGGBB`, empty for none) and checkmark states ("Checked", "Unchecked") hidden.
pub hidden_colors: Vec<String>,
pub hidden_checks: Vec<String>,
/// How the panel orders comments.
pub sort: SortBy,
/// Pages whose group is folded in the panel (when sorted by page).
pub collapsed_pages: Vec<usize>,
/// Comment Properties was asked for from the panel: (page, index).
pub props_request: Option<(usize, usize)>,
/// Make Current Properties Default was asked for: (page, index).
@@ -205,13 +158,10 @@ pub struct CommentView {
pub replace: Option<Vec<[f64; 8]>>,
/// Attach file: where the icon goes (page, top-left in user space), for the app to pick a file.
pub attach_at: Option<(usize, [f64; 2])>,
pub search_focus: bool,
/// Where the canvas context menu was opened: (page, user-space point).
pub context_at: Option<(usize, [f64; 2])>,
/// A one-shot tool just finished; the app returns to the Select tool unless pinned.
pub tool_done: bool,
/// What the inline editor (`editing`) does with the keyboard the next time it is drawn.
pub(crate) editor_focus: Option<EditorFocus>,
/// Snapshot of `(page, index)` comment slot identity from the last `DocInfo`, used to detect
/// when an edit removes or shifts `/Annots` entries under an active selection or editor.
pub(crate) slots: std::collections::HashMap<(usize, usize), CommentSlot>,
@@ -225,17 +175,6 @@ pub(crate) struct CommentSlot {
page_count: usize,
}
/// A one-off change to the keyboard focus of the Comments panel's inline editor. The editor
/// never asks for the keyboard on its own: when it did so on every frame, it took the keyboard
/// back after every click elsewhere, and the tool keys (V, H) were typed into it (#2669).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EditorFocus {
/// The editor just opened: it takes the keyboard, once.
Take,
/// Another comment was added: the editor keeps its text but gives the keyboard back.
Release,
}
impl CommentView {
/// Initial commenting state for `info`, recording its current annotation slots.
pub(crate) fn from_info(info: &DocInfo) -> Self {
@@ -277,19 +216,20 @@ impl CommentView {
cur.subtype == old.subtype && cur.name == old.name && cur.page_ord == old.page_ord && cur.page_count >= old.page_count
})
};
if self.selected.is_some_and(|(p, i)| !same_slot(p, i)) {
self.selected = None;
}
self.also.retain(|&(p, i)| same_slot(p, i));
if self.selected.is_none() {
self.selected = self.also.pop();
}
if self.member.is_some_and(|((mp, mi), (gp, gi))| Some((gp, gi)) != self.selected || !same_slot(mp, mi)) {
// The last id left is the primary, as the last of `also` became the selection before.
self.tool.selected.retain(|id| {
let (p, i) = bridge::key_of(*id);
same_slot(p, i)
});
let primary = self.primary();
if self.member.is_some_and(|((mp, mi), (gp, gi))| Some((gp, gi)) != primary || !same_slot(mp, mi)) {
self.member = None;
}
if self.editing.as_ref().is_some_and(|(p, i, _)| !same_slot(*p, *i)) {
self.editing = None;
self.editor_focus = None;
if self.panel.editing.as_ref().is_some_and(|(thread, _, _)| {
let (p, i) = bridge::thread_key(*thread);
!same_slot(p, i)
}) {
self.panel.editing = None;
}
if self.composer.as_ref().is_some_and(|c| match c.kind {
ComposerKind::Edit(i) => !same_slot(c.page, i),
@@ -297,34 +237,45 @@ impl CommentView {
}) {
self.composer = None;
}
if self.gesture.as_ref().is_some_and(|g| match g {
Gesture::Draw { page, .. } => *page >= page_count,
Gesture::Move { page, index, .. } | Gesture::Resize { page, index, .. } | Gesture::Reshape { page, index, .. } => {
!same_slot(*page, *index)
}
Gesture::Place { .. } => false,
}) {
self.gesture = None;
// A drawing on a page that is gone ends with nothing made.
if !self.tool.drawing().is_empty() && self.tool.page >= page_count {
self.tool.cancel_drawing();
}
self.slots = next;
}
/// Every selected comment, the one the handles belong to first.
pub fn selection(&self) -> Vec<(usize, usize)> {
let mut all: Vec<(usize, usize)> = self.selected.into_iter().collect();
all.extend(self.also.iter().copied().filter(|k| Some(*k) != self.selected));
all
self.tool.selected.iter().rev().map(|id| bridge::key_of(*id)).collect()
}
/// The selected comment the handles, the properties and the context menu act on: the last one selected.
pub fn primary(&self) -> Option<(usize, usize)> {
self.tool.selected.last().map(|id| bridge::key_of(*id))
}
/// Whether `key` (page, index) is among the selected comments.
pub fn is_selected(&self, key: (usize, usize)) -> bool {
self.selected == Some(key) || self.also.contains(&key)
self.tool.selected.contains(&bridge::id_of(key.0, key.1))
}
/// Select `key` alone.
pub fn select_only(&mut self, key: (usize, usize)) {
self.selected = Some(key);
self.also.clear();
self.tool.selected = vec![bridge::id_of(key.0, key.1)];
self.member = None;
}
/// Select `keys`, the first being the lead (the one with the handles): repeated keys count once, at
/// their first place. The tool keeps its primary last, so the others are stored in reverse and the
/// lead last: [`Self::selection`] gives `keys` back in order.
pub fn select_keys(&mut self, keys: &[(usize, usize)]) {
let mut unique: Vec<(usize, usize)> = Vec::with_capacity(keys.len());
for key in keys {
if !unique.contains(key) {
unique.push(*key);
}
}
self.tool.selected = unique.into_iter().rev().map(|(p, i)| bridge::id_of(p, i)).collect();
self.member = None;
}
@@ -333,31 +284,30 @@ impl CommentView {
/// range. Without a comment with the handles, or with either end not in the list, `key` is
/// added as by ⌘/Ctrl-click.
pub fn select_range(&mut self, order: &[(usize, usize)], key: (usize, usize)) {
let ends = self.selected.and_then(|anchor| Some((order.iter().position(|k| *k == anchor)?, order.iter().position(|k| *k == key)?)));
let Some((a, b)) = ends else { return self.toggle(key) };
let anchor = self.selected;
self.also = order.get(a.min(b)..=a.max(b)).unwrap_or_default().iter().copied().filter(|k| Some(*k) != anchor).collect();
let anchor = self.primary();
let ends = anchor.and_then(|anchor| Some((order.iter().position(|k| *k == anchor)?, order.iter().position(|k| *k == key)?)));
let (Some(anchor), Some((a, b))) = (anchor, ends) else { return self.toggle(key) };
let mut keys = vec![anchor];
keys.extend(order.get(a.min(b)..=a.max(b)).unwrap_or_default().iter().copied().filter(|k| *k != anchor));
self.select_keys(&keys);
}
/// ⌘/Ctrl-click: add `key` to the selection, or take it out again. The handles go to the
/// comment clicked last.
pub fn toggle(&mut self, key: (usize, usize)) {
self.member = None;
if self.selected == Some(key) {
self.selected = self.also.pop();
} else if let Some(at) = self.also.iter().position(|k| *k == key) {
self.also.remove(at);
} else {
if let Some(previous) = self.selected.replace(key) {
self.also.push(previous);
let id = bridge::id_of(key.0, key.1);
match self.tool.selected.iter().position(|k| *k == id) {
Some(at) => {
self.tool.selected.remove(at);
}
None => self.tool.selected.push(id),
}
}
/// Nothing selected.
pub fn clear_selection(&mut self) {
self.selected = None;
self.also.clear();
self.tool.selected.clear();
self.member = None;
}
@@ -365,8 +315,8 @@ impl CommentView {
/// else the selected comment.
pub(crate) fn target(&self) -> Option<(usize, usize)> {
match self.member {
Some((member, group)) if Some(group) == self.selected => Some(member),
_ => self.selected,
Some((member, group)) if Some(group) == self.primary() => Some(member),
_ => self.primary(),
}
}
@@ -385,39 +335,19 @@ impl CommentView {
/// ([`PageCx::picked`]). The only place that sets [`Self::member`].
pub(crate) fn pick(&mut self, cx: &PageCx<'_>, p: Pos2, a: &Annotation) {
self.select_only((cx.page, a.index));
self.member = cx.picked(p, self.selected);
self.member = cx.picked(p, self.primary());
}
/// Takes back the last point of a polygon, cloud or connected lines being drawn; the first
/// point's removal cancels the drawing. Returns whether there was such a drawing.
pub fn undo_point(&mut self) -> bool {
let Some(Gesture::Draw { tool, points, .. }) = self.gesture.as_mut() else { return false };
if !tool.clicks_points() {
return false;
}
points.pop();
if points.is_empty() {
self.gesture = None;
}
true
}
/// Open the inline editor on comment (page, index) with `text`. It takes the keyboard once,
/// as it opens; after that the keyboard goes wherever the user clicks.
/// Open the inline editor on the root message of comment (page, index) with `text`.
pub(crate) fn open_editor(&mut self, page: usize, index: usize, text: String) {
self.editing = Some((page, index, text));
self.editor_focus = Some(EditorFocus::Take);
self.panel.editing = Some((bridge::thread_id(page, index), 0, text));
}
/// A comment was just added. The editor open on another one must not keep the keyboard, or
/// the tool keys pressed next are typed into it (#2669): an empty editor closes, and one
/// holding text stays open with it, without the keyboard.
/// A comment was just added. An empty editor open on another one closes; one holding text
/// stays open with it.
pub(crate) fn comment_added(&mut self) {
if self.editing.as_ref().is_some_and(|(_, _, text)| !text.is_empty()) {
self.editor_focus = Some(EditorFocus::Release);
} else {
self.editing = None;
self.editor_focus = None;
if self.panel.editing.as_ref().is_some_and(|(_, _, text)| text.is_empty()) {
self.panel.editing = None;
}
}
@@ -428,26 +358,21 @@ impl CommentView {
pub(crate) fn annotation_deleted(&mut self, before: &[Annotation], info: &DocInfo, gone: (usize, usize)) {
let after = &info.annotations;
let moved = |k: (usize, usize)| after_delete(before, after, gone, k);
let selected = self.selected.and_then(moved);
let also: Vec<(usize, usize)> = std::mem::take(&mut self.also).into_iter().filter_map(moved).collect();
let editing = self.editing.take().and_then(|(p, i, text)| moved((p, i)).map(|(p, i)| (p, i, text)));
let focus = self.editor_focus.take();
let selected: Vec<_> = std::mem::take(&mut self.tool.selected)
.into_iter()
.filter_map(|id| moved(bridge::key_of(id)).map(|(p, i)| bridge::id_of(p, i)))
.collect();
let editing = self.panel.editing.take().and_then(|(thread, message, text)| {
moved(bridge::thread_key(thread)).map(|(p, i)| (bridge::thread_id(p, i), message, text))
});
// What is typed in a pop-up, and a window being dragged or resized, follow theirs too.
let popup_text = self.popup_text.take().and_then(|(p, i, text)| moved((p, i)).map(|(p, i)| (p, i, text)));
let popup_reply = self.popup_reply.take().and_then(|(p, i, text)| moved((p, i)).map(|(p, i)| (p, i, text)));
let popup_drag = self.popup_drag.and_then(|(p, i, at)| moved((p, i)).map(|(p, i)| (p, i, at)));
let popup_resize = self.popup_resize.and_then(|(p, i, size)| moved((p, i)).map(|(p, i)| (p, i, size)));
let drafts = self.popup_drafts.take().and_then(|(p, i, d)| moved((p, i)).map(|(p, i)| (p, i, d)));
// Other transient state still needs conservative pruning; refresh the slot snapshot too.
self.document_changed(info);
self.selected = selected;
self.also = also;
self.tool.selected = selected;
self.member = None;
self.editor_focus = editing.as_ref().and(focus);
self.editing = editing;
self.popup_text = popup_text;
self.popup_reply = popup_reply;
self.popup_drag = popup_drag;
self.popup_resize = popup_resize;
self.panel.editing = editing;
self.popup_drafts = drafts;
}
/// Undo or Redo just ran. Either may have put annotations back or taken them away, on any
@@ -456,21 +381,13 @@ impl CommentView {
/// took its place; so do the pop-ups' unsaved text and drags.
pub(crate) fn history_stepped(&mut self) {
self.clear_selection();
self.editing = None;
self.editor_focus = None;
self.popup_text = None;
self.popup_reply = None;
self.popup_drag = None;
self.popup_resize = None;
self.panel.editing = None;
self.popup_drafts = None;
}
/// The comments the pop-ups hold unsaved text, a reply or a drag for.
pub(crate) fn popup_keys(&self) -> Vec<(usize, usize)> {
let text = self.popup_text.as_ref().map(|(p, i, _)| (*p, *i));
let reply = self.popup_reply.as_ref().map(|(p, i, _)| (*p, *i));
let drag = self.popup_drag.map(|(p, i, _)| (p, i));
let resize = self.popup_resize.map(|(p, i, _)| (p, i));
[text, reply, drag, resize].into_iter().flatten().collect()
self.popup_drafts.iter().map(|(p, i, _)| (*p, *i)).collect()
}
/// An edit other than a deletion just ran: `before` are the comments at [`Self::popup_keys`]
@@ -483,17 +400,8 @@ impl CommentView {
list.iter().find(|a| (a.page, a.index) == k).map(|a| (a.subtype.clone(), a.author.clone(), a.name.clone()))
};
let kept = |p: usize, i: usize| who(before, (p, i)).is_some_and(|w| who(after, (p, i)) == Some(w));
if self.popup_text.as_ref().is_some_and(|(p, i, _)| !kept(*p, *i)) {
self.popup_text = None;
}
if self.popup_reply.as_ref().is_some_and(|(p, i, _)| !kept(*p, *i)) {
self.popup_reply = None;
}
if self.popup_drag.is_some_and(|(p, i, _)| !kept(p, i)) {
self.popup_drag = None;
}
if self.popup_resize.is_some_and(|(p, i, _)| !kept(p, i)) {
self.popup_resize = None;
if self.popup_drafts.as_ref().is_some_and(|(p, i, _)| !kept(*p, *i)) {
self.popup_drafts = None;
}
}
}
@@ -548,35 +456,16 @@ fn on_page(list: &[Annotation], page: usize) -> Vec<&Annotation> {
v
}
/// Comments panel order (Acrobat: Sort by page, author, date, type, colour).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SortBy {
#[default]
Page,
Author,
Date,
Type,
Color,
}
/// What a page needs to know to handle comment input.
pub(crate) struct PageCx<'a> {
pub page: usize,
pub xf: &'a PageXform,
/// The pointer as the pages see it this frame.
pub ptr: &'a PagePointer,
pub info: &'a DocInfo,
pub tool: QuickTool,
pub prefs: &'a CommentPrefs,
/// A redaction mark's fill while the pointer is over it, and its opacity (Redaction Tool
/// Properties).
pub redact_mark: ([f64; 3], f64),
/// The document allows commenting.
pub allowed: bool,
/// Comments are hidden (Hide all comments): nothing to select.
pub hidden: bool,
/// This frame's keys as the pages see them.
pub keys: PageKeys,
}
impl PageCx<'_> {
@@ -627,32 +516,6 @@ impl PageCx<'_> {
.chain(fallback)
}
/// A viewer-only marker for commented text markup intersecting the page.
pub(crate) fn comment_marker_rect(&self, a: &Annotation) -> Option<Rect> {
if !is_markup(&a.subtype) || a.contents.as_deref().is_none_or(|s| s.trim().is_empty()) {
return None;
}
let r = self.screen_rects(a).last()?;
let size = vec2(12.0, 12.0);
let page = self.xf.rect;
let marker_max = page.max - size;
let desired = pos2(r.right() + 3.0, r.top() - 14.0);
// Keep the fixed-size marker visible at page edges. At extremely small zooms,
// omit it rather than covering a page that is smaller than the marker itself.
if !page.is_finite()
|| !r.is_finite()
|| !desired.is_finite()
|| !page.intersects(r)
|| page.width() < size.x
|| page.height() < size.y
|| marker_max.x < page.min.x
|| marker_max.y < page.min.y
{
return None;
}
Some(Rect::from_min_size(desired.clamp(page.min, marker_max), size))
}
/// A redaction mark's areas: one per marked quad, or its rectangle.
pub(super) fn redact_rects(&self, a: &Annotation) -> Vec<Rect> {
if a.quads.is_empty() {
@@ -670,10 +533,11 @@ impl PageCx<'_> {
.collect()
}
/// The topmost comment under `p`: the one drawn last, in `/Annots` order (inspection lists
/// The topmost comment's body under `p`: the one drawn last, in `/Annots` order (inspection lists
/// comments by position, not in paint order). A Replace Text strikeout is grouped under its
/// caret (`/RT /Group`), which holds the proposal, so the strikeout is hit as that caret: the
/// proposal is picked by either part, not only by its small caret.
/// proposal is picked by either part, not only by its small caret. A marker's hit is the
/// framework's (`bridge::parts`).
pub(super) fn comment_at(&self, p: Pos2) -> Option<&Annotation> {
let under = |a: &&Annotation| self.screen_rects(a).any(|r| r.expand(3.0).contains(p));
let strikes = self
@@ -685,16 +549,9 @@ impl PageCx<'_> {
.filter_map(|s| {
let (page, index) = s.parent?;
let caret = self.get(index).filter(|c| page == self.page && c.subtype == "Caret")?;
Some((false, s.index, caret))
Some((s.index, caret))
});
self.comments()
.filter_map(|a| {
let marker = self.comment_marker_rect(a).is_some_and(|r| r.expand(3.0).contains(p));
(marker || under(&a)).then_some((marker, a.index, a))
})
.chain(strikes)
.max_by_key(|(marker, index, _)| (*marker, *index))
.map(|(_, _, a)| a)
self.comments().filter(under).map(|a| (a.index, a)).chain(strikes).max_by_key(|(index, _)| *index).map(|(_, a)| a)
}
pub(crate) fn get(&self, index: usize) -> Option<&Annotation> {
@@ -741,17 +598,10 @@ impl PageCx<'_> {
[a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
}
/// The same geometry drives the live image, its handles, and the edit on release.
/// `shift` is whether Shift is held now: it keeps the box's proportions from a corner.
pub(crate) fn adjusted_rect(
&self,
a: &Annotation,
gesture: Option<&Gesture>,
pointer: Option<Pos2>,
shift: bool,
pending: Option<&Edit>,
) -> Rect {
let r = self.frame_rect(a);
/// The same geometry drives the live image, its handles, and the edit on release: `pending` is
/// the edit just released and not yet applied, `in_flight` the tool's edit while the pointer
/// is down.
pub(crate) fn adjusted_rect(&self, a: &Annotation, in_flight: Option<AnnotationEdit>, pending: Option<&Edit>) -> Rect {
if let Some(Edit::ResizeAnnotation { page, index, rect }) = pending
&& (*page, *index) == (self.page, a.index)
{
@@ -763,12 +613,9 @@ impl PageCx<'_> {
let f = frame(a, self.rotation());
return self.xf.user_rect(self.info, self.page, [f[0] + *dx as f32, f[1] + *dy as f32, f[2] + *dx as f32, f[3] + *dy as f32]);
}
match (gesture, pointer) {
(Some(Gesture::Move { page, index, from }), Some(p)) if (*page, *index) == (self.page, a.index) => r.translate(p - *from),
(Some(Gesture::Resize { page, index, handle, from, aspect_ratio }), Some(p)) if (*page, *index) == (self.page, a.index) => {
resized(r, *handle, p - *from, corner_ratio(r, *aspect_ratio, shift))
}
_ => r,
match in_flight.and_then(|edit| bridge::edited_user_rect(self.info, a, &edit)) {
Some(r) => self.xf.user_rect(self.info, self.page, r),
None => self.frame_rect(a),
}
}
}