PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(comments): Delete asks the engine whether it would delete
alehel6a1783599dbf
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rsindex ae7e5a872..f51c64514 100644--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@ -36,8 +36,8 @@ use lookup::{annots, page_ref};pub use lookup::{has_visible_fill_sign, is_fill_sign, isolate_annotation, page_refs, picture_rotation, set_annots, signature_image};pub(crate) use modify::n;pub use modify::{- add_reply, add_text_replacement, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, set_contents, set_fill,- set_font_size, set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,+ add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, set_contents,+ set_fill, set_font_size, set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,};pub use types::{AttachIcon, FillMark, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Rgb, Shape,diff --git a/crates/annot/src/modify.rs b/crates/annot/src/modify.rsindex 8204e6510..2e3ae0b7d 100644--- a/crates/annot/src/modify.rs+++ b/crates/annot/src/modify.rs@@ -72,42 +72,51 @@ pub(crate) fn touch(d: &mut Dict, meta: &Meta) {/// Delete a comment together with its pop-up and its replies (and theirs), as Acrobat does./// Refused while it, or a reply that would go with it, is locked.pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {- remove_with_replies(doc, page, index, true)+ deletable(doc, page, index)?;+ lift_annotation(doc, page, index)}-/// Take the annotation at `(page, index)` out of its page with its pop-up and replies, as-/// [`delete_annotation`] does but whatever their locks: for drawing the page beneath it on a-/// copy of the document (a stamp or signature being dragged), which changes nothing.-pub fn lift_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {- remove_with_replies(doc, page, index, false)-}--fn remove_with_replies(doc: &mut Document, page: usize, index: usize, check_locks: bool) -> Result<(), AnnotError> {- let p = page_ref(doc, page)?;- let list = annots(doc, p);- let target = list.get(index).cloned().ok_or(AnnotError::NoSuchAnnotation { page, index })?;- if check_locks && let Some(r) = target.as_ref() {+/// Whether [`delete_annotation`] deletes the annotation at `(page, index)`, or why not, without+/// changing anything: what a Delete command asks before it is offered. It is refused while the+/// annotation is locked, or a reply that would go with it is.+pub fn deletable(doc: &Document, page: usize, index: usize) -> Result<(), AnnotError> {+ let list = annots(doc, page_ref(doc, page)?);+ let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;+ if let Some(r) = target.as_ref() {unlocked(doc, r)?;}- // An inline comment has no reference to collect; the pop-up it names still goes.- let seed = target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")));- let doomed = with_replies_and_popups(doc, &list, seed);+ let doomed = with_replies_and_popups(doc, &list, seed(target));// A locked reply can't be deleted on its own, so it doesn't go with the comment or reply it// answers either. Pop-ups follow their comment.- if check_locks {- for (_, e) in list.iter().enumerate().filter(|(i, e)| *i != index && goes_with(e, &doomed)) {- let obj = doc.resolve(e);- if let Some(d) = obj.as_dict().filter(|d| d.name(b"Subtype") != Some(b"Popup".as_slice()))- && annotation_flags(doc, d) & FLAG_LOCKED != 0- {- return Err(AnnotError::Invalid("a reply to it is locked".into()));- }+ for (_, e) in list.iter().enumerate().filter(|(i, e)| *i != index && goes_with(e, &doomed)) {+ let obj = doc.resolve(e);+ if let Some(d) = obj.as_dict().filter(|d| d.name(b"Subtype") != Some(b"Popup".as_slice()))+ && annotation_flags(doc, d) & FLAG_LOCKED != 0+ {+ return Err(AnnotError::Invalid("a reply to it is locked".into()));}}- let kept: Vec<Object> = list.into_iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e).collect();+ Ok(())+}++/// Take the annotation at `(page, index)` out of its page with its pop-up and replies, as+/// [`delete_annotation`] does but whatever their locks: for drawing the page beneath it on a+/// copy of the document (a stamp or signature being dragged), which changes nothing.+pub fn lift_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {+ let p = page_ref(doc, page)?;+ let list = annots(doc, p);+ let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;+ let doomed = with_replies_and_popups(doc, &list, seed(target));+ let kept: Vec<Object> = list.iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e.clone()).collect();Ok(set_annots(doc, p, kept)?)}+/// What deleting the `/Annots` entry `target` starts from: its reference, or for an inline+/// comment (which has none to collect) the pop-up it names, which still goes.+fn seed(target: &Object) -> Option<ObjRef> {+ target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")))+}+/// Whether the `/Annots` entry `entry` goes with `going` (from [`with_replies_and_popups`]): it is/// one of them, or it is written inline (a file can, though the standard asks for references) and/// replies to (`/IRT`) or pops up for (`/Parent`) one of them. An inline entry has no referencediff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex f9992a949..a3dc14e26 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -242,11 +242,16 @@ fn a_locked_reply_keeps_what_it_answers() {assert_eq!(delete_annotation(&mut doc, 0, reply), Err(AnnotError::Invalid("a reply to it is locked".into())));assert_eq!(delete_annotation(&mut doc, 0, note), Err(AnnotError::Invalid("a reply to it is locked".into())));assert_eq!(list(&doc, 0).len(), before, "nothing went");+ // Asked first, read-only, as a Delete command does: the same answer, and the answer's own+ // lock is its own.+ assert_eq!(deletable(&doc, 0, note), Err(AnnotError::Invalid("a reply to it is locked".into())));+ assert_eq!(deletable(&doc, 0, answer), Err(AnnotError::Invalid("the comment is locked".into())));// Lifted on a copy, to draw the page beneath, the locks don't count.let mut copy = doc.clone();lift_annotation(&mut copy, 0, note).unwrap();assert!(list(©, 0).len() < before, "the thread is lifted off the copy");set_locked(&mut doc, 0, answer, false).unwrap();+ assert_eq!(deletable(&doc, 0, reply), Ok(()));delete_annotation(&mut doc, 0, reply).unwrap();let left: Vec<String> = list(&doc, 0).iter().map(|d| text(d, b"Contents")).collect();assert!(!left.iter().any(|t| t == "first" || t == "locked answer"), "the reply and its answer went: {left:?}");diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rsindex 7023caa55..6220841f3 100644--- a/crates/engine/src/document.rs+++ b/crates/engine/src/document.rs@@ -305,6 +305,13 @@ impl Document {self.config.hide_comments}+ /// Whether `Edit::DeleteAnnotation` would delete the annotation at `(page, index)`: the+ /// engine's own check (it, and every reply that would go with it, unlocked), for a Delete+ /// command to ask before it is offered.+ pub fn annotation_deletable(&self, page: usize, index: usize) -> bool {+ self.editor.as_ref().is_some_and(|e| pdfcraft_annot::deletable(&e.cos, page, index).is_ok())+ }+pub fn can_undo(&self) -> Option<&str> {self.undo_label().map(Label::as_str)}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex ea37eb0df..ae00e1edf 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2074,7 +2074,8 @@ fn draw_pages(ui.separator();}}- canvas_action = comments::context_menu(ui, view, info, prefs, allowed, can_modify).or(copy_image);+ canvas_action =+ comments::context_menu(ui, view, info, &|page, index| doc.annotation_deletable(page, index), prefs, allowed, can_modify).or(copy_image);});*out = PageOut {badge_hover,diff --git a/crates/ui-egui/src/panels/comments_panel.rs b/crates/ui-egui/src/panels/comments_panel.rsindex 9d49a68c0..c549ed8e3 100644--- a/crates/ui-egui/src/panels/comments_panel.rs+++ b/crates/ui-egui/src/panels/comments_panel.rs@@ -115,13 +115,14 @@ fn any_contains<'a>(fields: impl IntoIterator<Item = &'a str>, q: &str) -> boolpub(crate) fn show(ui: &mut egui::Ui,t: &Tokens,- info: &DocInfo,+ doc: &pdfcraft_engine::Document,view: &mut DocView,prefs: &CommentPrefs,allowed: bool,nav: &mut Option<Nav>,) -> Option<Edit> {crate::widgets::begin_dialog(ui);+ let info = &doc.info;let mut edit = None;// Search (the header's magnifier toggles it).if let Some(q) = view.comments.search.as_mut() {@@ -286,7 +287,7 @@ pub(crate) fn show(}let thread = replies_of(a);let rotation = info.pages.get(a.page).map_or(0, |p| p.rotation);- if let Some(e) = card(ui, view, CardContext { theme: t, annotation: a, rotation, thread, info, prefs, allowed, nav }) {+ if let Some(e) = card(ui, view, CardContext { theme: t, annotation: a, rotation, thread, doc, prefs, allowed, nav }) {edit = Some(e);}}@@ -301,14 +302,15 @@ struct CardContext<'a> {// The clockwise `/Rotate` of the comment's page.rotation: u16,thread: &'a [&'a Annotation],- info: &'a DocInfo,+ doc: &'a pdfcraft_engine::Document,prefs: &'a CommentPrefs,allowed: bool,nav: &'a mut Option<Nav>,}fn card(ui: &mut egui::Ui, view: &mut DocView, context: CardContext<'_>) -> Option<Edit> {- let CardContext { theme: t, annotation: a, rotation, thread, info, prefs, allowed, nav } = context;+ let CardContext { theme: t, annotation: a, rotation, thread, doc, prefs, allowed, nav } = context;+ let info = &doc.info;let mut edit = None;let key = (a.page, a.index);let selected = view.comments.selected == Some(key);@@ -405,7 +407,7 @@ fn card(ui: &mut egui::Ui, view: &mut DocView, context: CardContext<'_>) -> Optiif selected && allowed && !r.grouped {ui.with_layout(Layout::right_to_left(Align::Center), |ui| {let more = icons::button(ui, "ellipsis", 20.0, false, tl!("Options for this reply"));- if let Some(e) = reply_menu(ui, view, r, info, &more) {+ if let Some(e) = reply_menu(ui, view, r, doc, &more) {edit = Some(e);}});@@ -525,10 +527,7 @@ fn card(ui: &mut egui::Ui, view: &mut DocView, context: CardContext<'_>) -> Opti}ui.separator();// A locked reply can't be deleted, so it keeps the comment it answers too.- if ui- .add_enabled(!a.locked && !crate::comments::locked_below(&info.annotations, (a.page, a.index)), egui::Button::new(tl!("Delete")))- .clicked()- {+ if ui.add_enabled(doc.annotation_deletable(a.page, a.index), egui::Button::new(tl!("Delete"))).clicked() {view.comments.selected = None;edit = Some(Edit::DeleteAnnotation { page: a.page, index: a.index });ui.close();@@ -566,7 +565,7 @@ fn inline_editor(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, key: (usize,/// the reply alone, with what hangs off it (its own replies, status changes and pop-up), as/// deleting a comment takes its thread; the comment and its other replies stay. Returns the/// edit to apply.-fn reply_menu(ui: &egui::Ui, view: &mut DocView, r: &Annotation, info: &DocInfo, more: &egui::Response) -> Option<Edit> {+fn reply_menu(ui: &egui::Ui, view: &mut DocView, r: &Annotation, doc: &pdfcraft_engine::Document, more: &egui::Response) -> Option<Edit> {let mut edit = None;let menu_id = ui.scope_id().with(("reply-menu", r.page, r.index));if more.clicked() {@@ -589,10 +588,7 @@ fn reply_menu(ui: &egui::Ui, view: &mut DocView, r: &Annotation, info: &DocInfo,ui.separator();// The card stays selected: the app finds its comment again after the delete. A locked// reply to this one keeps it.- if ui- .add_enabled(!r.locked && !crate::comments::locked_below(&info.annotations, (r.page, r.index)), egui::Button::new(tl!("Delete")))- .clicked()- {+ if ui.add_enabled(doc.annotation_deletable(r.page, r.index), egui::Button::new(tl!("Delete"))).clicked() {edit = Some(Edit::DeleteAnnotation { page: r.page, index: r.index });ui.close();}diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rsindex 0470543ac..a4bb7e62f 100644--- a/crates/ui-egui/src/panels/right.rs+++ b/crates/ui-egui/src/panels/right.rs@@ -178,7 +178,7 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {}egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| match panel {RightPanel::Comments => {- if let Some(e) = crate::comments_panel::show(ui, &t, info, view, prefs, comment_allowed, &mut nav) {+ if let Some(e) = crate::comments_panel::show(ui, &t, doc, view, prefs, comment_allowed, &mut nav) {panel_edit = Some(e);}}diff --git a/crates/ui-egui/src/tools/comments.rs b/crates/ui-egui/src/tools/comments.rsindex d86a0d58d..6f3c07442 100644--- a/crates/ui-egui/src/tools/comments.rs+++ b/crates/ui-egui/src/tools/comments.rs@@ -47,7 +47,7 @@ use paint::{changing_points, drawn_shape, edited_in_view};use state::after_delete;use state::login_name;pub use state::{CommentView, Composer, ComposerKind, Gesture, SortBy};-pub(crate) use state::{EditorFocus, PageCx, locked_below};+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);diff --git a/crates/ui-egui/src/tools/comments/menu.rs b/crates/ui-egui/src/tools/comments/menu.rsindex 0ce50e507..52ea8d707 100644--- a/crates/ui-egui/src/tools/comments/menu.rs+++ b/crates/ui-egui/src/tools/comments/menu.rs@@ -1,5 +1,5 @@use super::paint::edit_anchor;-use super::state::{Composer, ComposerKind, locked_below};+use super::state::{Composer, ComposerKind};use super::{Annotation, Color32, CommentPrefs, CommentTool, DocInfo, DocView, Edit, Rect, ReviewState, Rgb, SELECT_BLUE, SWATCHES, Sense, Stroke, color32,icons, theme, tool_for, vec2,@@ -24,10 +24,13 @@ pub(crate) fn attachment_items(ui: &mut egui::Ui, view: &mut DocView, info: &Doc/// Items of the canvas context menu for the selected comment (or the page)./// `can_modify`: the document's pages may change (Flatten comments draws into them).+/// `deletable`: whether Delete would delete the comment at (page, index) (the engine's+/// `Document::annotation_deletable`: unlocked, and no locked reply to it).pub(crate) fn context_menu(ui: &mut egui::Ui,view: &mut DocView,info: &DocInfo,+ deletable: &dyn Fn(usize, usize) -> bool,prefs: &CommentPrefs,allowed: bool,can_modify: bool,@@ -89,8 +92,8 @@ pub(crate) fn context_menu(ui.close();}ui.separator();- // A locked reply can't be deleted, so it keeps the comment it answers too.- if ui.add_enabled(allowed && !a.locked && !locked_below(&info.annotations, (page, index)), egui::Button::new(tl!("Delete"))).clicked() {+ // The engine's own check: a locked comment, or one with a locked reply, stays.+ if ui.add_enabled(allowed && deletable(page, index), egui::Button::new(tl!("Delete"))).clicked() {view.comments.selected = None;action = Some(CanvasAction::Edit(Box::new(Edit::DeleteAnnotation { page, index })));ui.close();diff --git a/crates/ui-egui/src/tools/comments/state.rs b/crates/ui-egui/src/tools/comments/state.rsindex c9ca91fb0..db4504190 100644--- a/crates/ui-egui/src/tools/comments/state.rs+++ b/crates/ui-egui/src/tools/comments/state.rs@@ -275,14 +275,6 @@ fn in_thread(page: &[&Annotation], top: (usize, usize)) -> impl Fn(usize) -> boo}}-/// Whether a reply to the annotation at `top`, at any depth, is locked: deleting it is refused-/// then, as the reply can't be deleted.-pub(crate) fn locked_below(annotations: &[Annotation], top: (usize, usize)) -> bool {- let page = on_page(annotations, top.0);- let goes = in_thread(&page, top);- page.iter().any(|a| a.index != top.1 && a.locked && goes(a.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();diff --git a/crates/ui-egui/src/tools/comments/tests.rs b/crates/ui-egui/src/tools/comments/tests.rsindex 36644bb44..2d6641f2d 100644--- a/crates/ui-egui/src/tools/comments/tests.rs+++ b/crates/ui-egui/src/tools/comments/tests.rs@@ -90,25 +90,6 @@ fn listed(page: usize, index: usize, contents: &str, parent: Option<(usize, usiz}}-/// A locked reply at any depth keeps what it answers, up its own chain only: its comment, the-/// reply above it, but not a sibling reply or a comment on another page.-#[test]-fn a_locked_reply_keeps_the_replies_and_comment_above_it() {- let lock = |a: Annotation| Annotation { locked: true, ..a };- let list = vec![- listed(0, 0, "comment", None),- listed(0, 1, "A", Some((0, 0))),- lock(listed(0, 2, "to A, locked", Some((0, 1)))),- listed(0, 3, "B", Some((0, 0))),- listed(1, 0, "other page", None),- ];- assert!(locked_below(&list, (0, 0)), "the comment");- assert!(locked_below(&list, (0, 1)), "the reply above the locked one");- assert!(!locked_below(&list, (0, 2)), "the locked reply itself: its own lock says so");- assert!(!locked_below(&list, (0, 3)), "a sibling reply");- assert!(!locked_below(&list, (1, 0)), "another page");-}-/// 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.@@ -371,7 +352,7 @@ fn context_menu_colour_submenu_keeps_its_picker_open_and_a_swatch_closes_the_menlet 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) {+ if let Some(a) = context_menu(ui, view, &info, &|_, _| true, &prefs, true, true) {actions.push(a);}});diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex c4670a584..4f897b489 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -4003,7 +4003,7 @@ milestone = "M5"status = "shipped"commands = ["comment.list"]tools = ["comment_delete"]-evidence = ["crates/ui-egui/tests/it/comments.rs::comments_are_selected_moved_and_deleted_with_the_select_tool", "crates/annot/src/tests.rs::delete_takes_popup_and_reply_chain", "crates/ui-egui/tests/it/comments.rs::one_reply_is_deleted_from_its_menu_and_the_thread_stays", "crates/ui-egui/src/tools/comments/tests.rs::a_kept_comment_is_found_where_a_delete_moved_it", "crates/automation/tests/it/automation.rs::deleting_a_reply_keeps_its_comment_and_the_other_replies", "crates/annot/src/tests.rs::a_locked_reply_keeps_what_it_answers", "crates/ui-egui/src/tools/comments/tests.rs::a_locked_reply_keeps_the_replies_and_comment_above_it", "crates/engine/src/tests.rs::a_stamp_with_a_locked_reply_still_has_its_drag_layers"]+evidence = ["crates/ui-egui/tests/it/comments.rs::comments_are_selected_moved_and_deleted_with_the_select_tool", "crates/annot/src/tests.rs::delete_takes_popup_and_reply_chain", "crates/ui-egui/tests/it/comments.rs::one_reply_is_deleted_from_its_menu_and_the_thread_stays", "crates/ui-egui/src/tools/comments/tests.rs::a_kept_comment_is_found_where_a_delete_moved_it", "crates/automation/tests/it/automation.rs::deleting_a_reply_keeps_its_comment_and_the_other_replies", "crates/annot/src/tests.rs::a_locked_reply_keeps_what_it_answers", "crates/engine/src/tests.rs::a_stamp_with_a_locked_reply_still_has_its_drag_layers"]notes = "deletes the pop-up and the reply thread. One reply is deleted from its own \"…\" in the Comments panel (comment_delete with the reply's id, or page and index), with its pop-up and the replies to it: the comment and its other replies stay, one undo step, and the card stays selected. A locked reply can't be deleted, nor the comment or reply it answers while it is locked (their Delete is greyed out; a stamp or signature with a locked reply still drags with its live preview)."[[feature]]