PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge origin/main into fix/delete-single-reply
aleheleabd91a54226
diff --cc ROADMAP.mdindex 7c52ddac1,f5de8044e..7708f1ae0--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -199,7 -200,7 +200,8 @@@ Ranked; detail and the full milestone t## Progress log+ - **2026-10-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence.+- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. A locked reply can't be deleted. Estimates unchanged.- **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.diff --cc crates/ui-egui/src/editing.rsindex 1ae66561b,4d09b5cf4..9535cfae1--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@@ -43,6 -27,79 +27,86 @@@ fn new_text_typed(v: &crate::DocView) -v.content.draft.as_ref().is_some_and(|d| d.index.is_none() && !d.text.trim().is_empty())}-/// Keeps the pages (or comment) the user acted on selected, where they now are.-fn select_after_edit(view: &mut crate::DocView, edit: Edit, info: &pdfcraft_render::DocInfo, quick_tool: crate::QuickTool) {++/// Keeps the pages (or comment) the user acted on selected, where they now are. `annots_before`++/// is a deleted annotation's page's annotations before the delete (empty for other edits).++fn select_after_edit(++ view: &mut crate::DocView,++ edit: Edit,++ info: &pdfcraft_render::DocInfo,++ annots_before: &[pdfcraft_render::Annotation],++ quick_tool: crate::QuickTool,++) {+ match edit {+ Edit::MovePages { pages, to } => {+ let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();+ let to = to.min(info.pages.len() - n);+ view.select_pages(&(to..to + n).collect::<Vec<_>>());+ }+ Edit::DuplicatePages { pages, at: Some(at) } => {+ let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();+ let at = at.min(info.pages.len().saturating_sub(n));+ view.select_pages(&(at..at + n).collect::<Vec<_>>());+ }+ Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),+ Edit::DeletePages { .. } => view.select_pages(&[]),+ // A stroke drawn with the pen stays unselected, so the selection box and+ // author popup don't sit over the next stroke (#429).+ Edit::AddAnnotation(a)+ if matches!(a.shape, pdfcraft_engine::Shape::Ink { .. })+ && quick_tool == crate::QuickTool::Comment(crate::comments::CommentTool::Ink) =>+ {+ view.comments.selected = None;+ }+ Edit::AddAnnotation(a) => {+ // Select the new comment (appended last among the page's comments).+ let newest = info.annotations.iter().filter(|x| x.page == a.page && !x.is_reply()).map(|x| x.index).max();+ view.comments.selected = newest.map(|n| (a.page, n));+ view.comments.reveal = true;+ // A new highlight opens its note for typing straight away, as in Acrobat,+ // unless a note typed into another card is still unsaved.+ if let (pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, .. }, Some(n)) = (&a.shape, newest)+ && a.contents.is_empty()+ && view.comments.editing.is_none()+ {+ view.comments.open_editor(a.page, n, String::new());+ }+ }- Edit::DeleteAnnotation { .. } => view.comments.selected = None,++ Edit::DeleteAnnotation { page, index } => view.comments.annotation_deleted(annots_before, &info.annotations, (page, index)),+ _ => {}+ }+ }++ /// The pages whose widgets differ between two form states, and the (field, page) pairs whose+ /// value changed and so must not be drawn from the baked page.+ fn form_edit_pages(+ before: &[pdfcraft_engine::FormField],+ after: &[pdfcraft_engine::FormField],+ ) -> (std::collections::BTreeSet<usize>, Vec<(String, usize)>) {+ let mut changed_pages = std::collections::BTreeSet::new();+ let mut unbaked = Vec::new();+ for f in after {+ let pages = |field: &pdfcraft_engine::FormField| field.widgets.iter().filter_map(|w| w.page).collect::<Vec<_>>();+ match before.iter().find(|old| old.name == f.name) {+ Some(old) if old == f => {}+ Some(old) => {+ changed_pages.extend(pages(f));+ changed_pages.extend(pages(old));+ if old.value != f.value {+ unbaked.extend(pages(f).into_iter().map(|p| (f.name.clone(), p)));+ }+ }+ None => {+ changed_pages.extend(pages(f));+ unbaked.extend(pages(f).into_iter().map(|p| (f.name.clone(), p)));+ }+ }+ }+ for old in before.iter().filter(|old| !after.iter().any(|f| f.name == old.name)) {+ changed_pages.extend(old.widgets.iter().filter_map(|w| w.page));+ }+ (changed_pages, unbaked)+ }+impl PdfCraftApp {/// Apply an edit to the active document. Returns `true` on success; failures are shown.pub fn apply_edit(&mut self, edit: Edit) -> bool {@@@ -143,44 -153,7 +166,7 @@@view.comments.comment_added();}// Keep the pages the user acted on selected, where they now are.- match edit {- Edit::MovePages { pages, to } => {- let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();- let to = to.min(info.pages.len() - n);- view.select_pages(&(to..to + n).collect::<Vec<_>>());- }- Edit::DuplicatePages { pages, at: Some(at) } => {- let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();- let at = at.min(info.pages.len().saturating_sub(n));- view.select_pages(&(at..at + n).collect::<Vec<_>>());- }- Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),- Edit::DeletePages { .. } => view.select_pages(&[]),- // A stroke drawn with the pen stays unselected, so the selection box and- // author popup don't sit over the next stroke (#429).- Edit::AddAnnotation(a)- if matches!(a.shape, pdfcraft_engine::Shape::Ink { .. })- && self.quick_tool == crate::QuickTool::Comment(crate::comments::CommentTool::Ink) =>- {- view.comments.selected = None;- }- Edit::AddAnnotation(a) => {- // Select the new comment (appended last among the page's comments).- let newest = info.annotations.iter().filter(|x| x.page == a.page && !x.is_reply()).map(|x| x.index).max();- view.comments.selected = newest.map(|n| (a.page, n));- view.comments.reveal = true;- // A new highlight opens its note for typing straight away, as in Acrobat,- // unless a note typed into another card is still unsaved.- if let (pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, .. }, Some(n)) = (&a.shape, newest)- && a.contents.is_empty()- && view.comments.editing.is_none()- {- view.comments.open_editor(a.page, n, String::new());- }- }- Edit::DeleteAnnotation { page, index } => view.comments.annotation_deleted(&annots_before, &info.annotations, (page, index)),- _ => {}- }- select_after_edit(view, edit, info, self.quick_tool);++ select_after_edit(view, edit, info, &annots_before, self.quick_tool);if std::mem::take(&mut view.comments.tool_done) && !self.comment_prefs.pinned {self.quick_tool = crate::QuickTool::Select;}diff --cc crates/ui-egui/src/tools/comments.rsindex 000000000,674a3b4ea..6f3c07442mode 000000,100644..100644--- a/crates/ui-egui/src/tools/comments.rs+++ b/crates/ui-egui/src/tools/comments.rs@@@ -1,0 -1,394 +1,396 @@@+ //! Commenting in the document view (execution plan M5.3–M5.4; Acrobat's "Add comments").+ //!+ //! - **Tools** ([`CommentTool`]): sticky note, text box, highlight / underline / strikethrough+ //! (driven by text selection), freehand, line, arrow, rectangle, oval. They live in the quick+ //! bar in three flyout groups, as in Acrobat's comment toolbar (audit `a14-*`).+ //! - **On the page:** drawing gestures with live previews; with the Select tool, comments can be+ //! hovered, selected (blue frame with 8 round handles), moved, resized (rectangles, ovals and+ //! text boxes), edited (double-click) and deleted (⌫ / Delete); a context menu offers Edit,+ //! Reply, Set status, Colour and Delete.+ //! - **Composer:** the floating "Add a comment" card used for new notes, text boxes and edits.+ //!+ //! Everything is turned into `pdfcraft_engine::Edit`s, queued on the view as `pending_edit` and+ //! applied by the app, so each change is one undo step.++ 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 crate::canvas::{DocView, PageXform};+ use crate::page_pointer::PagePointer;+ use crate::theme::{self, Tokens};+ use crate::{QuickTool, icons};++ mod composer;+ mod geometry;+ mod input;+ mod menu;+ mod paint;+ mod state;++ pub(crate) use composer::{composer, submit_key};+ #[cfg(test)]+ use geometry::handle_pos;+ #[cfg(test)]+ pub(crate) use geometry::{caret_snap, snapped_caret};+ pub(crate) use geometry::{corner_ratio, page_rotation, resized};+ pub use geometry::{drawn_text_box_rect, text_box_rect};+ pub(crate) use input::{fill_grabs, keys, nudge_keys, page_after_text, page_input, select_grabs};+ pub use menu::{CanvasAction, fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid};+ #[cfg(test)]+ use menu::{RECENT_CUSTOM, same_colour};+ pub(crate) use menu::{attachment_items, context_menu, quick_bar_controls};+ pub(crate) use paint::paint_page;+ #[cfg(test)]+ use paint::{changing_points, drawn_shape, edited_in_view};++#[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);++ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+ pub enum CommentTool {+ Note,+ TextBox,+ Highlight,+ Underline,+ StrikeOut,+ Squiggly,+ Ink,+ Line,+ Arrow,+ Rectangle,+ Oval,+ Polygon,+ PolyLine,+ Cloud,+ Callout,+ Caret,+ ReplaceText,+ Attach,+ Eraser,+ }++ /// The quick-bar flyout groups, in Acrobat's order: Comment ▸, Highlight ▸, Draw ▸.+ pub const GROUPS: [&[CommentTool]; 3] = [+ &[CommentTool::Note, CommentTool::TextBox, CommentTool::Callout, CommentTool::Attach],+ &[CommentTool::Highlight, CommentTool::Underline, CommentTool::StrikeOut, CommentTool::Squiggly, CommentTool::Caret, CommentTool::ReplaceText],+ &[+ CommentTool::Ink,+ CommentTool::Line,+ CommentTool::Arrow,+ CommentTool::Rectangle,+ CommentTool::Oval,+ CommentTool::PolyLine,+ CommentTool::Polygon,+ CommentTool::Cloud,+ CommentTool::Eraser,+ ],+ ];++ pub const ALL: [CommentTool; 19] = [+ CommentTool::Eraser,+ CommentTool::ReplaceText,+ CommentTool::Attach,+ CommentTool::Polygon,+ CommentTool::PolyLine,+ CommentTool::Cloud,+ CommentTool::Callout,+ CommentTool::Caret,+ CommentTool::Note,+ CommentTool::TextBox,+ CommentTool::Highlight,+ CommentTool::Underline,+ CommentTool::StrikeOut,+ CommentTool::Squiggly,+ CommentTool::Ink,+ CommentTool::Line,+ CommentTool::Arrow,+ CommentTool::Rectangle,+ CommentTool::Oval,+ ];++ impl CommentTool {+ pub fn command(self) -> &'static str {+ match self {+ Self::Note => "comment.note",+ Self::TextBox => "comment.freetext",+ Self::Highlight => "comment.highlight",+ Self::Underline => "comment.underline",+ Self::StrikeOut => "comment.strikeout",+ Self::Squiggly => "comment.squiggly",+ Self::Ink => "comment.ink",+ Self::Line => "comment.line",+ Self::Arrow => "comment.arrow",+ Self::Rectangle => "comment.square",+ Self::Oval => "comment.circle",+ Self::Polygon => "comment.polygon",+ Self::PolyLine => "comment.polyline",+ Self::Cloud => "comment.cloud",+ Self::Callout => "comment.callout",+ Self::Caret => "comment.caret",+ Self::ReplaceText => "comment.replace",+ Self::Attach => "comment.attach",+ Self::Eraser => "comment.eraser",+ }+ }++ pub fn from_command(id: &str) -> Option<Self> {+ ALL.into_iter().find(|t| t.command() == id)+ }++ pub fn label(self) -> &'static str {+ match self {+ Self::Note => "Add a sticky note",+ Self::TextBox => "Add a text box",+ Self::Highlight => "Highlight",+ Self::Underline => "Underline",+ Self::StrikeOut => "Strikethrough",+ Self::Squiggly => "Squiggly underline",+ Self::Ink => "Draw",+ Self::Line => "Line",+ Self::Arrow => "Arrow",+ Self::Rectangle => "Rectangle",+ Self::Oval => "Oval",+ Self::Polygon => "Polygon",+ Self::PolyLine => "Connected lines",+ Self::Cloud => "Cloud",+ Self::Callout => "Add a callout",+ Self::Caret => "Insert text",+ Self::ReplaceText => "Replace text",+ Self::Attach => "Attach file",+ Self::Eraser => "Eraser",+ }+ }++ 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::Squiggly => "spline",+ Self::Ink => "pencil",+ Self::Line => "minus",+ Self::Arrow => "move-right",+ Self::Rectangle => "square",+ Self::Oval => "circle",+ Self::Polygon => "pentagon",+ Self::PolyLine => "spline",+ Self::Cloud => "cloud",+ Self::Callout => "message-square-quote",+ Self::Caret => "text-cursor-input",+ Self::ReplaceText => "replace",+ Self::Attach => "paperclip",+ Self::Eraser => "eraser",+ }+ }++ pub fn group(self) -> usize {+ GROUPS.iter().position(|g| g.contains(&self)).unwrap_or(0)+ }++ pub fn markup(self) -> Option<Markup> {+ match self {+ Self::Highlight => Some(Markup::Highlight),+ Self::Underline => Some(Markup::Underline),+ Self::StrikeOut => Some(Markup::StrikeOut),+ Self::Squiggly => Some(Markup::Squiggly),+ _ => None,+ }+ }++ /// Tools that draw with a drag gesture.+ pub fn draws(self) -> bool {+ matches!(self, Self::Ink | Self::Line | Self::Arrow | Self::Rectangle | Self::Oval | Self::Eraser)+ }++ /// Tools that place points one click at a time (double-click or Enter finishes).+ pub fn clicks_points(self) -> bool {+ matches!(self, Self::Polygon | Self::PolyLine | Self::Cloud)+ }++ /// Whether the line-thickness control applies.+ pub fn has_width(self) -> bool {+ self.draws() || self.clicks_points() || matches!(self, Self::TextBox | Self::Callout)+ }++ /// Text comments may have no border while retaining visible text or fill.+ fn min_width(self) -> f64 {+ if matches!(self, Self::TextBox | Self::Callout) { 0.0 } else { 0.5 }+ }++ /// Whether the fill-colour control applies to this tool.+ pub fn has_fill(self) -> bool {+ matches!(self, Self::Rectangle | Self::Oval | Self::Polygon | Self::Cloud | Self::TextBox | Self::Callout)+ }++ /// A placeholder shape of this kind (for per-tool default styles).+ fn sample(self) -> Shape {+ match self {+ Self::Note => Shape::Note { at: [0.0; 2], icon: NoteIcon::Comment },+ Self::TextBox => Shape::TextBox { rect: [0.0; 4], font_size: 12.0 },+ Self::Highlight | Self::Underline | Self::StrikeOut | Self::Squiggly => {+ Shape::TextMarkup { kind: self.markup().unwrap_or(Markup::Highlight), quads: Vec::new() }+ }+ Self::Ink => Shape::Ink { strokes: Vec::new() },+ Self::Line => Shape::Line { from: [0.0; 2], to: [0.0; 2], start: LineEnding::None, end: LineEnding::None },+ Self::Arrow => Shape::Line { from: [0.0; 2], to: [0.0; 2], start: LineEnding::None, end: LineEnding::OpenArrow },+ Self::Rectangle => Shape::Rectangle { rect: [0.0; 4] },+ Self::Oval => Shape::Oval { rect: [0.0; 4] },+ Self::Polygon => Shape::Polygon { vertices: Vec::new(), cloud: false },+ Self::Cloud => Shape::Polygon { vertices: Vec::new(), cloud: true },+ Self::PolyLine => Shape::PolyLine { vertices: Vec::new(), start: LineEnding::None, end: LineEnding::None },+ Self::Callout => Shape::Callout { rect: [0.0; 4], knee: [0.0; 2], point: [0.0; 2], font_size: 10.0, ending: LineEnding::OpenArrow },+ Self::Caret => Shape::Caret { rect: [0.0; 4] },+ Self::ReplaceText => Shape::TextMarkup { kind: Markup::StrikeOut, quads: Vec::new() },+ Self::Eraser => Shape::Ink { strokes: Vec::new() },+ Self::Attach => Shape::Attachment { at: [0.0; 2], icon: pdfcraft_engine::AttachIcon::PushPin, file: String::new(), data: Vec::new() },+ }+ }+ }++ /// The comment swatches (our palette, close to Acrobat's quick colours).+ pub const SWATCHES: [(&str, Rgb); 10] = [+ ("Yellow", [1.0, 0.94, 0.0]),+ ("Orange", [1.0, 0.54, 0.0]),+ ("Red", [0.89, 0.13, 0.13]),+ ("Pink", [1.0, 0.37, 0.64]),+ ("Purple", [0.54, 0.25, 0.82]),+ ("Blue", [0.0, 0.47, 0.84]),+ ("Light blue", [0.36, 0.75, 0.98]),+ ("Green", [0.18, 0.62, 0.36]),+ ("Gray", [0.5, 0.5, 0.5]),+ ("Black", [0.0, 0.0, 0.0]),+ ];++ pub fn color32(c: Rgb) -> Color32 {+ let b = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))+ }++ /// Commenting preferences shared by every document (author, per-tool styles, pin).+ #[derive(Clone, Debug)]+ pub struct CommentPrefs {+ /// `/T` of new comments (Acrobat: Preferences ▸ Identity, default the login name).+ pub author: String,+ styles: Vec<(CommentTool, Style)>,+ /// Keep the tool selected after use (the pin).+ pub pinned: bool,+ /// The tool each flyout group shows (the last one used).+ pub group_tool: [CommentTool; 3],+ /// Hide hover previews on highlight annotations when they contain no comment text beyond the author.+ pub hide_empty_highlight_hover: bool,+ }++ impl Default for CommentPrefs {+ fn default() -> Self {+ Self {+ author: login_name(),+ styles: ALL.iter().map(|t| (*t, Style::default_for(&t.sample()))).collect(),+ pinned: false,+ group_tool: [CommentTool::Note, CommentTool::Highlight, CommentTool::Ink],+ hide_empty_highlight_hover: false,+ }+ }+ }++ impl CommentPrefs {+ pub fn style(&self, tool: CommentTool) -> Style {+ self.styles.iter().find(|(t, _)| *t == tool).map(|(_, s)| s.clone()).unwrap_or_default()+ }++ /// Every tool with its current default style (the persisted settings read this).+ pub fn styles(&self) -> impl Iterator<Item = (CommentTool, &Style)> {+ self.styles.iter().map(|(t, s)| (*t, s))+ }++ pub fn set_color(&mut self, tool: CommentTool, c: Rgb) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.color = c;+ }+ }++ pub fn set_width(&mut self, tool: CommentTool, w: f64) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.width = w.clamp(tool.min_width(), 12.0);+ }+ }++ /// The tool's opacity, 10–100 % (an invisible comment can't be found again).+ pub fn set_opacity(&mut self, tool: CommentTool, o: f64) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.opacity = if o.is_finite() { o.clamp(0.1, 1.0) } else { 1.0 };+ }+ }++ /// The tool's fill (`None`: no fill).+ pub fn set_fill(&mut self, tool: CommentTool, fill: Option<Rgb>) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ s.fill = if tool.has_fill() { fill.filter(|c| c.iter().all(|x| x.is_finite())).map(|c| c.map(|x| x.clamp(0.0, 1.0))) } else { None };+ }+ }++ pub fn set_style(&mut self, tool: CommentTool, style: Style) {+ if let Some((_, s)) = self.styles.iter_mut().find(|(t, _)| *t == tool) {+ *s = style;+ }+ }+ }++ /// Whether `tool` makes comments like `a`. Arrows are saved as plain Line annotations with an+ /// ending, so the Line and Arrow tools both match a line.+ pub(crate) fn made_by(a: &Annotation, tool: CommentTool) -> bool {+ match tool_for(a) {+ Some(CommentTool::Line) => matches!(tool, CommentTool::Line | CommentTool::Arrow),+ made => made == Some(tool),+ }+ }++ /// The tool whose defaults "Make Current Properties Default" should update.+ ///+ /// Arrows are stored as Line annotations. An arrow ending belongs to the Arrow tool, so its+ /// defaults stay separate from a plain line.+ pub(crate) fn tool_for_default(a: &Annotation, endings: Option<&[LineEnding]>) -> Option<CommentTool> {+ match tool_for(a) {+ Some(CommentTool::Line) if endings.is_some_and(|ends| ends.iter().copied().any(arrow_ending)) => Some(CommentTool::Arrow),+ other => other,+ }+ }++ fn arrow_ending(ending: LineEnding) -> bool {+ matches!(ending, LineEnding::OpenArrow | LineEnding::ClosedArrow | LineEnding::ROpenArrow | LineEnding::RClosedArrow)+ }++ /// The tool that makes comments like `a` (for Make Current Properties Default).+ pub fn tool_for(a: &Annotation) -> Option<CommentTool> {+ Some(match (a.subtype.as_str(), a.intent.as_deref()) {+ ("Text", _) => CommentTool::Note,+ ("FreeText", Some("FreeTextCallout")) => CommentTool::Callout,+ ("FreeText", Some("FreeTextTypeWriter")) => return None,+ ("FreeText", _) => CommentTool::TextBox,+ ("Highlight", _) => CommentTool::Highlight,+ ("Underline", _) => CommentTool::Underline,+ ("StrikeOut", Some("StrikeOutTextEdit")) => CommentTool::ReplaceText,+ ("StrikeOut", _) => CommentTool::StrikeOut,+ ("Squiggly", _) => CommentTool::Squiggly,+ ("Ink", _) => CommentTool::Ink,+ ("Line", _) => CommentTool::Line,+ ("Square", _) => CommentTool::Rectangle,+ ("Circle", _) => CommentTool::Oval,+ ("Polygon", Some("PolygonCloud")) => CommentTool::Cloud,+ ("Polygon", _) => CommentTool::Polygon,+ ("PolyLine", _) => CommentTool::PolyLine,+ ("Caret", _) => CommentTool::Caret,+ ("FileAttachment", _) => CommentTool::Attach,+ _ => return None,+ })+ }++ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/tools/comments/state.rsindex 000000000,36149bb2a..c40542248mode 000000,100644..100644--- a/crates/ui-egui/src/tools/comments/state.rs+++ b/crates/ui-egui/src/tools/comments/state.rs@@@ -1,0 -1,354 +1,411 @@@++use std::collections::HashMap;+++ use super::geometry::{corner_ratio, is_markup, resized};+ use super::{Annotation, CommentPrefs, CommentTool, DocInfo, Edit, PagePointer, PageXform, Pos2, QuickTool, Rect};++ /// The user's login name, which Acrobat uses as the default comment author.+ pub(super) fn login_name() -> String {+ #[cfg(not(target_arch = "wasm32"))]+ for var in ["USER", "USERNAME", "LOGNAME"] {+ if let Ok(v) = std::env::var(var)+ && !v.trim().is_empty()+ {+ return v;+ }+ }+ "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]> },+ }++ #[derive(Clone, Copy, Debug, PartialEq)]+ pub enum ComposerKind {+ Note,+ /// A text box; `size` is the box dragged out (displayed width and height, in user space+ /// units), `None` after a click: then the box fits its text.+ TextBox {+ size: Option<[f64; 2]>,+ },+ /// A callout whose arrow touches `point`; the composer's anchor is the text box's top-left.+ Callout {+ point: [f64; 2],+ },+ /// Insert text at the anchor (the caret's tip); `size` is the side of the caret's square box,+ /// in user space units.+ Caret {+ size: f64,+ },+ /// Replace the selected text (`CommentView::replace` holds the quads).+ Replace,+ /// Edit the text of the comment at this index on the composer's page.+ Edit(usize),+ }++ /// The floating "Add a comment" card.+ #[derive(Clone, Debug, PartialEq)]+ pub struct Composer {+ pub page: usize,+ /// Anchor in user space (the note's top-left, the text box's top-left, the comment's corner).+ pub at: [f64; 2],+ pub kind: ComposerKind,+ pub text: String,+ pub focus: bool,+ }++ /// A released drawing gesture waiting for the page raster to show its annotation.+ #[derive(Clone, Debug, PartialEq)]+ pub(crate) struct Settling {+ pub page: usize,+ pub tool: CommentTool,+ pub points: Vec<[f64; 2]>,+ /// Frame time (seconds) at release; a raster that never arrives must not leave a ghost.+ pub since: f64,+ /// Its annotation is in the document, so a raster of the page from now on draws it. Until+ /// then a raster is of the document without it (in full screen the edit is applied the frame+ /// after the release, and a raster already on its way can arrive in between).+ pub committed: bool,+ }++ /// Longest a released drawing stays painted without its page raster, and how many are kept.+ pub(super) const SETTLE_SECS: f64 = 20.0;++ const SETTLE_MAX: usize = 16;++ impl CommentView {+ /// Remember a released drag drawing so it stays on screen until its page is re-rendered.+ pub(crate) fn settle(&mut self, now: f64, page: usize, tool: CommentTool, points: &[[f64; 2]]) {+ if !matches!(tool, CommentTool::Ink | CommentTool::Line | CommentTool::Arrow | CommentTool::Rectangle | CommentTool::Oval) {+ return;+ }+ self.settling.retain(|s| now - s.since < SETTLE_SECS);+ if self.settling.len() >= SETTLE_MAX {+ self.settling.remove(0);+ }+ self.settling.push(Settling { page, tool, points: points.to_vec(), since: now, committed: false });+ }++ /// How many released drawings are still painted from their points (waiting for a raster).+ pub fn settling_len(&self) -> usize {+ self.settling.len()+ }++ /// A fresh raster of `page` is on screen: it draws the committed annotations itself. One+ /// still waiting for its edit isn't in that raster, and stays drawn from its points.+ pub(crate) fn page_rendered(&mut self, page: usize) {+ self.settling.retain(|s| s.page != page || !s.committed);+ }++ /// The edit adding the released drawings was applied: rasters from now on draw them.+ pub(crate) fn drawings_committed(&mut self) {+ for s in &mut self.settling {+ s.committed = true;+ }+ }++ /// The edit adding the released drawings failed: nothing will draw them.+ pub(crate) fn drawings_refused(&mut self) {+ self.settling.retain(|s| s.committed);+ }+ }++ /// Per-document commenting state.+ #[derive(Clone, Debug, Default)]+ pub struct CommentView {+ /// The selected comment: (page, index in `/Annots`).+ pub selected: Option<(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>,+ /// Escape ends egui's drag too; ignore its synthetic release until the mouse is up.+ pub(super) cancelled_drag: bool,+ 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 panel should scroll the selected card into view.+ pub reveal: bool,+ /// 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).+ pub default_request: Option<(usize, usize)>,+ /// A file attachment comment's file was asked for: (page, index, open it in a new tab+ /// rather than save it).+ pub attachment_request: Option<(usize, usize, bool)>,+ /// Replace Text: the struck-out text's quads while the replacement is typed.+ 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>,+ }++ /// 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 {+ /// 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.+ 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);+ }++ /// 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.+ 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;+ }+ }++++ /// The annotation at `gone` was just deleted; `before` and `after` are the document's++ /// annotations until then and now. The selection and the inline editor stay on what they++ /// were on, where it now is (deleting a reply keeps its comment selected), and close when it++ /// went too.++ pub(crate) fn annotation_deleted(&mut self, before: &[Annotation], after: &[Annotation], gone: (usize, usize)) {++ self.selected = self.selected.and_then(|k| after_delete(before, after, gone, k));++ self.editing = self.editing.take().and_then(|(p, i, text)| after_delete(before, after, gone, (p, i)).map(|(p, i)| (p, i, text)));++ if self.editing.is_none() {++ self.editor_focus = None;++ }++ }++}++++/// Where the annotation at `keep` is once the one at `gone` was deleted, or `None` when it went++/// with it. Deleting takes the annotation's replies (at any depth) and pop-ups out of its page's++/// `/Annots` (`pdfcraft_annot::delete_annotation`), and everything after them moves up, so `keep`++/// is found by its place among the page's annotations that stay. When the page lost other++/// annotations than those, or the one in that place reads differently, it is not guessed at.++pub(super) fn after_delete(before: &[Annotation], after: &[Annotation], gone: (usize, usize), keep: (usize, usize)) -> Option<(usize, usize)> {++ if keep == gone {++ return None;++ }++ if keep.0 != gone.0 {++ return Some(keep);++ }++ let (old, new) = (on_page(before, gone.0), on_page(after, gone.0));++ // Only replies on the page go with it: `/IRT` is followed through the page's `/Annots`.++ let parents: HashMap<usize, usize> = old.iter().filter_map(|a| a.parent.filter(|p| p.0 == gone.0).map(|p| (a.index, p.1))).collect();++ let goes = |mut i: usize| {++ // `link_replies` settles every chain within 64 steps.++ for _ in 0..=64 {++ if i == gone.1 {++ return true;++ }++ let Some(&up) = parents.get(&i) else { return false };++ i = up;++ }++ false++ };++ let stays: Vec<&Annotation> = old.iter().copied().filter(|a| !goes(a.index)).collect();++ if stays.len() != new.len() {++ return None;++ }++ let rank = stays.iter().position(|a| a.index == keep.1)?;++ let (was, now) = (stays.get(rank)?, new.get(rank)?);++ let same = (&was.subtype, &was.name, &was.author, &was.contents, was.rect) == (&now.subtype, &now.name, &now.author, &now.contents, now.rect);++ same.then_some((now.page, now.index))++}++++/// The annotations listed on `page`, in `/Annots` order.++fn on_page(list: &[Annotation], page: usize) -> Vec<&Annotation> {++ let mut v: Vec<&Annotation> = list.iter().filter(|a| a.page == page).collect();++ v.sort_by_key(|a| a.index);++ 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,+ }++ impl PageCx<'_> {+ pub(super) fn to_user(&self, p: Pos2) -> [f64; 2] {+ let (vx, vy) = self.xf.screen_to_view(p);+ let u = self.info.pages[self.page].view_to_user(vx, vy);+ [u[0] as f64, u[1] as f64]+ }++ pub(super) fn to_screen(&self, p: [f64; 2]) -> Pos2 {+ let v = self.info.pages[self.page].user_to_view(p[0] as f32, p[1] as f32);+ self.xf.norm_to_screen(v[0] / self.xf.pw, v[1] / self.xf.ph)+ }++ /// The page's clockwise `/Rotate`.+ pub(super) fn rotation(&self) -> u16 {+ self.info.pages.get(self.page).map_or(0, |p| p.rotation)+ }++ /// Where a comment is drawn on screen (a sticky note stays upright on a turned page).+ pub(super) fn screen_rect(&self, a: &Annotation) -> Rect {+ self.xf.user_rect(self.info, self.page, a.shown_rect(self.rotation()))+ }++ /// Top-level comments on this page, in paint order.+ pub(super) fn comments(&self) -> impl Iterator<Item = &Annotation> {+ self.info.annotations.iter().filter(move |a| !self.hidden && a.page == self.page && a.is_comment() && a.subtype != "Popup")+ }++ /// Where a comment is on screen: one rectangle, or one per marked line for text markup.+ pub(crate) fn screen_rects<'b>(&'b self, a: &'b Annotation) -> impl Iterator<Item = Rect> + 'b {+ let quads = if is_markup(&a.subtype) { a.quads.as_slice() } else { &[] };+ let fallback = quads.is_empty().then(|| self.screen_rect(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 (x0, x1) = (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max));+ let (y0, y1) = (ys.iter().copied().fold(f32::MAX, f32::min), ys.iter().copied().fold(f32::MIN, f32::max));+ self.xf.user_rect(self.info, self.page, [x0, y0, x1, y1])+ })+ .chain(fallback)+ }++ /// 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() {+ return vec![self.screen_rect(a)];+ }+ 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 (x0, x1) = (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max));+ let (y0, y1) = (ys.iter().copied().fold(f32::MAX, f32::min), ys.iter().copied().fold(f32::MIN, f32::max));+ self.xf.user_rect(self.info, self.page, [x0, y0, x1, y1])+ })+ .collect()+ }++ /// The topmost comment under `p`.+ pub(super) fn hit(&self, p: Pos2) -> Option<&Annotation> {+ self.comments().filter(|a| self.screen_rects(a).any(|r| r.expand(3.0).contains(p))).last()+ }++ pub(crate) fn get(&self, index: usize) -> Option<&Annotation> {+ self.comments().find(|a| a.index == index)+ }++ pub(crate) fn rect_to_user(&self, r: Rect) -> [f64; 4] {+ let (a, b) = (self.to_user(r.left_top()), self.to_user(r.right_bottom()));+ [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.screen_rect(a);+ if let Some(Edit::ResizeAnnotation { page, index, rect }) = pending+ && (*page, *index) == (self.page, a.index)+ {+ return self.xf.user_rect(self.info, self.page, a.shown(*rect, self.rotation()).map(|v| v as f32));+ }+ if let Some(Edit::MoveAnnotation { page, index, dx, dy }) = pending+ && (*page, *index) == (self.page, a.index)+ {+ let r = a.shown_rect(self.rotation());+ return self.xf.user_rect(self.info, self.page, [r[0] + *dx as f32, r[1] + *dy as f32, r[2] + *dx as f32, r[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,+ }+ }+ }diff --cc crates/ui-egui/src/tools/comments/tests.rsindex 000000000,fff7f0136..bf000539amode 000000,100644..100644--- a/crates/ui-egui/src/tools/comments/tests.rs+++ b/crates/ui-egui/src/tools/comments/tests.rs@@@ -1,0 -1,386 +1,446 @@@+ use super::*;++ /// A selected line is drawn where it is going: moved by its body (both ends follow the+ /// pointer), with an end dragged (that end alone), and as released until the page is drawn.+ #[test]+ fn a_moved_or_reshaped_line_is_drawn_at_its_new_points() {+ let line = [[10.0, 10.0], [50.0, 10.0]];+ let to_user = |p: Pos2| [f64::from(p.x), f64::from(p.y)];+ let moving = Gesture::Move { page: 0, index: 3, from: pos2(20.0, 10.0) };+ let at = Some(pos2(25.0, 30.0));+ assert_eq!(changing_points(Some(&moving), None, (0, 3), &line, to_user, at, false), Some(vec![[15.0, 30.0], [55.0, 30.0]]));+ assert_eq!(changing_points(Some(&moving), None, (0, 4), &line, to_user, at, false), None, "another comment's move");+ let released = Edit::MoveAnnotation { page: 0, index: 3, dx: 5.0, dy: 20.0 };+ assert_eq!(changing_points(None, Some(&released), (0, 3), &line, to_user, None, false), Some(vec![[15.0, 30.0], [55.0, 30.0]]));+ let dragging = Gesture::Reshape { page: 0, index: 3, point: 1, points: line.to_vec() };+ let to = Some(pos2(60.0, 10.0));+ assert_eq!(changing_points(Some(&dragging), None, (0, 3), &line, to_user, to, false), Some(vec![[10.0, 10.0], [60.0, 10.0]]));+ assert_eq!(changing_points(None, None, (0, 3), &line, to_user, to, false), None, "not changing");+ }++ /// A sticky note on a page turned a quarter is drawn upright beside its `/Rect`: an edit+ /// composer stays open while the drawn note is partly in view, even with `/Rect` out of it.+ #[test]+ fn an_upright_note_on_a_turned_page_is_in_view_where_it_is_drawn() {+ let note = |no_rotate| Annotation {+ page: 0,+ subtype: "Text".into(),+ author: None,+ contents: None,+ modified: None,+ name: None,+ in_reply_to: None,+ parent: None,+ grouped: false,+ rect: [40.0, 20.0, 70.0, 40.0],+ color: None,+ index: 0,+ state: None,+ quads: Vec::new(),+ locked: false,+ intent: None,+ fill_sign: false,+ no_rotate,+ points: Vec::new(),+ };+ let page = PageInfo { width: 140.0, height: 200.0, label: String::new(), crop: [0.0, 0.0, 200.0, 140.0], rotation: 90 };+ let xf = PageXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(140.0, 200.0)), rot: 0, pw: 140.0, ph: 200.0 };+ let prefs = CommentPrefs::default();+ // Screen x is user y here: `/Rect` spans x 20..40, the upright note x 40..70.+ let viewport = Rect::from_min_max(pos2(50.0, 0.0), pos2(140.0, 200.0));+ for (no_rotate, in_view) in [(true, true), (false, false)] {+ let info = DocInfo { pages: vec![page.clone()], annotations: vec![note(no_rotate)], ..Default::default() };+ let cx = PageCx {+ page: 0,+ xf: &xf,+ ptr: &PagePointer::default(),+ info: &info,+ tool: QuickTool::Select,+ prefs: &prefs,+ allowed: true,+ hidden: false,+ redact_mark: ([0.0; 3], 1.0),+ };+ assert_eq!(edited_in_view(&cx, 0, viewport), in_view, "no_rotate: {no_rotate}");+ }+ }+++/// A listed comment or reply at `index` on `page`, replying to `parent`.++fn listed(page: usize, index: usize, contents: &str, parent: Option<(usize, usize)>) -> Annotation {++ Annotation {++ page,++ subtype: "Text".into(),++ author: None,++ contents: Some(contents.into()),++ modified: None,++ name: None,++ in_reply_to: None,++ parent,++ grouped: false,++ rect: [0.0, 0.0, 20.0, 20.0],++ color: None,++ index,++ state: None,++ quads: Vec::new(),++ locked: false,++ intent: None,++ fill_sign: false,++ no_rotate: false,++ points: Vec::new(),++ }++}++++/// What stays selected or open in the editor after a delete is found where it moved to: the++/// reply's own replies go with it (pop-ups, unlisted, are gone too), and a page that lost++/// something else, or whose annotation in that place reads differently, keeps nothing.++#[test]++fn a_kept_comment_is_found_where_a_delete_moved_it() {++ // Page 0's `/Annots`: reply A, its pop-up (unlisted), the comment, reply B, a reply to A.++ let before = vec![++ listed(0, 0, "A", Some((0, 2))),++ listed(0, 2, "comment", None),++ listed(0, 3, "B", Some((0, 2))),++ listed(0, 4, "to A", Some((0, 0))),++ listed(1, 0, "other page", None),++ ];++ // Deleting A takes its pop-up and the reply to it: the comment and B move up two places.++ let after = vec![listed(0, 0, "comment", None), listed(0, 1, "B", Some((0, 0))), listed(1, 0, "other page", None)];++ let gone = (0, 0);++ assert_eq!(after_delete(&before, &after, gone, (0, 2)), Some((0, 0)), "the comment");++ assert_eq!(after_delete(&before, &after, gone, (0, 3)), Some((0, 1)), "the other reply");++ assert_eq!(after_delete(&before, &after, gone, (0, 4)), None, "the reply to A went with it");++ assert_eq!(after_delete(&before, &after, gone, gone), None, "the deleted one");++ assert_eq!(after_delete(&before, &after, gone, (1, 0)), Some((1, 0)), "another page keeps its places");++ // The page lost more than A and its replies: nothing is guessed.++ assert_eq!(after_delete(&before, &after[..1], gone, (0, 2)), None);++ // Another annotation in the comment's place.++ let changed = vec![listed(0, 0, "something else", None), listed(0, 1, "B", Some((0, 0)))];++ assert_eq!(after_delete(&before, &changed, gone, (0, 2)), None);++++ let mut view = CommentView { selected: Some((0, 2)), editing: Some((0, 3, "typed".into())), ..Default::default() };++ view.annotation_deleted(&before, &after, gone);++ assert_eq!((view.selected, view.editing), (Some((0, 0)), Some((0, 1, "typed".into()))), "both follow");++ let mut view = CommentView { editing: Some((0, 4, "typed".into())), editor_focus: Some(EditorFocus::Take), ..Default::default() };++ view.annotation_deleted(&before, &after, gone);++ assert_eq!((view.editing, view.editor_focus), (None, None), "the editor closes with the reply it was open on");++}+++ use pdfcraft_render::TextGlyph;++ /// One glyph per character, `w` points wide, on a line of `em`-point text whose baseline is at `y`, drawn+ /// along `direction` (a unit vector in view space, y down).+ fn line(chars: &str, x: f32, y: f32, w: f32, em: f32, direction: [f32; 2]) -> PageText {+ let [dx, dy] = direction;+ // "Up" for the glyph: its writing direction turned a quarter counterclockwise (y down).+ let [ux, uy] = [dy, -dx];+ let glyphs = chars+ .chars()+ .enumerate()+ .map(|(i, c)| {+ let start = [x + dx * w * i as f32, y + dy * w * i as f32];+ let at = |along: f32, up: f32| [start[0] + dx * along + ux * up, start[1] + dy * along + uy * up];+ let quad = [at(0.0, -0.2 * em), at(w, -0.2 * em), at(w, 0.8 * em), at(0.0, 0.8 * em)];+ let xs = quad.map(|p| p[0]);+ let ys = quad.map(|p| p[1]);+ let rect = [+ xs.into_iter().fold(f32::INFINITY, f32::min),+ ys.into_iter().fold(f32::INFINITY, f32::min),+ xs.into_iter().fold(f32::NEG_INFINITY, f32::max),+ ys.into_iter().fold(f32::NEG_INFINITY, f32::max),+ ];+ TextGlyph { text: c.to_string(), rect, quad, direction }+ })+ .collect::<Vec<_>>();+ let n = glyphs.len();+ PageText { glyphs, line_of: vec![0; n], space_before: vec![false; n] }+ }++ fn near(a: Option<([f32; 2], f32)>, b: ([f32; 2], f32)) -> bool {+ a.is_some_and(|([x, y], s)| (x - b.0[0]).abs() < 1e-3 && (y - b.0[1]).abs() < 1e-3 && (s - b.1).abs() < 1e-3)+ }++ #[test]+ fn the_caret_snaps_to_the_nearer_edge_on_the_baseline() {+ let text = line("abcd", 20.0, 100.0, 10.0, 14.0, [1.0, 0.0]);+ // "c" spans 40..50: its left half snaps before it, its right half after it.+ assert!(near(caret_snap(&text, 43.0, 95.0), ([40.0, 100.0], 7.0)));+ assert!(near(caret_snap(&text, 47.0, 92.0), ([50.0, 100.0], 7.0)));+ // Just past the last character, on the line: after it.+ assert!(near(caret_snap(&text, 63.0, 99.0), ([60.0, 100.0], 7.0)));+ }++ #[test]+ fn the_snapped_caret_follows_the_page_into_user_space() {+ let text = line("abcd", 20.0, 100.0, 10.0, 14.0, [1.0, 0.0]);+ let page = |rotation, user_unit: f32| PageInfo {+ width: 300.0 * user_unit,+ height: 200.0 * user_unit,+ label: "1".into(),+ crop: [0.0, 0.0, 300.0, 200.0],+ rotation,+ };+ // An unrotated page: view y = 100 is user y = 100 (y up from the bottom of a 200 pt page).+ let (tip, side) = snapped_caret(&page(0, 1.0), &text, 43.0, 95.0).expect("snaps");+ assert!((tip[0] - 40.0).abs() < 1e-3 && (tip[1] - 100.0).abs() < 1e-3 && (side - 7.0).abs() < 1e-3);+ // /UserUnit 2: the view is twice as large, so the same text is half as many user units.+ let doubled = line("abcd", 40.0, 200.0, 20.0, 28.0, [1.0, 0.0]);+ let (tip, side) = snapped_caret(&page(0, 2.0), &doubled, 86.0, 190.0).expect("snaps");+ assert!((tip[0] - 40.0).abs() < 1e-3 && (tip[1] - 100.0).abs() < 1e-3 && (side - 7.0).abs() < 1e-3, "{tip:?} {side}");+ // A rotated page: the caret would lie on its side, so it stays at the click.+ for rotation in [90, 180, 270] {+ assert_eq!(snapped_caret(&page(rotation, 1.0), &text, 43.0, 95.0), None, "/Rotate {rotation}");+ }+ }++ #[test]+ fn away_from_upright_horizontal_text_the_caret_stays_at_the_click() {+ let text = line("abcd", 20.0, 100.0, 10.0, 14.0, [1.0, 0.0]);+ assert_eq!(caret_snap(&text, 200.0, 100.0), None, "far to the right");+ assert_eq!(caret_snap(&text, 40.0, 40.0), None, "far above the line");+ assert_eq!(caret_snap(&PageText::default(), 40.0, 100.0), None, "no text");+ for (direction, what) in [([0.0, 1.0], "vertical"), ([-1.0, 0.0], "upside down"), ([0.995, 0.0998], "sloped")] {+ let turned = line("abcd", 20.0, 100.0, 10.0, 14.0, direction);+ let [x0, y0, x1, y1] = turned.glyphs[2].rect;+ assert_eq!(caret_snap(&turned, (x0 + x1) / 2.0, (y0 + y1) / 2.0), None, "{what}");+ }+ }++ #[test]+ fn recent_custom_colours_dedupe_cap_and_skip_swatches() {+ // #1193: "Other colour…" remembers what it applied, newest first.+ let ctx = egui::Context::default();+ assert!(recent_custom_colours(&ctx).is_empty());+ for i in 0..7 {+ remember_custom_colour(&ctx, [0.1 * f64::from(i), 0.3, 0.7]);+ }+ let recent = recent_custom_colours(&ctx);+ assert_eq!(recent.len(), RECENT_CUSTOM, "capped");+ assert!(same_colour(&recent[0], &[0.6, 0.3, 0.7]), "newest first: {recent:?}");+ remember_custom_colour(&ctx, [0.2, 0.3, 0.7]);+ let again = recent_custom_colours(&ctx);+ assert_eq!(again.len(), RECENT_CUSTOM);+ assert!(+ same_colour(&again[0], &[0.2, 0.3, 0.7]) && again.iter().filter(|c| same_colour(c, &[0.2, 0.3, 0.7])).count() == 1,+ "moved, not repeated"+ );+ // Swatches and unusable values are not remembered; out-of-range ones are clamped.+ remember_custom_colour(&ctx, SWATCHES[0].1);+ remember_custom_colour(&ctx, [f64::NAN, 0.0, 0.0]);+ assert!(same_colour(&recent_custom_colours(&ctx)[0], &[0.2, 0.3, 0.7]));+ remember_custom_colour(&ctx, [1.7, -0.5, 0.25]);+ assert!(same_colour(&recent_custom_colours(&ctx)[0], &[1.0, 0.0, 0.25]));+ }++ #[test]+ fn other_colour_applies_the_picked_colour_once() {+ // #1193: the swatch grid has a full picker; Apply returns its colour and remembers it.+ use egui_kittest::kittest::Queryable;+ let current = [0.2, 0.4, 0.6];+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, picked: &mut Vec<Rgb>| {+ if let Some(c) = swatch_grid(ui, Some(current)) {+ picked.push(c);+ }+ },+ Vec::new(),+ );+ h.run();+ assert!(h.query_by_label("Apply").is_none(), "the picker starts closed");+ assert!(h.query_by_label("Recent colours").is_none());+ h.get_by_label("Other colour…").click();+ h.run();+ h.get_by_label("Apply").click();+ h.run();+ let picked = h.state().clone();+ assert_eq!(picked.len(), 1, "one choice: {picked:?}");+ assert!(same_colour(&picked[0], ¤t), "the picker opens on the current colour: {picked:?}");+ assert!(h.query_by_label("Apply").is_none(), "applying closes the picker");+ assert!(h.query_by_label("Recent colours").is_some(), "the colour is offered again");+ }++ #[test]+ fn two_grids_in_one_parent_open_their_pickers_separately() {+ // Redaction properties and Prepare a form draw two grids in one parent ui.+ use egui_kittest::kittest::Queryable;+ let mut h = egui_kittest::Harness::new_ui(|ui| {+ let _ = swatch_grid(ui, Some([0.2, 0.4, 0.6]));+ let _ = swatch_grid(ui, Some([0.6, 0.4, 0.2]));+ });+ h.run();+ let plus = h.query_all_by_label("Other colour…").collect::<Vec<_>>();+ assert_eq!(plus.len(), 2);+ plus[0].click();+ h.run();+ assert_eq!(h.query_all_by_label("Apply").count(), 1, "only the first grid's picker opens");+ }++ #[test]+ fn other_colour_opens_the_picker_inside_the_quick_bar_popup() {+ use egui_kittest::kittest::Queryable;+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, prefs: &mut CommentPrefs| {+ let _ = quick_bar_controls(ui, CommentTool::Highlight, prefs);+ },+ CommentPrefs::default(),+ );+ h.run();+ h.get_by_label("Colour").click();+ h.run();+ h.get_by_label("Other colour…").click();+ h.run();+ assert!(h.query_by_label("Apply").is_some(), "the popup stays open with the picker showing");+ h.get_by_label("Apply").click();+ h.run();+ assert!(h.query_by_label("Other colour…").is_none(), "applying a colour closes the popup");+ }++ #[test]+ fn other_colour_opens_the_picker_inside_the_quick_bar_fill_popup() {+ use egui_kittest::kittest::Queryable;+ let prefs = CommentPrefs::default();+ let fill_label = if prefs.style(CommentTool::Rectangle).fill.is_some() { "Fill colour" } else { "Fill colour: none" };+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, prefs: &mut CommentPrefs| {+ let _ = quick_bar_controls(ui, CommentTool::Rectangle, prefs);+ },+ prefs,+ );+ h.ctx.set_fonts(theme::font_definitions());+ h.run();+ h.get_by_label(fill_label).click();+ h.run();+ h.get_by_label("Other colour…").click();+ h.run();+ assert!(h.query_by_label("Apply").is_some(), "the popup stays open with the picker showing");+ h.get_by_label("Apply").click();+ h.run();+ assert!(h.query_by_label("No fill").is_none(), "applying a colour closes the popup");+ assert!(h.state().style(CommentTool::Rectangle).fill.is_some());+ }++ #[test]+ fn context_menu_colour_submenu_keeps_its_picker_open_and_a_swatch_closes_the_menu() {+ use egui_kittest::kittest::Queryable;+ let info = DocInfo {+ pages: vec![PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 }],+ annotations: vec![Annotation {+ page: 0,+ subtype: "Square".into(),+ author: None,+ contents: None,+ modified: None,+ name: None,+ in_reply_to: None,+ parent: None,+ grouped: false,+ rect: [10.0, 10.0, 50.0, 50.0],+ color: None,+ index: 0,+ state: None,+ quads: Vec::new(),+ locked: false,+ intent: None,+ fill_sign: false,+ points: Vec::new(),+ no_rotate: false,+ }],+ ..Default::default()+ };+ let mut view = DocView::new(pdfcraft_engine::DocId(1), &info, crate::canvas::ViewDefaults::default());+ view.comments.selected = Some((0, 0));+ let prefs = CommentPrefs::default();+ let mut h = egui_kittest::Harness::new_ui_state(+ |ui, (view, actions): &mut (DocView, Vec<CanvasAction>)| {+ ui.button("Page").context_menu(|ui| {+ if let Some(a) = context_menu(ui, view, &info, &prefs, true, true) {+ actions.push(a);+ }+ });+ },+ (view, Vec::new()),+ );+ h.run();+ h.get_by_label("Page").click_secondary();+ h.run();+ h.get_by_label("Colour").click();+ h.run();+ h.get_by_label("Other colour…").click();+ h.run();+ assert!(h.query_by_label("Apply").is_some(), "the submenu stays open with the picker showing");+ h.get_by_label("Red").click();+ h.run();+ assert!(h.query_by_label("Edit text…").is_none(), "picking a swatch closes the whole menu");+ let actions = &h.state().1;+ assert!(+ matches!(actions.as_slice(), [CanvasAction::Edit(e)] if matches!(**e, Edit::StyleAnnotation { page: 0, index: 0, color: Some(_), .. })),+ "{actions:?}"+ );+ }++ #[test]+ fn shift_keeps_the_current_proportions_unless_the_box_has_its_own() {+ let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 132.0));+ assert_eq!(corner_ratio(r, None, false), None);+ assert_eq!(corner_ratio(r, None, true), Some(3.0));+ assert_eq!(corner_ratio(r, Some(2.0), false), Some(2.0));+ assert_eq!(corner_ratio(r, Some(2.0), true), Some(2.0));+ // A degenerate box has no proportions to keep (no division by zero).+ let flat = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 100.0));+ assert_eq!(corner_ratio(flat, None, true), None);+ // Dragging a corner with Shift held scales the box instead of stretching it.+ let out = resized(r, (1, 1), vec2(48.0, 0.0), corner_ratio(r, None, true));+ assert_eq!(out.min, r.min);+ assert!((out.width() / out.height() - 3.0).abs() < 0.001);+ }++ #[test]+ fn proportional_corners_keep_the_opposite_anchor_and_edges_stretch_one_axis() {+ let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 132.0));+ for (hx, hy) in [(-1, -1), (1, -1), (-1, 1), (1, 1)] {+ for (dx, dy) in [(24.0, 0.0), (0.0, 16.0), (-48.0, -20.0), (-200.0, -200.0)] {+ let out = resized(r, (hx, hy), vec2(f32::from(hx) * dx, f32::from(hy) * dy), Some(3.0));+ assert_eq!(handle_pos(out, (-hx, -hy)), handle_pos(r, (-hx, -hy)));+ assert!((out.width() / out.height() - 3.0).abs() < 0.001);+ assert!(out.width() >= 4.0 && out.height() >= 4.0);+ }+ }+ for handle in [(0, -1), (1, 0), (0, 1), (-1, 0)] {+ let out = resized(r, handle, vec2(24.0, 16.0), Some(3.0));+ assert_eq!(out, resized(r, handle, vec2(24.0, 16.0), None));+ assert_eq!(if handle.0 == 0 { out.width() } else { out.height() }, if handle.0 == 0 { r.width() } else { r.height() });+ }+ // Ordinary comment corners keep their existing independent width/height behavior.+ let free = resized(r, (1, 1), vec2(24.0, 0.0), None);+ assert_eq!(free.size(), vec2(120.0, 32.0));+ }++ #[test]+ fn tools_round_trip_through_their_commands() {+ for t in ALL {+ assert_eq!(CommentTool::from_command(t.command()), Some(t));+ assert!(pdfcraft_engine::commands::command(t.command()).is_some(), "{} is registered", t.command());+ assert!(icons::exists(t.icon()), "icon {}", t.icon());+ assert!(GROUPS[t.group()].contains(&t));+ }+ }++ #[test]+ fn drawn_shapes_ignore_slips() {+ assert_eq!(drawn_shape(CommentTool::Rectangle, &[[0.0, 0.0], [1.0, 1.0]]), None);+ assert_eq!(drawn_shape(CommentTool::Rectangle, &[[10.0, 0.0], [0.0, 10.0]]), Some(Shape::Rectangle { rect: [0.0, 0.0, 10.0, 10.0] }));+ assert_eq!(drawn_shape(CommentTool::Ink, &[[0.0, 0.0]]), Some(Shape::Ink { strokes: vec![vec![[0.0, 0.0]]] }));+ assert!(matches!(+ drawn_shape(CommentTool::Arrow, &[[0.0, 0.0], [5.0, 0.0]]),+ Some(Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. })+ ));+ }++ #[test]+ fn text_boxes_fit_their_text() {+ let r = text_box_rect([100.0, 500.0], "Hi", 12.0, 0);+ assert_eq!((r[0], r[3]), (100.0, 500.0));+ assert!(r[2] - r[0] < 60.0);+ let long = text_box_rect([0.0, 500.0], &"word ".repeat(80), 12.0, 0);+ assert_eq!(long[2], 300.0);+ assert!(long[3] - long[1] > 50.0);+ }diff --cc docs/roadmap.mdindex f1c3bfa10,25205e92c..daa80cdde--- a/docs/roadmap.md+++ b/docs/roadmap.md@@@ -1,6 -1,6 +1,7 @@@# PdfCraft roadmap: milestones and what's next+ > **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)+> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M5: one reply in the Comments panel is edited, copied or deleted from its own "…" menu; estimates unchanged)> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)