pdf-canvas-w12: net change of 3 commits

- pdf-canvas-w12: written from its sheet
- pdf-canvas-w12: repair 1
- pdf-canvas-w12: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:25 -05:00
parent 6b3f9ebd7b
commit b332867d28
5 changed files with 668 additions and 794 deletions
+157 -212
View File
@@ -3,10 +3,19 @@
//! other image as a lossless PNG (with its transparency). The clipboard gets the file, as when a
//! file is copied in Finder or Explorer; Copy Image copies the pixels instead.
use egui::{Color32, CornerRadius, Stroke};
use std::sync::Arc;
use craft::behavior::kurbo::BezPath;
use craft::host::queue::{JobQueue, Priority, QueueOptions};
use craft::host::{Jobs, Wake};
#[cfg(not(target_arch = "wasm32"))]
use craft::platform::clipboard::Flavor;
use craft::pages::ui::PageBody;
use craft::ui::canvas_controls::SelectionOutline;
use craft::ui::contract::Show as _;
use crate::PdfCraftApp;
use crate::canvas::{DocView, PageXform};
use crate::canvas::{DocView, PageSession, PageXform};
use pdfcraft_render::DocInfo;
/// The selected picture: page, index in `page_images` and its box in user space, and the
@@ -19,130 +28,93 @@ pub struct PickedImage {
pub generation: u64,
}
const BLUE: Color32 = Color32::from_rgb(0x3A, 0x7B, 0xF0);
/// A click on page `page` (Select tool, not taken by anything else) selects the picture under
/// it, even with text drawn over it (scans with an OCR layer, captions), with `pick` (a press
/// nobody holds: a link's click follows the link only); dragging or a double click still selects
/// text, and clears the picture.
#[allow(clippy::too_many_arguments)]
pub(crate) fn page_input(
resp: &egui::Response,
xf: &PageXform,
page: usize,
info: &DocInfo,
doc: &pdfcraft_engine::Document,
ptr: &crate::page_pointer::PagePointer,
pick: bool,
view: &mut DocView,
) {
let Some(info_page) = info.pages.get(page) else { return };
/// The picture a click asked for ([`DocView::pending_pick`]), once the page's pictures are known: the window stays live
/// until then. A click made before an edit asks for nothing.
// PLAN: assumed DocView::page_xform returns an owned PageXform (pdf-canvas-w8).
pub(crate) fn resolve_pending(view: &mut DocView, doc: &pdfcraft_engine::Document, info: &DocInfo, jobs: &Arc<dyn Jobs>, wake: &Wake) {
let Some((page, at, clicked_in)) = view.pending_pick else { return };
let generation = doc.edit_generation();
if let Some(p) = ptr.pos.filter(|p| xf.rect.contains(*p)) {
if ptr.drag_started || resp.double_clicked() || resp.triple_clicked() {
view.picked_image = None;
view.pending_pick = None;
return;
}
if resp.clicked() {
// A link's click picks nothing, and takes back an earlier click still being looked into.
view.pending_pick = None;
if pick {
let (vx, vy) = xf.screen_to_view(p);
let u = info_page.view_to_user(vx, vy);
view.picked_image = None;
view.pending_pick = Some((page, [f64::from(u[0]), f64::from(u[1])], generation));
}
}
}
// The click's picture, as soon as the page's pictures are known: the window stays live until then.
let Some((_, at, clicked_in)) = view.pending_pick.filter(|pending| pending.0 == page) else { return };
if clicked_in != generation {
view.pending_pick = None;
} else if let Some(pictures) = view.pictures.get(&resp.ctx, doc, page) {
return;
}
// A page not drawn keeps the click waiting.
let Some(xf) = view.page_xform(page) else { return };
let answer = view.pictures.get(jobs, wake, doc, page).map(|pictures| {
// Where the click was on the page now: the view may have moved while the page was read.
let point = xf.user_rect_f64(info, page, [at[0], at[1], at[0], at[1]]).center();
view.picked_image = pdfcraft_engine::picture_at(pictures, at).and_then(|(index, i)| {
let screen_rect = crate::canvas::image_screen_rect(i, xf, info, page);
pdfcraft_engine::picture_at(pictures, at).and_then(|(index, i)| {
let screen_rect = crate::canvas::image_screen_rect(i, &xf, info, page);
(screen_rect.is_positive() && screen_rect.contains(point)).then(|| PickedImage {
page,
index: *index,
rect: crate::canvas::image_selectable_bounds(i),
generation,
})
});
view.pending_pick = None;
}
})
});
let Some(picked) = answer else { return };
view.picked_image = picked;
view.pending_pick = None;
}
/// Page and document generation.
type PictureKey = (usize, u64);
/// The pictures of the page last asked about, found on their own thread: the search reads every
/// drawing operator on the page, seconds on a dense one. A small file answers on the spot, so its
/// menu and selection don't flicker. The web build has no threads, so there every search runs on
/// the spot, as before.
/// The pictures of the page last asked about, found on a job queue: the search reads every drawing operator on the
/// page, seconds on a dense one. A small file answers on the spot, so its menu and selection don't flicker. On the web
/// the queue has no lanes and each pass runs one search inline, so a dense page never holds a whole frame.
///
/// One search at a time: a page left while it is read is read to the end before the next one
/// starts (the read can't be stopped part-way).
/// One search at a time: a page left while it is read is dropped, and cancelled if it is running.
#[derive(Default)]
pub(crate) struct PagePictures {
/// Made on the first search, on the host's jobs.
queue: Option<JobQueue<PictureKey, Vec<pdfcraft_engine::PagePicture>>>,
/// The pictures of the key's page.
ready: Option<(PictureKey, Vec<pdfcraft_engine::PagePicture>)>,
/// The search under way. One at a time: each is a full read of a page.
job: Option<(PictureKey, std::sync::mpsc::Receiver<Vec<pdfcraft_engine::PagePicture>>)>,
}
impl PagePictures {
/// A file smaller than this has its pictures read on the spot.
const SMALL_FILE: usize = 8 * 1024 * 1024;
/// The pictures on `page`, or `None` while they are being found (a repaint follows the answer).
pub(crate) fn get(&mut self, ctx: &egui::Context, doc: &pdfcraft_engine::Document, page: usize) -> Option<&[pdfcraft_engine::PagePicture]> {
/// The pictures on `page`, or `None` while they are being found (the queue's `wake` repaints on the answer).
// PLAN: the decisions give `get(ctx, host, wake, doc, page)`; the queue needs the host's jobs and the wake only.
pub(crate) fn get(&mut self, jobs: &Arc<dyn Jobs>, wake: &Wake, doc: &pdfcraft_engine::Document, page: usize) -> Option<&[pdfcraft_engine::PagePicture]> {
let key = (page, doc.edit_generation());
self.poll();
if self.job.is_none() && !self.ready.as_ref().is_some_and(|(k, _)| *k == key) {
let known = self.ready.as_ref().is_some_and(|(k, _)| *k == key);
let searching = self.queue.as_ref().is_some_and(|q| q.contains(&key));
if !known && !searching {
match doc.page_pictures_job(page) {
Some(work) if doc.bytes.len() < Self::SMALL_FILE => self.ready = Some((key, work())),
Some(work) => self.start(ctx, key, work),
Some(work) => self.start(jobs, wake, key, work),
None => self.ready = Some((key, Vec::new())),
}
self.poll();
}
self.poll();
self.ready.as_ref().filter(|(k, _)| *k == key).map(|(_, pictures)| pictures.as_slice())
}
fn start(&mut self, ctx: &egui::Context, key: PictureKey, work: impl FnOnce() -> Vec<pdfcraft_engine::PagePicture> + Send + 'static) {
let (send, answer) = std::sync::mpsc::channel();
let ctx = ctx.clone();
let run = move || {
let _ = send.send(work());
ctx.request_repaint();
};
self.job = Some((key, answer));
#[cfg(target_arch = "wasm32")]
run();
#[cfg(not(target_arch = "wasm32"))]
if let Err(e) = std::thread::Builder::new().name("page-pictures".into()).spawn(run) {
log::warn!("page pictures thread: {e}");
self.job = None;
self.ready = Some((key, Vec::new()));
}
fn start(&mut self, jobs: &Arc<dyn Jobs>, wake: &Wake, key: PictureKey, work: impl FnOnce() -> Vec<pdfcraft_engine::PagePicture> + Send + 'static) {
let queue = self.queue.get_or_insert_with(|| {
let mut options = QueueOptions::default();
// One search at a time: each is a full read of a page. The web has no lanes; `poll` runs the job.
options.lanes = if cfg!(target_arch = "wasm32") { 0 } else { 1 };
options.name = "page-pictures";
JobQueue::new(Arc::clone(jobs), wake.clone(), options)
});
queue.reprioritize(|k, priority| (*k == key).then_some(priority));
queue.submit(key, Priority::VISIBLE, move |_| work());
}
/// Take the answer if it has come.
/// Take the answers that have come; on the web, first run one waiting search.
fn poll(&mut self) {
use std::sync::mpsc::TryRecvError;
let Some((key, answer)) = &self.job else { return };
let got = match answer.try_recv() {
Ok(pictures) => Some(pictures),
Err(TryRecvError::Empty) => None,
// The search failed: this page offers no pictures.
Err(TryRecvError::Disconnected) => Some(Vec::new()),
};
if let Some(pictures) = got {
self.ready = Some((*key, pictures));
self.job = None;
let Some(queue) = &self.queue else { return };
#[cfg(target_arch = "wasm32")]
queue.run_inline(1);
while let Some(done) = queue.try_recv() {
self.ready = Some((done.key, done.result));
}
}
}
@@ -150,62 +122,11 @@ impl PagePictures {
#[cfg(test)]
mod picture_tests {
use super::*;
/// A search that takes its time doesn't hold the window: starting and polling it return before
/// the search is let go, and the answer is picked up when it comes.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_slow_page_does_not_hold_up_the_window() {
let (release, wait) = std::sync::mpsc::channel::<()>();
// Lets the search go in the end, should it run on this thread or be waited for.
let late = release.clone();
let let_go = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let watchdog = let_go.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(2));
watchdog.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = late.send(());
});
let mut pictures = PagePictures::default();
let caller = std::thread::current().id();
let (ran_on, ran) = std::sync::mpsc::channel();
pictures.start(&egui::Context::default(), (3, 1), move || {
let _ = ran_on.send(std::thread::current().id());
let _ = wait.recv();
Vec::new()
});
pictures.poll();
assert!(!let_go.load(std::sync::atomic::Ordering::SeqCst), "starting and polling the search must not wait for it");
// A search that never ran (its thread couldn't start) fails the test rather than hanging it.
let ran_on = ran.recv_timeout(std::time::Duration::from_secs(10)).expect("the search ran");
assert_ne!(ran_on, caller, "the search must not run on the calling thread");
let _ = release.send(());
for _ in 0..500 {
std::thread::sleep(std::time::Duration::from_millis(10));
pictures.poll();
if pictures.ready.is_some() {
break;
}
}
assert_eq!(pictures.ready, Some(((3, 1), Vec::new())));
}
/// Escape takes back a click whose picture isn't known yet: it isn't selected when it is.
#[test]
fn escape_cancels_a_click_on_a_page_still_being_read() {
let mut app = PdfCraftApp::new();
app.open_bytes("notes.txt", None, b"hello".to_vec()).unwrap();
let (i, _) = app.active_ids().unwrap();
app.views[i].pending_pick = Some((0, [1.0, 1.0], 0));
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
egui::Context::default()
.run_ui(egui::RawInput { events: vec![escape], ..Default::default() }, |ui| app.image_pick_keys(i, ui.ctx()))
.drop_without_applying_deltas();
assert_eq!(app.views[i].pending_pick, None);
}
use craft::host::{AppInfo, Host, ManualJobs};
use egui_kittest::Harness;
/// A page (200 × 300) with a square comment over 20..80 × 20..80 and a link over 120..180 ×
/// 220..280.
/// 220..280, in a file past `SMALL_FILE`, so its pictures are found on the job queue.
fn page_with_a_comment_and_a_link() -> Vec<u8> {
let objs = [
"<< /Type /Catalog /Pages 2 0 R >>",
@@ -214,7 +135,9 @@ mod picture_tests {
"<< /Type /Annot /Subtype /Square /Rect [20 20 80 80] /C [1 0 0] /Border [0 0 2] >>",
"<< /Type /Annot /Subtype /Link /Rect [120 220 180 280] /Border [0 0 0] /A << /S /URI /URI (https://example.org/) >> >>",
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut out = b"%PDF-1.7\n%".to_vec();
out.extend(std::iter::repeat_n(b'x', PagePictures::SMALL_FILE));
out.push(b'\n');
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
@@ -229,42 +152,35 @@ mod picture_tests {
out
}
/// The page open with the Select tool, once it is on screen, and where a point on it is.
fn open_page() -> (egui_kittest::Harness<'static, PdfCraftApp>, impl Fn(f32, f32) -> egui::Pos2) {
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
let mut app = PdfCraftApp::new();
app.open_bytes("marks.pdf", None, page_with_a_comment_and_a_link()).unwrap();
/// The page open with the Select tool on an app whose jobs wait in `jobs`, once it is on screen, and where a point
/// on it is. The jobs are run only while the page settles.
fn open_page() -> (Harness<'static, PdfCraftApp>, Arc<ManualJobs>, impl Fn(f32, f32) -> egui::Pos2) {
let jobs = Arc::new(ManualJobs::new());
let host_jobs = jobs.clone();
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| {
let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(host_jobs).build();
// PLAN: assumed `AppServices::for_tests() -> AppServices` and `with_host(Arc<Host>, AppServices)`, `set_option` and
// `open_bytes` taking `&egui::Context` (L-207, L-208; pdf-hub-w1, pdf-shell-w9).
let mut app = PdfCraftApp::with_host(Arc::new(host), crate::AppServices::for_tests());
app.set_option("language", "en", &cc.egui_ctx).unwrap();
app.open_bytes("marks.pdf", None, page_with_a_comment_and_a_link(), &cc.egui_ctx).unwrap();
app
});
let mut on_screen = None;
for _ in 0..600 {
jobs.run_all();
h.run_steps(2);
on_screen = h.state().views[0].page_screen_rect(0);
if on_screen.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
let r = on_screen.expect("the page is on screen");
let k = r.width() / 200.0;
(h, move |x, y| r.min + egui::vec2(x * k, (300.0 - y) * k))
(h, jobs, move |x, y| r.min + egui::vec2(x * k, (300.0 - y) * k))
}
/// An earlier click on the page whose pictures are still being found, as on a dense drawing:
/// they don't come while the returned sender lives.
fn click_still_being_looked_into(
h: &mut egui_kittest::Harness<'static, PdfCraftApp>,
) -> std::sync::mpsc::Sender<Vec<pdfcraft_engine::PagePicture>> {
let id = h.state().views[0].id;
let generation = h.state().session.get(id).expect("the document").edit_generation();
let (send, answer) = std::sync::mpsc::channel();
let view = &mut h.state_mut().views[0];
view.pictures = PagePictures { ready: None, job: Some(((0, generation), answer)) };
view.pending_pick = Some((0, [150.0, 150.0], generation));
send
}
fn click(h: &mut egui_kittest::Harness<'static, PdfCraftApp>, p: egui::Pos2) {
fn click(h: &mut Harness<'static, PdfCraftApp>, p: egui::Pos2) {
h.hover_at(p);
h.run_steps(1);
h.drag_at(p);
@@ -273,12 +189,45 @@ mod picture_tests {
h.run_steps(4);
}
/// A click on a blank part of the page whose pictures are still being found, as on a dense drawing: the search waits
/// in the jobs, which the test does not run.
fn click_still_being_looked_into(h: &mut Harness<'static, PdfCraftApp>, at: &impl Fn(f32, f32) -> egui::Pos2) {
click(h, at(100.0, 150.0));
h.run_steps(2);
assert!(h.state().views[0].pending_pick.is_some(), "the click waits for its page");
}
/// A search that takes its time doesn't hold the window: the click returns before the search runs, and its answer is
/// taken in the pass after the job has.
#[test]
fn a_slow_page_does_not_hold_up_the_window() {
let (mut h, jobs, at) = open_page();
click_still_being_looked_into(&mut h, &at);
assert!(jobs.waiting() > 0, "the search is queued as a job");
assert_eq!(h.state().views[0].picked_image, None);
jobs.run_all();
h.run_steps(3);
assert_eq!(h.state().views[0].pending_pick, None, "the answer came: no picture there");
}
/// Escape takes back a click whose picture isn't known yet: it isn't selected when it is.
#[test]
fn escape_cancels_a_click_on_a_page_still_being_read() {
let (mut h, _jobs, at) = open_page();
click_still_being_looked_into(&mut h, &at);
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert_eq!(h.state().views[0].pending_pick, None);
}
/// Another tool lets go of the click, even while its page isn't drawn (Organize pages).
#[test]
fn another_tool_takes_back_a_click_on_a_page_not_drawn() {
let (mut h, _) = open_page();
let _keep = click_still_being_looked_into(&mut h);
assert!(h.state_mut().execute("page.organize"));
let (mut h, _jobs, at) = open_page();
click_still_being_looked_into(&mut h, &at);
// PLAN: assumed `execute(command, &egui::Context)` (L-208).
let ctx = h.ctx.clone();
assert!(h.state_mut().execute("page.organize", &ctx));
h.run_steps(2);
assert!(h.state().views[0].pending_pick.is_some(), "the click waits while the page isn't drawn");
h.state_mut().quick_tool = crate::QuickTool::Hand;
@@ -292,18 +241,20 @@ mod picture_tests {
/// comment is selected.
#[test]
fn a_click_on_a_comment_takes_back_the_earlier_click() {
let (mut h, at) = open_page();
let _keep = click_still_being_looked_into(&mut h);
let (mut h, _jobs, at) = open_page();
click_still_being_looked_into(&mut h, &at);
h.run_steps(30);
click(&mut h, at(50.0, 50.0));
assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment is selected");
assert!(h.state().views[0].comments.primary().is_some(), "the comment is selected");
assert_eq!(h.state().views[0].pending_pick, None);
}
/// A click on a link follows it and lets go of the earlier click too.
#[test]
fn a_click_on_a_link_takes_back_the_earlier_click() {
let (mut h, at) = open_page();
let _keep = click_still_being_looked_into(&mut h);
let (mut h, _jobs, at) = open_page();
click_still_being_looked_into(&mut h, &at);
h.run_steps(30);
click(&mut h, at(150.0, 250.0));
assert!(h.state().pending_link.is_some(), "the link is followed");
assert_eq!(h.state().views[0].pending_pick, None);
@@ -319,15 +270,26 @@ pub(crate) fn drop_stale(doc: &pdfcraft_engine::Document, view: &mut DocView) {
}
}
/// The selected picture's highlight on page `page`.
pub(crate) fn paint(painter: &egui::Painter, xf: &PageXform, page: usize, info: &DocInfo, view: &DocView) {
let Some(picked) = view.picked_image.filter(|p| p.page == page) else { return };
if info.pages.get(page).is_none() || !picked.rect.iter().all(|v| v.is_finite()) {
/// The selected picture's outline in the page body, over the page as shown with the view turned by `rotation`.
// PLAN: pdf-canvas-w8's body calls `selection::show_picked(ui, body, session, cx.info)`; it is here, and takes
// `cx.rotation` after `session`.
pub(crate) fn show_picked(ui: &mut egui::Ui, body: &PageBody<'_>, session: &PageSession, rotation: u16, info: &DocInfo) {
let Some(picked) = session.picked_image else { return };
let Some(info_page) = info.pages.get(picked.page) else { return };
if !picked.rect.iter().all(|v| v.is_finite()) {
return;
}
let r = xf.user_rect(info, page, picked.rect.map(|v| v as f32));
painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 50));
painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(2.0, BLUE), egui::StrokeKind::Outside);
let Some(placed) = session.placed.iter().find(|p| p.page == picked.page) else { return };
let xf = PageXform::of(placed, rotation, (info_page.width, info_page.height));
let r = xf.user_rect(info, picked.page, picked.rect.map(|v| v as f32));
let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| body.view.to_doc(p));
let mut path = BezPath::new();
path.move_to(corners[0]);
for corner in &corners[1..] {
path.line_to(*corner);
}
path.close_path();
let _ = SelectionOutline::solid(tl!("Picked picture"), &[path]).show_at(ui, body.rect);
}
/// A file name without characters file systems refuse.
@@ -338,7 +300,7 @@ pub(crate) fn safe_name(s: &str) -> String {
}
/// The per-user folder that holds the file of the last Copy Image in Original Format: `Clipboard`
/// in the portable data folder in portable mode ([`crate::portable`]), otherwise the platform's
/// in the portable data folder in portable mode ([`crate::settings::portable_dir`]), otherwise the platform's
/// per-user cache folder: `~/Library/Caches/PdfCraft/Clipboard` (macOS),
/// `%LOCALAPPDATA%\PdfCraft\Clipboard` (Windows), or `$XDG_CACHE_HOME/pdfcraft/clipboard` /
/// `~/.cache/pdfcraft/clipboard` (others). Never the shared temporary folder, where another user
@@ -346,7 +308,7 @@ pub(crate) fn safe_name(s: &str) -> String {
#[cfg(not(target_arch = "wasm32"))]
fn clipboard_dir() -> Option<std::path::PathBuf> {
use std::path::PathBuf;
if let Some(dir) = crate::portable::data_dir() {
if let Some(dir) = crate::settings::portable_dir() {
return Some(dir.join("Clipboard"));
}
let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from).filter(|p| p.is_absolute());
@@ -416,33 +378,21 @@ fn write_clipboard_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> Resu
}
impl PdfCraftApp {
/// ⌘C / Ctrl+C copies the selected picture in its original format; Escape deselects it, or
/// takes back a click whose picture isn't known yet.
pub(crate) fn image_pick_keys(&mut self, i: usize, ctx: &egui::Context) {
if ctx.egui_wants_keyboard_input() {
return;
}
if self.page_keys.pressed(ctx, egui::Key::Escape) {
if let Some(view) = self.views.get_mut(i) {
view.picked_image = None;
view.pending_pick = None;
}
return;
}
let Some(picked) = self.views.get(i).and_then(|v| v.picked_image) else { return };
let copy = self.page_keys.clipboard(ctx).copy;
if !copy || self.views[i].selected_text().is_some() {
return;
}
// The document may have changed since the click: the same picture must still be there.
let current =
self.session.get(self.views[i].id).and_then(|d| d.page_images(picked.page).get(picked.index).map(crate::canvas::image_selectable_bounds));
/// ⌘C / Ctrl+C with a picture picked and no text selected: copies the picture in its original format. The document
/// may have changed since the click: the same picture must still be there, else it is let go. Returns whether
/// there was a picked picture to copy.
pub(crate) fn copy_picked_image(&mut self, i: usize) -> bool {
let Some((id, picked)) = self.views.get(i).and_then(|v| Some((v.id, v.picked_image?))) else { return false };
let current = self.session.get(id).and_then(|d| d.page_images(picked.page).get(picked.index).map(crate::canvas::image_selectable_bounds));
if current == Some(picked.rect) {
self.copy_page_image_file(picked.page, picked.index);
} else {
self.views[i].picked_image = None;
if let Some(view) = self.views.get_mut(i) {
view.picked_image = None;
}
self.notify_tr("The page has changed; select the image again");
}
true
}
/// Copy Image in Original Format: image `index` on `page` as a file on the clipboard (JPEG
@@ -473,21 +423,16 @@ impl PdfCraftApp {
/// Writes `bytes` to PdfCraft's private clipboard folder ([`clipboard_dir`]), replacing the
/// previous copy, and puts that file on the system clipboard.
#[cfg(not(target_arch = "wasm32"))]
fn put_file_on_clipboard(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
if !self.system_clipboard {
return Ok(());
}
fn put_file_on_clipboard(&mut self, name: &str, bytes: &[u8]) -> Result<(), String> {
let dir = clipboard_dir().ok_or("there is no folder for the copied file")?;
let path = write_clipboard_file(&dir, name, bytes)?;
crate::os_clipboard::with(|c| c.set().file_list(&[path])).map_err(|e| e.to_string())
// PLAN: assumed `PdfCraftApp.clipboard: craft::platform::clipboard::Clipboard` (pdf-hub-w1, the services given to `with_host`)
self.clipboard.write(&[Flavor::files(&[path])]).map(|_| ()).map_err(|e| e.to_string())
}
#[cfg(target_arch = "wasm32")]
fn put_file_on_clipboard(&self, _name: &str, _bytes: &[u8]) -> Result<(), String> {
if self.system_clipboard {
return Err("the web version can't put files on the clipboard yet; use Save Image As".to_string());
}
Ok(())
fn put_file_on_clipboard(&mut self, _name: &str, _bytes: &[u8]) -> Result<(), String> {
Err("the web version can't put files on the clipboard yet; use Save Image As".to_string())
}
}
+126
View File
@@ -0,0 +1,126 @@
//! The Select tool on the page view: the framework's text selection, and the pick of a picture under a click.
use craft::behavior::{CancelReason, Cursor};
use craft::pages::ui::{PageTexts, PlacedPage, TextSelectState, TextSelectTool};
use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft::ui::primitives::Draw;
use pdfcraft_render::DocInfo;
use crate::canvas::PageXform;
use crate::canvas::image_pick::PickedImage;
/// The two places a pick lives: the click whose picture is still being looked for, and the picture found.
pub(crate) struct PickSlots<'a> {
pending: &'a mut Option<(usize, [f64; 2], u64)>,
picked: &'a mut Option<PickedImage>,
}
impl<'a> PickSlots<'a> {
/// The slots over the view's `pending_pick` and `picked_image`.
pub(crate) fn new(pending: &'a mut Option<(usize, [f64; 2], u64)>, picked: &'a mut Option<PickedImage>) -> Self {
Self { pending, picked }
}
fn let_go(&mut self) {
*self.picked = None;
*self.pending = None;
}
fn held(&self) -> bool {
self.picked.is_some() || self.pending.is_some()
}
}
/// Acrobat's Select tool: [`TextSelectTool`] for the text, plus the picture a click picks (a press nobody's part took
/// reaches the tool). Built per pass over the disjoint fields of the view, so the text layers can be borrowed beside it.
///
/// The pick is set by the press and let go by the first `drag` (the host calls it only past the click distance), so a
/// click keeps it and a drag, a double click and Escape drop it, with nothing carried from one pass to the next in the
/// tool.
pub(crate) struct PageSelectTool<'a> {
text: TextSelectTool<'a>,
info: &'a DocInfo,
picks: PickSlots<'a>,
xforms: &'a [(usize, PageXform)],
generation: u64,
}
impl<'a> PageSelectTool<'a> {
/// The tool over the placed `pages` and their `xforms` (the pages as the view shows them), reading text from
/// `texts`, keeping its gesture in `text`; `generation` is the document's edit generation, which a pick carries.
// PLAN: the decisions give no `info`; the view-to-user mapping of the pick needs it (pdf-canvas-w9's arm passes it,
// and the two pick fields as `PickSlots::new(&mut pending_pick, &mut picked_image)`).
pub(crate) fn new(
pages: &'a [PlacedPage],
texts: &'a dyn PageTexts,
text: &'a mut TextSelectState,
info: &'a DocInfo,
picks: PickSlots<'a>,
xforms: &'a [(usize, PageXform)],
generation: u64,
) -> Self {
Self { text: TextSelectTool::new(pages, texts, text), info, picks, xforms, generation }
}
/// The Column Select tool is active.
pub(crate) fn column(mut self, on: bool) -> Self {
self.text = self.text.column(on);
self
}
/// A press asks for the picture under it, unless it is a double click or more, which select text.
fn pick(&mut self, pointer: &ToolPointer) {
self.picks.let_go();
if pointer.clicks >= 2 {
return;
}
let Some((page, xf)) = self.xforms.iter().find(|(_, xf)| xf.rect.contains(pointer.pos)) else { return };
let Some(info_page) = self.info.pages.get(*page) else { return };
let (vx, vy) = xf.screen_to_view(pointer.pos);
let u = info_page.view_to_user(vx, vy);
*self.picks.pending = Some((*page, [f64::from(u[0]), f64::from(u[1])], self.generation));
}
}
impl CanvasTool for PageSelectTool<'_> {
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
self.text.cursor(cx)
}
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
let action = self.text.press(pointer, cx);
self.pick(pointer);
action
}
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
self.picks.let_go();
self.text.drag(pointer, cx);
}
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
self.text.release(pointer, cx);
}
fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) {
self.picks.let_go();
self.text.cancel(reason, cx);
}
/// Escape lets go of the picked picture, or of a click whose picture is not known yet, before it clears the text.
fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool {
if matches!(key, ToolKey::Cancel) && self.picks.held() {
self.picks.let_go();
return true;
}
self.text.key(key, cx)
}
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
self.text.paint(draw, cx);
}
fn command_form(&self) -> ToolPath {
self.text.command_form()
}
}
+310 -247
View File
@@ -1,126 +1,148 @@
use super::{Arc, DocInfo, DocView, Edit, HashMap, PageText, Pos2, Range, Rect, comments, pos2};
use super::{Arc, DocInfo, DocView, Edit, PageSession, PageText, Pos2, Range, Rect, comments};
use crate::QuickTool;
use std::ops::RangeInclusive;
use craft::behavior::kurbo::{self, Point};
use craft::pages::ui::{PageBody, PageTextSource, PageTexts, TextSelection, TextSpan as FwSpan};
use craft::ui::buttons::Button;
use craft::ui::canvas_controls::TaskBar;
use craft::ui::contract::{Props as _, Show as _};
use std::collections::{HashMap, HashSet};
/// 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,
pub(super) span: Span,
/// The text layer of a page that could not be read: a page with nothing to select, which a selection across
/// pages passes over.
static NO_TEXT: PageText = PageText { glyphs: Vec::new(), line_of: Vec::new(), space_before: Vec::new(), truncated: false };
/// One page's extracted text as the framework's selection tool reads it. The tool works in the page as shown (the view
/// rotation applied, `PlacedPage::to_page`); the text layer is in view space, which the rotation leaves unturned, so
/// points and rectangles are mapped between the two here, along with `f32` to `f64`.
pub(crate) struct AppText<'a> {
text: &'a PageText,
/// The view rotation in degrees, 0 to 359.
rotation: i32,
/// The page's size in view space.
size: (f64, f64),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Span {
/// 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<f32> },
/// 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] },
}
impl Selection {
pub(super) fn run(page: usize, anchor: usize, head: usize) -> Self {
Self { page, span: Span::Run { anchor, head, head_page: page, head_x: None } }
impl<'a> AppText<'a> {
/// The layer `text` of a page `size` points large in view space, shown turned by `rotation` degrees.
pub(crate) fn new(text: &'a PageText, rotation: i32, size: (f32, f32)) -> Self {
Self { text, rotation: rotation.rem_euclid(360), size: (f64::from(size.0), f64::from(size.1)) }
}
fn range(anchor: usize, head: usize) -> Range<usize> {
anchor.min(head)..anchor.max(head).saturating_add(1)
}
/// What a drag over table rows selects by rows, not reading order's detour down each column.
/// 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<f32>) -> Option<Vec<usize>> {
head_x.and_then(|x| text.visual_between(anchor, head, Some(x)))
}
/// The pages the selection covers, first to last.
pub(super) fn pages(&self) -> RangeInclusive<usize> {
match self.span {
Span::Run { head_page, .. } => self.page.min(head_page)..=self.page.max(head_page),
Span::Column { .. } => self.page..=self.page,
}
}
/// 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 { 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<Range<usize>> {
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<TextSpan> {
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))
/// A point of the page as shown, in view space.
fn to_view(&self, p: Point) -> (f32, f32) {
let (w, h) = self.size;
let (x, y) = match self.rotation {
90 => (p.y, h - p.x),
180 => (w - p.x, h - p.y),
270 => (w - p.y, p.x),
_ => (p.x, p.y),
};
Some(TextSpan { start, end })
(x as f32, y as f32)
}
/// 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(),
/// A point of view space, in the page as shown.
fn to_shown(&self, x: f32, y: f32) -> Point {
let (w, h) = self.size;
let (x, y) = (f64::from(x), f64::from(y));
match self.rotation {
90 => Point::new(h - y, x),
180 => Point::new(w - x, h - y),
270 => Point::new(y, w - x),
_ => Point::new(x, y),
}
}
/// 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(),
}
fn shown_rect(&self, r: [f32; 4]) -> kurbo::Rect {
kurbo::Rect::from_points(self.to_shown(r[0], r[1]), self.to_shown(r[2], r[3]))
}
/// 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<f32>) {
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);
/// A rectangle of the page as shown, in view space as `[x0, y0, x1, y1]`.
pub(crate) fn view_rect(&self, r: kurbo::Rect) -> [f32; 4] {
let (a, b) = (self.to_view(Point::new(r.x0, r.y0)), self.to_view(Point::new(r.x1, r.y1)));
[a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)]
}
}
impl PageTextSource for AppText<'_> {
fn glyph_count(&self) -> usize {
self.text.glyphs.len()
}
fn glyph_at(&self, p: Point) -> Option<usize> {
let (x, y) = self.to_view(p);
self.text.nearest(x, y)
}
fn glyph_box_at(&self, p: Point) -> Option<usize> {
let (x, y) = self.to_view(p);
self.text.glyphs.iter().position(|g| g.rect[0] <= x && x <= g.rect[2] && g.rect[1] <= y && y <= g.rect[3])
}
fn line_rects(&self, glyphs: Range<usize>) -> Vec<kurbo::Rect> {
self.text.line_rects(glyphs).into_iter().map(|r| self.shown_rect(r)).collect()
}
fn glyphs_in(&self, rect: kurbo::Rect) -> Vec<usize> {
self.text.glyphs_in(self.view_rect(rect))
}
fn word_at(&self, glyph: usize) -> Option<Range<usize>> {
self.text.word_at(glyph).map(|(first, last)| first..last.saturating_add(1))
}
fn line_at(&self, glyph: usize) -> Option<Range<usize>> {
self.text.line_at(glyph).map(|(first, last)| first..last.saturating_add(1))
}
fn text_of(&self, glyphs: Range<usize>) -> String {
self.text.text_of(glyphs)
}
fn column_text(&self, glyphs: &[usize]) -> String {
self.text.column_text(glyphs)
}
/// What a drag over table rows selects by rows, not reading order's detour down each column. Rows run along the
/// text layer's x axis, which a quarter turn of the view makes the shown y axis: only an unturned or half-turned
/// page has an `end_x` to take.
fn rows_between(&self, anchor: usize, head: usize, end_x: f64) -> Option<Vec<usize>> {
let x = match self.rotation {
0 => end_x,
180 => self.size.0 - end_x,
_ => return None,
};
self.text.visual_between(anchor, head, Some(x as f32))
}
}
/// The text layers of a document's pages for the selection tool, built per pass from what the view has read.
pub(crate) struct DocTexts<'a> {
pages: HashMap<usize, AppText<'a>>,
}
impl<'a> DocTexts<'a> {
/// The layers in `texts`, shown turned by `rotation`, with `sizes` the pages' sizes in view space. A page in
/// `failed` has an empty layer: nothing is selected on it, and it does not hold a copy back.
// PLAN: the decisions give `new(texts, rotation, sizes)`; `failed` is added so failed pages stay out of a copy.
pub(crate) fn new(texts: &'a HashMap<usize, Arc<PageText>>, failed: &HashSet<usize>, rotation: impl Into<i32>, sizes: &[(f32, f32)]) -> Self {
let rotation = rotation.into();
let size = |page: usize| sizes.get(page).copied().unwrap_or_default();
let mut pages: HashMap<usize, AppText<'a>> = texts.iter().map(|(&p, t)| (p, AppText::new(t, rotation, size(p)))).collect();
for &p in failed {
pages.entry(p).or_insert_with(|| AppText::new(&NO_TEXT, rotation, size(p)));
}
Self { pages }
}
/// Page `page`'s layer, with its mappings to view space.
pub(crate) fn app(&self, page: usize) -> Option<&AppText<'a>> {
self.pages.get(&page)
}
}
impl PageTexts for DocTexts<'_> {
fn page(&self, page: usize) -> Option<&dyn PageTextSource> {
self.pages.get(&page).map(|t| t as &dyn PageTextSource)
}
}
@@ -158,77 +180,103 @@ impl TextSpan {
}
}
/// 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))
};
/// A reading-order selection's ends in reading order; `None` for a column selection.
fn reading_span(selection: &TextSelection) -> Option<TextSpan> {
let FwSpan::Run { anchor, head, head_page, .. } = selection.span else { return None };
// (page, glyph) pairs compare in reading order.
let (start, end) = if (selection.page, anchor) <= (head_page, head) {
((selection.page, anchor), (head_page, head))
} else {
((head_page, head), (selection.page, anchor))
};
Some(TextSpan { start, end })
}
/// The page the selection ends on, where its drag finished: a reading-order selection's head page, a column
/// selection's own page.
fn head_page_of(selection: &TextSelection) -> usize {
match selection.span {
FwSpan::Run { head_page, .. } => head_page,
_ => selection.page,
}
}
/// The glyphs `clicks` quick clicks select around glyph `a`: two the word, three the line, more
/// the page.
pub(super) fn click_unit(text: &PageText, clicks: u32, a: usize) -> Option<(usize, usize)> {
match clicks {
2 => text.word_at(a),
3 => text.line_at(a),
_ => text.glyphs.len().checked_sub(1).map(|last| (0, last)),
}
/// The pages' sizes in view space, which the text layers are mapped by.
fn page_sizes(info: &DocInfo) -> Vec<(f32, f32)> {
info.pages.iter().map(|p| (p.width, p.height)).collect()
}
impl DocView {
/// 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<Vec<(usize, &Arc<PageText>)>> {
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 selection's state lives in the page session, which the page body works on while the page view holds the view
// state; the view's methods below delegate to it.
impl PageSession {
/// The text layers read so far, shown turned by `rotation`, with `sizes` the pages' sizes in view space.
fn doc_texts(&self, rotation: u16, sizes: &[(f32, f32)]) -> DocTexts<'_> {
DocTexts::new(&self.texts, &self.text_failed, rotation, sizes)
}
/// 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)| {
pub(crate) fn selection_quads(&self, info: &DocInfo, rotation: u16) -> Vec<(usize, Vec<[f64; 8]>)> {
let Some(s) = self.text.selection else { return Vec::new() };
let sizes = page_sizes(info);
let texts = self.doc_texts(rotation, &sizes);
if !s.unread_pages(&texts).is_empty() {
return Vec::new();
}
s.pages()
.filter_map(|p| {
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();
let app = texts.app(p)?;
let quads: Vec<[f64; 8]> = s.rects_on(p, app).into_iter().map(|r| page.view_rect_to_quad(app.view_rect(r))).collect();
(!quads.is_empty()).then_some((p, quads))
})
.collect()
}
/// Drops the selection, with the bar and the marks that waited on it.
pub(crate) fn clear_selection(&mut self) {
self.text.selection = None;
self.actions_dismissed = None;
self.marks_waiting = None;
}
/// The edit adding what a tool marks on a text selection ([`DocView::selection_marks_edit`]).
pub(crate) fn selection_marks_edit(&mut self, edits: Vec<Edit>, head: usize) -> Option<Edit> {
let edit = one_undo_step(edits);
self.marks_across_pages = matches!(edit, Some(Edit::Batch { .. })).then_some(head);
edit
}
}
impl DocView {
/// The text layers the view has read, for the selection tool and what reads its selection.
pub(crate) fn doc_texts(&self) -> DocTexts<'_> {
DocTexts::new(&self.texts, &self.text_failed, self.rotation, &self.page_sizes)
}
/// Whether a page the selection covers is still to be read, so a selection is never copied or marked short.
fn selection_unread(&self) -> bool {
self.text.selection.is_some_and(|s| !s.unread_pages(&self.doc_texts()).is_empty())
}
/// 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]>)> {
self.session.selection_quads(info, self.view.rotation)
}
/// 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<TextSpan> {
self.selection.filter(|_| self.selection_texts().is_none())?.text_span()
let s = self.text.selection.filter(|_| self.selection_unread())?;
reading_span(&s)
}
/// 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)))
self.text.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
@@ -240,14 +288,14 @@ impl DocView {
/// 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<usize>, whole: bool, info: &DocInfo) -> ToolMarks {
let Some(sel) = self.selection else {
let Some(sel) = self.text.selection else {
self.marks_waiting = None;
return ToolMarks::None;
};
if finished {
self.marks_waiting = Some((tool, sel));
}
if self.marks_waiting != Some((tool, sel)) {
if !self.marks_waiting.as_ref().is_some_and(|(t, s)| *t == tool && *s == 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;
@@ -257,7 +305,7 @@ impl DocView {
self.marks_waiting = None;
return ToolMarks::Unreadable;
}
if self.selection_texts().is_none() {
if self.selection_unread() {
return ToolMarks::None;
}
let marks = self.selection_quads(info);
@@ -270,7 +318,7 @@ impl DocView {
return ToolMarks::None;
}
self.marks_waiting = None;
ToolMarks::Marks(marks, sel.head_page())
ToolMarks::Marks(marks, head_page_of(&sel))
}
/// The edit adding what a tool marks on a text selection, one edit per page, as one undo
@@ -279,21 +327,17 @@ impl DocView {
/// 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<Edit>, head: usize) -> Option<Edit> {
let edit = one_undo_step(edits);
self.marks_across_pages = matches!(edit, Some(Edit::Batch { .. })).then_some(head);
edit
self.session.selection_marks_edit(edits, head)
}
pub(crate) fn clear_selection(&mut self) {
self.selection = None;
self.actions_dismissed = None;
self.marks_waiting = None;
self.session.clear_selection();
}
/// Select text on `page` from glyph `from` to glyph `to` (tests and automation).
pub fn select_text(&mut self, page: usize, from: usize, to: usize) {
self.all_text = false;
self.selection = Some(Selection::run(page, from, to));
self.text.selection = Some(TextSelection::new(page, FwSpan::run(from, page, to)));
}
/// Screen position of the centre of glyph `glyph` on `page`, if that page is on screen and its
@@ -309,7 +353,6 @@ impl DocView {
Some(xf.view_rect(g.rect))
}
/// 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`]). A selection across pages has each page's
/// part on a line of its own, as Select All of the document does.
@@ -317,9 +360,7 @@ impl DocView {
if self.all_text {
return Some(self.whole_text(&HashMap::new())).filter(|x| !x.is_empty());
}
let (s, texts) = (self.selection?, self.selection_texts()?);
let parts: Vec<String> = 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())
self.text.selection?.text(&self.doc_texts()).filter(|x| !x.is_empty())
}
/// The selection's page, its text layer and the selected glyphs in copy order, for Copy with
@@ -331,17 +372,18 @@ impl DocView {
if self.all_text {
return None;
}
let s = self.selection.filter(|s| !s.spans_pages())?;
let s = self.text.selection.filter(|s| s.pages().start() == s.pages().end())?;
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() => {
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. Across pages is excluded above.
Span::Run { .. } | Span::Column { .. } => return None,
};
Some((s.page, t.clone(), glyphs))
let texts = self.doc_texts();
let source = texts.page(s.page)?;
let FwSpan::Run { anchor, head, end_x, .. } = s.span else { return None };
// A table's rows, like a column, are tab-separated cells.
if end_x.and_then(|x| source.rows_between(anchor, head, x)).is_some() {
return None;
}
let from = anchor.min(head);
let to = anchor.max(head).saturating_add(1).min(t.glyphs.len());
Some((s.page, t.clone(), (from..to).collect()))
}
/// Select every page without navigating; shared by Organize and the Pages sidebar.
@@ -361,7 +403,7 @@ impl DocView {
// Like the page's, true once some text is selected: the pages whose text isn't read yet are
// read when the selection is copied.
if self.continuous && self.page_count > 1 {
self.selection = None;
self.text.selection = None;
self.all_text = true;
return self.selected_text().is_some();
}
@@ -371,7 +413,7 @@ impl DocView {
if t.glyphs.is_empty() {
return false;
}
self.selection = Some(Selection::run(page, 0, t.glyphs.len() - 1));
self.text.selection = Some(TextSelection::new(page, FwSpan::run(0, page, t.glyphs.len() - 1)));
true
}
@@ -407,9 +449,6 @@ enum SelectionAction {
Copy,
}
/// 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.
@@ -422,88 +461,92 @@ pub(crate) fn one_undo_step(mut edits: Vec<Edit>) -> Option<Edit> {
}
/// 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
/// screen, as a rectangle of the page as shown. 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<PageText>)]) -> 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);
pub(super) fn bar_anchor(selection: &TextSelection, texts: &dyn PageTexts) -> Option<(usize, kurbo::Rect)> {
let at_head = || {
let FwSpan::Run { head_page, .. } = selection.span else { return None };
let backward = head_page < selection.page;
let rects = selection.rects_on(head_page, texts.page(head_page)?);
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))))
};
at_head().or_else(|| {
selection.pages().rev().find_map(|p| {
let rects = selection.rects_on(p, texts.page(p)?);
rects.last().map(|r| (p, *r))
})
})
}
/// Actions on an existing text selection, next to the selected words.
pub(super) fn selection_actions(
/// Actions on an existing text selection, next to the selected words. Returns whether Copy was chosen; the caller
/// copies once the session borrow ends. It works on the page session, as the page body does, and takes the view's
/// `rotation` for where the words are shown.
// PLAN: pdf-canvas-w8's body calls `selection_bar(ui, body, session, info, prefs, may_mark, can_copy)`; `rotation`
// (`cx.rotation`) goes after `info`.
pub(super) fn selection_bar(
ui: &mut egui::Ui,
viewport: Rect,
view: &mut DocView,
body: &PageBody<'_>,
session: &mut PageSession,
info: &DocInfo,
rotation: u16,
prefs: &comments::CommentPrefs,
can_comment: bool,
can_copy: bool,
) -> bool {
if ui.input(|input| input.pointer.is_decidedly_dragging()) {
if body.pass.is_some_and(|p| p.press.phase.button_down()) {
return false;
}
let Some(selection) = view.selection else {
view.actions_dismissed = None;
let Some(selection) = session.text.selection else {
session.actions_dismissed = None;
return false;
};
if view.actions_dismissed == Some(selection) {
if session.actions_dismissed == Some(selection) {
return false;
}
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 };
let sizes = page_sizes(info);
let anchor = {
let texts = session.doc_texts(rotation, &sizes);
if selection.text(&texts).is_none_or(|t| t.is_empty()) {
return false;
}
let Some((page, last)) = bar_anchor(&selection, &texts) else { return false };
let Some(placed) = body.pages.iter().find(|p| p.page == page) else { return false };
let corners = [Point::new(last.x0, last.y0), Point::new(last.x1, last.y0), Point::new(last.x1, last.y1), Point::new(last.x0, last.y1)];
let screen = corners.map(|c| placed.to_screen(c));
if !body.rect.intersects(egui::Rect::from_points(&screen)) {
return false;
}
screen.map(|p| body.view.to_doc(p)).to_vec()
};
// 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;
}
let id = egui::Id::unique(("text-selection-actions", view.view_key()));
// The bar stays inside the pages' area, by the width it had last frame (its labels make it
// wider in some languages), so it never covers a side panel; a first guess before it has one.
let width = egui::AreaState::load(ui.ctx(), id).and_then(|a| a.size).map_or(SELECTION_BAR_GUESS, |s| s.x);
let x = rect.left().clamp(viewport.left() + 8.0, (viewport.right() - width - 8.0).max(viewport.left() + 8.0));
let y = if rect.bottom() + 48.0 < viewport.bottom() { rect.bottom() + 6.0 } else { (rect.top() - 44.0).max(viewport.top() + 6.0) };
let across_pages = selection.pages().start() != selection.pages().end();
let mut chosen = None;
egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos2(x, y)).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
for (label, action) in [
(tl!("Add comment"), SelectionAction::Note),
(tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
(tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
(tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
(tl!("Replace text"), SelectionAction::Replace),
] {
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);
}
}
if ui.add_enabled(can_copy, egui::Button::new(tl!("Copy"))).clicked() {
chosen = Some(SelectionAction::Copy);
}
});
});
TaskBar::fixed(tl!("Selection"), &anchor).show(ui, body.rect, |ui, _| {
for (label, action) in [
(tl!("Add comment"), SelectionAction::Note),
(tl!("Highlight"), SelectionAction::Markup(comments::CommentTool::Highlight)),
(tl!("Underline"), SelectionAction::Markup(comments::CommentTool::Underline)),
(tl!("Strikethrough"), SelectionAction::Markup(comments::CommentTool::StrikeOut)),
(tl!("Replace text"), SelectionAction::Replace),
] {
let one_page_only = matches!(action, SelectionAction::Note | SelectionAction::Replace);
if Button::new(label).enabled(can_comment && !(across_pages && one_page_only)).show(ui).clicked() {
chosen = Some(action);
}
}
if Button::new(tl!("Copy")).enabled(can_copy).show(ui).clicked() {
chosen = Some(SelectionAction::Copy);
}
});
let Some(action) = chosen else { return false };
if let SelectionAction::Copy = action {
// Copying closes the bar but keeps the words selected, for ⌘C or a second action.
view.actions_dismissed = Some(selection);
session.actions_dismissed = Some(selection);
return true;
}
let marks = view.selection_quads(info);
let marks = session.selection_quads(info, rotation);
if marks.is_empty() {
return false;
}
@@ -513,19 +556,19 @@ pub(super) fn selection_actions(
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();
session.clear_selection();
let kind = if matches!(action, SelectionAction::Replace) {
view.comments.replace = Some(quads);
session.comments.replace = Some(quads);
comments::ComposerKind::Replace
} else {
comments::ComposerKind::TextNote { quads }
};
view.comments.composer = Some(comments::Composer { page, at, kind, text: String::new(), focus: true });
session.comments.composer = Some(comments::Composer { page, at, kind, text: String::new(), focus: true });
}
SelectionAction::Markup(tool) => {
// Every markup button carries a markup tool; anything else adds nothing.
let Some(kind) = tool.markup() else { return false };
view.clear_selection();
session.clear_selection();
let edits = marks.into_iter().map(|(page, quads)| {
Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {
page,
@@ -535,10 +578,30 @@ pub(super) fn selection_actions(
author: prefs.author.clone(),
})
});
view.pending_edit = view.selection_marks_edit(edits.collect(), selection.head_page());
session.pending_edit = session.selection_marks_edit(edits.collect(), head_page_of(&selection));
}
// Copy is dispatched through the app after the view borrow ends.
SelectionAction::Copy => {}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
/// A selection that covers a page whose text is not read yet gives no text: a copy waits instead of copying short.
#[test]
fn selected_text_is_none_while_a_covered_page_is_unread() {
let mut texts = HashMap::new();
texts.insert(0, Arc::new(PageText { glyphs: Vec::new(), line_of: Vec::new(), space_before: Vec::new(), truncated: false }));
let sizes = [(300.0, 200.0); 2];
let selection = TextSelection::new(0, FwSpan::run(0, 1, 0));
let doc = DocTexts::new(&texts, &HashSet::new(), 0, &sizes);
assert_eq!(selection.unread_pages(&doc), vec![1]);
assert_eq!(selection.text(&doc), None);
let failed = HashSet::from([1]);
let doc = DocTexts::new(&texts, &failed, 0, &sizes);
assert!(selection.unread_pages(&doc).is_empty(), "a page that failed is not waited for");
}
}
+12 -11
View File
@@ -28,8 +28,14 @@ trailer << /Root 1 0 R >>
}
fn harness(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
harness_on(crate::support::RecordingClipboard::default(), setup)
}
/// `harness` on the injected `clipboard`, whose recorded writes a test reads.
fn harness_on(clipboard: crate::support::RecordingClipboard, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
// PLAN: assumed support::app_with_clipboard(RecordingClipboard) -> PdfCraftApp (pdf-chrome-w9: `PdfCraftApp::with_host` over `AppServices` holding the clipboard)
let mut app = crate::support::app_with_clipboard(clipboard);
app.set_option("language", "en").unwrap();
app.open_bytes("table.pdf", None, table()).expect("opens");
app.set_option("left", "closed").unwrap();
@@ -152,20 +158,15 @@ fn alt_drag_with_the_highlighter_marks_only_the_column() {
/// the clipboard and no HTML, even where the clipboard would take it.
#[test]
fn a_column_selection_copies_plain_text_only() {
let offered = std::sync::Arc::new(std::sync::Mutex::new(0usize));
let seen = offered.clone();
let mut h = harness(move |app| {
app.system_clipboard = true;
app.html_clipboard_override = Some(Box::new(move |_, _| {
*seen.lock().unwrap() += 1;
true
}));
});
let clipboard = crate::support::RecordingClipboard::default();
let mut h = harness_on(clipboard.clone(), |_| {});
let (from, to) = top_two_rows(&h);
drag(&mut h, from, to, Modifiers::ALT);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert_eq!(*offered.lock().unwrap(), 0, "no HTML for a column selection");
// PLAN: assumed RecordingClipboard::writes() -> Vec<Vec<Flavor>> (each write's flavours, `mime` and `data`).
let html = clipboard.writes().iter().flatten().any(|flavor| flavor.mime.to_string() == "text/html");
assert!(!html, "no HTML for a column selection");
let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == "Name\tQty\nApple\t12"));
assert!(copied, "the plain text goes out the usual way");
}
+63 -324
View File
@@ -5,6 +5,8 @@ use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, Pos2, TouchPhase};
use egui_kittest::Harness;
use pdfcraft_ui_egui::PdfCraftApp;
use crate::support::RecordingClipboard;
/// One 300×200 page with two lines of Helvetica text.
fn two_lines() -> Vec<u8> {
text_pdf("BT /F1 14 Tf 20 150 Td (The quick brown fox) Tj 0 -24 Td (jumps over the dog) Tj ET")
@@ -35,8 +37,13 @@ fn harness(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> (Harness<'static,
/// `harness` with another document; the pointer ends over glyph 5 of its first page.
fn harness_with(pdf: Vec<u8>, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> (Harness<'static, PdfCraftApp>, Pos2) {
harness_clip(pdf, RecordingClipboard::default(), setup)
}
/// `harness_with` on the injected `clipboard`, whose recorded writes a test reads.
fn harness_clip(pdf: Vec<u8>, clipboard: RecordingClipboard, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> (Harness<'static, PdfCraftApp>, Pos2) {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
let mut app = app_on(clipboard);
app.set_option("language", "en").unwrap();
app.open_bytes("lines.pdf", None, pdf).expect("opens");
app.set_option("left", "closed").unwrap();
@@ -52,6 +59,25 @@ fn harness_with(pdf: Vec<u8>, setup: impl FnOnce(&mut PdfCraftApp) + 'static) ->
(h, at)
}
/// The app on the injected `clipboard`.
fn app_on(clipboard: RecordingClipboard) -> PdfCraftApp {
// PLAN: assumed support::app_with_clipboard(RecordingClipboard) -> PdfCraftApp (pdf-chrome-w9: `PdfCraftApp::with_host` over `AppServices` holding the clipboard)
crate::support::app_with_clipboard(clipboard)
}
/// What Copy with formatting wrote to the clipboard: `(html, plain text)` per write that had HTML.
fn html_sets(clipboard: &RecordingClipboard) -> Vec<(String, String)> {
// PLAN: assumed RecordingClipboard::writes() -> Vec<Vec<Flavor>> recording every attempt, with `mime` and `data`.
clipboard
.writes()
.iter()
.filter_map(|flavors| {
let part = |mime: &str| flavors.iter().find(|f| f.mime.to_string() == mime).map(|f| String::from_utf8_lossy(&f.data).into_owned());
Some((part("text/html")?, part("text/plain").unwrap_or_default()))
})
.collect()
}
/// Press and release without moving or leaving the page.
fn click(h: &mut Harness<'static, PdfCraftApp>, pos: Pos2) {
for pressed in [true, false] {
@@ -60,20 +86,6 @@ fn click(h: &mut Harness<'static, PdfCraftApp>, pos: Pos2) {
h.run_steps(1);
}
#[test]
fn quick_clicks_select_a_word_then_the_line_then_the_page() {
let (mut h, at) = harness(|_| {});
let page = "The quick brown fox\njumps over the dog";
for (n, want) in [None, Some("quick"), Some("The quick brown fox"), Some(page), Some(page)].into_iter().enumerate() {
click(&mut h, at);
assert_eq!(h.state().views[0].selected_text().as_deref(), want, "after {} clicks", n + 1);
}
// A pause ends the run: the next double-click selects a word again.
h.run_steps(60);
click(&mut h, at);
click(&mut h, at);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
}
#[test]
fn quick_clicks_with_the_highlighter_mark_only_the_word() {
@@ -154,72 +166,6 @@ fn drag(h: &mut Harness<'static, PdfCraftApp>, from: Pos2, to: Pos2) {
h.run_steps(1);
}
/// Click at `pos` with Shift held.
fn shift_click(h: &mut Harness<'static, PdfCraftApp>, pos: Pos2) {
h.event(Event::ModifiersChanged(Modifiers::SHIFT));
h.hover_at(pos);
h.run_steps(1);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT });
}
h.run_steps(1);
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(1);
}
/// Issue #527: ⇧-click extends the text selection to the click, keeping its anchor.
#[test]
fn shift_click_extends_the_selection_from_its_anchor() {
let (mut h, _) = harness(|_| {});
let glyph = |h: &Harness<'static, PdfCraftApp>, g: usize| h.state().views[0].glyph_screen_pos(0, g).expect("glyph on screen");
// Drag over "quick" (glyphs 4..=8).
let (q, k) = (glyph(&h, 4), glyph(&h, 8));
drag(&mut h, q, k);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
h.run_steps(60);
// ⇧-click on the "n" of "brown": the selection runs from the anchor to it.
let n = glyph(&h, 14);
shift_click(&mut h, n);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick brown"));
h.run_steps(60);
// ⇧-click before the anchor: the anchor stays, the selection now runs back to the click.
let t = glyph(&h, 0);
shift_click(&mut h, t);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("The q"));
h.run_steps(60);
// A plain click still clears it.
click(&mut h, n);
assert_eq!(h.state().views[0].selected_text(), None);
h.run_steps(60);
// ⇧-click with nothing selected selects nothing.
shift_click(&mut h, n);
assert_eq!(h.state().views[0].selected_text(), None);
}
/// Issue #1024: multi-click selection triggers immediately on pointer press, before release.
#[test]
fn multiclick_selects_on_pointer_press_before_release() {
let (mut h, at) = harness(|_| {});
// First click: press and release.
click(&mut h, at);
// Second click: press and HOLD (do not release).
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"), "word highlights on press");
// Release the second click: still selected.
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(1);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"), "word stays selected on release");
// Third click: press and HOLD.
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("The quick brown fox"), "line highlights on press");
// Release third click.
h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(1);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("The quick brown fox"), "line stays selected on release");
}
// Issue #1225: page-text Copy belongs in both menus and observes PDF permissions.
fn copied(h: &Harness<'static, PdfCraftApp>, want: &str) -> bool {
@@ -230,7 +176,7 @@ fn copied(h: &Harness<'static, PdfCraftApp>, want: &str) -> bool {
#[test]
fn selected_text_copy_edit_and_context_menus() {
use egui_kittest::kittest::Queryable;
let (mut h, at) = harness(|app| app.system_clipboard = false);
let (mut h, at) = harness(|_| {});
click(&mut h, at);
click(&mut h, at);
h.state_mut().quick_tool = pdfcraft_ui_egui::QuickTool::Hand;
@@ -261,28 +207,10 @@ fn selected_text_copy_edit_and_context_menus() {
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
}
#[test]
fn escape_closes_an_open_menu_before_it_clears_the_selection() {
// #3535: one Escape closed the menu and dropped the selection with it.
let (mut h, at) = harness(|_| {});
click(&mut h, at);
click(&mut h, at);
h.run_steps(2);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
crate::support::open_menu(&mut h, "View");
assert!(egui::Popup::is_any_open(&h.ctx), "the menu is open");
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert!(!egui::Popup::is_any_open(&h.ctx), "Escape closes the menu");
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"), "and keeps the selection");
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert_eq!(h.state().views[0].selected_text(), None, "a second Escape clears it");
}
#[test]
fn selected_text_copy_command_requires_selection() {
let (mut h, at) = harness(|app| app.system_clipboard = false);
let (mut h, at) = harness(|_| {});
assert!(!h.state_mut().execute("edit.copy"));
click(&mut h, at);
click(&mut h, at);
@@ -309,12 +237,11 @@ fn selected_text_copy_floating_button_honours_permissions() {
.unwrap();
let bytes = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
let mut app = app_on(RecordingClipboard::default());
app.set_option("language", "en").unwrap();
app.open_bytes("no-copy.pdf", None, bytes).unwrap();
app.submit_password(Some(password.into()));
app.set_option("left", "closed").unwrap();
app.system_clipboard = false;
app
});
let mut loaded = false;
@@ -339,20 +266,6 @@ fn selected_text_copy_floating_button_honours_permissions() {
}
}
/// What the stand-in for the system clipboard was given: `(html, plain text)` per copy.
type HtmlSets = std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>>;
/// The system clipboard on, through a stand-in that takes or refuses Copy with formatting.
fn html_clipboard(app: &mut PdfCraftApp, takes: bool) -> HtmlSets {
let sets = HtmlSets::default();
let seen = sets.clone();
app.system_clipboard = true;
app.html_clipboard_override = Some(Box::new(move |html, text| {
seen.lock().unwrap().push((html.to_owned(), text.to_owned()));
takes
}));
sets
}
fn any_copy_text(h: &Harness<'static, PdfCraftApp>) -> bool {
h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(_)))
@@ -363,14 +276,14 @@ fn any_copy_text(h: &Harness<'static, PdfCraftApp>) -> bool {
/// replace the HTML. A new copy replaces it.
#[test]
fn selected_text_copy_keeps_the_formatting_as_html() {
let (mut h, at) = harness(|_| {});
let sets = html_clipboard(h.state_mut(), true);
let clipboard = RecordingClipboard::default();
let (mut h, at) = harness_clip(two_lines(), clipboard.clone(), |_| {});
click(&mut h, at);
click(&mut h, at);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert_eq!(
sets.lock().unwrap().as_slice(),
html_sets(&clipboard).as_slice(),
[("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:14pt\">quick</span></p>\n".to_owned(), "quick".to_owned())]
);
assert!(!any_copy_text(&h), "egui's own text copy would replace the HTML");
@@ -380,7 +293,7 @@ fn selected_text_copy_keeps_the_formatting_as_html() {
click(&mut h, at);
}
assert!(h.state_mut().execute("edit.copy"));
let last = sets.lock().unwrap().last().cloned().unwrap_or_default();
let last = html_sets(&clipboard).last().cloned().unwrap_or_default();
assert!(last.0.contains(">The quick brown fox</span>"), "{last:?}");
assert_eq!(last.1, "The quick brown fox");
}
@@ -388,27 +301,28 @@ fn selected_text_copy_keeps_the_formatting_as_html() {
/// When the system clipboard refuses the HTML, Copy still copies the plain text.
#[test]
fn selected_text_copy_falls_back_to_plain_text_when_html_is_refused() {
let (mut h, at) = harness(|_| {});
let sets = html_clipboard(h.state_mut(), false);
// PLAN: assumed RecordingClipboard::refusing(mime) refuses a write that has that flavour, and records the attempt.
let clipboard = RecordingClipboard::refusing("text/html");
let (mut h, at) = harness_clip(two_lines(), clipboard.clone(), |_| {});
click(&mut h, at);
click(&mut h, at);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert_eq!(sets.lock().unwrap().len(), 1, "the HTML was offered");
assert_eq!(html_sets(&clipboard).len(), 1, "the HTML was offered");
assert!(copied(&h, "quick"), "the plain text goes out the usual way");
}
/// With the system clipboard off, no HTML is built and the plain text goes out as before.
/// With a clipboard that takes no write, no HTML is built and the plain text goes out as before.
#[test]
fn selected_text_copy_without_system_clipboard_builds_no_html() {
let (mut h, at) = harness(|_| {});
let sets = html_clipboard(h.state_mut(), true);
h.state_mut().system_clipboard = false;
// PLAN: assumed RecordingClipboard::refusing_all(): a backend with no clipboard behind it, which takes nothing.
let clipboard = RecordingClipboard::refusing_all();
let (mut h, at) = harness_clip(two_lines(), clipboard.clone(), |_| {});
click(&mut h, at);
click(&mut h, at);
assert!(h.state_mut().execute("edit.copy"));
h.step();
assert!(sets.lock().unwrap().is_empty());
assert!(html_sets(&clipboard).is_empty());
assert!(copied(&h, "quick"));
}
@@ -426,23 +340,22 @@ fn selected_text_copy_with_formatting_honours_permissions() {
})
.unwrap();
let bytes = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
let (mut h, at) = harness_with(bytes, |app| app.submit_password(Some("pw".into())));
let sets = html_clipboard(h.state_mut(), true);
let clipboard = RecordingClipboard::default();
let (mut h, at) = harness_clip(bytes, clipboard.clone(), |app| app.submit_password(Some("pw".into())));
click(&mut h, at);
click(&mut h, at);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
assert!(!h.state_mut().execute("edit.copy"));
h.step();
assert!(!any_copy_text(&h));
assert!(sets.lock().unwrap().is_empty());
assert!(html_sets(&clipboard).is_empty());
}
#[test]
fn selected_text_copy_preserves_unicode_and_page_clipboard() {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
let mut app = PdfCraftApp::new();
let mut app = app_on(RecordingClipboard::default());
app.set_option("language", "en").unwrap();
app.system_clipboard = false;
app.open_bytes("unicode.pdf", None, text_pdf(r"BT /F1 14 Tf 20 150 Td (caf\351) Tj ET")).unwrap();
app
});
@@ -477,8 +390,10 @@ fn selected_text_copy_keeps_focused_input_clipboard_ownership() {
h.state_mut().views[0].open_find();
h.state_mut().views[0].find.as_mut().unwrap().query = "widget café".into();
h.run_steps(3);
let find_input = h.state().views[0].find_input_id();
h.ctx.memory_mut(|m| m.request_focus(find_input));
{
use egui_kittest::kittest::Queryable;
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Find").click();
}
h.run_steps(2);
h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A);
h.run_steps(2);
@@ -600,54 +515,6 @@ 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]
@@ -666,139 +533,12 @@ fn a_selection_across_pages_is_marked_on_every_page_in_one_step() {
};
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");
assert!(h.state().views[0].comments.primary().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<u8> {
let content = "BT /F1 14 Tf 20 570 Td (Top line) Tj 0 -550 Td (Bottom line) Tj ET";
format!(
"%PDF-1.7
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 600] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj
4 0 obj << /Length {} >> stream
{content}
endstream endobj
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj
trailer << /Root 1 0 R >>
%%EOF",
content.len()
)
.into_bytes()
}
/// Issue #1670: holding a selection drag at the bottom edge of the view scrolls it, and the
/// selection follows the pointer down to text that was off screen.
#[test]
fn a_selection_drag_held_at_the_bottom_edge_scrolls_the_view() {
let (mut h, _) = harness_with(tall_page(), |app| {
app.set_option("layout", "continuous").unwrap();
app.set_option("zoom", "200").unwrap();
});
let view = &h.state().views[0];
let viewport = view.viewport_rect();
assert!(view.page_screen_rect(0).expect("page on screen").bottom() > viewport.bottom() + 100.0, "the page must not fit");
// "Top" (glyphs 0..=2).
let (from, to) = (view.glyph_screen_pos(0, 0).expect("glyph on screen"), view.glyph_screen_pos(0, 2).expect("glyph on screen"));
press_and_move(&mut h, from, to);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("Top"));
let edge = egui::pos2(to.x, viewport.bottom() - 2.0);
let before = page_top(&h, 0);
h.hover_at(edge);
h.run_steps(120);
assert!(page_top(&h, 0) < before - 100.0, "the view scrolls while the pointer rests at its edge ({before} -> {})", page_top(&h, 0));
let held = h.state().views[0].selected_text().expect("still selected");
// The pointer stays above the "t" of "Top", so the selection ends at the "t" of "Bottom".
assert_eq!(held, "Top line\nBot", "the selection reaches the bottom line");
h.event(Event::PointerButton { pos: edge, 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");
}
/// Click at `at`, then press there again and drag to `to` before releasing: a double-click drag.
fn double_click_drag(h: &mut Harness<'static, PdfCraftApp>, at: Pos2, to: Pos2) {
click(h, at);
press_and_move(h, at, to);
h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(1);
}
/// Issue #1685: dragging after a double-click extends the selection a word at a time, and the
/// double-clicked word stays selected whichever way the drag goes.
#[test]
fn a_double_click_drag_extends_by_whole_words_both_ways() {
let (mut h, _) = harness(|_| {});
let glyph = |h: &Harness<'static, PdfCraftApp>, g: usize| h.state().views[0].glyph_screen_pos(0, g).expect("glyph on screen");
// "The quick brown fox": the "u" of "quick" is glyph 5, the "o" of "brown" glyph 12.
let (u, o) = (glyph(&h, 5), glyph(&h, 12));
double_click_drag(&mut h, u, o);
let right = h.state().views[0].selected_text();
h.run_steps(60);
double_click_drag(&mut h, o, u);
let left = h.state().views[0].selected_text();
assert_eq!([right.as_deref(), left.as_deref()], [Some("quick brown"); 2], "dragging right, then left");
}
/// Issue #1685: after a triple-click the drag extends a whole line at a time.
#[test]
fn a_triple_click_drag_extends_by_whole_lines() {
let (mut h, at) = harness(|_| {});
// A glyph inside "jumps over the dog", on the second line.
let below = h.state().views[0].glyph_screen_pos(0, 23).expect("glyph on screen");
click(&mut h, at);
double_click_drag(&mut h, at, below);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("The quick brown fox\njumps over the dog"));
}
/// Coalesced down/up keeps the same word/line selection as separate press and release passes.
#[test]
fn coalesced_primary_clicks_select_line_then_spaced_click_clears() {
for coalesced in [true, false] {
let (mut h, at) = harness(|_| {});
h.ctx.options_mut(|o| o.max_passes = 1.try_into().unwrap());
let id = h.state().views[0].id;
let saved = h.state().session.get(id).unwrap().saved_bytes();
assert!(h.state().views[0].selected_text().is_none());
assert!(!h.state().session.get(id).unwrap().dirty);
for want in [None, Some("quick"), Some("The quick brown fox")] {
if coalesced {
// Harness::event steps each queued event separately; RawInput keeps this pair together.
h.input_mut().events.extend([true, false].map(|pressed| Event::PointerButton {
pos: at,
button: PointerButton::Primary,
pressed,
modifiers: Modifiers::NONE,
}));
h.step();
} else {
click(&mut h, at);
}
assert_eq!(h.state().views[0].selected_text().as_deref(), want, "coalesced={coalesced}");
}
h.run_steps(60);
if coalesced {
h.input_mut().events.extend([true, false].map(|pressed| Event::PointerButton {
pos: at,
button: PointerButton::Primary,
pressed,
modifiers: Modifiers::NONE,
}));
h.step();
} else {
click(&mut h, at);
}
assert_eq!(h.state().views[0].selected_text(), None, "a spaced click clears either gesture path");
assert_eq!(h.state().views[0].id, id);
let doc = h.state().session.get(id).unwrap();
assert!(!doc.dirty);
assert_eq!((doc.can_undo(), doc.can_redo()), (None, None));
assert_eq!(doc.saved_bytes(), saved);
}
}
/// Review on #2070: a click on the page in full screen waits out the double-click time before
/// it turns the page, and a link clicked meanwhile used to leave that turn pending: the link
@@ -831,7 +571,7 @@ fn full_screen_link_click_cancels_the_pending_page_turn() {
h.run_steps(1);
click(&mut h, at(240.0, 40.0));
h.run_steps(30);
assert_eq!(h.state().views[0].current, 2, "the link's page, and no turn after it");
assert_eq!(h.state().views[0].current(), 2, "the link's page, and no turn after it");
}
/// Review on #2070: in full screen a click goes forward a page, but a double-click selects the
@@ -861,7 +601,7 @@ fn full_screen_double_click_selects_a_word_and_stays_on_the_page() {
click(&mut h, at);
assert_eq!(h.state().views[0].selected_text().as_deref(), Some("quick"));
h.run_steps(30);
assert_eq!(h.state().views[0].current, 0, "the double-click didn't turn the page");
assert_eq!(h.state().views[0].current(), 0, "the double-click didn't turn the page");
// A single click turns it once the double-click time is over.
// Entering full screen again clears the selection.
@@ -870,7 +610,7 @@ fn full_screen_double_click_selects_a_word_and_stays_on_the_page() {
h.run_steps(30);
click(&mut h, at);
h.run_steps(30);
assert_eq!(h.state().views[0].current, 1, "a click goes forward");
assert_eq!(h.state().views[0].current(), 1, "a click goes forward");
// A click right before leaving full screen doesn't turn the page after it.
h.state_mut().views[0].go_to_page(0);
@@ -878,7 +618,7 @@ fn full_screen_double_click_selects_a_word_and_stays_on_the_page() {
click(&mut h, at);
h.state_mut().apply_full_screen(false);
h.run_steps(30);
assert_eq!(h.state().views[0].current, 0, "no page turn after leaving");
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
@@ -994,8 +734,8 @@ fn a_highlight_across_pages_selects_its_last_part_and_opens_its_note() {
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");
assert_eq!(app.views[0].comments.primary(), Some((1, on_page_2)), "the part where the selection ends is selected");
assert!(app.views[0].comments.panel.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
@@ -1011,8 +751,8 @@ fn a_highlight_dragged_back_across_pages_selects_its_part_where_the_drag_ended()
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");
assert_eq!(app.views[0].comments.primary(), Some((0, on_page_1)), "the part where the drag ended is selected");
assert!(app.views[0].comments.panel.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.
@@ -1021,12 +761,11 @@ fn a_highlight_dragged_back_across_pages_selects_its_part_where_the_drag_ended()
#[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.state_mut().redact_pages(&[0, 1, 2]);
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");
assert_eq!(app.views[0].comments.primary(), None, "no mark selected");
assert!(app.views[0].comments.panel.editing.is_none(), "no editor opened");
}