diff --git a/ROADMAP.md b/ROADMAP.md index 80ed00b40a..8465f9f68b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -345,6 +345,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-29 (M7, #2517):** Widening a paragraph rejoins a wrap with the number of spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split. The count survives an incremental save and a full rewrite, and a width-only `text_edit` uses it. Estimates unchanged. - **2026-10-29 (M2):** Scanned pages look like the paper again. An image that doesn't ask for /Interpolate was shrunk by nearest-neighbour (since #635), which kept one sample in N per axis, so the text of a 300 dpi scan at 100% lost most of its strokes; it is now area-averaged to whole device pixels (on a 13-page 300 dpi scan every sample at 96–192 dpi is within 1 of the exact area average; it was up to 255 off). Enlarged, an image of page-scan size is smoothed bilinearly, so a zoomed scan has no staircases; icons, QR codes and pixel art keep hard pixels. Estimates unchanged. - **2026-10-26 (M11, JBIG2 symbols):** Lossless JBIG2 now stores each distinct mark of a black-and-white image once, as a symbol, and places its exact copies, when that is smaller than the generic region: on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's, and the same bits back through two independent decoders (hayro-jbig2 and Poppler). Scans, whose letters are seldom identical, gain little until refinement coding; a dictionary shared between pages (`/JBIG2Globals`) is next. Estimates unchanged. +- **2026-10-26 (M3, view.text-select):** Text selection runs across pages: dragging onto another page (also a quick flick off the page, and the edge and wheel scrolling of #721/#1670) or ⇧-clicking there selects the rest of the first page, the pages between and the last page up to the pointer. Copy has each page's part on a line of its own, reading pages not yet read off the UI thread; highlight, underline, strikethrough and Redact put one mark on each page in one undo step (a tool that finishes first marks once the pages are read; Redact refuses a selection over a page whose text could not be read); Add comment and Replace text stay one-page. A drag from one page's text that is already over the next when it starts no longer begins a Redact or area-highlight box there. Estimates unchanged. - **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`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged. - **2026-10-25 (M7, #2750):** Single-style Keep source fonts edits retain source glyphs and batch only missing glyphs in fallback fonts. Per-rewrite character eligibility and widths are cached; source and fallback edge spaces stay extractable. Estimates unchanged. - **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes. diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index ce4b60bcd3..7d9e5320a4 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -77,7 +77,10 @@ impl PdfCraftApp { if objects { self.copy_objects(i, ctx, cut); } - let text_selected = copy && self.views.get(i).and_then(|v| v.selected_text()).is_some_and(|t| !t.is_empty()); + // A selection across pages still being read has no text yet, but is selected all the + // same: ⌘C starts its copy rather than copying the selected comments. + let text_selected = + copy && self.views.get(i).is_some_and(|v| v.selection_waits_for_text().is_some() || v.selected_text().is_some_and(|t| !t.is_empty())); if copy && !objects && (text_selected || !self.copy_selected_comments(i)) @@ -313,12 +316,19 @@ impl PdfCraftApp { self.document_copy = None; let Some(v) = self.views.get(i) else { return false }; let id = v.id; - if v.all_text && !v.pages_without_text().is_empty() { + // So are a selection's pages not read yet (a selection across pages copied before every + // page it covers has its text), rather than copying nothing. + let waiting = v.selection_waits_for_text(); + if (v.all_text && !v.pages_without_text().is_empty()) || waiting.is_some() { // Checked before any page is read: a document that refuses copying reads nothing. if !self.may_copy(id) { return false; } - let Some(job) = self.views.get(i).and_then(|v| Some(DocumentCopyJob::of(v, self.session.get(id)?))) else { return false }; + let job = |v: &crate::DocView, doc: &pdfcraft_engine::Document| match waiting { + Some(span) if !v.all_text => DocumentCopyJob::of_selection(v, doc, span), + _ => DocumentCopyJob::of(v, doc), + }; + let Some(job) = self.views.get(i).and_then(|v| Some(job(v, self.session.get(id)?))) else { return false }; self.document_copy = Some(DocumentCopy::start(id, job, ctx)); return true; } @@ -608,4 +618,27 @@ mod review_tests { .drop_without_applying_deltas(); assert!(app.views[0].image_selection.is_some()); } + + /// Review of #5017: ⌘C on a text selection still waiting for its pages' text starts its copy, + /// even with a comment selected too, rather than copying the comment. + #[test] + fn a_selection_waiting_for_its_text_takes_copy_over_a_selected_comment() { + let mut app = PdfCraftApp::new(); + app.system_clipboard = false; + app.create_blank(); + let shape = pdfcraft_engine::Shape::Rectangle { rect: [10.0, 10.0, 50.0, 50.0] }; + let style = pdfcraft_engine::Style::default_for(&shape); + let note = pdfcraft_engine::NewAnnotation { page: 0, shape, style, contents: String::new(), author: String::new() }; + assert!(app.apply_edit(pdfcraft_engine::Edit::AddAnnotation(note))); + app.views[0].comments.select_only((0, 0)); + // The page's text is not read yet: the selection waits for it. + app.views[0].texts.clear(); + app.views[0].select_text(0, 0, 0); + assert!(app.views[0].selection_waits_for_text().is_some()); + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput { events: vec![egui::Event::Copy], ..Default::default() }, |ui| app.clipboard_keys(0, ui.ctx())) + .drop_without_applying_deltas(); + assert!(app.document_copy.is_some(), "the selection's copy started"); + assert!(app.comment_clipboard.is_none(), "the comment was not copied"); + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b835dd652c..5ef59e76aa 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -69,7 +69,8 @@ use organize::organize_grid; use organize::sharp_enough; pub(crate) use page_input::PageToolContext; use page_input::{PageInput, cancel_on_escape, page_overlays, page_tool_input, text_layer}; -use selection::{Selection, Span, click_unit, selection_actions}; +use selection::{Selection, Span, click_unit, selection_actions, start_selection_drag}; +pub(crate) use selection::{TextSpan, ToolMarks}; pub use xform::PageXform; use xform::snap_to_pixels; use zoom::anchored_scroll; @@ -479,6 +480,9 @@ pub(crate) fn snapshot_tab_name(title: &str, file_name: &str, snapshot: &Snapsho } } +/// Markup quadrilaterals in user space, one entry per page: (page, quads). +pub type PageMarks = Vec<(usize, Vec<[f64; 8]>)>; + pub struct DocView { /// Where the tab shows (split view's panes) and the key that tells two /// views of one document apart (`crate::panes`). @@ -601,6 +605,9 @@ pub struct DocView { /// The drag in progress started a text selection: the wheel scrolls the page during it /// (#721), which egui's scroll area refuses while anything is dragged. selection_drag: bool, + /// The frame a text-selection drag is released: `selection_drag` is already off, but the + /// pages still extend the selection to where it was let go. + selection_drag_ended: bool, /// Clicks in the current run on the text layer: two select a word, three the line, four the page. clicks: u32, last_press_time: f64, @@ -703,9 +710,13 @@ pub struct DocView { pub content: crate::content_ui::ContentView, /// Edit a PDF ▸ Link tool state. pub links: crate::link_ui::LinkView, - /// Redact tool: the box being drawn, and a mark to add (page, quads) for the app to style. + /// Redact tool: the box being drawn, and the marks to add (page, quads) for the app to style, + /// one per page (a text selection can cover several), added in one undo step. pub redact_drag: crate::redact_ui::AreaDrag, - pub pending_redaction: Option<(usize, Vec<[f64; 8]>)>, + /// With the tool that made them, read when they are styled: a key handled later in the same + /// frame (Escape back to Select) must not turn an area highlight into a redaction. + /// The last field is the page the marks are followed up on (where a selection ended). + pub pending_redaction: Option<(QuickTool, PageMarks, usize)>, /// How many Apply redactions steps are in effect in this view. While it is above 0, Save /// proposes the name with `_Redacted` ([`pdfcraft_engine::redacted_file_name`]), and while it is /// above `redactions_downloaded`, Save asks where. @@ -724,6 +735,17 @@ pub struct DocView { /// `redactions_applied` is below it, a delivered step is undone and Save asks where. A desktop /// save leaves it at 0. pub redactions_downloaded: usize, + /// A text selection Redact did not mark: it covers a page whose text could not be read + /// ([`ToolMarks::Unreadable`]). The app says so. + pub(crate) redaction_refused: bool, + /// The next edit applied is markup on a text selection across pages, one comment per page in + /// one batch ([`DocView::selection_marks_edit`]): `apply_edit` follows it up as one markup and + /// takes this back, whatever becomes of the edit. It holds the page the selection ends on, + /// whose markup is followed up. + pub(crate) marks_across_pages: Option, + /// A marking tool finished this text selection while a page it covers was still to be read + /// (or none was drawn): it is marked once they are ([`DocView::tool_marks`]). + marks_waiting: Option<(QuickTool, Selection)>, /// A crop rectangle being dragged (Crop tool). pub crop_drag: crate::crop::CropDrag, /// Enhance ▸ Camera image: the quadrilateral being placed. @@ -1000,6 +1022,7 @@ impl DocView { self.org_drag = None; self.panel_drag = None; self.selection_drag = false; + self.selection_drag_ended = false; self.router.cancel(); self.auto_scroll.cancel(); self.prepare.cancel_pointer_gesture(); @@ -1081,6 +1104,7 @@ impl DocView { all_text: false, actions_dismissed: None, selection_drag: false, + selection_drag_ended: false, clicks: 0, last_press_time: 0.0, last_press_pos: None, @@ -1160,6 +1184,9 @@ impl DocView { redactions_undone_after_save: 0, saved_redactions_cut_off: false, redactions_downloaded: 0, + redaction_refused: false, + marks_across_pages: None, + marks_waiting: None, crop_drag: None, camera: None, camera_done: None, @@ -1870,6 +1897,7 @@ fn draw_pages( let (resp_rect, resp) = ui.allocate_exact_size(response_size, Sense::click_and_drag()); view.page_widget = Some(resp.id); // A drag lasts only while egui reports it, so the mark can't outlive one. + view.selection_drag_ended = view.selection_drag && resp.drag_stopped_by(egui::PointerButton::Primary); if !resp.dragged_by(egui::PointerButton::Primary) { view.selection_drag = false; } @@ -2018,7 +2046,8 @@ fn draw_pages( } } // Held at the top or bottom edge, or dragged past it, a text selection scrolls the view - // so it can reach text off screen (#1670); the selection follows the pointer on its page. + // so it can reach text off screen (#1670); the selection follows the pointer, onto the + // pages it scrolls to. if view.selection_drag && navigation_enabled && unobstructed @@ -2195,7 +2224,9 @@ fn draw_pages( canvas_action = copy_image; } let (page, at) = view.comments.context_at.unwrap_or((view.current, [0.0, 0.0])); - let can_copy_items = can_copy && (view.image_selection.is_some() || view.selected_text().is_some() || has_copy_image); + // A text selection whose pages are still being read copies once they are. + let has_text = view.selected_text().is_some() || view.selection_waits_for_text().is_some(); + let can_copy_items = can_copy && (view.image_selection.is_some() || has_text || has_copy_image); let can_paste = can_paste_image && can_modify; let perms = PageMenuPerms { can_modify, @@ -2587,6 +2618,11 @@ fn plan_renders(ui: &egui::Ui, view: &mut DocView, info: &DocInfo, renders: Page // the rest, as text far away is let go to bound memory.) let need_text = |p: &usize| !view.texts.contains_key(p) && !view.text_failed.contains(p); let mut text_pages: Vec = if hand { Vec::new() } else { visible_now.iter().copied().filter(need_text).collect() }; + // A selection across pages copies and marks every page it covers, scrolled past or not. + if let Some(s) = view.selection { + let rest: Vec = s.pages().filter(|p| *p < info.pages.len()).filter(need_text).filter(|p| !text_pages.contains(p)).collect(); + text_pages.extend(rest); + } if view.find.as_ref().is_some_and(|f| !f.case_query.trim().is_empty()) { let n = info.pages.len(); let rest: Vec = (0..n).map(|k| (cur + k) % n).filter(need_text).filter(|p| !text_pages.contains(p)).collect(); @@ -3681,21 +3717,31 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, if let Some((page, i)) = app.views[index].links.open_existing.take() { app.open_link_props(page, None, Some(i)); } - if let Some((page, quads)) = app.views[index].pending_redaction.take() { + if std::mem::take(&mut app.views[index].redaction_refused) { + app.notify_tr("Part of the selected text is on a page whose text could not be read, so nothing was marked for redaction. Mark that page with a box instead."); + } + if let Some((made_by, marks, head)) = app.views[index].pending_redaction.take() { let author = app.comment_prefs.author.clone(); - app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) { - // An area highlight: a highlight over the box. - let style = app.comment_prefs.style(comments::CommentTool::Highlight); - pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { - page, - shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads }, - style, - contents: String::new(), - author, + let edits: Vec = marks + .into_iter() + .map(|(page, quads)| { + if made_by == QuickTool::Comment(comments::CommentTool::Highlight) { + // An area highlight: a highlight over the box. + let style = app.comment_prefs.style(comments::CommentTool::Highlight); + pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { + page, + shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads }, + style, + contents: String::new(), + author: author.clone(), + }) + } else { + app.redact_prefs.mark(page, quads, &author) + } }) - } else { - app.redact_prefs.mark(page, quads, &author) - }); + .collect(); + let edit = app.views[index].selection_marks_edit(edits, head); + app.views[index].pending_edit = edit; } match image_action { Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index), @@ -3743,7 +3789,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, Some(PageMenuAction::Copy) => { if let Some(sel) = app.views[index].image_selection.clone() { app.copy_page_image(sel.page, sel.index); - } else if app.views[index].selected_text().is_some() { + } else if app.views[index].selected_text().is_some() || app.views[index].selection_waits_for_text().is_some() { app.execute("edit.copy"); } else if let Some((page, at)) = app.views[index].comments.context_at && let Some(doc) = app.session.get(app.views[index].id) diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rs index 2b2e519f4c..4b9f596bec 100644 --- a/crates/ui-egui/src/canvas/cache.rs +++ b/crates/ui-egui/src/canvas/cache.rs @@ -196,7 +196,9 @@ impl DocView { self.slow_pages.clear(); self.waiting_since.clear(); self.last_queue.clear(); + // Marks a tool waits to make go with the selection: its glyphs may name other text now. self.selection = None; + self.marks_waiting = None; self.all_text = false; // A content change is not reader navigation: keep the automatic anchor so the // re-extracted layers still follow it, and keep `follow_ended` so a reader who already @@ -238,8 +240,10 @@ impl DocView { self.errors.remove(&page); self.cut_pages.remove(&page); self.last_queue.clear(); - if self.selection.is_some_and(|s| s.page == page) { + if self.selection.is_some_and(|s| s.pages().contains(&page)) { + // With the marks a tool waits to make on it (#5017 review). self.selection = None; + self.marks_waiting = None; } } @@ -559,7 +563,7 @@ impl DocView { } let mut keep: HashSet = self.frame_visible.clone(); if let Some(s) = self.selection { - keep.insert(s.page); + keep.extend(s.pages()); } if let Some(f) = self.find.as_ref() { keep.extend(f.matches.iter().map(|(p, _)| *p)); diff --git a/crates/ui-egui/src/canvas/navigation.rs b/crates/ui-egui/src/canvas/navigation.rs index 0fdb2d3bfd..1dfadf0963 100644 --- a/crates/ui-egui/src/canvas/navigation.rs +++ b/crates/ui-egui/src/canvas/navigation.rs @@ -14,15 +14,19 @@ impl DocView { if self.organize { return None; } + // Across pages, the corner is on the selection's first page. + let first = self.selection.map(|s| *s.pages().start()); if let Some(sel) = self.selection - && let Some(text) = self.texts.get(&sel.page) - && let Some(p) = info.pages.get(sel.page) + && let Some(first) = first + && let Some(text) = self.texts.get(&first) + && let Some(p) = info.pages.get(first) { // The selection's bounds in view space, which View ▸ Rotate View leaves unturned: the // corner at the screen's top-left is a different one for each quarter turn. - let [x0, y0, x1, y1] = sel.rects(text).iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, r| { - [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])] - }); + let [x0, y0, x1, y1] = + sel.rects_on(first, text).iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, r| { + [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])] + }); let (x, y) = match self.rotation { 90 => (x0, y1), 180 => (x1, y1), @@ -30,7 +34,7 @@ impl DocView { _ => (x0, y0), }; if x.is_finite() && y.is_finite() { - return Some((sel.page, p.xyz_for_view(Some(x), Some(y)))); + return Some((first, p.xyz_for_view(Some(x), Some(y)))); } } // The page showing at the window's top edge: one that crosses it (the first, in a spread diff --git a/crates/ui-egui/src/canvas/page_input.rs b/crates/ui-egui/src/canvas/page_input.rs index e3fd66e70a..5964afa4ed 100644 --- a/crates/ui-egui/src/canvas/page_input.rs +++ b/crates/ui-egui/src/canvas/page_input.rs @@ -7,7 +7,7 @@ use pdfcraft_render::{DocInfo, LinkTarget, PageText}; use super::area::{SignTab, paint_sign_tab, sign_tab_at, sign_tabs}; use super::{ DocView, MARK_ICON_SHARE, PageEnv, PageFrame, PageSlot, PageXform, Selection, Span, cached_edit_images, click_unit, mark_anchor, - signature_badges, verdict_mark_rect, + signature_badges, start_selection_drag, verdict_mark_rect, }; use crate::page_cursor::{Layer, Subject}; use crate::page_keys::PageKeys; @@ -208,7 +208,7 @@ pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut let (vx, vy) = xf.screen_to_view(p); text.as_ref().is_some_and(|t| t.glyph_at(vx, vy).is_some()) }; - crate::redact_ui::page_input(cx, over_text, press == PagePress::Free, view) + crate::redact_ui::page_input(cx, tool, over_text, press == PagePress::Free, view) }; // Edit text's group: the objects selected together, added content, the paragraphs and the // pictures, each told what the press is to this page. Edit text ignores input while a dialog, @@ -685,6 +685,20 @@ pub(super) fn text_layer(ui: &mut egui::Ui, view: &mut DocView, frame: &mut Page let over_link = input.hover.as_ref().is_some_and(|h| matches!(h.owner, Owner::Link { .. } | Owner::TextLink { .. })); let pointer = TextPointer { page: i, xf, rect: r, tool, resp, ptr: ptr.clone(), pointer: p, over_link, text_drag: input.text_drag }; text_pointer_input(ui, view, &text, pointer); + } else if selects_text + && !input.consumed + && input.text_drag + && input.press != PagePress::Elsewhere + && ptr.drag_started + && let (Some(origin), Some(p)) = (ptr.origin, pointer) + { + // A quick drag can leave the page it was pressed on before egui calls it a drag (a + // flick off the bottom of a page, onto the gap or the next page): the press is still + // this page's, so it starts the selection here, for the next page to extend. A press + // something on the page keeps (a link, a comment) selects nothing. + let column = tool == QuickTool::ColumnSelect || ui.input(|input| input.modifiers.alt); + let clicks = selection_click_count(view.clicks, tool); + start_selection_drag(view, i, &text, clicks, column, xf.screen_to_view(origin), xf.screen_to_view(p)); } } } @@ -712,8 +726,8 @@ fn paint_text_marks(ui: &egui::Ui, view: &DocView, text: &PageText, page: usize, painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70)); } } - if let Some(selection) = view.selection.filter(|selection| selection.page == page) { - for line_rect in selection.rects(text) { + if let Some(selection) = view.selection.filter(|selection| selection.pages().contains(&page)) { + for line_rect in selection.rects_on(page, text) { painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70)); } if let Span::Column { rect } = selection.span @@ -796,17 +810,9 @@ fn update_selection_on_press(ui: &egui::Ui, view: &mut DocView, text: &PageText, } } if gesture.ptr.drag_started && press_here && gesture.text_drag { - view.actions_dismissed = None; - view.selection_drag = true; - let origin = gesture.ptr.origin.unwrap_or(gesture.pointer); - let (ox, oy) = gesture.xf.screen_to_view(origin); - if view.clicks < 2 { - view.selection = if gesture.column { - Some(Selection { page: gesture.page, span: Span::Column { rect: [ox, oy, gesture.vx, gesture.vy] } }) - } else { - text.nearest(ox, oy).map(|anchor| Selection::run(gesture.page, anchor, anchor)) - }; - } + let origin = gesture.xf.screen_to_view(gesture.ptr.origin.unwrap_or(gesture.pointer)); + let clicks = selection_click_count(view.clicks, gesture.tool); + start_selection_drag(view, gesture.page, text, clicks, gesture.column, origin, (gesture.vx, gesture.vy)); } } @@ -816,46 +822,84 @@ fn selection_click_count(clicks: u32, tool: QuickTool) -> u32 { fn update_dragged_selection(view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) { let clicks = selection_click_count(view.clicks, gesture.tool); - if gesture.resp.dragged_by(egui::PointerButton::Primary) - && let Some(selection) = view.selection.as_mut().filter(|selection| selection.page == gesture.page) + // The drag extends the selection on its own page and, for a reading-order selection the drag + // started, on any page the pointer moves on to. Its release frame too: a quick flick back + // onto an earlier page, drawn before the page that started the drag, may be over it only then. + let selecting = view.selection_drag || view.selection_drag_ended; + if (gesture.resp.dragged_by(egui::PointerButton::Primary) || gesture.resp.drag_stopped_by(egui::PointerButton::Primary)) + && let Some(mut selection) = + view.selection.filter(|selection| selection.page == gesture.page || (selecting && matches!(selection.span, Span::Run { .. }))) { - match &mut selection.span { - Span::Run { anchor, head, head_x } if clicks >= 2 => { - if let Some(hit) = text.nearest(gesture.vx, gesture.vy) - && let Some((first, last)) = click_unit(text, clicks, *anchor) - { - let (to_first, to_last) = click_unit(text, clicks, hit).unwrap_or((hit, hit)); - // A drag, so it selects table rows as a plain drag does, by whole units. - // The page unit (four clicks) is the page's text in reading order. - *head_x = Some(gesture.vx).filter(|x| x.is_finite() && clicks < 4); - let in_order = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) }; - // Rows take both units whole, from the earlier one's start to the later one's end. - let by_rows = text.row_ends((first, last), (to_first, to_last)); - let rows = head_x.is_some() && text.visual_between(by_rows.0, by_rows.1, *head_x).is_some(); - (*anchor, *head) = if rows { by_rows } else { in_order }; + let hit = text.nearest(gesture.vx, gesture.vy); + match selection.span { + Span::Run { .. } if clicks >= 2 => { + if let Some(hit) = hit { + if selection.page == gesture.page { + // Same page: also select table rows by whole units, as a plain drag does. + extend_by_unit_on_page(&mut selection, text, clicks, hit, gesture.vx); + } else { + extend_by_unit(view, &mut selection, text, clicks, (gesture.page, hit)); + } } } - Span::Run { head, head_x, .. } => { - if let Some(hit) = text.nearest(gesture.vx, gesture.vy) { - *head = hit; - *head_x = Some(gesture.vx).filter(|x| x.is_finite()); + Span::Run { .. } => { + if let Some(hit) = hit { + selection.extend_to_at(gesture.page, hit, Some(gesture.vx).filter(|x| x.is_finite())); } } - Span::Column { rect } => { - rect[2] = gesture.vx; - rect[3] = gesture.vy; - } + Span::Column { rect } => selection.span = Span::Column { rect: [rect[0], rect[1], gesture.vx, gesture.vy] }, } + view.selection = Some(selection); } if gesture.resp.drag_stopped() && view.selection.is_some_and(|selection| { - selection.page == gesture.page && matches!(selection.span, Span::Column { .. }) && selection.text(text).is_empty() + selection.page == gesture.page && matches!(selection.span, Span::Column { .. }) && selection.text_on(gesture.page, text).is_empty() }) { view.selection = None; } } +/// After a multi-click the drag extends by its unit (#1685), as in Acrobat and browsers: whole +/// words or lines, always keeping the one clicked, which holds the anchor whichever way the drag +/// went. On another page than the one clicked, the clicked unit is read from its own page. +fn extend_by_unit(view: &DocView, selection: &mut Selection, text: &PageText, clicks: u32, (page, hit): (usize, usize)) { + let Span::Run { anchor, .. } = selection.span else { return }; + let start_page = selection.page; + let other = if start_page == page { None } else { view.texts.get(&start_page).cloned() }; + let anchor_text = match other.as_deref() { + Some(t) => t, + None if start_page == page => text, + None => return, + }; + let Some((first, last)) = click_unit(anchor_text, clicks, anchor) else { return }; + let (to_first, to_last) = click_unit(text, clicks, hit).unwrap_or((hit, hit)); + // (page, glyph) pairs compare in reading order. + let (anchor, head) = if (page, to_first) < (start_page, first) { + (last, to_first) + } else if page == start_page { + (first, to_last.max(last)) + } else { + (first, to_last) + }; + selection.span = Span::Run { anchor, head, head_page: page, head_x: None }; +} + +/// After a multi-click, a same-page drag extends by its unit and, over a table, by visual rows +/// (the rest of the first row, the rows between, the start of the last). The page unit (four +/// clicks) is the page's text in reading order, so it has no `head_x`. +fn extend_by_unit_on_page(selection: &mut Selection, text: &PageText, clicks: u32, hit: usize, vx: f32) { + let Span::Run { anchor, head, head_page, head_x } = &mut selection.span else { return }; + let Some((first, last)) = click_unit(text, clicks, *anchor) else { return }; + let (to_first, to_last) = click_unit(text, clicks, hit).unwrap_or((hit, hit)); + *head_x = Some(vx).filter(|x| x.is_finite() && clicks < 4); + let in_order = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) }; + let by_rows = text.row_ends((first, last), (to_first, to_last)); + let rows = head_x.is_some() && text.visual_between(by_rows.0, by_rows.1, *head_x).is_some(); + (*anchor, *head) = if rows { by_rows } else { in_order }; + *head_page = selection.page; +} + fn finish_text_pointer_gesture(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) { let release_clicks = if gesture.resp.triple_clicked() { view.clicks.max(2).saturating_add(1) @@ -876,14 +920,14 @@ fn finish_text_pointer_gesture(ui: &egui::Ui, view: &mut DocView, text: &PageTex { view.selection = Some(Selection::run(gesture.page, first, last)); } else if gesture.resp.clicked() && view.clicks < 2 && gesture.text_drag { + // ⇧-click extends a reading-order selection to the click, on its page or another, + // keeping its anchor (#527). Otherwise (no shift, no selection, or a column selection, + // which has no anchor glyph) a click clears the selection. let shift = ui.input(|input| input.modifiers.shift); - match ( - view.selection.as_mut().filter(|selection| shift && selection.page == gesture.page).map(|selection| &mut selection.span), - text.nearest(gesture.vx, gesture.vy), - ) { - (Some(Span::Run { head, head_x, .. }), Some(hit)) => { - *head = hit; - *head_x = Some(gesture.vx).filter(|x| x.is_finite()); + match (view.selection.as_mut().filter(|selection| shift && matches!(selection.span, Span::Run { .. })), text.nearest(gesture.vx, gesture.vy)) + { + (Some(selection), Some(hit)) => { + selection.extend_to_at(gesture.page, hit, Some(gesture.vx).filter(|x| x.is_finite())); } _ => view.selection = None, } diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 57af908cbe..c1c085595a 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -1,6 +1,9 @@ use super::{Arc, DocInfo, DocView, Edit, HashMap, PageText, Pos2, Range, Rect, comments, pos2}; +use crate::QuickTool; +use std::ops::RangeInclusive; -/// A text selection on one page. +/// A text selection. `page` is the page it started on: a column selection stays there, a +/// reading-order one may run on to other pages. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct Selection { pub(super) page: usize, @@ -9,10 +12,13 @@ pub(super) struct Selection { #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Span { - /// Reading order, between two glyph indices. `head_x` is where a drag's pointer ended (page - /// view space), which may lie well past the head glyph, as in the empty end of a table row; - /// `None` when the head came from a click or a command. - Run { anchor: usize, head: usize, head_x: Option }, + /// Reading order, from glyph `anchor` on the selection's page to glyph `head` on `head_page` + /// (either may come first). Across pages it takes the rest of the first page, every page + /// between whole, and the last page up to its end, as Acrobat does. `head_x` is where a + /// drag's pointer ended (page view space), which may lie well past the head glyph, as in the + /// empty end of a table row; `None` when the head came from a click or a command, and when + /// the selection runs across pages (table rows are one page). + Run { anchor: usize, head: usize, head_page: usize, head_x: Option }, /// Column select (#740): the glyphs inside a rectangle in page view space, drawn from the /// corner the drag started at (`rect[0..2]`) to the pointer (`rect[2..4]`). Column { rect: [f32; 4] }, @@ -20,7 +26,7 @@ pub(super) enum Span { impl Selection { pub(super) fn run(page: usize, anchor: usize, head: usize) -> Self { - Self { page, span: Span::Run { anchor, head, head_x: None } } + Self { page, span: Span::Run { anchor, head, head_page: page, head_x: None } } } fn range(anchor: usize, head: usize) -> Range { @@ -28,34 +34,148 @@ impl Selection { } /// What a drag over table rows selects by rows, not reading order's detour down each column. - /// Only a drag (also one after a double- or triple-click) or a ⇧-click has a pointer end; a - /// clicked word, line or page, Select all and a command's selection keep reading order, which - /// is the text they stand for. + /// Only a same-page drag (also one after a double- or triple-click) or a ⇧-click has a + /// pointer end; a clicked word, line or page, Select all, a command's selection, and a + /// selection across pages keep reading order. fn by_rows(text: &PageText, anchor: usize, head: usize, head_x: Option) -> Option> { head_x.and_then(|x| text.visual_between(anchor, head, Some(x))) } - /// One rectangle per selected piece of a line, in view space (highlighting, markup quads). - pub(super) fn rects(&self, text: &PageText) -> Vec<[f32; 4]> { + /// The pages the selection covers, first to last. + pub(super) fn pages(&self) -> RangeInclusive { match self.span { - Span::Run { anchor, head, head_x } => match Self::by_rows(text, anchor, head, head_x) { - Some(row) => text.glyph_rects(&row), - None => text.line_rects(Self::range(anchor, head)), - }, - Span::Column { rect } => text.glyph_rects(&text.glyphs_in(rect)), + Span::Run { head_page, .. } => self.page.min(head_page)..=self.page.max(head_page), + Span::Column { .. } => self.page..=self.page, } } - /// The selected text, as Copy puts it on the clipboard. - pub(super) fn text(&self, text: &PageText) -> String { + /// The page the selection ends on, where its drag finished: a reading-order selection's head + /// page, a column selection's own page. + pub(super) fn head_page(&self) -> usize { match self.span { - Span::Run { anchor, head, head_x } => match Self::by_rows(text, anchor, head, head_x) { - Some(row) => text.column_text(&row), - None => text.text_of(Self::range(anchor, head)), - }, - Span::Column { rect } => text.column_text(&text.glyphs_in(rect)), + Span::Run { head_page, .. } => head_page, + Span::Column { .. } => self.page, } } + + /// Whether the selection runs over more than one page. + pub(super) fn spans_pages(&self) -> bool { + self.pages().start() != self.pages().end() + } + + /// The reading-order glyphs selected on `page`, which has `len` glyphs; `None` off the + /// selection's pages and for a column selection. + pub(super) fn run_on(&self, page: usize, len: usize) -> Option> { + self.text_span()?.on(page, len) + } + + /// A reading-order selection's ends in reading order; `None` for a column selection. + pub(super) fn text_span(&self) -> Option { + let Span::Run { anchor, head, head_page, .. } = self.span else { return None }; + // (page, glyph) pairs compare in reading order. + let (start, end) = if (self.page, anchor) <= (head_page, head) { + ((self.page, anchor), (head_page, head)) + } else { + ((head_page, head), (self.page, anchor)) + }; + Some(TextSpan { start, end }) + } + + /// One rectangle per selected piece of a line on `page`, in view space (highlighting, + /// markup quads). + pub(super) fn rects_on(&self, page: usize, text: &PageText) -> Vec<[f32; 4]> { + match self.span { + Span::Run { anchor, head, head_page, head_x } if page == self.page && head_page == self.page => { + match Self::by_rows(text, anchor, head, head_x) { + Some(row) => text.glyph_rects(&row), + None => self.run_on(page, text.glyphs.len()).map(|r| text.line_rects(r)).unwrap_or_default(), + } + } + Span::Run { .. } => self.run_on(page, text.glyphs.len()).map(|r| text.line_rects(r)).unwrap_or_default(), + Span::Column { rect } if page == self.page => text.glyph_rects(&text.glyphs_in(rect)), + Span::Column { .. } => Vec::new(), + } + } + + /// The text selected on `page`, as Copy puts it on the clipboard. + pub(super) fn text_on(&self, page: usize, text: &PageText) -> String { + match self.span { + Span::Run { anchor, head, head_page, head_x } if page == self.page && head_page == self.page => { + match Self::by_rows(text, anchor, head, head_x) { + Some(row) => text.column_text(&row), + None => self.run_on(page, text.glyphs.len()).map(|r| text.text_of(r)).unwrap_or_default(), + } + } + Span::Run { .. } => self.run_on(page, text.glyphs.len()).map(|r| text.text_of(r)).unwrap_or_default(), + Span::Column { rect } if page == self.page => text.column_text(&text.glyphs_in(rect)), + Span::Column { .. } => String::new(), + } + } + + /// Extend a reading-order selection to glyph `head` on `page`. `head_x` is the pointer's + /// page-view x, used to select table rows on the same page; it is dropped when the head + /// moves to another page. + pub(super) fn extend_to_at(&mut self, page: usize, glyph: usize, head_x: Option) { + if let Span::Run { head, head_page, head_x: x, .. } = &mut self.span { + let same_page = page == self.page; + (*head, *head_page) = (glyph, page); + *x = head_x.filter(|_| same_page); + } + } +} + +/// What [`DocView::tool_marks`] gives a marking tool. +#[derive(Debug, PartialEq)] +pub(crate) enum ToolMarks { + /// Nothing to mark now (perhaps later, once the selection's pages are read). + None, + /// (page, quads) for each page the selection covers: mark them all, in one undo step. Then + /// the page the selection ends on, where the drag finished ([`DocView::selection_marks_edit`]). + Marks(Vec<(usize, Vec<[f64; 8]>)>, usize), + /// The selection covers a page whose text could not be read: not marked, say why. + Unreadable, +} + +/// Reading-order text from glyph `start.1` on page `start.0` to glyph `end.1` on page `end.0`, +/// both included, `start` first: what a reading-order selection covers, which a copy reads off +/// the UI thread too ([`crate::DocumentCopyJob::of_selection`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct TextSpan { + pub(crate) start: (usize, usize), + pub(crate) end: (usize, usize), +} + +impl TextSpan { + /// The glyphs covered on `page`, which has `len` glyphs: the rest of the first page, every + /// page between whole, the last page up to its end glyph. `None` off its pages. + pub(crate) fn on(&self, page: usize, len: usize) -> Option> { + if page < self.start.0 || page > self.end.0 { + return None; + } + let from = if page == self.start.0 { self.start.1 } else { 0 }; + let to = if page == self.end.0 { self.end.1.saturating_add(1) } else { len }; + Some(from..to.max(from)) + } +} + +/// A drag pressed on `page` starts a text selection there: from the glyph nearest `origin`, or +/// a column rectangle from `origin` to `to` (page view space). After a multi-click the word or +/// line the clicks selected stays, for the drag to extend by that unit. `clicks` is the press's +/// effective click count (`selection_click_count`): past a double click, tools other than Select +/// start over from one. +pub(super) fn start_selection_drag(view: &mut DocView, page: usize, text: &PageText, clicks: u32, column: bool, origin: (f32, f32), to: (f32, f32)) { + // A drag replaces the selection without passing through none, so a re-drag over text whose + // bar Copy closed would keep the bar hidden. + view.actions_dismissed = None; + view.selection_drag = true; + if clicks < 2 { + let (ox, oy) = origin; + view.selection = if column { + Some(Selection { page, span: Span::Column { rect: [ox, oy, to.0, to.1] } }) + } else { + text.nearest(ox, oy).map(|a| Selection::run(page, a, a)) + }; + } } /// The glyphs `clicks` quick clicks select around glyph `a`: two the word, three the line, more @@ -69,18 +189,105 @@ pub(super) fn click_unit(text: &PageText, clicks: u32, a: usize) -> Option<(usiz } impl DocView { - /// The text selection as markup quadrilaterals in user space: (page, quads). - pub(crate) fn selection_quads(&self, info: &DocInfo) -> Option<(usize, Vec<[f64; 8]>)> { - let s = self.selection?; - let text = self.texts.get(&s.page)?; - let page = info.pages.get(s.page)?; - let quads: Vec<[f64; 8]> = s.rects(text).into_iter().map(|r| page.view_rect_to_quad(r)).collect(); - (!quads.is_empty()).then_some((s.page, quads)) + /// The text layers of the selection's pages, first to last: `None` while one of them is still + /// to be read, so a selection is never copied or marked short. A page whose text could not be + /// read has nothing selected and is left out. + fn selection_texts(&self) -> Option)>> { + let mut texts = Vec::new(); + for p in self.selection?.pages() { + match self.texts.get(&p) { + Some(t) => texts.push((p, t)), + None if self.text_failed.contains(&p) => {} + None => return None, + } + } + Some(texts) + } + + /// The text selection as markup quadrilaterals in user space, one entry per page with + /// selected text: (page, quads). Empty when there is nothing to mark yet. + pub(crate) fn selection_quads(&self, info: &DocInfo) -> Vec<(usize, Vec<[f64; 8]>)> { + let (Some(s), Some(texts)) = (self.selection, self.selection_texts()) else { return Vec::new() }; + texts + .into_iter() + .filter_map(|(p, text)| { + let page = info.pages.get(p)?; + let quads: Vec<[f64; 8]> = s.rects_on(p, text).into_iter().map(|r| page.view_rect_to_quad(r)).collect(); + (!quads.is_empty()).then_some((p, quads)) + }) + .collect() + } + + /// A reading-order selection whose pages are not all read yet: Copy reads them off the UI + /// thread ([`crate::DocumentCopyJob::of_selection`]) rather than copying short or nothing. + pub(crate) fn selection_waits_for_text(&self) -> Option { + self.selection.filter(|_| self.selection_texts().is_none())?.text_span() + } + + /// Whether the selection covers a page whose text could not be read. Nothing there can be + /// selected, so a redaction of the rest would leave that page's content in place: Redact + /// refuses such a selection rather than mark it short. + pub(crate) fn selection_has_unreadable_page(&self) -> bool { + self.selection.is_some_and(|s| s.pages().any(|p| self.text_failed.contains(&p))) + } + + /// What a marking tool (a markup tool, Redact) marks for the text selection a drag, a + /// multi-click or picking the tool just finished (`finished`): (page, quads) for every page + /// the selection covers, as [`Self::selection_quads`], returned once: from one of its pages + /// (`Some(page)`, called for each page drawn) or from anywhere (`None`). While a page it + /// covers is still to be read, or none of its pages is drawn, nothing is marked yet: the + /// selection is remembered with the tool and marked on a later frame, as long as neither has + /// changed meanwhile. With `whole`, a selection over a page whose text could not be read is + /// refused instead ([`Self::selection_has_unreadable_page`]). + pub(crate) fn tool_marks(&mut self, tool: QuickTool, finished: bool, page: Option, whole: bool, info: &DocInfo) -> ToolMarks { + let Some(sel) = self.selection else { + self.marks_waiting = None; + return ToolMarks::None; + }; + if finished { + self.marks_waiting = Some((tool, sel)); + } + if self.marks_waiting != Some((tool, sel)) { + // The selection or the tool changed: the wait is over, so a drag passing back through + // the selection it was for doesn't mark it before it is released. + self.marks_waiting = None; + return ToolMarks::None; + } + if whole && self.selection_has_unreadable_page() { + self.marks_waiting = None; + return ToolMarks::Unreadable; + } + if self.selection_texts().is_none() { + return ToolMarks::None; + } + let marks = self.selection_quads(info); + if marks.is_empty() { + // Every page is read and nothing is selected: nothing to wait for. + self.marks_waiting = None; + return ToolMarks::None; + } + if page.is_some_and(|page| !marks.iter().any(|(p, _)| *p == page)) { + return ToolMarks::None; + } + self.marks_waiting = None; + ToolMarks::Marks(marks, sel.head_page()) + } + + /// The edit adding what a tool marks on a text selection, one edit per page, as one undo + /// step ([`one_undo_step`]). Across pages it is marked as such for `apply_edit` + /// ([`Self::marks_across_pages`]), with `head`, the page the selection ends on, which it + /// follows up as one markup: other batches of comments (Redact's page range or search) are + /// not followed up. + pub(crate) fn selection_marks_edit(&mut self, edits: Vec, head: usize) -> Option { + let edit = one_undo_step(edits); + self.marks_across_pages = matches!(edit, Some(Edit::Batch { .. })).then_some(head); + edit } pub(crate) fn clear_selection(&mut self) { self.selection = None; self.actions_dismissed = None; + self.marks_waiting = None; } /// Select text on `page` from glyph `from` to glyph `to` (tests and automation). @@ -104,30 +311,34 @@ impl DocView { /// Selected text, if any (⌘C). /// The selected text: of the pages read so far, after Select All of the document (Copy reads - /// the others, [`DocView::pages_without_text`]). + /// the others, [`DocView::pages_without_text`]). A selection across pages has each page's + /// part on a line of its own, as Select All of the document does. pub fn selected_text(&self) -> Option { if self.all_text { return Some(self.whole_text(&HashMap::new())).filter(|x| !x.is_empty()); } - let s = self.selection?; - let t = self.texts.get(&s.page)?; - Some(s.text(t)).filter(|x| !x.is_empty()) + let (s, texts) = (self.selection?, self.selection_texts()?); + let parts: Vec = texts.into_iter().map(|(p, t)| s.text_on(p, t)).filter(|x| !x.is_empty()).collect(); + Some(parts.join("\n")).filter(|x| !x.is_empty()) } /// The selection's page, its text layer and the selected glyphs in copy order, for Copy with - /// formatting. `None` after Select All of the document and for a column selection or a table's - /// rows, which copy plain text (rows and tab-separated cells are not paragraphs). + /// formatting. `None` after Select All of the document, for a column selection or a table's + /// rows, which copy plain text (rows and tab-separated cells are not paragraphs), and for a + /// selection across pages, whose formatted copy would hold one page of it: it copies plain + /// text, every page's. pub(crate) fn selected_glyphs(&self) -> Option<(usize, Arc, Vec)> { if self.all_text { return None; } - let s = self.selection?; + let s = self.selection.filter(|s| !s.spans_pages())?; let t = self.texts.get(&s.page)?; let glyphs = match s.span { - Span::Run { anchor, head, head_x } if Selection::by_rows(t, anchor, head, head_x).is_none() => { - Selection::range(anchor, head).take(t.glyphs.len()).collect() + Span::Run { anchor, head, head_x, .. } if Selection::by_rows(t, anchor, head, head_x).is_none() => { + let r = Selection::range(anchor, head); + (r.start..r.end.min(t.glyphs.len())).collect() } - // A table's rows, like a column, are tab-separated cells. + // A table's rows, like a column, are tab-separated cells. Across pages is excluded above. Span::Run { .. } | Span::Column { .. } => return None, }; Some((s.page, t.clone(), glyphs)) @@ -199,6 +410,33 @@ enum SelectionAction { /// The selection bar's width before it has been laid out once (English labels). const SELECTION_BAR_GUESS: f32 = 520.0; +/// Edits that each add a page's part of something marked on a text selection, as one undo step: +/// the edit itself for one page, a batch named like it for several. For edits whose label has no +/// hole (adding a comment), so the batch's name is a wording the catalogues translate. +pub(crate) fn one_undo_step(mut edits: Vec) -> Option { + if edits.len() <= 1 { + return edits.pop(); + } + let label = edits.first()?.label().wording.to_owned(); + Some(Edit::Batch { label, edits }) +} + +/// Where the selection bar goes: next to the selected text where the drag ended, which is on +/// screen. Forward, the last rectangle on the head's page; backward across pages, the first one +/// there. Otherwise (a column, or nothing selected on the head's page) the last rectangle on the +/// last page with text selected. +pub(super) fn bar_anchor(selection: &Selection, texts: &[(usize, &Arc)]) -> Option<(usize, [f32; 4])> { + let at_head = selection.text_span().and_then(|span| { + let Span::Run { head_page, .. } = selection.span else { return None }; + let backward = span.start.0 == head_page && span.start.0 != span.end.0; + let (_, text) = texts.iter().find(|(p, _)| *p == head_page)?; + let rects = selection.rects_on(head_page, text); + let rect = if backward { rects.first() } else { rects.last() }; + rect.map(|r| (head_page, *r)) + }); + at_head.or_else(|| texts.iter().rev().find_map(|(p, t)| selection.rects_on(*p, t).last().map(|r| (*p, *r)))) +} + /// Actions on an existing text selection, next to the selected words. pub(super) fn selection_actions( ui: &mut egui::Ui, @@ -219,13 +457,14 @@ pub(super) fn selection_actions( if view.actions_dismissed == Some(selection) { return false; } - let Some(text) = view.texts.get(&selection.page) else { return false }; - let Some(xf) = view.page_xform(selection.page) else { return false }; - let Some(last) = selection.rects(text).last().copied() else { return false }; - let selected = selection.text(text); - if selected.is_empty() { + if view.selected_text().is_none() { return false; } + let Some(texts) = view.selection_texts() else { return false }; + let Some((page, last)) = bar_anchor(&selection, &texts) else { return false }; + let Some(xf) = view.page_xform(page) else { return false }; + // A comment or a replacement sits on one page: across pages, only markup and Copy. + let across_pages = selection.spans_pages(); let rect = xf.view_rect(last); if !viewport.intersects(rect) { return false; @@ -247,7 +486,8 @@ pub(super) fn selection_actions( (tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)), (tl!("Replace text"), SelectionAction::Replace), ] { - if ui.add_enabled(can_comment, egui::Button::new(label)).clicked() { + let one_page_only = matches!(action, SelectionAction::Note | SelectionAction::Replace); + if ui.add_enabled(can_comment && !(across_pages && one_page_only), egui::Button::new(label)).clicked() { chosen = Some(action); } } @@ -263,12 +503,17 @@ pub(super) fn selection_actions( view.actions_dismissed = Some(selection); return true; } - let Some((page, quads)) = view.selection_quads(info) else { return false }; - let last = quads.last().copied().unwrap_or_default(); - let at = [last[2].max(last[6]), last[1].max(last[3])]; - view.clear_selection(); + let marks = view.selection_quads(info); + if marks.is_empty() { + return false; + } match action { SelectionAction::Note | SelectionAction::Replace => { + // Disabled across pages (above). + let Ok([(page, quads)]) = <[_; 1]>::try_from(marks) else { return false }; + let last = quads.last().copied().unwrap_or_default(); + let at = [last[2].max(last[6]), last[1].max(last[3])]; + view.clear_selection(); let kind = if matches!(action, SelectionAction::Replace) { view.comments.replace = Some(quads); comments::ComposerKind::Replace @@ -280,13 +525,17 @@ pub(super) fn selection_actions( SelectionAction::Markup(tool) => { // Every markup button carries a markup tool; anything else adds nothing. let Some(kind) = tool.markup() else { return false }; - view.pending_edit = Some(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { - page, - shape: pdfcraft_engine::Shape::TextMarkup { kind, quads }, - style: prefs.style(tool), - contents: String::new(), - author: prefs.author.clone(), - })); + view.clear_selection(); + let edits = marks.into_iter().map(|(page, quads)| { + Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { + page, + shape: pdfcraft_engine::Shape::TextMarkup { kind, quads }, + style: prefs.style(tool), + contents: String::new(), + author: prefs.author.clone(), + }) + }); + view.pending_edit = view.selection_marks_edit(edits.collect(), selection.head_page()); } // Copy is dispatched through the app after the view borrow ends. SelectionAction::Copy => {} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a04f6d2a35..ce99e2764e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1164,12 +1164,19 @@ fn a_later_copy_cancels_a_document_copy_still_reading() { assert!(app.document_copy.is_none(), "cancelled"); let copies: Vec<_> = out.platform_output.commands.iter().filter(|c| matches!(c, egui::OutputCommand::CopyText(_))).collect(); assert_eq!(copies, vec![&egui::OutputCommand::CopyText("a word".to_owned())], "the later copy stays"); - // So does copying a page selection. + // So does copying a page selection whose page is read. app.views[0].select_all(); assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some()); + app.views[0].texts.insert(0, Arc::new(line_text("abcdef"))); app.views[0].select_text(0, 0, 5); app.copy_selected_text(0, &ctx); assert!(app.document_copy.is_none(), "a page selection's copy cancels it"); + // One whose pages are still to be read replaces it with its own (#5017 review). + app.views[0].select_all(); + assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some()); + app.views[0].select_text(0, 0, 5); + app.views[0].selection = Some(Selection { page: 0, span: Span::Run { anchor: 0, head: 0, head_page: 1, head_x: None } }); + assert!(app.copy_selected_text(0, &ctx) && app.document_copy.is_some(), "the selection's own copy"); } /// A press anywhere on a page ends Select All of the document, whatever the tool (here the @@ -1284,6 +1291,157 @@ fn text_layers_keep_the_selection_page() { v.frame_visible = HashSet::from([90, 91]); let _ = v.prepare_render_queue(&info, 1.0); assert_eq!(v.selected_text().as_deref(), Some("x"), "stale selections still copy"); + // Every page of a selection across pages stays, however far from the pages shown. + for p in 0..100 { + v.texts.insert(p, Arc::new(text.clone())); + } + v.selection = Some(Selection { page: 0, span: Span::Run { anchor: 0, head: 0, head_page: 40, head_x: None } }); + let _ = v.prepare_render_queue(&info, 1.0); + assert!((0..=40).all(|p| v.texts.contains_key(&p)), "the selection's pages are kept"); + assert_eq!(v.selected_text().map(|t| t.lines().count()), Some(41)); +} + +/// One line of 10-wide glyphs, one per char. +fn line_text(s: &str) -> PageText { + PageText { + glyphs: s + .chars() + .map(|c| pdfcraft_render::TextGlyph { text: c.into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] }) + .collect(), + line_of: s.chars().map(|_| 0).collect(), + space_before: s.chars().map(|_| false).collect(), + truncated: false, + } +} + +/// Two lines of two glyphs: "ab" at the top, "cd" below it. +fn two_line_text() -> PageText { + let glyph = + |c: char, y: f32| pdfcraft_render::TextGlyph { text: c.into(), rect: [0.0, y, 10.0, y + 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] }; + PageText { + glyphs: vec![glyph('a', 0.0), glyph('b', 0.0), glyph('c', 20.0), glyph('d', 20.0)], + line_of: vec![0, 0, 1, 1], + space_before: vec![false; 4], + truncated: false, + } +} + +/// Review of #5017: the selection bar goes where the drag ended, which is on screen: dragged +/// back from page 3 to page 1, at the start of what page 1 has selected, not at the end of page +/// 3 (perhaps scrolled away). +#[test] +fn the_selection_bar_sits_where_the_drag_ended() { + let text = Arc::new(two_line_text()); + let texts: Vec<(usize, &Arc)> = (1..=3).map(|p| (p, &text)).collect(); + let anchor = |s: Selection| super::selection::bar_anchor(&s, &texts).map(|(page, r)| (page, r[1])); + // Backward: page 1, its top line (the first rectangle there). + let back = Selection { page: 3, span: Span::Run { anchor: 1, head: 0, head_page: 1, head_x: None } }; + assert_eq!(anchor(back), Some((1, 0.0))); + // Forward: page 3, the last line selected there. + let forward = Selection { page: 1, span: Span::Run { anchor: 0, head: 3, head_page: 3, head_x: None } }; + assert_eq!(anchor(forward), Some((3, 20.0))); + // On one page, as before: the end of the selection, whichever way it was dragged. + assert_eq!(anchor(Selection::run(2, 3, 0)), Some((2, 20.0))); + assert_eq!(anchor(Selection::run(2, 0, 3)), Some((2, 20.0))); +} + +#[test] +fn a_selection_across_pages_takes_the_rest_of_the_first_and_the_start_of_the_last() { + let s = Selection { page: 1, span: Span::Run { anchor: 2, head: 1, head_page: 3, head_x: None } }; + assert_eq!(s.pages(), 1..=3); + assert!(s.spans_pages()); + let on = |s: &Selection| (0..5).map(|p| s.run_on(p, 5)).collect::>(); + assert_eq!(on(&s), [None, Some(2..5), Some(0..5), Some(0..2), None]); + // Anchored on the last page and dragged back: the same glyphs. + let back = Selection { page: 3, span: Span::Run { anchor: 1, head: 2, head_page: 1, head_x: None } }; + assert_eq!(on(&back), on(&s)); + assert_eq!(back.pages(), 1..=3); + // On one page, as before: either way round, both ends included. + let one = Selection::run(2, 4, 1); + assert!(!one.spans_pages()); + assert_eq!(on(&one), [None, None, Some(1..5), None, None]); + // A column selection stays on its page and has no reading-order run. + let column = Selection { page: 2, span: Span::Column { rect: [0.0, 0.0, 100.0, 100.0] } }; + assert_eq!(column.pages(), 2..=2); + assert_eq!(column.run_on(2, 5), None); + let t = line_text("abcde"); + assert!(column.rects_on(1, &t).is_empty() && column.text_on(1, &t).is_empty(), "nothing off its page"); + // Extending moves the head, onto another page too; a column selection has none to move. + let mut ext = Selection::run(0, 3, 3); + ext.extend_to_at(2, 1, None); + assert_eq!(ext, Selection { page: 0, span: Span::Run { anchor: 3, head: 1, head_page: 2, head_x: None } }); + let mut col = column; + col.extend_to_at(4, 0, None); + assert_eq!(col, column); + // Hostile indices: no overflow, no inverted range. + let edge = Selection { page: usize::MAX, span: Span::Run { anchor: usize::MAX, head: usize::MAX, head_page: usize::MAX, head_x: None } }; + assert_eq!(edge.run_on(usize::MAX, 3), Some(usize::MAX..usize::MAX)); + assert_eq!(edge.text_on(usize::MAX, &t), ""); + // Glyph indices past a page's end (a stale selection) select only what is there. + let stale = Selection { page: 0, span: Span::Run { anchor: 3, head: 99, head_page: 1, head_x: None } }; + assert_eq!(stale.text_on(0, &t), "de"); + assert_eq!(stale.text_on(1, &t), "abcde"); +} + +#[test] +fn a_selection_across_pages_copies_each_page_on_its_own_line_once_all_are_read() { + let info = thumbnail_info(4); + let mut v = DocView::new(DocId(1), &info, ViewDefaults::default()); + v.texts.insert(0, Arc::new(line_text("abc"))); + v.texts.insert(2, Arc::new(line_text("ghi"))); + v.texts.insert(3, Arc::new(line_text("jkl"))); + v.selection = Some(Selection { page: 2, span: Span::Run { anchor: 0, head: 1, head_page: 0, head_x: None } }); + assert_eq!(v.selected_text(), None, "page 2 is not read yet: no short copy"); + assert!(v.selection_quads(&info).is_empty(), "nor a short markup"); + v.texts.insert(1, Arc::new(line_text("def"))); + assert_eq!(v.selected_text().as_deref(), Some("bc\ndef\ng")); + // A page whose text could not be read has nothing selected and is passed over. + v.texts.remove(&1); + v.text_failed.insert(1); + assert_eq!(v.selected_text().as_deref(), Some("bc\ng")); + let pages: Vec = v.selection_quads(&info).into_iter().map(|(p, _)| p).collect(); + assert_eq!(pages, [0, 2], "one set of quads per page with text selected"); + // A change to one of its pages ends it, as on one page; to another page it stays. + v.page_changed(3); + assert!(v.selection.is_some()); + v.page_changed(1); + assert!(v.selection.is_none()); +} + +/// Copy with formatting takes one page's glyphs: a selection on one page keeps it, as before; one +/// across pages copies plain text, every page's, rather than formatted text of one page. +#[test] +fn copy_with_formatting_takes_a_selection_on_one_page_only() { + let info = thumbnail_info(3); + let mut v = DocView::new(DocId(1), &info, ViewDefaults::default()); + v.texts.insert(0, Arc::new(line_text("abc"))); + v.texts.insert(1, Arc::new(line_text("def"))); + v.selection = Some(Selection::run(0, 2, 1)); + assert_eq!(v.selected_glyphs().map(|(page, _, glyphs)| (page, glyphs)), Some((0, vec![1, 2]))); + // Glyphs past a stale selection's page end are left out. + v.selection = Some(Selection::run(0, 1, 99)); + assert_eq!(v.selected_glyphs().map(|(_, _, glyphs)| glyphs), Some(vec![1, 2])); + v.selection = Some(Selection { page: 0, span: Span::Run { anchor: 1, head: 1, head_page: 1, head_x: None } }); + assert!(v.selected_glyphs().is_none(), "across pages: plain text"); + assert_eq!(v.selected_text().as_deref(), Some("bc\nde"), "which has every page's part"); +} + +#[test] +fn markup_on_several_pages_is_one_undo_step_named_like_one() { + let mark = |page| { + Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { + page, + shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads: vec![[0.0; 8]] }, + style: Default::default(), + contents: String::new(), + author: String::new(), + }) + }; + assert!(selection::one_undo_step(Vec::new()).is_none()); + assert!(matches!(selection::one_undo_step(vec![mark(0)]), Some(Edit::AddAnnotation(_)))); + let Some(Edit::Batch { label, edits }) = selection::one_undo_step(vec![mark(0), mark(1)]) else { panic!("a batch") }; + assert_eq!((label.as_str(), edits.len()), (mark(0).label().wording, 2)); + assert!(pdfcraft_engine::EDIT_LABELS.contains(&label.as_str()), "a wording the catalogues translate"); } #[test] @@ -3193,3 +3351,190 @@ fn only_pixel_snapping_passes_for_fitting_the_view() { assert!(!fits_height(Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 600.5)), 600.0, ppp)); } } + +/// Review of #5017: a selection across pages copied before every page it covers is read is not +/// dropped. Copy stays on and reads those pages off the UI thread, taking only the part each +/// page has selected. +#[test] +fn a_selection_across_pages_still_to_be_read_is_copied_once_read() { + let mut app = PdfCraftApp::new(); + app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap(); + // From the second glyph of page 1 to the first of page 3, no page read yet. + app.views[0].selection = Some(Selection { page: 0, span: Span::Run { anchor: 1, head: 0, head_page: 2, head_x: None } }); + let span = app.views[0].selection_waits_for_text().expect("waits for its pages"); + assert_eq!(span, TextSpan { start: (0, 1), end: (2, 0) }); + assert!(app.views[0].selected_text().is_none(), "nothing to copy on this thread yet"); + assert!(pdfcraft_engine::commands::command("edit.copy").is_some_and(|c| app.command_enabled(c)), "Copy stays on"); + // The job reads only the selection's part of each page, and no page outside it. + let doc = app.session.get(app.views[0].id).unwrap(); + let text = crate::DocumentCopyJob::of_selection(&app.views[0], doc, span).text(&std::sync::atomic::AtomicBool::new(false)); + assert_eq!(text.as_deref(), Some("lpha one\nBravo two\nC")); + let later = crate::DocumentCopyJob::of_selection(&app.views[0], doc, TextSpan { start: (1, 0), end: (1, 4) }); + assert!(matches!(later.pages[0], crate::CopyPage::Skip) && matches!(later.pages[2], crate::CopyPage::Skip)); + assert_eq!(later.text(&std::sync::atomic::AtomicBool::new(false)).as_deref(), Some("Bravo")); + // Copy starts that job, and the clipboard gets the text when it is done. + let ctx = egui::Context::default(); + assert!(app.copy_selected_text(0, &ctx), "the copy starts"); + let mut copied = None; + for _ in 0..500 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.finish_document_copy(ui.ctx())); + out.textures_delta.clear(); + copied = out.platform_output.commands.iter().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }); + if copied.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(copied.as_deref(), Some("lpha one\nBravo two\nC")); +} + +/// Review of #5017: Redact refuses a selection across a page whose text could not be read, +/// rather than leave that page unmarked, and says why; markup tools mark the readable pages. +#[test] +fn redaction_refuses_a_selection_over_an_unreadable_page() { + let mut app = PdfCraftApp::new(); + app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap(); + let info = app.session.get(app.views[0].id).unwrap().info.clone(); + let v = &mut app.views[0]; + v.texts.insert(0, Arc::new(line_text("abc"))); + v.texts.insert(2, Arc::new(line_text("ghi"))); + v.text_failed.insert(1); + let sel = Selection { page: 0, span: Span::Run { anchor: 1, head: 1, head_page: 2, head_x: None } }; + v.selection = Some(sel); + assert!(v.selection_has_unreadable_page()); + assert_eq!(v.tool_marks(QuickTool::Redact, true, None, true, &info), ToolMarks::Unreadable); + let pages = |m: ToolMarks| match m { + ToolMarks::Marks(m, _) => m.into_iter().map(|(p, _)| p).collect::>(), + other => panic!("marks expected, got {other:?}"), + }; + let highlight = QuickTool::Comment(comments::CommentTool::Highlight); + assert_eq!(pages(v.tool_marks(highlight, true, None, false, &info)), [0, 2], "a highlight has nothing to hide"); + // Redact ▸ Mark on it: nothing marked, the selection kept, and the reason given. + app.views[0].selection = Some(sel); + assert!(app.execute("redact.mark")); + let doc = app.session.get(app.views[0].id).unwrap(); + assert_eq!(doc.redaction_marks(), 0, "no partial redaction"); + assert_eq!(app.views[0].selection, Some(sel), "still selected"); + assert!(app.toast.as_ref().is_some_and(|(t, _)| t.contains("could not be read")), "{:?}", app.toast); +} + +/// Review of #5017: a marking tool that finishes a selection while a page it covers is still +/// to be read marks it once that page is read, from one of its pages, unless the selection or +/// the tool changed meanwhile. +#[test] +fn a_marking_tool_waits_for_the_selections_pages() { + let info = thumbnail_info(3); + let mut v = DocView::new(DocId(1), &info, ViewDefaults::default()); + v.texts.insert(0, Arc::new(line_text("abc"))); + v.texts.insert(2, Arc::new(line_text("ghi"))); + let sel = Selection { page: 0, span: Span::Run { anchor: 1, head: 1, head_page: 2, head_x: None } }; + v.selection = Some(sel); + let tool = QuickTool::Comment(comments::CommentTool::Underline); + assert_eq!(v.tool_marks(tool, true, Some(0), false, &info), ToolMarks::None, "page 2 is not read yet"); + assert_eq!(v.tool_marks(tool, false, Some(0), false, &info), ToolMarks::None, "still waiting"); + v.texts.insert(1, Arc::new(line_text("def"))); + // Asked from a page it doesn't cover, it keeps waiting; from one it covers, all of it, once. + let mut w = DocView::new(DocId(2), &thumbnail_info(4), ViewDefaults::default()); + w.texts = v.texts.clone(); + w.selection = Some(sel); + assert_eq!(w.tool_marks(tool, true, Some(3), false, &info), ToolMarks::None); + assert!(matches!(w.tool_marks(tool, false, Some(2), false, &info), ToolMarks::Marks(ref m, _) if m.len() == 3)); + assert_eq!(w.tool_marks(tool, false, Some(2), false, &info), ToolMarks::None, "marked once"); + assert!(matches!(v.tool_marks(tool, false, Some(1), false, &info), ToolMarks::Marks(ref m, _) if m.len() == 3)); + // Another tool, or another selection, does not inherit the wait. + v.texts.remove(&1); + assert_eq!(v.tool_marks(tool, true, Some(0), false, &info), ToolMarks::None); + v.texts.insert(1, Arc::new(line_text("def"))); + assert_eq!(v.tool_marks(QuickTool::Redact, false, Some(0), true, &info), ToolMarks::None, "another tool"); + v.selection = Some(Selection::run(0, 0, 2)); + assert_eq!(v.tool_marks(tool, false, Some(0), false, &info), ToolMarks::None, "another selection"); + // Clearing the selection ends the wait. + v.selection = Some(sel); + v.texts.remove(&1); + assert_eq!(v.tool_marks(tool, true, Some(0), false, &info), ToolMarks::None); + v.clear_selection(); + v.selection = Some(sel); + v.texts.insert(1, Arc::new(line_text("def"))); + assert_eq!(v.tool_marks(tool, false, Some(0), false, &info), ToolMarks::None, "cleared"); +} + +/// Review of #5017: a wait ends as soon as the selection changes, so a new drag that passes back +/// through the selection it was for doesn't mark that selection before the drag is let go. +#[test] +fn a_wait_ends_when_the_selection_changes() { + let info = thumbnail_info(3); + let mut v = DocView::new(DocId(1), &info, ViewDefaults::default()); + v.texts.insert(0, Arc::new(line_text("abc"))); + v.texts.insert(2, Arc::new(line_text("ghi"))); + let sel = Selection { page: 0, span: Span::Run { anchor: 1, head: 1, head_page: 2, head_x: None } }; + v.selection = Some(sel); + let tool = QuickTool::Comment(comments::CommentTool::Underline); + assert_eq!(v.tool_marks(tool, true, Some(0), false, &info), ToolMarks::None, "page 2 is not read yet"); + // A new drag starts elsewhere, page 2 is read, and the drag comes back to the same selection. + v.selection = Some(Selection::run(0, 0, 0)); + assert_eq!(v.tool_marks(tool, false, Some(0), false, &info), ToolMarks::None); + v.texts.insert(1, Arc::new(line_text("def"))); + v.selection = Some(sel); + assert_eq!(v.tool_marks(tool, false, Some(0), false, &info), ToolMarks::None, "not marked mid-drag"); +} + +/// Review of #5017 (FredApps): marks a tool is still waiting to make, for a page whose text has +/// not arrived, never land on a page that changed or went away meanwhile. Deleting a page, or a +/// change to a page the selection covers, ends the selection, and the wait goes with it. +#[test] +fn waiting_marks_are_dropped_when_their_pages_change() { + let mut app = PdfCraftApp::new(); + app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap(); + let id = app.views[0].id; + let info = |app: &PdfCraftApp| app.session.get(id).unwrap().info.clone(); + let sel = Selection { page: 0, span: Span::Run { anchor: 1, head: 1, head_page: 2, head_x: None } }; + let wait = |app: &mut PdfCraftApp| { + let info = info(app); + let v = &mut app.views[0]; + v.texts.clear(); + v.texts.insert(0, Arc::new(line_text("abc"))); + v.texts.insert(2, Arc::new(line_text("ghi"))); + v.selection = Some(sel); + assert_eq!(v.tool_marks(QuickTool::Redact, true, Some(0), true, &info), ToolMarks::None, "waiting for page 2's text"); + }; + // Page 2 deleted while the marks wait. + wait(&mut app); + assert!(app.apply_edit(Edit::DeletePages { pages: vec![1] })); + let after = info(&app); + assert_eq!(after.pages.len(), 2); + let v = &mut app.views[0]; + assert!(v.selection.is_none(), "a change to the document's pages ends the selection"); + for p in 0..2 { + v.texts.insert(p, Arc::new(line_text("abc"))); + } + // The old selection's glyph positions now name other pages: even made again, nothing is + // marked unless the tool finishes it again. + v.selection = Some(Selection { page: 0, span: Span::Run { anchor: 1, head: 1, head_page: 1, head_x: None } }); + assert_eq!(v.tool_marks(QuickTool::Redact, false, Some(0), true, &after), ToolMarks::None, "the wait went with the selection"); + let redactions = app.session.get(id).unwrap().redaction_marks(); + assert_eq!(redactions, 0); + // A change to one page the selection covers (a comment added on it) ends it too. + let mut app = PdfCraftApp::new(); + app.open_bytes("three.pdf", None, text_pages_pdf(&["Alpha one", "Bravo two", "Charlie three"])).unwrap(); + let id = app.views[0].id; + wait(&mut app); + let note = Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { + page: 2, + shape: pdfcraft_engine::Shape::Note { at: [10.0, 10.0], icon: pdfcraft_engine::NoteIcon::Comment }, + style: Default::default(), + contents: "x".into(), + author: String::new(), + }); + assert!(app.apply_edit(note)); + let now = info(&app); + let v = &mut app.views[0]; + assert!(v.selection.is_none(), "a change to a page it covers ends the selection"); + v.texts.insert(1, Arc::new(line_text("def"))); + v.texts.insert(2, Arc::new(line_text("ghi"))); + v.selection = Some(sel); + assert_eq!(v.tool_marks(QuickTool::Redact, false, Some(0), true, &now), ToolMarks::None, "nothing marked"); + assert_eq!(app.session.get(id).unwrap().redaction_marks(), 0); +} diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 3b422181a9..a51575f3b3 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -93,10 +93,9 @@ impl PdfCraftApp { || spec.needs == commands::Needs::Undo && self.page_typing_unapplied() || spec.needs == commands::Needs::Redo && self.open_box_can_redo()) && (spec.id != "edit.copy" - || self - .active - .and_then(|i| self.views.get(i)) - .is_some_and(|v| !v.organize && (v.all_text || v.selected_text().is_some_and(|t| !t.is_empty())))) + || self.active.and_then(|i| self.views.get(i)).is_some_and(|v| { + !v.organize && (v.all_text || v.selection_waits_for_text().is_some() || v.selected_text().is_some_and(|t| !t.is_empty())) + })) && (spec.needs != commands::Needs::TwoPageView || self.active.and_then(|i| self.views.get(i)).is_some_and(crate::DocView::cover_applies)) && match spec.id { "comment.copy" => self.active.and_then(|i| self.views.get(i)).is_some_and(|v| v.comments.selected.is_some()), @@ -491,17 +490,27 @@ impl PdfCraftApp { if self.right.is_none() && !self.comments_panel_closed { self.choose_right_panel(Some(RightPanel::Comments)); } - // A text selection made before picking a markup tool is marked right away. + // A text selection made before picking a markup tool is marked right away, on + // every page it covers, in one undo step. if let (Some(kind), Some(i)) = (tool.markup(), active) && let Some(doc) = self.session.get(self.views[i].id) { - let info = &doc.info; - if let Some((page, quads)) = self.views[i].selection_quads(info) { - self.views[i].clear_selection(); - let style = self.comment_prefs.style(tool); - let author = self.comment_prefs.author.clone(); - let shape = pdfcraft_engine::Shape::TextMarkup { kind, quads }; - self.apply_edit(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { page, shape, style, contents: String::new(), author })); + // Pages still to be read are marked when they are, by the tool now picked. + let tool_now = self.quick_tool; + if let crate::canvas::ToolMarks::Marks(marks, head) = self.views[i].tool_marks(tool_now, true, None, false, &doc.info) { + let edits: Vec = marks + .into_iter() + .map(|(page, quads)| { + let style = self.comment_prefs.style(tool); + let author = self.comment_prefs.author.clone(); + let shape = pdfcraft_engine::Shape::TextMarkup { kind, quads }; + Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { page, shape, style, contents: String::new(), author }) + }) + .collect(); + if let Some(edit) = self.views[i].selection_marks_edit(edits, head) { + self.views[i].clear_selection(); + self.apply_edit(edit); + } } } } @@ -773,15 +782,26 @@ impl PdfCraftApp { self.quick_tool = crate::QuickTool::Redact; self.left = crate::LeftPanel::Tool("redact"); self.reveal_tools(); - // A text selection made first is marked right away. + // A text selection made first is marked right away, on every page it covers, in + // one undo step. if let Some(i) = active && let Some(doc) = self.session.get(self.views[i].id) { - let info = &doc.info; - if let Some((page, quads)) = self.views[i].selection_quads(info) { - self.views[i].clear_selection(); - let author = self.comment_prefs.author.clone(); - self.apply_edit(self.redact_prefs.mark(page, quads, &author)); + let author = self.comment_prefs.author.clone(); + // Pages still to be read are marked when they are, by the Redact tool now + // picked; a page that could not be read refuses the whole selection. + match self.views[i].tool_marks(crate::QuickTool::Redact, true, None, true, &doc.info) { + crate::canvas::ToolMarks::Marks(marks, head) => { + let edits: Vec = marks.into_iter().map(|(page, quads)| self.redact_prefs.mark(page, quads, &author)).collect(); + if let Some(edit) = self.views[i].selection_marks_edit(edits, head) { + self.views[i].clear_selection(); + self.apply_edit(edit); + } + } + crate::canvas::ToolMarks::Unreadable => { + self.notify_tr("Part of the selected text is on a page whose text could not be read, so nothing was marked for redaction. Mark that page with a box instead."); + } + crate::canvas::ToolMarks::None => {} } } } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index f6144ec143..cd61e82e43 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -41,13 +41,15 @@ fn clear_shifted_page_comment_state(view: &mut crate::DocView, shifted_from: usi } /// Keeps the pages (or comment) the user acted on selected, where they now are. `annots_before` -/// is the page's annotations before a delete or a paste of comments (empty for other edits). +/// is the page's annotations before a delete or a paste of comments (empty for other edits); +/// `across_pages`, for markup on a text selection across pages, the page that selection ends on. fn select_after_edit( view: &mut crate::DocView, edit: &Edit, info: &pdfcraft_render::DocInfo, annots_before: &[pdfcraft_render::Annotation], quick_tool: crate::QuickTool, + across_pages: Option, ) { match edit { Edit::MovePages { pages, to } => { @@ -98,6 +100,18 @@ fn select_after_edit( view.comments.open_editor(a.page, n, String::new()); } } + // Markup on a text selection across pages (marked so when it was made, + // [`crate::DocView::selection_marks_edit`]; other batches of comments, such as Redact's + // page range or search, are not) is followed up as one markup is: on the page the + // selection ends, where the drag finished and is on screen, its comment selected and, for + // a highlight, its note open. One level: the batch holds only `AddAnnotation`s. + Edit::Batch { edits, .. } if across_pages.is_some() && edits.iter().all(|e| matches!(e, Edit::AddAnnotation(_))) => { + // The selection's pages are in page order: dragged back up, it ends on the first. + let on_head = edits.iter().find(|e| matches!(e, Edit::AddAnnotation(a) if Some(a.page) == across_pages)); + if let Some(head) = on_head.or(edits.last()) { + select_after_edit(view, head, info, &[], quick_tool, None); + } + } // A group moved together stays selected (its positions don't change), so it // can be moved or copied again; anything else in a batch clears the selection. Edit::Batch { edits, .. } if edits.iter().all(|e| matches!(e, Edit::MoveAnnotation { .. })) => {} @@ -156,6 +170,8 @@ 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 { let Some((i, id)) = self.active_ids() else { return false }; + // Taken whatever happens to this edit, so it never carries over to another. + let across_pages = std::mem::take(&mut self.views[i].marks_across_pages).filter(|_| annotated_pages(&edit).is_some()); let label = edit.label(); let target_arrange_image = match &edit { Edit::EditPageImage { page, index, change: pdfcraft_engine::ImageEdit::Arrange(_) } => { @@ -230,7 +246,13 @@ impl PdfCraftApp { if signatures_before.is_some_and(|before| crate::canvas::signature_states_changed(&before, &doc.signatures)) { signatures_changed_after_edit(view, &edit, info, &annots_before, form_edit.map(|(_, u)| u), one_page); } else if let Some(page) = one_page { + // Comment and content edits change one page: keep every other raster. one_page_changed(view, &edit, page, &annots_before, info); + } else if let Some(pages) = annotated_pages(&edit) { + // Markup on a selection across pages adds one comment on each of them: those + // pages' rasters, then the comments once, however many pages. + pages.into_iter().for_each(|page| view.page_changed(page)); + view.comments.document_changed(info); } else if let Some((changed_pages, unbaked)) = form_edit { view.forms.unbaked.extend(unbaked); for page in changed_pages { @@ -240,7 +262,7 @@ impl PdfCraftApp { } else { view.document_changed(info); } - if matches!(edit, Edit::AddAnnotation(_)) { + if matches!(edit, Edit::AddAnnotation(_)) || across_pages.is_some() { view.comments.comment_added(); } // A deletion moves the pop-ups' state with its comments (`annotation_deleted`). @@ -248,7 +270,7 @@ impl PdfCraftApp { view.comments.popups_after_edit(&popups_before, &info.annotations); } // Keep the pages the user acted on selected, where they now are. - select_after_edit(view, &edit, info, &annots_before, self.quick_tool); + select_after_edit(view, &edit, info, &annots_before, self.quick_tool, across_pages); if let (Some((target, ambiguous_before)), Edit::EditPageImage { page, .. }) = (target_arrange_image, &edit) { let page_images = doc.page_images(*page); re_resolve_image_selection(view, *page, &target, ambiguous_before, &page_images); @@ -1239,6 +1261,20 @@ fn comment_page(edit: &Edit) -> Option { } } +/// The pages of a batch that only adds annotations (markup on a text selection across pages), +/// each of which changes only its own page; `None` for anything else. +fn annotated_pages(edit: &Edit) -> Option> { + let Edit::Batch { edits, .. } = edit else { return None }; + let pages: Vec = edits + .iter() + .map(|e| match e { + Edit::AddAnnotation(a) => Some(a.page), + _ => None, + }) + .collect::>()?; + (!pages.is_empty()).then_some(pages) +} + /// Whether `edit` is a form-related modification. fn is_form_edit(edit: &Edit) -> bool { matches!( diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 9acbc370f5..8d524ad85b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -271,9 +271,11 @@ pub(crate) enum CopyPage { } /// What a whole-document copy needs, taken from the view on the UI thread: each page's text -/// layer as far as it was read, and the document to read the others from. +/// layer as far as it was read, and the document to read the others from. A copy of a text +/// selection across pages whose pages are not all read yet is one too, limited to its `span`. pub(crate) struct DocumentCopyJob { pub(crate) pages: Vec, + span: Option, bytes: std::sync::Arc>, password: Option>, } @@ -287,7 +289,20 @@ impl DocumentCopyJob { None => CopyPage::ToRead, }) .collect(); - DocumentCopyJob { pages, bytes: doc.bytes.clone(), password: doc.password.as_deref().map(std::sync::Arc::from) } + DocumentCopyJob { pages, span: None, bytes: doc.bytes.clone(), password: doc.password.as_deref().map(std::sync::Arc::from) } + } + + /// A copy of the reading-order text `span` covers: its pages as [`Self::of`] takes them, every + /// other page skipped. + pub(crate) fn of_selection(v: &DocView, doc: &pdfcraft_engine::Document, span: crate::canvas::TextSpan) -> DocumentCopyJob { + let mut job = DocumentCopyJob::of(v, doc); + for (page, p) in job.pages.iter_mut().enumerate() { + if page < span.start.0 || page > span.end.0 { + *p = CopyPage::Skip; + } + } + job.span = Some(span); + job } /// The document's text in page order, a page per line run. Each page read here is let go @@ -304,12 +319,18 @@ impl DocumentCopyJob { out.push_str(&text); } }; + // The glyphs taken from `page`: all of them, or the part a selection covers. + let span = self.span; + let part = |page: usize, t: &pdfcraft_render::PageText| match span { + Some(span) => span.on(page, t.glyphs.len()).map(|r| t.text_of(r)).unwrap_or_default(), + None => t.text_of(0..t.glyphs.len()), + }; for (page, p) in self.pages.into_iter().enumerate() { if cancel.load(std::sync::atomic::Ordering::Relaxed) { return None; } match p { - CopyPage::Read(t) => push(t.text_of(0..t.glyphs.len())), + CopyPage::Read(t) => push(part(page, &t)), CopyPage::ToRead => { let r = renderer.get_or_insert_with(|| { let config = pdfcraft_render::RenderConfig { password: self.password.clone(), ..Default::default() }; @@ -324,7 +345,7 @@ impl DocumentCopyJob { preview: false, }; if let Some(t) = r.render(req).text { - push(t.text_of(0..t.glyphs.len())); + push(part(page, &t)); } } CopyPage::Skip => {} diff --git a/crates/ui-egui/src/tools/comments/input.rs b/crates/ui-egui/src/tools/comments/input.rs index a23b8e26ae..a8b83c1776 100644 --- a/crates/ui-egui/src/tools/comments/input.rs +++ b/crates/ui-egui/src/tools/comments/input.rs @@ -431,7 +431,11 @@ pub(crate) fn page_after_text(resp: &egui::Response, cx: &PageCx<'_>, view: &mut let QuickTool::Comment(tool) = cx.tool else { return }; let finished = resp.drag_stopped_by(egui::PointerButton::Primary) || resp.double_clicked(); if tool == CommentTool::ReplaceText && cx.allowed && finished { - if let Some((page, quads)) = view.selection_quads(cx.info).filter(|(p, _)| *p == cx.page) { + // A replacement sits on one page: a selection across pages stays selected for the bar's + // markup or Copy. + if let Ok([(page, quads)]) = <[_; 1]>::try_from(view.selection_quads(cx.info)) + && page == cx.page + { view.clear_selection(); let last = quads.last().copied().unwrap_or_default(); let at = [last[2].max(last[6]), last[1].max(last[3])]; @@ -440,15 +444,22 @@ pub(crate) fn page_after_text(resp: &egui::Response, cx: &PageCx<'_>, view: &mut } return; } - if tool.markup().is_none() || !cx.allowed || !finished { - return; - } - if let Some(kind) = tool.markup() - && let Some((page, quads)) = view.selection_quads(cx.info).filter(|(p, _)| *p == cx.page) - { + let Some(kind) = tool.markup().filter(|_| cx.allowed) else { return }; + // Once, from whichever of the selection's pages is drawn: after an edge scroll its first page + // may be out of view. Every page it covers gets its own markup, in one undo step, once all + // of them are read. + if let crate::canvas::ToolMarks::Marks(marks, head) = view.tool_marks(cx.tool, finished, Some(cx.page), false, cx.info) { view.clear_selection(); - view.pending_edit = Some(new_comment(cx, tool, Shape::TextMarkup { kind, quads }, String::new())); - let _ = page; + let edits = marks.into_iter().map(|(page, quads)| { + Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { + page, + shape: Shape::TextMarkup { kind, quads }, + style: cx.prefs.style(tool), + contents: String::new(), + author: cx.prefs.author.clone(), + }) + }); + view.pending_edit = view.selection_marks_edit(edits.collect(), head); } } diff --git a/crates/ui-egui/src/tools/redact_ui.rs b/crates/ui-egui/src/tools/redact_ui.rs index 01c74c46ea..a3fc0f5ec3 100644 --- a/crates/ui-egui/src/tools/redact_ui.rs +++ b/crates/ui-egui/src/tools/redact_ui.rs @@ -235,7 +235,7 @@ fn to_user(xf: &PageXform, info: &DocInfo, page: usize, p: Pos2) -> [f64; 2] { /// Redact tool input on a page. Presses on text are left to text selection (the selection is /// marked when it ends, see [`after_text`]); presses nobody holds (`free`) elsewhere draw a box. /// Returns `true` when the gesture is a box. -pub(crate) fn page_input(cx: PageToolContext<'_>, over_text: impl Fn(Pos2) -> bool, free: bool, view: &mut DocView) -> bool { +pub(crate) fn page_input(cx: PageToolContext<'_>, tool: crate::QuickTool, over_text: impl Fn(Pos2) -> bool, free: bool, view: &mut DocView) -> bool { let PageToolContext { resp, xf, ptr, page, info, .. } = cx; let pointer = ptr.pos; if let Some((dp, start)) = view.redact_drag @@ -247,7 +247,7 @@ pub(crate) fn page_input(cx: PageToolContext<'_>, over_text: impl Fn(Pos2) -> bo let r = Rect::from_two_pos(start, end).intersect(xf.rect); if r.width() >= 3.0 && r.height() >= 3.0 { let (a, b) = (to_user(xf, info, page, r.min), to_user(xf, info, page, r.max)); - view.pending_redaction = Some((page, vec![rect_quad([a[0], a[1], b[0], b[1]])])); + view.pending_redaction = Some((tool, vec![(page, vec![rect_quad([a[0], a[1], b[0], b[1]])])], page)); } } return true; @@ -268,13 +268,20 @@ pub(crate) fn page_input(cx: PageToolContext<'_>, over_text: impl Fn(Pos2) -> bo } /// A finished text selection with the Redact tool becomes a mark. +/// Across pages: a mark on each page it covers, once all are read; refused when one of them could +/// not be read, rather than leave it unmarked. pub(crate) fn after_text(resp: &egui::Response, page: usize, info: &DocInfo, view: &mut DocView) { - if !(resp.drag_stopped_by(egui::PointerButton::Primary) || resp.double_clicked()) || view.redact_drag.is_some() { + if view.redact_drag.is_some() { return; } - if let Some((p, quads)) = view.selection_quads(info).filter(|(p, _)| *p == page) { - view.clear_selection(); - view.pending_redaction = Some((p, quads)); + let finished = resp.drag_stopped_by(egui::PointerButton::Primary) || resp.double_clicked(); + match view.tool_marks(crate::QuickTool::Redact, finished, Some(page), true, info) { + crate::canvas::ToolMarks::Marks(marks, head) => { + view.clear_selection(); + view.pending_redaction = Some((crate::QuickTool::Redact, marks, head)); + } + crate::canvas::ToolMarks::Unreadable => view.redaction_refused = true, + crate::canvas::ToolMarks::None => {} } } diff --git a/crates/ui-egui/tests/it/text_select.rs b/crates/ui-egui/tests/it/text_select.rs index 4bae9a3154..7176ac1ebb 100644 --- a/crates/ui-egui/tests/it/text_select.rs +++ b/crates/ui-egui/tests/it/text_select.rs @@ -105,6 +105,43 @@ fn quick_clicks_with_the_highlighter_mark_only_the_word() { assert!(app.views[0].selected_text().is_none()); } +/// Wait for the page a mark just re-rendered to have its text layer back, glyph `g` of page 1 +/// on screen, within the multi-click window: at most 12 frames of 1/60 s, with real time between +/// them for the render to finish. +fn text_back(h: &mut Harness<'static, PdfCraftApp>, g: usize) { + for _ in 0..12 { + if !h.state().render_pending() && h.state().views[0].glyph_screen_pos(0, g).is_some() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(25)); + h.run_steps(1); + } + panic!("the text layer did not come back within the multi-click window"); +} + +/// Review of #5017: with a markup tool, a third quick press after a double-click starts over +/// from one click, so its drag selects and marks what it moves over, even though the +/// double-click's mark has used up the selection. +#[test] +fn a_markup_drag_right_after_a_double_click_marks_what_it_drags_over() { + let (mut h, at) = harness(|app| assert!(app.execute("comment.underline"))); + click(&mut h, at); + click(&mut h, at); + // A glyph inside "jumps over the dog", on the second line. + text_back(&mut h, 23); + let below = h.state().views[0].glyph_screen_pos(0, 23).expect("glyph on screen"); + press_and_move(&mut h, at, below); + h.event(Event::PointerButton { pos: below, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + crate::support::wait_until(&mut h, "the dragged underline", |app| { + app.session.get(app.views[0].id).is_some_and(|d| d.info.annotations.len() == 2) && !app.render_pending() + }); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + let marks: Vec<(&str, usize)> = doc.info.annotations.iter().map(|a| (a.subtype.as_str(), a.quads.len())).collect(); + assert_eq!(marks, [("Underline", 1), ("Underline", 2)], "the double-clicked word, then the two lines dragged over"); +} + /// Press at `from`, move to `to` and release there. fn drag(h: &mut Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2) { h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); @@ -507,8 +544,8 @@ fn page_top(h: &Harness<'static, PdfCraftApp>, page: usize) -> f32 { } /// Issue #721: selecting near the bottom of a page with the button held, the wheel keeps -/// scrolling while the pointer crosses the gap onto the next page. The selection stays on its -/// own page (a selection can't span pages yet). +/// scrolling while the pointer crosses the gap onto the next page, and the selection follows the +/// pointer onto that page. #[test] fn a_selection_drag_keeps_scrolling_over_the_gap_and_the_next_page() { let (mut h, _) = harness_with(bottom_lines(3), |app| { @@ -534,13 +571,107 @@ fn a_selection_drag_keeps_scrolling_over_the_gap_and_the_next_page() { } } assert!(over_gap && over_next, "the pointer crossed the gap ({over_gap}) onto the next page ({over_next})"); + // The next page's text layer may still be on its way: the selection reaches it once read. + crate::support::wait_until(&mut h, "page 2's text layer", |app| app.views[0].glyph_screen_pos(1, 0).is_some()); + h.hover_at(to); + h.run_steps(2); let held = h.state().views[0].selected_text().expect("still selected"); - assert!(held.starts_with("ends") && "Page 1 ends with this line".contains(held.as_str()), "the selection stays on page 1: {held:?}"); + assert!(held.starts_with("ends with this line\nPage 2"), "the selection runs on onto page 2: {held:?}"); h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); h.run_steps(2); assert_eq!(h.state().views[0].selected_text(), Some(held), "releasing keeps the selection"); } +/// `bottom_lines(3)` at 75 %, every page on screen with its text layer read. +fn three_pages() -> Harness<'static, PdfCraftApp> { + let (mut h, _) = harness_with(bottom_lines(3), |app| { + app.set_option("layout", "continuous").unwrap(); + app.set_option("zoom", "75").unwrap(); + }); + crate::support::wait_until(&mut h, "every page's text layer", |app| { + (0..3).all(|p| app.views[0].glyph_screen_pos(p, 10).is_some()) && !app.render_pending() + }); + let viewport = h.state().views[0].viewport_rect(); + assert!((0..3).all(|p| h.state().views[0].page_screen_rect(p).is_some_and(|r| viewport.contains_rect(r))), "every page in view"); + h +} + +fn glyph_on(h: &Harness<'static, PdfCraftApp>, page: usize, g: usize) -> Pos2 { + h.state().views[0].glyph_screen_pos(page, g).expect("glyph on screen") +} + +/// A drag from one page onto the next selects to the end of the first page and from the start +/// of the next, as in Acrobat, and Copy has both parts in reading order. Dragging the other way +/// selects the same text. +#[test] +fn a_drag_selects_text_across_pages() { + let mut h = three_pages(); + // From "ends" on page 1 (glyph 7) to the "s" of "ends" on page 2 (glyph 10). + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + drag(&mut h, from, to); + let want = "ends with this line\nPage 2 ends"; + assert_eq!(h.state().views[0].selected_text().as_deref(), Some(want), "dragging down"); + h.run_steps(60); + drag(&mut h, to, from); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some(want), "dragging up"); + // Over three pages: the middle one is selected whole. + h.run_steps(60); + let page3 = glyph_on(&h, 2, 3); + drag(&mut h, from, page3); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("ends with this line\nPage 2 ends with this line\nPage")); + // ⌘C copies all of it. + h.event(Event::Copy); + let mut did_copy = false; + for _ in 0..4 { + h.step(); + did_copy |= copied(&h, "ends with this line\nPage 2 ends with this line\nPage"); + } + assert!(did_copy, "Copy has the text of every page"); +} + +/// ⇧-click on another page extends the selection there from its anchor, either way. +#[test] +fn shift_click_extends_the_selection_onto_another_page() { + let mut h = three_pages(); + // "ends" on page 2. + let (from, to) = (glyph_on(&h, 1, 7), glyph_on(&h, 1, 10)); + drag(&mut h, from, to); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("ends")); + h.run_steps(60); + let page3 = glyph_on(&h, 2, 3); + shift_click(&mut h, page3); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("ends with this line\nPage")); + h.run_steps(60); + // Before the anchor, on page 1: from the click to the anchor. + // Glyph 22 is the "l" of "line" (spaces are glyphs too). + let line = glyph_on(&h, 0, 22); + shift_click(&mut h, line); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("line\nPage 2 e")); +} + +/// Marking a selection that runs across pages puts one markup on each page, in one undo step. +#[test] +fn a_selection_across_pages_is_marked_on_every_page_in_one_step() { + use egui_kittest::kittest::Queryable; + let mut h = three_pages(); + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + drag(&mut h, from, to); + h.run_steps(3); + h.get_by_label("Underline").click(); + h.run_steps(3); + let marks = |h: &Harness<'static, PdfCraftApp>| { + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + doc.info.annotations.iter().map(|a| (a.page, a.subtype.clone())).collect::>() + }; + assert_eq!(marks(&h), [(0, "Underline".to_string()), (1, "Underline".to_string())]); + assert!(h.state().views[0].selected_text().is_none(), "the selection is consumed"); + assert!(h.state().views[0].comments.selected.is_some_and(|(page, _)| page == 1), "its last part is selected, as one markup is"); + h.state_mut().undo(); + h.run_steps(3); + assert_eq!(marks(&h), [], "one undo removes both"); +} + /// One 300×600 page with a line of Helvetica text at its top and another at its bottom. fn tall_page() -> Vec { let content = "BT /F1 14 Tf 20 570 Td (Top line) Tj 0 -550 Td (Bottom line) Tj ET"; @@ -749,3 +880,153 @@ fn full_screen_double_click_selects_a_word_and_stays_on_the_page() { h.run_steps(30); assert_eq!(h.state().views[0].current, 0, "no page turn after leaving"); } + +/// A quick drag can be off its page by the frame egui calls it a drag, in the gap or on the next +/// page: the selection still starts where the button went down and runs on to the pointer. +#[test] +fn a_flick_off_the_page_still_selects_from_the_press() { + let mut h = three_pages(); + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + let gap = + egui::pos2(from.x, (h.state().views[0].page_screen_rect(0).unwrap().bottom() + h.state().views[0].page_screen_rect(1).unwrap().top()) / 2.0); + h.hover_at(gap); + h.run_steps(1); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("e"), "started at the press, on page 1; the gap moves nothing"); + h.hover_at(to); + h.run_steps(1); + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("ends with this line\nPage 2 ends")); +} + +/// Review of #5017: a flick back up onto the page before, let go on the frame after the drag +/// starts, selects up to where it was let go. The earlier page is drawn first, so the release +/// frame is the only one that sees the pointer over it with the selection started. +#[test] +fn a_flick_back_onto_the_page_before_selects_to_the_release() { + let mut h = three_pages(); + let (from, to) = (glyph_on(&h, 1, 10), glyph_on(&h, 0, 7)); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.hover_at(to); + h.run_steps(1); + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert_eq!(h.state().views[0].selected_text().as_deref(), Some("ends with this line\nPage 2 ends")); +} + +/// The markup and Redact tools mark a drag across pages on every page it covers, in one step, +/// and so does picking a markup tool with such a selection already made. +#[test] +fn markup_tools_mark_a_selection_across_pages_on_every_page() { + let marks = |h: &Harness<'static, PdfCraftApp>| { + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + doc.info.annotations.iter().map(|a| (a.page, a.subtype.clone())).collect::>() + }; + let both = |kind: &str| vec![(0, kind.to_string()), (1, kind.to_string())]; + for (command, kind) in [("comment.strikeout", "StrikeOut"), ("redact.mark", "Redact")] { + // Dragging with the tool. + let mut h = three_pages(); + assert!(h.state_mut().execute(command)); + h.run_steps(2); + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + drag(&mut h, from, to); + h.run_steps(3); + assert_eq!(marks(&h), both(kind), "{command}: dragged with the tool"); + h.state_mut().undo(); + h.run_steps(3); + assert_eq!(marks(&h), [], "{command}: one undo step"); + // Selecting first, then picking the tool. + // (The tool opened the Comments panel above, which moved the pages.) + let mut h = three_pages(); + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + drag(&mut h, from, to); + assert!(h.state().views[0].selected_text().is_some()); + assert!(h.state_mut().execute(command)); + h.run_steps(3); + assert_eq!(marks(&h), both(kind), "{command}: picked after selecting"); + } +} + +/// Review of #5017: an area highlight whose drag ends in the same frame as Escape (which drops +/// the Highlight tool for Select) is still a highlight, never a redaction: the queued box keeps +/// the tool that drew it. +#[test] +fn an_area_highlight_ended_with_escape_stays_a_highlight() { + let mut h = three_pages(); + assert!(h.state_mut().execute("comment.highlight")); + h.run_steps(2); + // A box in the empty top of page 1 (its text is at the bottom). + let page = h.state().views[0].page_screen_rect(0).expect("page on screen"); + let (from, to) = (page.min + egui::vec2(20.0, 15.0), page.min + egui::vec2(120.0, 60.0)); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for k in 1..=4 { + h.hover_at(from + (to - from) * (k as f32 / 4.0)); + h.run_steps(1); + } + // Release and Escape in one frame. + h.input_mut().events.extend([ + Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }, + ]); + h.run_steps(3); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + let marks: Vec<&str> = doc.info.annotations.iter().map(|a| a.subtype.as_str()).collect(); + assert_eq!(marks, ["Highlight"], "the box is a highlight"); + assert_eq!(doc.redaction_marks(), 0, "nothing marked for redaction"); +} + +/// Review of #5017: a highlight across pages is followed up as one on a single page is: the +/// comment where the selection ends is selected and its note opens for typing. +#[test] +fn a_highlight_across_pages_selects_its_last_part_and_opens_its_note() { + let mut h = three_pages(); + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + drag(&mut h, from, to); + h.run_steps(3); + assert!(h.state_mut().execute("comment.highlight")); + h.run_steps(3); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + let on_page_2 = doc.info.annotations.iter().find(|a| a.page == 1 && a.subtype == "Highlight").map(|a| a.index).expect("a highlight on page 2"); + assert_eq!(app.views[0].comments.selected, Some((1, on_page_2)), "the part where the selection ends is selected"); + assert!(app.views[0].comments.editing.as_ref().is_some_and(|(p, i, _)| (*p, *i) == (1, on_page_2)), "its note is open"); +} + +/// Review of #5017: dragged back up, from page 2 to page 1, the selection ends on page 1: the +/// highlight's part there is the one selected, with its note open. +#[test] +fn a_highlight_dragged_back_across_pages_selects_its_part_where_the_drag_ended() { + let mut h = three_pages(); + let (from, to) = (glyph_on(&h, 0, 7), glyph_on(&h, 1, 10)); + drag(&mut h, to, from); + h.run_steps(3); + assert!(h.state_mut().execute("comment.highlight")); + h.run_steps(3); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + let on_page_1 = doc.info.annotations.iter().find(|a| a.page == 0 && a.subtype == "Highlight").map(|a| a.index).expect("a highlight on page 1"); + assert_eq!(app.views[0].comments.selected, Some((0, on_page_1)), "the part where the drag ended is selected"); + assert!(app.views[0].comments.editing.as_ref().is_some_and(|(p, i, _)| (*p, *i) == (0, on_page_1)), "its note is open"); +} + +/// Review of #5017: only markup on a text selection across pages is followed up as one markup. +/// Redact ▸ Mark Page Range, also one comment per page in one batch, selects nothing and leaves +/// the comment editor alone, as before. +#[test] +fn a_page_range_redaction_is_not_followed_up_as_a_selection() { + let mut h = three_pages(); + h.state_mut().redact_pages_draft = pdfcraft_ui_egui::RedactPagesDraft { current: false, from: 1, to: 3 }; + h.state_mut().redact_pages(); + h.run_steps(3); + let app = h.state(); + let doc = app.session.get(app.views[0].id).unwrap(); + assert_eq!(doc.redaction_marks(), 3, "a mark on every page"); + assert_eq!(app.views[0].comments.selected, None, "no mark selected"); + assert!(app.views[0].comments.editing.is_none(), "no editor opened"); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index b9a87c6058..fd70c61a9b 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -1538,8 +1538,8 @@ milestone = "M3" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/ui.rs::drag_selects_text_and_copy_returns_it", "crates/ui-egui/tests/it/ui.rs::selection_works_in_every_view_rotation", "crates/ui-egui/tests/it/text_select.rs::quick_clicks_select_a_word_then_the_line_then_the_page", "crates/ui-egui/tests/it/text_select.rs::quick_clicks_with_the_highlighter_mark_only_the_word", "crates/ui-egui/tests/it/text_select.rs::shift_click_extends_the_selection_from_its_anchor", "crates/ui-egui/tests/it/comments.rs::selected_text_shows_actions_and_underlines_without_changing_tools", "crates/ui-egui/tests/it/comments.rs::selected_text_replace_action_opens_replacement_composer", "crates/ui-egui/tests/it/comments.rs::selected_text_comment_action_opens_note_composer", "crates/render/src/text/tests.rs::a_drag_along_one_table_row_selects_that_row", "crates/render/src/text/tests.rs::a_drag_over_table_rows_selects_those_rows", "crates/render/src/text/tests.rs::a_pointer_ending_beside_the_column_takes_the_rows", "crates/render/src/text/tests.rs::a_drag_in_the_right_column_takes_nothing_from_the_left", "crates/render/src/text/tests.rs::a_cell_padded_with_spaces_joins_the_next_cell_of_its_row", "crates/ui-egui/tests/it/column_select.rs::a_plain_drag_along_one_table_row_selects_only_that_row", "crates/ui-egui/tests/it/column_select.rs::a_drag_ending_between_the_columns_selects_the_rows", "crates/render/src/text/tests.rs::a_barcode_drawn_with_a_font_reads_apart_from_the_text_beside_it", "crates/render/src/text/tests.rs::a_point_beside_a_barcode_takes_the_text_not_the_code_row", "crates/ui-egui/tests/it/column_select.rs::a_drag_down_text_beside_a_barcode_selects_only_the_text"] -notes = "Drag to select; across a table, which reads column by column, a drag selects by visual rows (the rest of its first row, the rows between, the start of its last), and copy gives the cells tab-separated; a drag down one column keeps reading order, and a QR or Aztec code drawn with a barcode font (as on Mexican CFDI invoices) reads apart from the text beside it. ⇧-click extends the selection to the click, keeping its anchor (same page only); with the Select tool, quick clicks select a word (two), the line (three) or all the text on the page (four). A floating action bar offers comment, highlight, underline, strikethrough, replace text and copy after selection. The markup and Redact tools mark a double-clicked word and stop there. Missing: selection across pages (dragging or ⇧-clicking onto another page), paragraph selection, and ⌘A across the whole document (it selects the current page). Acrobat's other selection context actions such as bookmark, link and export selection remain outside this bar." +evidence = ["crates/ui-egui/tests/it/ui.rs::drag_selects_text_and_copy_returns_it", "crates/ui-egui/tests/it/ui.rs::selection_works_in_every_view_rotation", "crates/ui-egui/tests/it/text_select.rs::quick_clicks_select_a_word_then_the_line_then_the_page", "crates/ui-egui/tests/it/text_select.rs::quick_clicks_with_the_highlighter_mark_only_the_word", "crates/ui-egui/tests/it/text_select.rs::shift_click_extends_the_selection_from_its_anchor", "crates/ui-egui/tests/it/text_select.rs::a_drag_selects_text_across_pages", "crates/ui-egui/tests/it/text_select.rs::shift_click_extends_the_selection_onto_another_page", "crates/ui-egui/tests/it/text_select.rs::a_selection_across_pages_is_marked_on_every_page_in_one_step", "crates/ui-egui/tests/it/text_select.rs::a_highlight_across_pages_selects_its_last_part_and_opens_its_note", "crates/ui-egui/tests/it/text_select.rs::an_area_highlight_ended_with_escape_stays_a_highlight", "crates/ui-egui/tests/it/text_select.rs::a_page_range_redaction_is_not_followed_up_as_a_selection", "crates/ui-egui/tests/it/text_select.rs::a_selection_drag_keeps_scrolling_over_the_gap_and_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_selection_across_pages_copies_each_page_on_its_own_line_once_all_are_read", "crates/ui-egui/src/canvas/tests.rs::a_selection_across_pages_still_to_be_read_is_copied_once_read", "crates/ui-egui/src/canvas/tests.rs::redaction_refuses_a_selection_over_an_unreadable_page", "crates/ui-egui/src/canvas/tests.rs::a_marking_tool_waits_for_the_selections_pages", "crates/ui-egui/src/canvas/tests.rs::waiting_marks_are_dropped_when_their_pages_change", "crates/ui-egui/tests/it/comments.rs::selected_text_shows_actions_and_underlines_without_changing_tools", "crates/ui-egui/tests/it/comments.rs::selected_text_replace_action_opens_replacement_composer", "crates/ui-egui/tests/it/comments.rs::selected_text_comment_action_opens_note_composer", "crates/render/src/text/tests.rs::a_drag_along_one_table_row_selects_that_row", "crates/render/src/text/tests.rs::a_drag_over_table_rows_selects_those_rows", "crates/render/src/text/tests.rs::a_pointer_ending_beside_the_column_takes_the_rows", "crates/render/src/text/tests.rs::a_drag_in_the_right_column_takes_nothing_from_the_left", "crates/render/src/text/tests.rs::a_cell_padded_with_spaces_joins_the_next_cell_of_its_row", "crates/ui-egui/tests/it/column_select.rs::a_plain_drag_along_one_table_row_selects_only_that_row", "crates/ui-egui/tests/it/column_select.rs::a_drag_ending_between_the_columns_selects_the_rows", "crates/render/src/text/tests.rs::a_barcode_drawn_with_a_font_reads_apart_from_the_text_beside_it", "crates/render/src/text/tests.rs::a_point_beside_a_barcode_takes_the_text_not_the_code_row", "crates/ui-egui/tests/it/column_select.rs::a_drag_down_text_beside_a_barcode_selects_only_the_text"] +notes = "Drag to select; ⇧-click extends the selection to the click, keeping its anchor. A selection runs across pages (dragging onto another page, with the edge and wheel scrolling of #721/#1670, or ⇧-clicking there): the rest of the first page, the pages between whole and the last page up to the pointer, copied with each page on a line of its own; pages not read yet are read off the UI thread for Copy, and a markup or Redact tool that finishes the selection first marks it once they are. Across a table, which reads column by column, a drag selects by visual rows (the rest of its first row, the rows between, the start of its last), and copy gives the cells tab-separated; a drag down one column keeps reading order, and a QR or Aztec code drawn with a barcode font (as on Mexican CFDI invoices) reads apart from the text beside it. With the Select tool, quick clicks select a word (two), the line (three) or all the text on the page (four). A floating action bar offers comment, highlight, underline, strikethrough, replace text and copy after selection; across pages, highlight, underline, strikethrough and Redact put one mark on each page in one undo step (Redact refuses a selection over a page whose text could not be read, and says so, rather than leave that page unmarked), while Add comment and Replace text (one page each) are greyed out. The markup and Redact tools mark a double-clicked word and stop there. Missing: paragraph selection, column selection across pages, an explanation on the greyed-out cross-page actions, and a check against Acrobat of its cross-page copied-text format (not observed). Acrobat's other selection context actions such as bookmark, link and export selection remain outside this bar." [[feature]] id = "view.column-select"